repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Zig1375/SwiftClickHouse
|
refs/heads/master
|
Sources/SwiftClickHouse/Core/ClichHouseValue.swift
|
mit
|
1
|
import Foundation
public struct ClickHouseValue : CustomStringConvertible {
public let val_number : NSNumber?;
public let val_string : String?;
public let val_date : Date?;
public let val_array : [ClickHouseValue]?;
public let type : ClickHouseType;
public let isNull : Bool;
public init(type : ClickHouseType, number : NSNumber, isNull: Bool = false) {
self.type = type;
self.val_number = number;
self.val_string = nil;
self.val_date = nil;
self.val_array = nil;
self.isNull = isNull;
}
public init(type : ClickHouseType, string : String) {
self.type = type;
self.val_number = nil;
self.val_string = string;
self.val_date = nil;
self.val_array = nil;
self.isNull = false;
}
public init(type : ClickHouseType, date : Date) {
self.type = type;
self.val_number = nil;
self.val_string = nil;
self.val_date = date;
self.val_array = nil;
self.isNull = false;
}
public init(type : ClickHouseType, array : [ClickHouseValue]) {
self.type = type;
self.val_number = nil;
self.val_string = nil;
self.val_date = nil;
self.val_array = array;
self.isNull = false;
}
public init(type : ClickHouseType) {
self.type = type;
self.val_number = nil;
self.val_string = nil;
self.val_date = nil;
self.val_array = nil;
self.isNull = true;
}
public var int8 : Int8? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8 :
return self.val_number?.int8Value;
default :
return nil;
}
}
public var uint8 : UInt8? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8 :
return self.val_number?.uint8Value;
default :
return nil;
}
}
public var uint16 : UInt16? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8, .UInt16 :
return self.val_number?.uint16Value;
default :
return nil;
}
}
public var int16 : Int16? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8, .Int16 :
return self.val_number?.int16Value;
default :
return nil;
}
}
public var uint32 : UInt32? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8, .UInt16, .UInt32 :
return self.val_number?.uint32Value;
default :
return nil;
}
}
public var int32 : Int32? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8, .Int16, .Int32 :
return self.val_number?.int32Value;
default :
return nil;
}
}
public var uint64 : UInt64? {
if self.isNull {
return nil;
}
switch (self.type) {
case .UInt8, .UInt16, .UInt32, .UInt64 :
return self.val_number?.uint64Value;
default :
return nil;
}
}
public var int64 : Int64? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Int8, .Int16, .Int32, .Int64 :
return self.val_number?.int64Value;
default :
return nil;
}
}
public var float : Float? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Float32 :
if let n = self.val_number?.floatValue, !n.isNaN && !n.isInfinite {
return n;
} else {
return nil;
}
default :
return nil;
}
}
public var double : Double? {
if self.isNull {
return nil;
}
switch (self.type) {
case .Float32 :
if let n = self.val_number?.floatValue, !n.isNaN && !n.isInfinite {
return Double(n);
} else {
return nil;
}
case .Float64 :
if let n = self.val_number?.doubleValue, !n.isNaN && !n.isInfinite {
return n;
} else {
return nil;
}
default :
return nil;
}
}
public var float32 : Float? {
return self.float;
}
public var float64 : Double? {
return self.double;
}
public var uint : UInt64? {
return self.uint64;
}
public var int : Int64? {
return self.int64;
}
public var date : Date? {
return self.val_date;
}
public var datetime : Date? {
return self.val_date;
}
public var enum8 : String {
return self.string;
}
public var enum16 : String {
return self.string;
}
public var string : String {
if (self.isNull) {
return "NIL";
}
switch (self.type) {
case .String, .FixedString :
return self.val_string!;
case .Int8, .Int16, .Int32, .Int64, .UInt8, .UInt16, .UInt32, .UInt64, .Float32, .Float64 :
return "\(self.val_number!)";
case let .Enum8(variants) :
let v : Int16 = self.val_number!.int16Value;
return variants[v] ?? "Unknown enum";
case let .Enum16(variants) :
let v : Int16 = self.val_number!.int16Value;
return variants[v] ?? "Unknown enum";
case .Date :
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier: "en_GB")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: self.val_date!);
case .DateTime :
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale.init(identifier: "en_GB")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: self.val_date!);
case .Array :
var list = [String]();
for l in self.val_array! {
list.append(l.description);
}
return list.joined(separator: ", ");
default :
return "Unknown";
}
}
public var description : String {
switch (self.type) {
case .String, .FixedString, .Enum8, .Enum16, .Date, .DateTime :
return "'\(self.string)'";
case .Int8, .Int16, .Int32, .Int64, .UInt8, .UInt16, .UInt32, .UInt64, .Float32, .Float64 :
return self.string;
case .Array :
return "[\(self.string)]"
default :
return "Unknown";
}
}
}
|
15b2bfe81a9f9cd0b0ebfff5659e2da9
| 23.748344 | 103 | 0.460591 | false | false | false | false |
sleekbyte/tailor
|
refs/heads/master
|
src/test/swift/com/sleekbyte/tailor/grammar/ClassesAndStructures.swift
|
mit
|
1
|
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
let someResolution = Resolution()
let someVideoMode = VideoMode()
print("The width of someResolution is \(someResolution.width)")
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
let vga = Resolution(width: 640, height: 480)
enum CompassPoint {
case North, South, East, West
}
var currentDirection = CompassPoint.West
let rememberedDirection = currentDirection
currentDirection = .East
if rememberedDirection == .West {
print("The remembered direction is still .West")
}
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
"PROPERTIES"
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a non-trivial amount of time to initialize.
*/
var fileName = "data.txt"
// the DataImporter class would provide data importing functionality here
}
class DataManager {
lazy var importer = DataImporter()
var data = [String]()
// the DataManager class would provide data management functionality here
}
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set(newCenter) {
origin.x = newCenter.x - (size.width / 2)
origin.y = newCenter.y - (size.height / 2)
}
}
}
var square = Rect(origin: Point(x: 0.0, y: 0.0),
size: Size(width: 10.0, height: 10.0))
let initialSquareCenter = square.center
square.center = Point(x: 15.0, y: 15.0)
print("square.origin is now at (\(square.origin.x), \(square.origin.y))")
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
struct Cuboid {
var width = 0.0, height = 0.0, depth = 0.0
var volume: Double {
return width * height * depth
}
}
let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0)
print("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)")
class StepCounter {
var totalSteps: Int = 0 {
willSet(newTotalSteps) {
print("About to set totalSteps to \(newTotalSteps)")
}
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue) steps")
}
}
}
}
let stepCounter = StepCounter()
struct SomeStructure {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 1
}
}
enum SomeEnumeration {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 6
}
}
class SomeClass {
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
return 27
}
class var overrideableComputedTypeProperty: Int {
return 107
}
}
struct AudioChannel {
static let thresholdLevel = 10
static var maxInputLevelForAllChannels = 0
var currentLevel: Int = 0 {
didSet {
if currentLevel > AudioChannel.thresholdLevel {
// cap the new audio level to the threshold level
currentLevel = AudioChannel.thresholdLevel
}
if currentLevel > AudioChannel.maxInputLevelForAllChannels {
// store this as the new overall maximum input level
AudioChannel.maxInputLevelForAllChannels = currentLevel
}
}
}
}
@objc final internal class World {
internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }
internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }
}
@objc internal final class World {
internal var exampleHooks: ExampleHooks {return configuration.exampleHooks }
internal var suiteHooks: SuiteHooks { return configuration.suiteHooks }
}
public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
}
public subscript(i: Int) -> Element {
get {
return getElement(i, wasNativeTypeChecked: _isNativeTypeChecked)
}
// declarationModifier before setterClause
nonmutating set {
if _fastPath(_isNative) {
_native[i] = newValue
}
else {
var refCopy = self
refCopy.replace(
subRange: i...i, with: 1, elementsOf: CollectionOfOne(newValue))
}
}
}
|
23f724f8e400258aa8ecb05299430659
| 26.865979 | 150 | 0.650018 | false | false | false | false |
JasonChen2015/Paradise-Lost
|
refs/heads/master
|
Paradise Lost/Classes/ViewControllers/Tool/PaintingVC.swift
|
mit
|
3
|
//
// PaintingVC.swift
// Paradise Lost
//
// Created by jason on 26/9/2017.
// Copyright © 2017 Jason Chen. All rights reserved.
//
import UIKit
class PaintingVC: UIViewController, PaintingViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var mainView: PaintingView!
var toolView: PaintingToolView!
var colorView: PaintingColorView!
/// flag of current picture whether has been saved
var isCurrentPicSave: Bool = true
// MARK: life cycle
override var prefersStatusBarHidden: Bool {
get {
return true
}
}
override var shouldAutorotate : Bool {
return true
}
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return .portrait
}
override func viewDidLoad() {
super.viewDidLoad()
let rect = UIScreen.main.bounds
let toolheigh = rect.height / 13
let colorheight = CGFloat(40)
mainView = PaintingView(frame: rect)
mainView.delegate = self
view.addSubview(mainView)
toolView = PaintingToolView(frame: CGRect(x: 0, y: (rect.height - toolheigh), width: rect.width, height: toolheigh))
toolView.delegate = self
view.addSubview(toolView)
colorView = PaintingColorView(frame: CGRect(x: 0, y: (rect.height - toolheigh - colorheight), width: rect.width, height: colorheight))
colorView.isHidden = true
view.addSubview(colorView)
}
// MARK: PaintingViewDelegate
func exit() {
self.dismiss(animated: false, completion: nil)
}
func savePic() {
savePicToPhotoLibrary(nil)
}
func getPic() {
if (mainView.hasImage && !isCurrentPicSave) {
AlertManager.showTipsWithContinue(self, message: LanguageManager.getToolString(forKey: "paint.getImage.message"), handler: savePicToPhotoLibrary, cHandler: nil)
}
getPicFromPhotoLibrary()
}
func changePenMode() {
if (toolView.currentMode == .pen) {
colorView.isHidden = false
} else {
colorView.isHidden = true
}
}
func changeResizeMode() {
colorView.isHidden = true
}
func changeTextMode() {
colorView.isHidden = true
}
// MARK: UIImagePickerControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerEditedImage] as? UIImage {
mainView.loadImage(rawImage: image)
isCurrentPicSave = false
} else if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
mainView.loadImage(rawImage: image)
isCurrentPicSave = false
} else {
AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.getImage.error"), handler: nil)
}
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// MARK: private methods
fileprivate func getPicFromPhotoLibrary() {
let picker = UIImagePickerController()
picker.delegate = self
//picker.allowsEditing = true
picker.sourceType = .photoLibrary
self.present(picker, animated: true, completion: nil)
}
fileprivate func savePicToPhotoLibrary(_ alert: UIAlertAction?) {
if let image = mainView.getImage() {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(PaintingVC.image(_:didFinishSavingWithError:contextInfo:)), nil)
}
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let _ = error {
// fail
AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.saveImage.fail"), handler: nil)
} else {
// success
AlertManager.showTips(self, message: LanguageManager.getToolString(forKey: "paint.saveImage.success"), handler: nil)
isCurrentPicSave = true
}
}
}
|
649072251ab9321ada268656b617d75d
| 31.328358 | 172 | 0.633887 | false | false | false | false |
alex-d-fox/iDoubtIt
|
refs/heads/master
|
iDoubtIt/Code/Preferences.swift
|
gpl-3.0
|
1
|
//
// Preferences.swift
// iDoubtIt
//
// Created by Alexander Fox on 10/12/16.
//
//
import Foundation
import SpriteKit
var soundOn = Pref().Sound()
var isWacky = Pref().Wacky()
var difficulty = Pref().LevelDifficulty()
var background = Pref().BackgroundImage()
var cardCover = Pref().CardCover()
let screenSize: CGRect = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
let prefs = UserDefaults.standard
struct Pref {
func Sound() -> Bool {
if (prefs.object(forKey: "Sound") == nil) {
prefs.set(true, forKey: "Sound")
}
let soundOn = prefs.bool(forKey: "Sound")
return soundOn
}
func Wacky() -> Bool {
if (prefs.object(forKey: "Wacky") == nil) {
prefs.set(false, forKey: "Wacky")
}
let isWacky = prefs.bool(forKey: "Wacky")
return isWacky
}
func LevelDifficulty() -> Int {
if (prefs.object(forKey: "Difficulty") == nil) {
prefs.set(Difficulty.easy.rawValue, forKey: "Difficulty")
}
let difficulty = prefs.integer(forKey: "Difficulty")
return difficulty
}
func BackgroundImage() -> String {
if (prefs.object(forKey: "Background") == nil) {
prefs.setValue(Background.bg_blue.rawValue, forKey: "Background")
}
let background = prefs.string(forKey: "Background")!
return background
}
func CardCover() -> String {
if (prefs.object(forKey: "CardCover") == nil) {
prefs.setValue(cardBack.cardBack_blue4.rawValue, forKey: "CardCover")
}
let cardCover = prefs.string(forKey: "CardCover")!
return cardCover
}
func updateVars() {
soundOn = Sound()
isWacky = Wacky()
difficulty = LevelDifficulty()
background = BackgroundImage()
cardCover = CardCover()
}
}
|
57bef36d1ed692abc1bbd2816a06a045
| 25.888889 | 81 | 0.592975 | false | false | false | false |
yichizhang/SubjectiveCCastroControls_Swift
|
refs/heads/master
|
SCCastroControls/SCPlaybackItem.swift
|
mit
|
1
|
//
// SCPlaybackItem.swift
// SCCastroControls
//
// Created by Yichi on 4/03/2015.
// Copyright (c) 2015 Subjective-C. All rights reserved.
//
import Foundation
class SCPlaybackItem : NSObject {
var totalTime:NSTimeInterval = 0
var elapsedTime:NSTimeInterval {
set {
_elapsedTime = max(0, min(totalTime, newValue))
}
get {
return _elapsedTime
}
}
private var _elapsedTime:NSTimeInterval = 0
// MARK: Public methods
func stringForElapsedTime() -> String! {
return stringForHours(hoursComponentForTimeInterval(elapsedTime), minutes: minutesComponentForTimeInterval(elapsedTime), seconds: secondsComponentForTimeInterval(elapsedTime))
}
func stringForRemainingTime() -> String! {
let remainingTime = totalTime - elapsedTime
return "-" + stringForHours(hoursComponentForTimeInterval(remainingTime), minutes: minutesComponentForTimeInterval(remainingTime), seconds: secondsComponentForTimeInterval(remainingTime))
}
// MARK: Private methods
private func stringForHours(hours: UInt, minutes: UInt, seconds: UInt) -> String! {
var string:NSString!
if hours > 0 {
string = NSString(format: "%lu:%lu:%02lu", u_long(hours), u_long(minutes), CUnsignedLong(seconds) )
} else {
string = NSString(format: "%lu:%02lu", u_long(minutes), CUnsignedLong(seconds) )
}
return string
}
private func hoursComponentForTimeInterval(timeInterval: NSTimeInterval) -> UInt {
return UInt(timeInterval) / 60 / 60
}
private func minutesComponentForTimeInterval(timeInterval: NSTimeInterval) -> UInt {
return (UInt(timeInterval) / 60) % 60
}
private func secondsComponentForTimeInterval(timeInterval: NSTimeInterval) -> UInt {
return UInt(timeInterval) % 60
}
}
|
23606c877738f9f99f57d17cb3e33bb3
| 29.553571 | 189 | 0.74152 | false | false | false | false |
MJHee/QRCode
|
refs/heads/master
|
QRCode/QRCode/WebViewController.swift
|
mit
|
1
|
//
// WebViewController.swift
// QRCode
//
// Created by MJHee on 2017/3/18.
// Copyright © 2017年 MJBaby. All rights reserved.
//
import UIKit
import WebKit
class WebViewController: UIViewController, WKNavigationDelegate {
var url : String?
override func viewDidLoad() {
super.viewDidLoad()
let str = url! as String
let path = URL(string: str)
let webView = WKWebView(frame: self.view.bounds)
webView.load(URLRequest(url: path!))
webView.navigationDelegate = self
self.view.addSubview(webView)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.title = webView.title
}
}
|
ff92747f2e4e486942be90e8b6b5fb1f
| 22.483871 | 77 | 0.625 | false | false | false | false |
jiecao-fm/SwiftTheme
|
refs/heads/master
|
Demo/GlobalPicker.swift
|
mit
|
1
|
//
// GlobalPicker.swift
// Demo
//
// Created by Gesen on 16/3/1.
// Copyright © 2016年 Gesen. All rights reserved.
//
import SwiftTheme
enum GlobalPicker {
static let backgroundColor: ThemeColorPicker = ["#fff", "#fff", "#fff", "#292b38"]
static let textColor: ThemeColorPicker = ["#000", "#000", "#000", "#ECF0F1"]
static let barTextColors = ["#FFF", "#000", "#FFF", "#FFF"]
static let barTextColor = ThemeColorPicker.pickerWithColors(barTextColors)
static let barTintColor: ThemeColorPicker = ["#EB4F38", "#F4C600", "#56ABE4", "#01040D"]
}
|
a853b263d53570ab797dad6fb145ae42
| 30.888889 | 92 | 0.651568 | false | false | false | false |
bitboylabs/selluv-ios
|
refs/heads/master
|
selluv-ios/selluv-ios/Classes/Controller/UI/Product/views/SLVProductInfo3Cell.swift
|
mit
|
1
|
//
// SLVProductInfo3Cell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 7..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
/*
판매자/스타일/하자/엑세사리/추천착샷/비슷한 상품/코멘트 타이틀 셀
*/
class SLVProductInfo3Cell: UITableViewCell {
@IBOutlet weak var mainTitleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var moreButton: UIButton!
var cellIndex = 0
override public func awakeFromNib() {
super.awakeFromNib()
}
//TODO: 추후 처리할 것 ....
@IBAction func touchMore(_ sender: Any) {
if cellIndex == 13 {//추천 착용 사진 더보기
}
else if cellIndex == 15 {//비슷한 상품
}
}
}
|
acc53707cd9b124481fce613edca6ec5
| 19 | 55 | 0.589189 | false | false | false | false |
memexapp/memex-swift-sdk
|
refs/heads/master
|
Sources/DecimalNumberTransform.swift
|
mit
|
1
|
import Foundation
import ObjectMapper
class DecimalNumberTransform: TransformType {
typealias Object = NSDecimalNumber
typealias JSON = Any
init() {}
func transformFromJSON(_ value: Any?) -> NSDecimalNumber? {
if let value = value {
let string = "\(value)"
return NSDecimalNumber(string: string)
}
return nil
}
func transformToJSON(_ value: NSDecimalNumber?) -> Any? {
if let value = value {
return value.stringValue as AnyObject?
}
return nil
}
}
|
4c858d6fe0c5c8afdc870ab38a78975b
| 18.923077 | 61 | 0.65251 | false | false | false | false |
lantun/ThreeBall
|
refs/heads/master
|
ThreeBall/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// ThreeBall
//
// Created by LanTun on 16/2/13.
// Copyright © 2016年 LanTun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var waittingView:UIView! // 动画view
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor(red: 0.96470588235294119, green: 0.36470588235294116, blue: 0.18823529411764706, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playAction(sender: AnyObject) {
if (waittingView != nil){
waittingView.removeFromSuperview()
}
waittingView = UIView(frame: CGRectMake(0,0,200,200))
waittingView.center = self.view.center
waittingView.backgroundColor = UIColor.clearColor()
let repeatcount:Float = 6*20
let timeDuration:NSTimeInterval = 3.4
let s3:CGFloat = sqrt(3.0)
// 圆半径
let radius:CGFloat = 9
// 圆的距离
let distance: CGFloat = radius/5
// 六芒星阵的边长
let lineWidth:CGFloat = 2*radius
let path1 = UIBezierPath()
let center = CGPointMake(100, 100)
path1.moveToPoint(CGPointMake(center.x+lineWidth/2, center.y-s3*lineWidth/2))
// path1.addLineToPoint(CGPointMake(center.x, center.y-s3*lineWidth))2
// path1.addLineToPoint(CGPointMake(center.x-lineWidth/2, center.y-s3*lineWidth/2))3
// path1.addLineToPoint(CGPointMake(center.x-lineWidth*3/2, center.y-s3*lineWidth/2))4
// path1.addLineToPoint(CGPointMake(center.x-lineWidth, center.y))5
// path1.addLineToPoint(CGPointMake(center.x-lineWidth*3/2, center.y+s3*lineWidth/2))6
// path1.addLineToPoint(CGPointMake(center.x-lineWidth/2, center.y+s3*lineWidth/2))7
// path1.addLineToPoint(CGPointMake(center.x, center.y+s3*lineWidth))8
// path1.addLineToPoint(CGPointMake(center.x+lineWidth/2, center.y+s3*lineWidth/2))9
// path1.addLineToPoint(CGPointMake(center.x+lineWidth*3/2, center.y+s3*lineWidth/2))10
// path1.addLineToPoint(CGPointMake(center.x+lineWidth, center.y))11
// path1.addLineToPoint(CGPointMake(center.x+lineWidth*3/2, center.y-s3*lineWidth/2))12
path1.addCurveToPoint(CGPointMake(center.x-lineWidth/2, center.y-s3*lineWidth/2), controlPoint1: CGPointMake(center.x, center.y-s3*lineWidth), controlPoint2: CGPointMake(center.x, center.y-s3*lineWidth))
path1.addCurveToPoint(CGPointMake(center.x-lineWidth, center.y), controlPoint1: CGPointMake(center.x-lineWidth*3/2, center.y-s3*lineWidth/2), controlPoint2: CGPointMake(center.x-lineWidth*3/2, center.y-s3*lineWidth/2))
path1.addCurveToPoint(CGPointMake(center.x-lineWidth/2, center.y+s3*lineWidth/2), controlPoint1: CGPointMake(center.x-lineWidth*3/2, center.y+s3*lineWidth/2), controlPoint2: CGPointMake(center.x-lineWidth*3/2, center.y+s3*lineWidth/2))
path1.addCurveToPoint(CGPointMake(center.x+lineWidth/2, center.y+s3*lineWidth/2), controlPoint1: CGPointMake(center.x, center.y+s3*lineWidth), controlPoint2: CGPointMake(center.x, center.y+s3*lineWidth))
path1.addCurveToPoint(CGPointMake(center.x+lineWidth, center.y), controlPoint1: CGPointMake(center.x+lineWidth*3/2, center.y+s3*lineWidth/2), controlPoint2: CGPointMake(center.x+lineWidth*3/2, center.y+s3*lineWidth/2))
path1.addCurveToPoint(CGPointMake(center.x+lineWidth/2, center.y-s3*lineWidth/2), controlPoint1: CGPointMake(center.x+lineWidth*3/2, center.y-s3*lineWidth/2), controlPoint2: CGPointMake(center.x+lineWidth*3/2, center.y-s3*lineWidth/2))
let keyframeAnimation1=CAKeyframeAnimation(keyPath: "position")
keyframeAnimation1.path = path1.CGPath
keyframeAnimation1.repeatCount = repeatcount/6
keyframeAnimation1.removedOnCompletion = false
keyframeAnimation1.duration = timeDuration
keyframeAnimation1.cumulative = false
keyframeAnimation1.fillMode = kCAFillModeForwards
keyframeAnimation1.timingFunction=CAMediaTimingFunction(name: "linear")
let circle1 = UIView()
circle1.frame = CGRectMake(0, 0, radius*2, radius*2)
circle1.backgroundColor = UIColor.whiteColor()
circle1.layer.cornerRadius = radius
circle1.layer.masksToBounds = true
circle1.layer.addAnimation(keyframeAnimation1, forKey: "position")
waittingView.addSubview(circle1)
// 换成两个圆
let sectionView = UIView()
sectionView.frame = CGRectMake(0, 0, radius*4+distance*2, radius*2)
sectionView.backgroundColor = UIColor.clearColor()
// 左边的圆
let circle2 = UIView()
circle2.frame = CGRectMake(0, 0, radius*2, radius*2)
circle2.backgroundColor = UIColor.whiteColor()
circle2.layer.cornerRadius = radius
circle2.layer.masksToBounds = true
sectionView.addSubview(circle2)
// 右边的圆
let circle3 = UIView()
circle3.frame = CGRectMake(radius*2+distance*2, 0, radius*2, radius*2)
circle3.backgroundColor = UIColor.whiteColor()
circle3.layer.cornerRadius = radius
circle3.layer.masksToBounds = true
sectionView.addSubview(circle3)
// 旋转整体 120度/0.5秒
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = (CGFloat)(120/360*(2*M_PI))
rotationAnimation.duration = timeDuration/6.0
rotationAnimation.additive = true
rotationAnimation.cumulative = true
rotationAnimation.repeatCount = repeatcount
rotationAnimation.fillMode = kCAFillModeForwards
rotationAnimation.removedOnCompletion = false
rotationAnimation.timingFunction = CAMediaTimingFunction(name: "linear")
let path2 = UIBezierPath(arcCenter: center, radius: radius*0.5, startAngle: (CGFloat)(4/6*M_PI), endAngle: (CGFloat)(-1*M_PI-2/6*M_PI), clockwise: false)
let keyframeAnimation2=CAKeyframeAnimation(keyPath: "position")
keyframeAnimation2.path = path2.CGPath
keyframeAnimation2.repeatCount = repeatcount/6
keyframeAnimation2.removedOnCompletion = false
keyframeAnimation2.duration = timeDuration
keyframeAnimation2.repeatDuration = 0
keyframeAnimation2.fillMode = kCAFillModeForwards
keyframeAnimation2.timingFunction=CAMediaTimingFunction(name: "linear")
sectionView.transform = CGAffineTransformMakeRotation((CGFloat)(30/360*M_PI))
sectionView.layer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
sectionView.layer.addAnimation(keyframeAnimation2, forKey: "keyframeAnimation")
waittingView.addSubview(sectionView)
self.view.addSubview(waittingView)
}
}
|
80f9de6fc5592fc2516e9fb3bf842d9a
| 47.932432 | 243 | 0.678956 | false | false | false | false |
egnwd/ic-bill-hack
|
refs/heads/master
|
quick-split/quick-split/FriendCollectionViewCell.swift
|
mit
|
1
|
//
// FriendCollectionViewCell.swift
// quick-split
//
// Created by Elliot Greenwood on 02.20.2016.
// Copyright © 2016 stealth-phoenix. All rights reserved.
//
import UIKit
class FriendCollectionViewCell: UICollectionViewCell {
let cellSize = CGSize(width: 75, height: 100)
let defaultColour = UIColor.clearColor()
var name: UILabel = UILabel()
var avatar: UIImageView = UIImageView()
var friend: Friend?
var isChosen = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func populateWithFriend(friend: Friend) {
self.friend = friend
let imageLength = 64
let imageX = (Int(cellSize.width) - imageLength) / 2
avatar = UIImageView(frame: CGRect(x: imageX, y: 0, width: imageLength, height: imageLength))
avatar.image = friend.picture
let lyr = avatar.layer
lyr.masksToBounds = true
lyr.cornerRadius = avatar.bounds.size.width / 2
self.addSubview(avatar)
name = UILabel(frame: CGRect(x: 0, y: imageLength+10, width: Int(cellSize.width), height: 24))
name.text = friend.name
name.textAlignment = .Center
self.addSubview(name)
}
func highlightCell(withColour colour: UIColor) {
self.avatar.layer.borderWidth = 4
self.avatar.layer.borderColor = colour.CGColor
friend!.colour = colour
}
func unhighlightCell() {
self.avatar.layer.borderWidth = 0
friend!.colour = defaultColour
}
}
|
18468f01554716ac73ec6443de21ba28
| 26.576923 | 98 | 0.691771 | false | false | false | false |
GoodMorningCody/EverybodySwift
|
refs/heads/master
|
WeeklyToDo/WeeklyToDo/Weekly.swift
|
mit
|
1
|
//
// Weekly.swift
// WeeklyToDo
//
// Created by Cody on 2015. 1. 22..
// Copyright (c) 2015년 TIEKLE. All rights reserved.
//
import Foundation
class Weekly {
class func weekday(index : Int, useStandardFormat : Bool) -> String {
// index에 해당하는 요일을 다국어로 변환한 후 반환
// ie. index =0 is today
var dateFormatter = NSDateFormatter()
if useStandardFormat==false {
dateFormatter.locale = NSLocale.currentLocale()
}
return dateFormatter.weekdaySymbols[index] as String
}
class func weekdayFromNow(offset : Int, useStandardFormat : Bool) -> String {
var dateFormatter = NSDateFormatter()
if useStandardFormat==false {
dateFormatter.locale = NSLocale.currentLocale()
}
dateFormatter.dateFormat = "EEEE"
var date = NSDate(timeIntervalSinceNow: 60.0*60.0*24.0 * Double(offset))
return dateFormatter.stringFromDate(date)
}
class func dateFromNow(toSymbol: String) -> NSDate? {
var symbols = NSDateFormatter().weekdaySymbols + NSDateFormatter().weekdaySymbols as [String]
var symbolOnToday = weekdayFromNow(0, useStandardFormat:false)
var length = 0
var foundedStartIndex = false
for symbol in symbols {
if symbol==symbolOnToday {
foundedStartIndex = true
}
else if foundedStartIndex==true {
++length
}
if symbol == toSymbol {
break
}
}
var component = NSCalendar.currentCalendar().components(
NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay,
fromDate: NSDate(timeIntervalSinceNow: Double(60*60*24*length))
)
return NSCalendar.currentCalendar().dateFromComponents(component)
}
// class func lengthFromNow(toSymbol:String) -> Int {
// var symbols = NSDateFormatter().weekdaySymbols + NSDateFormatter().weekdaySymbols
// var symbolOnToday = weekdayFromNow(0, useStandardFormat:false)
// var length = 0
// var foundedStartIndex = false
// for symbol in symbols {
// if symbol as String==symbolOnToday {
// foundedStartIndex = true
// }
// else if foundedStartIndex==true {
// ++length
// }
//
// if symbol as String == toSymbol {
// break
// }
// }
// return length
// }
}
|
54bdbeee3d2d5b29bbcdc7f7ab3ebd6e
| 31.7875 | 112 | 0.576659 | false | false | false | false |
lojals/curiosity_reader
|
refs/heads/master
|
curiosity_reader/curiosity_reader/src/components/ArticleComponent.swift
|
gpl-2.0
|
1
|
//
// ArticleComponent.swift
// curiosity_reader
//
// Created by Jorge Raul Ovalle Zuleta on 5/16/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
@objc protocol ArticleComponentDelegate{
optional func tapInArticle()
}
class ArticleComponent: UIView {
var tapGesture:UITapGestureRecognizer!
var delegate:ArticleComponentDelegate!
var question:UILabel!
var data:JSON!
init(frame: CGRect, data:JSON) {
super.init(frame: frame)
self.data = data
self.backgroundColor = UIColor.whiteColor()
self.layer.borderColor = UIColor.themeGreyMedium().CGColor
self.layer.borderWidth = 1
tapGesture = UITapGestureRecognizer(target: self, action: Selector("goToArticle:"))
self.addGestureRecognizer(tapGesture)
question = UILabel(frame: CGRectMake(20, 5, frame.width-50, 70))
question.font = UIFont.fontRegular(17.5)
question.numberOfLines = 0
question.text = "¿Cuál es el nombre del director de Star War Episodio VII: The Force Awakeness?"
question.textAlignment = NSTextAlignment.Left
question.textColor = UIColor.blackColor()
self.addSubview(question)
var tag = TagComponent(tag: "Ciencia ficción", icon: UIImage(named: "sfi"))
tag.frame.origin.x = 20
tag.frame.origin.y = question.frame.maxY + 5
self.addSubview(tag)
}
func goToArticle(sender:UIView){
delegate.tapInArticle!()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
2d931b0c8696b945787ec3f4a0ef682f
| 29.773585 | 104 | 0.663397 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
refs/heads/good
|
SwiftGL-Demo/Source/Common/TextureShader.swift
|
mit
|
1
|
//
// TextureShader.swift
// SwiftGL
//
// Created by jerry on 2016/3/13.
// Copyright © 2016年 Jerry Chan. All rights reserved.
//
import SwiftGL
struct TextureMappingVertice{
var position:Vec4
var textureUV:Vec2
}
enum ImageMode{
case fill
case fit
}
class TextureShader: GLShaderWrapper {
var imgWidth:Float = 0,imgHeight:Float = 0
init() {
super.init(name:"RenderTexture")
//
addAttribute("position", type: Vec4.self)
addAttribute("textureUV", type: Vec2.self)
//
addUniform("MVP")
addUniform("imageTexture")
addUniform("alpha")
}
func setSize(_ width:Float,height:Float)
{
initVertex(width, height: height)
}
func genImageVertices(_ leftTop:Vec4,rightBottom:Vec4)
{
let ltx = leftTop.x / imgWidth
let lty = leftTop.y / imgHeight
let rbx = rightBottom.x / imgWidth
let rby = rightBottom.y / imgHeight
let v1 = TextureMappingVertice(position: Vec4(leftTop.x,leftTop.y), textureUV: Vec2(ltx,lty))
let v2 = TextureMappingVertice(position: Vec4(rightBottom.x,leftTop.y), textureUV: Vec2(rbx,lty))
let v3 = TextureMappingVertice(position: Vec4(leftTop.x,rightBottom.y), textureUV: Vec2(ltx,rby))
let v4 = TextureMappingVertice(position:Vec4(rightBottom.x,rightBottom.y), textureUV: Vec2(rbx,rby))
imageVertices = [v1,v2,v3,v4]
}
func genImageVertices(_ position:Vec4,size:Vec2)
{
imageVertices[0].position = position
imageVertices[1].position = Vec4(position.x+size.x,position.y)
imageVertices[2].position = Vec4(position.x,position.y+size.y)
imageVertices[3].position = Vec4(position.x+size.x,position.y+size.y)
}
var imageVertices:[TextureMappingVertice] = []
// var squareVertices:[GLfloat] = [
// 0, 0,
// 200, 0,
// 0, 200,
// 200, 200,
// ]
//
// let textureVertices:[GLfloat] = [
// 0.0, 1.0,
// 1.0, 1.0,
// 0.0, 0.0,
// 1.0, 0.0,
//
// ]
func initVertex(_ width:Float,height:Float)
{
imgWidth = width
imgHeight = height
imageVertices.append(TextureMappingVertice(position: Vec4(0,0), textureUV: Vec2(0,0)))
imageVertices.append(TextureMappingVertice(position: Vec4(width,0), textureUV: Vec2(1,0)))
imageVertices.append(TextureMappingVertice(position: Vec4(0,height), textureUV: Vec2(0,1)))
imageVertices.append(TextureMappingVertice(position: Vec4(width,height), textureUV: Vec2(1,1)))
}
func bindImageTexture(_ texture:Texture,alpha:Float,leftTop:Vec4,rightBottom:Vec4)
{
shader.bind(getUniform("imageTexture")!,texture , index: 2)
shader.bind(getUniform("alpha")!, alpha)
shader.useProgram()
genImageVertices(leftTop, rightBottom: rightBottom)
bindVertexs(imageVertices)
}
func bindImageTexture(_ texture:Texture,alpha:Float,position:Vec4,size:Vec2)
{
shader.bind(getUniform("imageTexture")!,texture , index: 2)
shader.bind(getUniform("alpha")!, alpha)
shader.useProgram()
genImageVertices(position, size: size)
//genImageVertices(leftTop, rightBottom: rightBottom)
bindVertexs(imageVertices)
}
func bindImageTexture(_ texture:Texture,alpha:Float)
{
bindImageTexture(texture, alpha: alpha, position: Vec4(0,0), size: Vec2(imgWidth,imgHeight))
}
}
|
45381a0ea5ef07bec8977321a2be481b
| 30.565217 | 108 | 0.613774 | false | false | false | false |
notohiro/NowCastMapView
|
refs/heads/master
|
NowCastMapView/Overlay.swift
|
mit
|
1
|
//
// Overlay.swift
// NowCastMapView
//
// Created by Hiroshi Noto on 6/20/15.
// Copyright (c) 2015 Hiroshi Noto. All rights reserved.
//
import Foundation
import MapKit
public class Overlay: NSObject, MKOverlay {
public var coordinate: CLLocationCoordinate2D {
let latitude = (Constants.originLatitude + Constants.terminalLatitude) / 2
let longitude = (Constants.originLongitude + Constants.terminalLongitude) / 2
return CLLocationCoordinate2DMake(latitude, longitude)
}
public var boundingMapRect: MKMapRect {
let origin = MKMapPoint(CLLocationCoordinate2DMake(Constants.originLatitude, Constants.originLongitude))
let end = MKMapPoint(CLLocationCoordinate2DMake(Constants.terminalLatitude, Constants.terminalLongitude))
let size = MKMapSize(width: end.x - origin.x, height: end.y - origin.y)
return MKMapRect(x: origin.x, y: origin.y, width: size.width, height: size.height)
}
public func intersects(_ mapRect: MKMapRect) -> Bool {
return mapRect.intersects(TileModel.serviceAreaMapRect)
}
}
|
b74a47407ff08421b7b30b0c8f9740ed
| 34.666667 | 110 | 0.737383 | false | false | false | false |
OctMon/OMExtension
|
refs/heads/master
|
OMExtension/OMExtension/Source/UIKit/OMTextView.swift
|
mit
|
1
|
//
// OMTextView.swift
// OMExtension
//
// The MIT License (MIT)
//
// Copyright (c) 2016 OctMon
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if os(iOS)
import UIKit
public extension OMExtension where OMBase: UITextView {
func addTextLimit(length: Int, limitHandler: (() -> Void)? = nil) {
NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextViewTextDidChange, object: nil, queue: OperationQueue.main) { (notification) in
if (((self.base.text! as NSString).length > length) && self.base.markedTextRange == nil) {
self.base.text = (self.base.text! as NSString).substring(to: length)
limitHandler?()
}
}
}
func addDoneButton(barStyle: UIBarStyle = .default, title: String? = "完成") {
let toolbar = UIToolbar()
toolbar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), UIBarButtonItem(title: title, style: .done, target: self, action: #selector(UITextView.doneAction))]
toolbar.barStyle = barStyle
toolbar.sizeToFit()
base.inputAccessoryView = toolbar
}
}
public extension UITextView {
@objc fileprivate func doneAction() { endEditing(true) }
}
#endif
|
6faf85d30612745ac194922787e88dcd
| 36.138462 | 205 | 0.678542 | false | false | false | false |
fernandomarins/food-drivr-pt
|
refs/heads/master
|
hackathon-for-hunger/User.swift
|
mit
|
1
|
//
// User.swift
// hackathon-for-hunger
//
// Created by Ian Gristock on 4/2/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import Foundation
import RealmSwift
import ObjectMapper
enum UserRole: Int {
case Donor = 0
case Driver = 1
}
class User: Object, Mappable {
typealias JsonDict = [String: AnyObject]
dynamic var id: Int = 0
dynamic var auth_token: String?
dynamic var name: String?
dynamic var email: String?
dynamic var avatar: String?
dynamic var organisation: String?
dynamic var phone: String?
dynamic var role = 0
dynamic var settings: Setting?
var userRole: UserRole {
get{
if let userRole = UserRole(rawValue: role) {
return userRole
}
return .Donor
}
set{
role = newValue.rawValue
}
}
required convenience init?(_ map: Map) {
self.init()
}
func mapping(map: Map) {
id <- map["id"]
auth_token <- map["auth_token"]
name <- map["name"]
email <- map["email"]
avatar <- map["avatar"]
organisation <- map["organization.name"]
phone <- map["phone"]
role <- map["role_id"]
settings <- map["setting"]
}
convenience init(dict: JsonDict) {
self.init()
self.id = dict["id"] as! Int
self.auth_token = dict["auth_token"] as? String
self.avatar = dict["avatar"] as? String
self.email = dict["email"] as? String
self.name = dict["name"] as? String
if let org = dict["organization"]?["name"] as? String {
self.organisation = org
}
self.phone = dict["phone"] as? String
self.role = dict["role_id"] as! Int
if let settingDict = dict["setting"] as? JsonDict {
self.settings = Setting(value: settingDict)
}
}
}
|
1601b9565786bd15a45dd30f933c1b36
| 25.447368 | 63 | 0.530612 | false | false | false | false |
Andruschenko/SeatTreat
|
refs/heads/master
|
SeatTreat/TopSeatView.swift
|
gpl-2.0
|
1
|
//
// TopSeatView.swift
// SeatTreat
//
// Created by Andru on 17/10/15.
// Copyright © 2015 André Kovac. All rights reserved.
//
import UIKit
import Font_Awesome_Swift
@IBDesignable class TopSeatView: UIView {
// Our custom view from the XIB file
var view: UIView!
let faType: FAType = FAType.FADiamond
// Outlets
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var icon: UILabel!
@IBInspectable var image: UIImage? {
get {
return imageView.image
}
set(image) {
imageView.image = image
}
}
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
// set icon
icon.setFAIcon(faType, iconSize: 25)
}
required init?(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
xibSetup()
// set icon
icon.setFAIcon(faType, iconSize: 25)
}
func xibSetup() {
view = loadViewFromNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nibName = "TopSeatView"
let nib = UINib(nibName: nibName, bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
return view
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
b28db382282f9965e2d3d365e0f06837
| 24.829545 | 101 | 0.58161 | false | false | false | false |
admkopec/BetaOS
|
refs/heads/x86_64
|
Kernel/Modules/ACPI/SDTHeader.swift
|
apache-2.0
|
1
|
//
// SDTHeader.swift
// Kernel
//
// Created by Adam Kopeć on 10/16/17.
// Copyright © 2017 Adam Kopeć. All rights reserved.
//
struct SDTHeader: CustomStringConvertible {
let Signature: String
let Length: UInt32
let Revision: UInt8
let Checksum: UInt8
let OemID: String
let OemTableID: String
let OemRev: UInt32
let CreatorID: String
let CreatorRev: UInt32
var description: String {
return "\(Signature): \(OemID): \(CreatorID): \(OemTableID): rev: \(Revision)"
}
init(ptr: UnsafeMutablePointer<ACPISDTHeader_t>) {
Signature = String(&ptr.pointee.Signature.0, maxLength: 4)
Length = ptr.pointee.Length
Revision = ptr.pointee.Revision
Checksum = ptr.pointee.Checksum
OemID = String(&ptr.pointee.OEMID.0, maxLength: 6)
OemTableID = String(&ptr.pointee.OEMTableID.0, maxLength: 8)
OemRev = ptr.pointee.OEMRevision
CreatorID = String(&ptr.pointee.CreatorID, maxLength: 4)
CreatorRev = ptr.pointee.CreatorRevision
}
}
|
ac2f524eb003479674259535d9b0d416
| 30.428571 | 86 | 0.63 | false | false | false | false |
filestack/filestack-ios
|
refs/heads/master
|
Sources/Filestack/UI/Internal/PhotoEditor/EditionController/ViewController/EditorViewController.swift
|
mit
|
1
|
//
// EditorViewController.swift
// EditImage
//
// Created by Mihály Papp on 03/07/2018.
// Copyright © 2018 Mihály Papp. All rights reserved.
//
import UIKit
final class EditorViewController: UIViewController, UIGestureRecognizerDelegate {
enum EditMode {
case crop, circle, none
}
var editMode = EditMode.none {
didSet {
turnOff(mode: oldValue)
turnOn(mode: editMode)
updatePaths()
}
}
var editor: ImageEditor?
let bottomToolbar = BottomEditorToolbar()
let topToolbar = TopEditorToolbar()
let preview = UIView()
let imageView = ImageEditorView()
let imageClearBackground = UIView()
private let cropLayer = CropLayer()
private let circleLayer = CircleLayer()
var panGestureRecognizer = UIPanGestureRecognizer()
var pinchGestureRecognizer = UIPinchGestureRecognizer()
lazy var cropHandler = CropGesturesHandler(delegate: self)
lazy var circleHandler = CircleGesturesHandler(delegate: self)
var completion: ((UIImage?) -> Void)?
init(image: UIImage, completion: @escaping (UIImage?) -> Void) {
self.editor = ImageEditor(image: image)
self.completion = completion
super.init(nibName: nil, bundle: nil)
setupGestureRecognizer()
setupView()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension EditorViewController {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updatePaths()
imageClearBackground.frame = imageFrame.applying(CGAffineTransform(translationX: 4, y: 4))
}
}
private extension EditorViewController {
func turnOff(mode: EditMode) {
hideLayer(for: mode)
}
func turnOn(mode: EditMode) {
addLayer(for: mode)
bottomToolbar.isEditing = (mode != .none)
}
}
private extension EditorViewController {
func layer(for mode: EditMode) -> CALayer? {
switch mode {
case .crop: return cropLayer
case .circle: return circleLayer
case .none: return nil
}
}
func isVisible(layer: CALayer) -> Bool {
return imageView.layer.sublayers?.contains(layer) ?? false
}
func addLayer(for mode: EditMode) {
guard let editLayer = layer(for: mode), !isVisible(layer: editLayer) else { return }
imageView.layer.addSublayer(editLayer)
}
func hideLayer(for mode: EditMode) {
layer(for: mode)?.removeFromSuperlayer()
}
func updatePaths() {
switch editMode {
case .crop: updateCropPaths()
case .circle: updateCirclePaths()
case .none: return
}
}
func updateCropPaths() {
cropLayer.imageFrame = imageFrame
cropLayer.cropRect = cropHandler.croppedRect
}
func updateCirclePaths() {
circleLayer.imageFrame = imageFrame
circleLayer.circleCenter = circleHandler.circleCenter
circleLayer.circleRadius = circleHandler.circleRadius
}
}
extension EditorViewController {
@objc func handlePanGesture(recognizer: UIPanGestureRecognizer) {
switch editMode {
case .crop: cropHandler.handlePanGesture(recognizer: recognizer)
case .circle: circleHandler.handlePanGesture(recognizer: recognizer)
case .none: return
}
}
@objc func handlePinchGesture(recognizer: UIPinchGestureRecognizer) {
switch editMode {
case .crop: return
case .circle: circleHandler.handlePinchGesture(recognizer: recognizer)
case .none: return
}
}
}
// MARK: EditCropDelegate
extension EditorViewController: EditCropDelegate {
func updateCropInset(_: UIEdgeInsets) {
updateCropPaths()
}
}
// MARK: EditCircleDelegate
extension EditorViewController: EditCircleDelegate {
func updateCircle(_: CGPoint, radius _: CGFloat) {
updateCirclePaths()
}
}
|
9d18ce55b423ef04a9c1dd0e3a4e8ea4
| 25.350993 | 98 | 0.659211 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
refs/heads/trunk
|
WordPress/Classes/ViewRelated/Domains/Views/ShapeWithTextView.swift
|
gpl-2.0
|
1
|
import SwiftUI
/// A rounded rectangle shape with a white title and a primary background color
struct ShapeWithTextView: View {
var title: String
var body: some View {
Text(title)
}
func largeRoundedRectangle(textColor: Color = .white,
backgroundColor: Color = Appearance.largeRoundedRectangleDefaultTextColor) -> some View {
body
.frame(minWidth: 0, maxWidth: .infinity)
.padding(.all, Appearance.largeRoundedRectangleTextPadding)
.foregroundColor(textColor)
.background(backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: Appearance.largeRoundedRectangleCornerRadius,
style: .continuous))
}
func smallRoundedRectangle(textColor: Color = Appearance.smallRoundedRectangleDefaultTextColor,
backgroundColor: Color = Appearance.smallRoundedRectangleDefaultBackgroundColor) -> some View {
body
.font(.system(size: Appearance.smallRoundedRectangleFontSize))
.padding(Appearance.smallRoundedRectangleInsets)
.foregroundColor(textColor)
.background(backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: Appearance.smallRoundedRectangleCornerRadius,
style: .continuous))
}
private enum Appearance {
// large rounded rectangle
static let largeRoundedRectangleCornerRadius: CGFloat = 8.0
static let largeRoundedRectangleTextPadding: CGFloat = 12.0
static let largeRoundedRectangleDefaultTextColor = Color(UIColor.muriel(color: .primary))
// small rounded rectangle
static let smallRoundedRectangleCornerRadius: CGFloat = 4.0
static let smallRoundedRectangleInsets = EdgeInsets(top: 4.0, leading: 8.0, bottom: 4.0, trailing: 8.0)
static let smallRoundedRectangleDefaultBackgroundColor = Color(UIColor.muriel(name: .green, .shade5))
static let smallRoundedRectangleDefaultTextColor = Color(UIColor.muriel(name: .green, .shade100))
static let smallRoundedRectangleFontSize: CGFloat = 14.0
}
}
|
19c5b15d9bfdd749b512e0391541c1d7
| 46.826087 | 126 | 0.675455 | false | false | false | false |
glassonion1/R9HTTPRequest
|
refs/heads/master
|
R9HTTPRequest/HttpJsonClient.swift
|
mit
|
1
|
//
// HttpJsonClient.swift
// R9HTTPRequest
//
// Created by taisuke fujita on 2017/10/03.
// Copyright © 2017年 Revolution9. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
public class HttpJsonClient<T: Codable>: HttpClient {
public typealias ResponseType = T
public init() {
}
public func action(method: HttpClientMethodType, url: URL, requestBody: Data?, headers: HTTPHeaders?) -> Observable<T> {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData)
request.httpMethod = method.rawValue
request.allHTTPHeaderFields = headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = requestBody
let scheduler = ConcurrentDispatchQueueScheduler(qos: .background)
return URLSession.shared.rx.data(request: request).timeout(30, scheduler: scheduler).map { data -> T in
let jsonDecoder = JSONDecoder()
let response = try! jsonDecoder.decode(T.self, from: data)
return response
}
}
}
|
dae25f150a49729a555e0cac63f70f89
| 31.676471 | 124 | 0.674167 | false | false | false | false |
marcw/volte-ios
|
refs/heads/master
|
Volte/Timeline/TimelineView.swift
|
agpl-3.0
|
1
|
//
// TimelineView.swift
// Volte
//
// Created by Romain Pouclet on 2016-10-12.
// Copyright © 2016 Perfectly-Cooked. All rights reserved.
//
import Foundation
import ReactiveSwift
import UIKit
protocol TimelineViewDelegate: class {
func didPullToRefresh()
func didTap(url: URL)
}
class TimelineView: UIView {
private let tableView: UITableView = {
let tableView = UITableView(frame: .zero, style: .plain)
tableView.register(TimelineMessageCell.self, forCellReuseIdentifier: "TimelineItemCell")
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.estimatedRowHeight = 140
tableView.rowHeight = UITableViewAutomaticDimension
tableView.allowsSelection = false
return tableView
}()
private let emptyMessage: UILabel = {
let message = UILabel()
message.text = L10n.Timeline.Empty
message.textColor = .black
message.alpha = 0
message.translatesAutoresizingMaskIntoConstraints = false
return message
}()
private let refreshControl = UIRefreshControl()
fileprivate let viewModel: TimelineViewModel
weak var delegate: TimelineViewDelegate?
init(viewModel: TimelineViewModel) {
self.viewModel = viewModel
super.init(frame: .zero)
backgroundColor = .white
tableView.dataSource = self
tableView.refreshControl = refreshControl
refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
addSubview(tableView)
addSubview(emptyMessage)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: topAnchor),
tableView.leftAnchor.constraint(equalTo: leftAnchor),
tableView.bottomAnchor.constraint(equalTo: bottomAnchor),
tableView.rightAnchor.constraint(equalTo: rightAnchor),
emptyMessage.centerXAnchor.constraint(equalTo: centerXAnchor),
emptyMessage.centerYAnchor.constraint(equalTo: centerYAnchor)
])
let messagesCount = viewModel.messages.producer.map({ $0.count })
messagesCount.observe(on: UIScheduler()).startWithValues { [weak self] count in
CATransaction.begin()
CATransaction.setCompletionBlock({
self?.tableView.reloadData()
})
self?.refreshControl.endRefreshing()
CATransaction.commit()
UIView.animate(withDuration: 0.3) {
let isEmpty = count == 0
self?.tableView.alpha = isEmpty ? 0 : 1
self?.emptyMessage.alpha = isEmpty ? 1 : 0
}
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleRefresh() {
self.delegate?.didPullToRefresh()
}
}
extension TimelineView: UITableViewDataSource, UITableViewDataSourcePrefetching {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.messages.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let messages = viewModel.messages.value
let cell = tableView.dequeueReusableCell(withIdentifier: "TimelineItemCell", for: indexPath) as! TimelineMessageCell
cell.delegate = self
cell.configure(item: messages[indexPath.row])
let digest = messages[indexPath.row].author!.data(using: String.Encoding.utf8)!
let avatarURL = URL(string: "https://www.gravatar.com/avatar/\(digest.md5().toHexString())?d=identicon")!
URLSession.shared.dataTask(with: avatarURL) { data, _, _ in
guard let data = data else {
print("Unable to load avatar")
return
}
DispatchQueue.main.async {
cell.avatarView.image = UIImage(data: data)
}
}.resume()
return cell
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
}
}
extension TimelineView: TimelineMessageCellDelegate {
func didTap(url: URL) {
delegate?.didTap(url: url)
}
}
|
6a5ad39aa74eadfc6054fd4df2d950f4
| 30.820896 | 124 | 0.651032 | false | false | false | false |
3ph/SplitSlider
|
refs/heads/master
|
Example/SplitSlider/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// SplitSlider
//
// Created by Tomas Friml on 06/22/2017.
//
// MIT License
//
// Copyright (c) 2017 Tomas Friml
//
// 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 SplitSlider
class ViewController: UIViewController {
@IBOutlet weak var splitSlider: SplitSlider!
@IBOutlet weak var snapToStep: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
splitSlider.delegate = self
splitSlider.labelFont = UIFont.systemFont(ofSize: UIFont.smallSystemFontSize)
splitSlider.left.step = 30
}
@IBAction func snapToStepToggle(_ sender: Any) {
if let toggle = sender as? UISwitch {
splitSlider.snapToStep = toggle.isOn
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController : SplitSliderDelegate {
func slider(_ slider: SplitSlider, didSelect portion: SplitSliderPortion?) {
let portionString = portion == slider.left ? "left" : "right"
NSLog("Selected part: \(portion == nil ? "none" : portionString)")
}
func slider(_ slider: SplitSlider, didUpdate value: CGFloat, for portion: SplitSliderPortion) {
NSLog("Current value: \(value)")
}
}
|
2cb27a646ca8923b4cca4335741e815d
| 34.865672 | 99 | 0.697045 | false | false | false | false |
MangoMade/MMSegmentedControl
|
refs/heads/master
|
Example/Example/SegmentedViewController.swift
|
mit
|
1
|
//
// SegmentedViewController.swift
// MMSegmentedControl
//
// Created by Aqua on 2017/4/17.
// Copyright © 2017年 Aqua. All rights reserved.
//
import UIKit
import MMSegmentedControl
class ChildViewController: UIViewController {
var backgroundColor: UIColor = .white
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
print(#function)
view.backgroundColor = backgroundColor
}
}
class SegmentedViewController: UIViewController {
private var children = [UIViewController]()
private let segmentedView = SegmentedControlView()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
automaticallyAdjustsScrollViewInsets = false
let titles = ["推荐", "开庭", "开庭", "开庭", "开庭"]
let items = titles.enumerated().map { (index, title) -> SegmentedControlViewItem in
let viewController = ChildViewController()
viewController.backgroundColor = index % 2 == 1 ? UIColor.white : UIColor.lightGray
addChildViewController(viewController)
viewController.didMove(toParentViewController: self)
children.append(viewController)
// let label = UILabel()
// label.text = title
// label.bounds = CGRect(x: 0, y: 0, width: 100, height: 50)
// label.center = CGPoint(x: Screen.width / 2, y: 100)
// label.textAlignment = .center
// viewController.view.addSubview(label)
return SegmentedControlViewItem(title: title, childViewController: viewController)
}
segmentedView.items = items
segmentedView.segmentedControl.shouldFill = true
segmentedView.segmentedControl.leftMargin = 30
segmentedView.segmentedControl.rightMargin = 30
segmentedView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(segmentedView)
// segmentedView.frame = CGRect(x: 0,
// y: Screen.navBarHeight,
// width: Screen.width,
// height: Screen.height - Screen.navBarHeight)
NSLayoutConstraint(item: segmentedView,
attribute: .left,
relatedBy: .equal,
toItem: view,
attribute: .left,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: segmentedView,
attribute: .right,
relatedBy: .equal,
toItem: view,
attribute: .right,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: segmentedView,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1,
constant: 0).isActive = true
NSLayoutConstraint(item: segmentedView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant: Screen.navBarHeight).isActive = true
let add = UIBarButtonItem(title: "add", style: .plain, target: self, action: #selector(add(_:)))
let pop = UIBarButtonItem(title: "delete", style: .plain, target: self, action: #selector(pop(_:)))
navigationItem.rightBarButtonItems = [pop, add]
}
@objc func add(_ sender: UIBarButtonItem) {
let viewController = UIViewController()
viewController.view.backgroundColor = .white
addChildViewController(viewController)
viewController.didMove(toParentViewController: self)
children.append(viewController)
let label = UILabel()
label.text = title
label.bounds = CGRect(x: 0, y: 0, width: 100, height: 50)
label.center = CGPoint(x: Screen.width / 2, y: 100)
label.textAlignment = .center
viewController.view.addSubview(label)
segmentedView.items.append(SegmentedControlViewItem(title: "开庭", childViewController: viewController))
}
@objc func pop(_ sender: UIBarButtonItem) {
let _ = segmentedView.items.popLast()
// segmentedView.segmentedControlHeight = 50
}
}
|
8c3d4825ca2e5b987866448536fe6c94
| 36.296875 | 110 | 0.547759 | false | false | false | false |
IvoPaunov/selfie-apocalypse
|
refs/heads/master
|
Selfie apocalypse/Frameworks/DCKit/UITextFields/DCMandatoryNumberTextField.swift
|
mit
|
1
|
//
// MandatoryNumberTextField.swift
// DCKit
//
// Created by Andrey Gordeev on 11/03/15.
// Copyright (c) 2015 Andrey Gordeev ([email protected]). All rights reserved.
//
import UIKit
/// Allows to set a max possible value.
public class DCMandatoryNumberTextField: DCMandatoryTextField {
@IBInspectable public var maxValue: Float = 999
// MARK: - Initializers
// IBDesignables require both of these inits, otherwise we'll get an error: IBDesignable View Rendering times out.
// http://stackoverflow.com/questions/26772729/ibdesignable-view-rendering-times-out
override public init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Build control
override public func customInit() {
super.customInit()
keyboardType = UIKeyboardType.DecimalPad
}
// MARK: - Validation
override public func isValid() -> Bool {
let value = (text ?? "" as NSString).floatValue
var valid = value < maxValue
// If the field is Mandatory and empty - it's invalid
if text == "" {
valid = !isMandatory
}
selected = !valid
return valid
}
}
|
af2d511ea9602177ba3a0533bb8dc48e
| 24.75 | 118 | 0.613891 | false | false | false | false |
ZackKingS/Tasks
|
refs/heads/master
|
task/Classes/Main/View/RefreshHeder.swift
|
apache-2.0
|
1
|
//
// HomeRefreshHeder.swift
// TodayNews
//
// Created by 杨蒙 on 2017/8/17.
// Copyright © 2017年 hrscy. All rights reserved.
//
import MJRefresh
class RefreshHeder: MJRefreshGifHeader {
override func prepare() {
super.prepare()
// 设置普通状态图片
var images = [UIImage]()
for index in 0..<30 {
let image = UIImage(named: "dropdown_0\(index)")
images.append(image!)
}
setImages(images, for: .idle)
// 设置即将刷新状态的动画图片(一松开就会刷新的状态)
var refreshingImages = [UIImage]()
for index in 0..<16 {
let image = UIImage(named: "dropdown_loading_0\(index)")
refreshingImages.append(image!)
}
// 设置正在刷新状态的动画图片
setImages(refreshingImages, for: .refreshing)
/// 设置state状态下的文字
setTitle("下拉推荐", for: .idle)
setTitle("松开推荐", for: .pulling)
setTitle("推荐中", for: .refreshing)
}
override func placeSubviews() {
super.placeSubviews()
gifView.contentMode = .center
gifView.frame = CGRect(x: 0, y: 4, width: mj_w, height: 25)
stateLabel.font = UIFont.systemFont(ofSize: 12)
stateLabel.frame = CGRect(x: 0, y: 35, width: mj_w, height: 14)
}
}
|
459ce7061fe1502023cb7091437b4602
| 28.046512 | 71 | 0.577262 | false | false | false | false |
zmeriksen/Layers
|
refs/heads/master
|
Layers/LayerHandler.swift
|
mit
|
1
|
//
// LayerHandler.swift
// Layers
//
// Created by Zach Eriksen on 6/26/15.
// Copyright (c) 2015 Leif. All rights reserved.
//
import Foundation
import UIKit
let purple = UIColor(red: 115/255, green: 115/255, blue: 150/255, alpha: 1)
let blue = UIColor(red: 102/255, green: 168/255, blue: 174/255, alpha: 1)
let lightGreen = UIColor(red: 196/255, green: 213/255, blue: 173/255, alpha: 1)
let darkGreen = UIColor(red: 107/255, green: 134/255, blue: 113/255, alpha: 1)
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
class LayerHandler : UIView{
fileprivate let WarningLayer = [
"WARNING: Layer limit of 8 hit",
"WARNING: Default init will have frame of x: 0, y: 0, width: \(screenWidth), height: \(screenHeight)",
"WARNING: You must have at least one layer!"
]
var layers : [Layer] = [] {
didSet{
layerHeight = frame.height/CGFloat(layers.count)
var y : CGFloat = 0
for layer in layers{
layer.frame = CGRect(x: layer.frame.origin.x, y: y, width: layer.frame.width, height: layerHeight!)
layer.updateLayer()
layer.layerHeight = layerHeight
y += layerHeight!
}
}
}
fileprivate var y : CGFloat = 0
fileprivate var tagForLayers = 0
fileprivate var layerHeight : CGFloat?
init(){
super.init(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
layerHeight = frame.height
print(WarningLayer[1])
}
override init(frame: CGRect) {
super.init(frame: frame)
layerHeight = frame.height
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func layerPressed(_ sender : AnyObject){
for layer in layers{
switch sender.tag! {
case layer.tag:
layer.animateToMaximizedPosition()
case -1..<layer.tag:
layer.animateBackToOriginalPosition()
default:
layer.animateToMinimizedPosition()
}
}
}
func resetLayersToOriginalPosition(){
for layer in layers{
layer.animateBackToOriginalPosition()
}
}
func addLayer(_ color : UIColor, title : String) -> Layer?{
if layers.count >= 8 {
print(WarningLayer[0])
return nil
}
resetLayersToOriginalPosition()
let layer = Layer(y: y, color: color, title: title, tag: tagForLayers,layerWidth: frame.width, layerHeight : layerHeight!)
tagForLayers += 1
y += layerHeight!
let button = UIButton(frame: CGRect(x: 0, y: 0, width: frame.width, height: layerHeight!))
button.addTarget(self, action: #selector(LayerHandler.layerPressed(_:)), for: UIControlEvents.touchUpInside)
button.tag = layer.tag
layer.addSubview(button)
layer.sendSubview(toBack: button)
layers.append(layer)
addSubview(layer)
return layer
}
func layerWithTitle(_ title : String) -> Layer? {
for layer in layers {
if layer.label?.text == title {
return layer
}
}
return nil
}
func removeLayerWithTitle(_ title : String){
if layers.count == 1 {
print(WarningLayer[2])
return
}
for layer in layers {
layer.removeFromSuperview()
if layer.label?.text == title {
layers.remove(at: layer.tag)
}
}
resetLayersTags()
}
func removeLayerWithTag(_ tag : UInt32){
if layers.count == 1 {
print(WarningLayer[2])
return
}
for l in layers {
l.removeFromSuperview()
if UInt32(l.label!.tag) == tag {
layers.remove(at: l.tag)
}
}
resetLayersTags()
}
fileprivate func resetLayersTags(){
tagForLayers = 0
for layer in layers {
layer.tag = tagForLayers
for sub in layer.subviews {
if let button : UIButton = sub as? UIButton {
button.frame = CGRect(x: 0, y: 0, width: layer.frame.width, height: layer.frame.height)
button.tag = tagForLayers
tagForLayers += 1
}
}
addSubview(layer)
}
resetLayersToOriginalPosition()
}
}
|
2b6949ba750fcaf575a61d32cae41b14
| 30.306122 | 130 | 0.556932 | false | false | false | false |
wangruofeng/ClassicPhotos-Starter-fixed
|
refs/heads/master
|
ClassicPhotos/ListViewController.swift
|
mit
|
1
|
//
// ListViewController.swift
// ClassicPhotos
//
// Created by Richard Turton on 03/07/2014.
// Copyright (c) 2014 raywenderlich. All rights reserved.
//
import UIKit
import CoreImage
let dataSourceURL = NSURL(string:"http://www.raywenderlich.com/downloads/ClassicPhotosDictionary.plist")
class ListViewController: UITableViewController {
var photos = [PhotoRecord]()
let pendingOperations = PendingOperations()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Classic Photos"
fetchPhotoDetails()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fetchPhotoDetails() {
let request = NSURLRequest(URL:dataSourceURL!)
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if data != nil {
var datasourceDictionary = [:]
do {
datasourceDictionary = try NSPropertyListSerialization.propertyListWithData(data!, options: NSPropertyListMutabilityOptions.Immutable, format: nil) as! NSDictionary as! [String : String]
} catch {
print("Error occured while reading from the plist file")
}
for(key, value) in datasourceDictionary {
let name = key as? String
let url = NSURL(string:value as? String ?? "")
if name != nil && url != nil {
let photoRecord = PhotoRecord(name:name!, url:url!)
self.photos.append(photoRecord)
}
}
self.tableView.reloadData()
}
if error != nil {
let alert = UIAlertView(title:"Oops!",message:error!.localizedDescription, delegate:nil, cancelButtonTitle:"OK")
alert.show()
}
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
}
// #pragma mark - Table view data source
override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
return photos.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath)
//1
if cell.accessoryView == nil {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
cell.accessoryView = indicator
}
let indicator = cell.accessoryView as! UIActivityIndicatorView
//2
let photoDetails = photos[indexPath.row]
//3
cell.textLabel?.text = photoDetails.name
cell.imageView?.image = photoDetails.image
//4
switch (photoDetails.state){
case .Filtered:
indicator.stopAnimating()
case .Failed:
indicator.stopAnimating()
cell.textLabel?.text = "Failed to load"
case .New, .Downloaded:
indicator.startAnimating()
if (!tableView.dragging && !tableView.decelerating) {
self.startOperationsForPhotoRecord(photoDetails, indexPath: indexPath)
}
}
return cell
}
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
//1
suspendAllOperations()
}
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
// 2
if !decelerate {
loadImagesForOnscreenCells()
resumeAllOperations()
}
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
// 3
loadImagesForOnscreenCells()
resumeAllOperations()
}
func suspendAllOperations () {
pendingOperations.downloadQueue.suspended = true
pendingOperations.filtrationQueue.suspended = true
}
func resumeAllOperations () {
pendingOperations.downloadQueue.suspended = false
pendingOperations.filtrationQueue.suspended = false
}
func loadImagesForOnscreenCells () {
//1
if let pathsArray = tableView.indexPathsForVisibleRows {
//2
var allPendingOperations = Set(pendingOperations.downloadsInProgress.keys)
allPendingOperations.unionInPlace(pendingOperations.filtrationsInProgress.keys)
//3
var toBeCancelled = allPendingOperations
let visiblePaths = Set(pathsArray as [NSIndexPath])
toBeCancelled.subtractInPlace(visiblePaths)
//4
var toBeStarted = visiblePaths
toBeStarted.subtractInPlace(allPendingOperations)
// 5
for indexPath in toBeCancelled {
if let pendingDownload = pendingOperations.downloadsInProgress[indexPath] {
pendingDownload.cancel()
}
pendingOperations.downloadsInProgress.removeValueForKey(indexPath)
if let pendingFiltration = pendingOperations.filtrationsInProgress[indexPath] {
pendingFiltration.cancel()
}
pendingOperations.filtrationsInProgress.removeValueForKey(indexPath)
}
// 6
for indexPath in toBeStarted {
let indexPath = indexPath as NSIndexPath
let recordToProcess = self.photos[indexPath.row]
startOperationsForPhotoRecord(recordToProcess, indexPath: indexPath)
}
}
}
func startOperationsForPhotoRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
switch (photoDetails.state) {
case .New:
startDownloadForRecord(photoDetails, indexPath: indexPath)
case .Downloaded:
startFiltrationForRecord(photoDetails, indexPath: indexPath)
default:
NSLog("do nothing")
}
}
func startDownloadForRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
//1
if let _ = pendingOperations.downloadsInProgress[indexPath] {
return
}
//2
let downloader = ImageDownloader(photoRecord: photoDetails)
//3
downloader.completionBlock = {
if downloader.cancelled {
return
}
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.downloadsInProgress.removeValueForKey(indexPath)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
}
//4
pendingOperations.downloadsInProgress[indexPath] = downloader
//5
pendingOperations.downloadQueue.addOperation(downloader)
}
func startFiltrationForRecord(photoDetails: PhotoRecord, indexPath: NSIndexPath){
if let _ = pendingOperations.filtrationsInProgress[indexPath]{
return
}
let filterer = ImageFiltration(photoRecord: photoDetails)
filterer.completionBlock = {
if filterer.cancelled {
return
}
dispatch_async(dispatch_get_main_queue(), {
self.pendingOperations.filtrationsInProgress.removeValueForKey(indexPath)
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
}
pendingOperations.filtrationsInProgress[indexPath] = filterer
pendingOperations.filtrationQueue.addOperation(filterer)
}
}
|
bf7f02ea0bfb429a62101579a664f6b0
| 30.127193 | 194 | 0.688037 | false | false | false | false |
TonnyTao/HowSwift
|
refs/heads/master
|
Funny Swift.playground/Pages/GCD.xcplaygroundpage/Contents.swift
|
mit
|
1
|
import Foundation
import Dispatch
import PlaygroundSupport
//: The most common GCD patterns: run IO operation or compute in background thread then update UI in main thread
DispatchQueue.global().async {
// Cocurrent thread
dispatchPrecondition(condition: .notOnQueue(DispatchQueue.main))
DispatchQueue.main.async {
// Main thread
}
}
//: Perform mutiple times concurrently
DispatchQueue.concurrentPerform(iterations: 2) { (i) in
print(i)
}
//: Cancelable block only existed in NSOperation in old times, and before Swift3.0 we have to use complex tricks to implement it in GCD. But now cancelable closure is easy in Swift3.0.
let workItem = DispatchWorkItem {
print("a")
}
DispatchQueue.global().async(execute: workItem)
workItem.cancel()
//: dispatch_once is no longer available in Swift. Goodbye, dispatch_once, Hello, globals initialize or static properties.
// Static properties (useful for singletons).
class Object {
static let sharedInstance = Object()
//or
static let sharedInstance1 = { () -> Object in
let obj = Object()
obj.doSomething()
return obj
}()
func doSomething() {
}
}
// Global constant.
let variable: Object = {
let variable = Object()
variable.doSomething()
return variable
}()
//: Delay perform after 3 seconds
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
print("World")
}
print("Hello ")
//: Group, parallel
let group1 = DispatchGroup()
group1.enter()
DispatchQueue.global().sync { //remote api fetch
group1.leave()
}
group1.enter()
DispatchQueue.global().sync { //another remote api fetch
group1.leave()
}
group1.notify(queue: .main) {
print("parallel end")
}
//: Group with different queue
let group = DispatchGroup()
let queue1 = DispatchQueue(label: "networking")
let queue2 = DispatchQueue(label: "process")
queue1.async(group: group) {
print("task 1")
}
queue2.async(group: group) {
print("task 2")
}
group.notify(queue: .main) {
print("end")
}
PlaygroundPage.current.needsIndefiniteExecution = true
|
0f9c6598ead201610d989b8b3e2236d5
| 19.921569 | 184 | 0.686504 | false | false | false | false |
thelukester92/swift-engine
|
refs/heads/master
|
swift-engine/Engine/Systems/LGAnimationSystem.swift
|
mit
|
1
|
//
// LGAnimationSystem.swift
// swift-engine
//
// Created by Luke Godfrey on 8/8/14.
// Copyright (c) 2014 Luke Godfrey. See LICENSE.
//
public final class LGAnimationSystem: LGSystem
{
public enum Event: String
{
case AnimationEnd = "animationEnd"
}
var sprites = [LGSprite]()
var animatables = [LGAnimatable]()
var animations = [LGAnimation?]()
public override init() {}
override public func accepts(entity: LGEntity) -> Bool
{
return entity.has(LGSprite) && entity.has(LGAnimatable)
}
override public func add(entity: LGEntity)
{
super.add(entity)
let sprite = entity.get(LGSprite)!
let animatable = entity.get(LGAnimatable)!
sprites.append(sprite)
animatables.append(animatable)
animations.append(nil)
}
override public func remove(index: Int)
{
super.remove(index)
sprites.removeAtIndex(index)
animatables.removeAtIndex(index)
animations.removeAtIndex(index)
}
override public func update()
{
for id in 0 ..< entities.count
{
let sprite = sprites[id]
let animatable = animatables[id]
if let animation = animatable.currentAnimation
{
if animations[id] == nil || animations[id]! != animation
{
animations[id] = animation
sprite.frame = animation.start
animatable.counter = 0
}
if animation.end > animation.start
{
if ++animatable.counter > animation.ticksPerFrame
{
animatable.counter = 0
if ++sprite.frame > animation.end
{
if animation.loops
{
sprite.frame = animation.start
}
else
{
sprite.frame = animation.end
}
if let scriptable = entities[id].get(LGScriptable)
{
scriptable.events.append(LGScriptable.Event(name: Event.AnimationEnd.rawValue))
}
}
}
}
}
}
}
}
|
ae0cf0dedc5610783c6f751cd9ac7f58
| 19.362637 | 87 | 0.636805 | false | false | false | false |
envoyproxy/envoy
|
refs/heads/main
|
mobile/test/swift/integration/DirectResponsePrefixPathMatchIntegrationTest.swift
|
apache-2.0
|
2
|
import Envoy
import XCTest
final class DirectResponsePrefixPathMatchIntegrationTest: XCTestCase {
func testDirectResponseWithPrefixMatch() {
let headersExpectation = self.expectation(description: "Response headers received")
let dataExpectation = self.expectation(description: "Response data received")
let requestHeaders = RequestHeadersBuilder(
method: .get, authority: "127.0.0.1", path: "/v1/foo/bar?param=1"
).build()
let engine = TestEngineBuilder()
.addDirectResponse(
.init(
matcher: RouteMatcher(pathPrefix: "/v1/foo"),
status: 200, body: "hello world", headers: ["x-response-foo": "aaa"]
)
)
.build()
var responseBuffer = Data()
engine
.streamClient()
.newStreamPrototype()
.setOnResponseHeaders { headers, endStream, _ in
XCTAssertEqual(200, headers.httpStatus)
XCTAssertEqual(["aaa"], headers.value(forName: "x-response-foo"))
XCTAssertFalse(endStream)
headersExpectation.fulfill()
}
.setOnResponseData { data, endStream, _ in
responseBuffer.append(contentsOf: data)
if endStream {
XCTAssertEqual("hello world", String(data: responseBuffer, encoding: .utf8))
dataExpectation.fulfill()
}
}
.start()
.sendHeaders(requestHeaders, endStream: true)
let expectations = [headersExpectation, dataExpectation]
XCTAssertEqual(.completed, XCTWaiter().wait(for: expectations, timeout: 10, enforceOrder: true))
engine.terminate()
}
}
|
7c358d2139d2448d97b5513b9dc525d7
| 32.340426 | 100 | 0.663689 | false | true | false | false |
eriklu/qch
|
refs/heads/master
|
Extension/UIImage+qch.swift
|
mit
|
1
|
//
// UIImage+qch.swift
//
import UIKit
extension UIImage {
/**
* 返回一个指定高度,一像素款宽的指定颜色的图片
*/
static func qch_imageWithColor( color : UIColor, height : CGFloat) -> UIImage{
let rect = CGRect(x: 0, y: 0, width: 1.0, height: height)
UIGraphicsBeginImageContext(rect.size)
let content = UIGraphicsGetCurrentContext()
content?.setFillColor(color.cgColor)
content?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
/**
* 返回指定宽度的图片。图片宽高比和原图片相同,图片最小高度为1
* width: 目标图片宽度; <=0 返回图片自身
*/
func qch_resizeToWidth( width : CGFloat = 800) -> UIImage? {
return autoreleasepool(invoking: { () -> UIImage? in
if width <= 0 {
return self
}
// if self.size.width <= width {
// return self
// }
let newSize = CGSize(width: width, height: ceil(size.height * width / size.width) )
UIGraphicsBeginImageContext(newSize)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage
})
}
}
|
6e3d3703962e1d64b4988c4c85f47446
| 28.586957 | 95 | 0.570169 | false | false | false | false |
kairosinc/Kairos-SDK-iOS-Swift
|
refs/heads/master
|
examples/enroll.swift
|
mit
|
1
|
/*
* Copyright (c) 2017, Kairos AR, Inc.
* All rights reserved.
*
* Api Docs: https://www.kairos.com/docs/api/
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
import Foundation
import PlaygroundSupport
import UIKit
// Signup for a free Kairos API credentials at: https://developer.kairos.com/signup
struct KairosConfig {
static let app_id = "xxxxxxxxxxxx"
static let app_key = "xxxxxxxxxxxx"
}
// Instantiate KairosAPI class
var Kairos = KairosAPI(app_id: KairosConfig.app_id, app_key: KairosConfig.app_key)
// setup json request params, with image url
var jsonBody = [
"image": "https://media.kairos.com/test1.jpg",
"gallery_name": "kairos-test",
"subject_id": "test1"
]
// Example - Enroll
Kairos.request(method: "enroll", data: jsonBody) { data in
// check image key exist and get data
if let image = ((data as? [String : AnyObject])!["images"])![0] {
// get root image and primary key objects
let attributes = (image as? [String : AnyObject])!["attributes"]
let transaction = (image as? [String : AnyObject])!["transaction"]
// get specific enrolled attributes
var gender = (attributes as? [String : AnyObject])?["gender"]!["type"]!! as! String
let gender_type = (gender == "F") ? "female" : "male"
let age = (attributes as? [String : AnyObject])!["age"]! as! Int
let confidence_percent = 100 * ((transaction as? [String : AnyObject])!["confidence"]! as! Double)
// display results
print("\n--- Enroll")
print("Gender: \(gender_type)")
print("Age: \(age)")
print("Confidence: \(confidence_percent)% \n")
}
else {
print("Error - Enroll: unable to get image data")
}
}
|
76e721f839db86487cb2676c457490c9
| 33.75 | 106 | 0.635663 | false | true | false | false |
Constructor-io/constructorio-client-swift
|
refs/heads/master
|
AutocompleteClient/FW/Logic/Request/CIOTrackBrowseResultClickData.swift
|
mit
|
1
|
//
// CIOTrackBrowseResultClickData.swift
// Constructor.io
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating the parameters that must/can be set set in order to track browse result click
*/
struct CIOTrackBrowseResultClickData: CIORequestData {
let filterName: String
let filterValue: String
let customerID: String
let resultPositionOnPage: Int?
var sectionName: String?
let resultID: String?
let variationID: String?
func url(with baseURL: String) -> String {
return String(format: Constants.TrackBrowseResultClick.format, baseURL)
}
init(filterName: String, filterValue: String, customerID: String, resultPositionOnPage: Int?, sectionName: String? = nil, resultID: String? = nil, variationID: String? = nil) {
self.filterName = filterName
self.filterValue = filterValue
self.customerID = customerID
self.resultPositionOnPage = resultPositionOnPage
self.sectionName = sectionName
self.resultID = resultID
self.variationID = variationID
}
func decorateRequest(requestBuilder: RequestBuilder) {}
func httpMethod() -> String {
return "POST"
}
func httpBody(baseParams: [String: Any]) -> Data? {
var dict = [
"filter_name": self.filterName,
"filter_value": self.filterValue,
"item_id": self.customerID
] as [String: Any]
if self.variationID != nil {
dict["variation_id"] = self.variationID
}
if self.resultPositionOnPage != nil {
dict["result_position_on_page"] = Int(self.resultPositionOnPage!)
}
if self.sectionName != nil {
dict["section"] = self.sectionName
}
if self.resultID != nil {
dict["result_id"] = self.resultID
}
dict["beacon"] = true
dict.merge(baseParams) { current, _ in current }
return try? JSONSerialization.data(withJSONObject: dict)
}
}
|
75f5df1d9604b145dc4e0179e1aaee0c
| 29.057971 | 180 | 0.636451 | false | false | false | false |
CoderHarry/Melon
|
refs/heads/master
|
Melon/Melon.swift
|
mit
|
1
|
//
// Melon
// Melon
//
// Created by Caiyanzhi on 2016/10/7.
// Copyright © 2016年 Caiyanzhi. All rights reserved.
//
import UIKit
public class Melon {
fileprivate var melonManager:MelonManager!
public static func build(HTTPMethod method: Melon.HTTPMethod, url: String) -> Melon {
let melon = Melon()
melon.melonManager = MelonManager(url: url, method: method)
return melon
}
public init() {}
public static func GET(_ url:String) -> Melon {
return build(HTTPMethod: .GET, url: url)
}
public static func POST(_ url:String) -> Melon {
return build(HTTPMethod: .POST, url: url)
}
public func addParams(_ params:[String: Any]) -> Melon {
melonManager.addParams(params)
return self
}
public func setTimeoutInterval(_ timeoutInterval:TimeInterval) {
melonManager.setTimeoutInterval(timeoutInterval)
}
public func addHeaders(_ headers: [String:String]) -> Melon {
melonManager.addHeaders(headers)
return self
}
public func setHTTPHeader(_ key: String, _ value: String) -> Melon {
melonManager.setHTTPHeader(key, value)
return self
}
public func cancel(_ callback: (() -> Void)? = nil) {
melonManager.cancelCallback = callback
melonManager.task.cancel()
}
}
// MARK: - call back
extension Melon {
public func responseString(_ callback: ((_ jsonString:String?, _ response:HTTPURLResponse?)->Void)?) -> Melon {
return responseData({ (data, response) in
if let data = data {
let string = String(data: data, encoding: .utf8)
callback?(string, response)
} else {
callback?(nil, response)
}
})
}
public func responseJSON(_ callback: ((_ jsonObject:Any?, _ response:HTTPURLResponse?)->Void)?) -> Melon {
return responseData { (data, response) in
if let data = data {
let object = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
callback?(object, response)
} else {
callback?(nil, response)
}
}
}
public func responseData(_ callback:((_ data:Data?, _ response:HTTPURLResponse?) -> Void)?) -> Melon {
melonManager.fire(callback)
return self
}
public func responseXML() -> Melon {
return self
}
public func onNetworkError(_ errorCallback: ((_ error:NSError)->Void)?) -> Melon {
melonManager.addErrorCallback(errorCallback)
return self
}
}
// MARK: - upload Methods
public extension Melon {
public func uploadProgress(_ uploadProgress:((_ bytesSent: Int64, _ totalBytesSent: Int64, _ totalBytesExpectedToSend: Int64)->Void)?) -> Melon {
melonManager.addUploadProgressCallback(uploadProgress)
return self
}
public func addFiles(_ formdatas: [Melon.FormData]) -> Melon {
melonManager.addFiles(formdatas)
return self
}
}
// MARK: - download Methods
public extension Melon {
public static func Download(_ url:String) -> Melon {
let melon = Melon()
melon.melonManager = MelonManager(downloadUrl: url)
return melon
}
public func downloadProgress(_ downloadProgress:((_ bytesWritten: Int64, _ totalBytesWritten: Int64, _ totalBytesExpectedToWrite: Int64) -> Void)?) -> Melon {
melonManager.addDownloadProgressCallback(downloadProgress)
return self
}
}
|
108bcfc34acbc766f39b433c440e534d
| 27.372093 | 162 | 0.597541 | false | false | false | false |
Knowinnovation/kitime
|
refs/heads/master
|
KITime WatchKit Extension/InterfaceController.swift
|
gpl-2.0
|
1
|
//
// InterfaceController.swift
// KITime
//
// Created by Drew Dunne on 7/7/15.
// Copyright (c) 2015 Know Innovation. All rights reserved.
//
import WatchKit
import Foundation
enum TimerState: String {
case Stopped = "stopped"
case Paused = "paused"
case Running = "running"
case Finished = "finished"
case None = "none"
}
class InterfaceController: WKInterfaceController {
@IBOutlet weak var startStopButton: WKInterfaceButton!
@IBOutlet weak var cancelButton: WKInterfaceButton!
var timerIsSelected: Bool = false
var inControl: Bool = false
//Local references to the values online in Firebase
var clockState: TimerState = .None
var timerIsRuning: Bool = false
@IBAction func startStopPressed() {
//Check the state and see how to handle the press
if clockState == .Stopped {
WKInterfaceController.openParentApplication(["action": "running"], reply: nil)
} else if clockState == .Paused {
WKInterfaceController.openParentApplication(["action": "running"], reply: nil)
} else {
WKInterfaceController.openParentApplication(["action": "paused"], reply: nil)
}
}
@IBAction func cancelPressed() {
WKInterfaceController.openParentApplication(["action": "stopped"], reply: nil)
}
func updateButtons() {
if inControl && timerIsSelected {
if clockState != .None {
startStopButton.setEnabled(true)
if clockState == .Running {
startStopButton.setTitle("Pause")
cancelButton.setEnabled(false)
} else if clockState == .Stopped {
startStopButton.setTitle("Start")
cancelButton.setEnabled(false)
} else if clockState == .Paused {
startStopButton.setTitle("Resume")
cancelButton.setEnabled(true)
} else if clockState == .Finished {
startStopButton.setTitle("Start")
startStopButton.setEnabled(false)
cancelButton.setEnabled(true)
} else {
startStopButton.setEnabled(false)
cancelButton.setEnabled(false)
}
} else {
startStopButton.setEnabled(true)
cancelButton.setEnabled(false)
}
} else {
startStopButton.setEnabled(false)
cancelButton.setEnabled(false)
}
}
func requestTimerInfo() {
WKInterfaceController.openParentApplication(["action": "getWatchInfo"], reply: { (replyInfo, error) -> Void in
if let replyInfo = replyInfo, let replyInfoType = replyInfo["replyInfoType"] as? String {
if replyInfoType == "watchInfo" {
var key = replyInfo["timerSelected"] as! Bool
if key == false {
//no timer selected
self.timerIsSelected = false
self.updateButtons()
} else {
self.inControl = replyInfo["inControl"] as! Bool
let clockVal = replyInfo["clockState"] as! String
switch clockVal {
case "stopped":
self.clockState = .Stopped
case "paused":
self.clockState = .Paused
case "running":
self.clockState = .Running
case "finished":
self.clockState = .Finished
default:
self.clockState = .None
}
println("ready")
self.timerIsSelected = true
self.updateButtons()
}
}
} else {
//no timer selected
self.timerIsSelected = false
self.updateButtons()
}
NSLog("Reply: \(replyInfo)")
})
}
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
startStopButton.setEnabled(false)
cancelButton.setEnabled(false)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("requestTimerInfo"), name: "com.knowinnovation.kitime-watchkit.secondRequestData", object: nil)
let darwinNotificationCenter = WatchDarwinNotifier.sharedInstance()
darwinNotificationCenter.registerForNotificationName("com.knowinnovation.kitime-watchkit.requestData")
self.requestTimerInfo()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
}
|
d09bba357b46d68b9f036a391933fcbb
| 34.141026 | 177 | 0.516235 | false | false | false | false |
stripe/stripe-ios
|
refs/heads/master
|
StripePayments/StripePayments/API Bindings/Models/STPConnectAccountAddress.swift
|
mit
|
1
|
//
// STPConnectAccountAddress.swift
// StripePayments
//
// Created by Yuki Tokuhiro on 8/2/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import Foundation
/// An address to use with `STPConnectAccountParams`.
public class STPConnectAccountAddress: NSObject {
/// City, district, suburb, town, or village.
/// For addresses in Japan: City or ward.
@objc public var city: String?
/// Two-letter country code (ISO 3166-1 alpha-2).
/// - seealso: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
@objc public var country: String?
/// Address line 1 (e.g., street, PO Box, or company name).
/// For addresses in Japan: Block or building number.
@objc public var line1: String?
/// Address line 2 (e.g., apartment, suite, unit, or building).
/// For addresses in Japan: Building details.
@objc public var line2: String?
/// ZIP or postal code.
@objc public var postalCode: String?
/// State, county, province, or region.
/// For addresses in Japan: Prefecture.
@objc public var state: String?
/// Town or cho-me.
/// This property only applies to Japanese addresses.
@objc public var town: String?
/// :nodoc:
@objc public var additionalAPIParameters: [AnyHashable: Any] = [:]
/// :nodoc:
@objc public override var description: String {
let props = [
// Object
String(format: "%@: %p", NSStringFromClass(STPConnectAccountAddress.self), self),
// Properties
"line1 = \(String(describing: line1))",
"line2 = \(String(describing: line2))",
"town = \(String(describing: town))",
"city = \(String(describing: city))",
"state = \(String(describing: state))",
"postalCode = \(String(describing: postalCode))",
"country = \(String(describing: country))",
]
return "<\(props.joined(separator: "; "))>"
}
}
// MARK: - STPFormEncodable
extension STPConnectAccountAddress: STPFormEncodable {
@objc
public class func propertyNamesToFormFieldNamesMapping() -> [String: String] {
return [
NSStringFromSelector(#selector(getter:line1)): "line1",
NSStringFromSelector(#selector(getter:line2)): "line2",
NSStringFromSelector(#selector(getter:town)): "town",
NSStringFromSelector(#selector(getter:city)): "city",
NSStringFromSelector(#selector(getter:country)): "country",
NSStringFromSelector(#selector(getter:state)): "state",
NSStringFromSelector(#selector(getter:postalCode)): "postal_code",
]
}
@objc
public class func rootObjectName() -> String? {
return nil
}
}
|
36ce36e68ab6af290b8526b31bab0309
| 32.597561 | 93 | 0.619964 | false | false | false | false |
vrisch/Starburst
|
refs/heads/master
|
Sources/Starburst/Internals.swift
|
mit
|
1
|
import Foundation
final class Box {
init<T>(value: T) {
self.value = value
}
func wrap<T>(value: T) {
self.value = value
}
func unwrap<T>() -> T? {
return value as? T
}
private var value: Any
}
final class ReducerBox {
init<S: State, A: Action>(reducer: @escaping Reducer<S, A>) {
box = Box(value: reducer)
perform = { box, state, action, observe in
guard let reducer: Reducer<S, A> = box.unwrap() else { return [] }
guard var state = state as? S else { return [] }
guard let action = action as? A else { return [] }
var effects: [Action] = []
switch try reducer(&state, action) {
case .unmodified:
break
case let .modified(newState):
try observe(newState)
case let .effect(newState, action):
try observe(newState)
effects.append(action)
case let .effects(newState, actions):
try observe(newState)
effects += actions
}
return effects
}
}
func apply(state: State, action: Action, observe: (State) throws -> Void) throws -> [Action] {
return try perform(box, state, action, observe)
}
private let box: Box
private let perform: (Box, State, Action, (State) throws -> Void) throws -> [Action]
}
final class StateBox {
init<S: State>(state: S) {
box = Box(value: state)
perform = { box, action, reducers, observers, middlewares in
guard let state: S = box.unwrap() else { return [] }
var effects: [Action] = []
for reducer in reducers {
effects += try reducer.apply(state: state, action: action) { newState in
guard var newState = newState as? S else { return }
// State has changed
box.wrap(value: newState)
// Notify observers
try observers.forEach {
try $0.apply(state: newState, reason: .modified)
}
// Notify middlewares
var changes = false
try middlewares.forEach {
if let state = try $0.apply(state: newState) {
// State has changed again
box.wrap(value: state)
newState = state
changes = true
}
}
if changes {
// Notify observers
try observers.forEach { try $0.apply(state: newState, reason: .middleware) }
}
}
}
return effects
}
}
func apply(action: Action, reducers: [ReducerBox], observers: [ObserverBox], middlewares: [MiddlewareBox]) throws -> [Action] {
return try perform(box, action, reducers, observers, middlewares)
}
func apply<S: State>(observer: Observer<S>) throws {
guard let state: S = box.unwrap() else { return }
try observer(state, .subscribed)
}
private var box: Box
private var perform: (Box, Action, [ReducerBox], [ObserverBox], [MiddlewareBox]) throws -> [Action]
}
/*
final class MiddlewareBox {
init(middleware: Middleware) {
box = Box(value: middleware)
}
func apply(action: Action) throws {
guard let middleware: Middleware = box.unwrap() else { return }
if case let .action(f) = middleware {
try f(action)
}
}
func apply(state: State) throws -> State? {
guard let middleware: Middleware = box.unwrap() else { return nil }
if case let .state(f) = middleware {
return try f(state)
}
return nil
}
private var box: Box
}
*/
final class MiddlewareBox {
init(_ f: @escaping (Action) throws -> [Action]) {
perform = { action, _ in
guard let action = action else { return (nil, nil) }
return (nil, try f(action))
}
}
init<S: State>(_ f: @escaping (inout S) throws -> Reduction<S>) {
perform = { action, state in
guard var newState = state as? S else { return (nil, nil) }
switch try f(&newState) {
case .unmodified: return (nil, nil)
case let .effect(newState, _): return (newState, nil)
case let .modified(newState): return (newState, nil)
case let .effects(newState, _): return (newState, nil)
}
}
}
func apply(action: Action) throws -> [Action] {
guard let actions = try perform(action, nil).1 else { return [] }
return actions
}
func apply<S: State>(state: S) throws -> S? {
guard let state = try perform(nil, state).0 as? S else { return nil }
return state
}
private var perform: (Action?, State?) throws -> (State?, [Action]?)
}
final class ObserverBox {
let priority: Priority
init<S: State>(priority: Priority, observer: @escaping Observer<S>) {
self.priority = priority
box = Box(value: observer)
}
func apply<S: State>(state: S, reason: Reason) throws {
guard let observer: Observer<S> = box.unwrap() else { return }
try observer(state, reason)
}
func apply<S: State>(state: S) throws {
guard let observer: Observer<S> = box.unwrap() else { return }
try observer(state, .subscribed)
}
private var box: Box
}
|
7a779d6f909a54b7660288df63d5b027
| 31.47486 | 131 | 0.511612 | false | false | false | false |
inacioferrarini/York
|
refs/heads/master
|
Classes/Extensions/UIImageExtensions.swift
|
mit
|
1
|
// The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import Foundation
public extension UIImage {
public class func circularScaleAndCropImage(_ image: UIImage, frame: CGRect) -> UIImage {
let size = CGSize(width: frame.size.width, height: frame.size.height)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
let imageWidth = image.size.width
let imageHeight = image.size.height
let rectWidth = frame.size.width
let rectHeight = frame.size.height
let scaleFactorX = rectWidth / imageWidth
let scaleFactorY = rectHeight / imageHeight
let imageCenterX = rectWidth / 2
let imageCenterY = rectHeight / 2
let radius = rectWidth / 2
if let context = context {
context.beginPath()
let center = CGPoint(x: imageCenterX, y: imageCenterY)
context.addArc(center: center, radius: radius, startAngle: 0, endAngle: CGFloat(2 * M_PI), clockwise: false)
context.closePath()
context.clip()
context.scaleBy (x: scaleFactorX, y: scaleFactorY)
let myRect = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)
image.draw(in: myRect)
}
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return croppedImage!
}
public class func imageFromColor(_ color: UIColor, withSize size: CGSize, withCornerRadius cornerRadius: CGFloat) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
var image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIGraphicsBeginImageContext(size)
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
image?.draw(in: rect)
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
public class func maskedImageNamed(_ image: UIImage, color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, image.scale)
let context = UIGraphicsGetCurrentContext()
image.draw(in: rect)
context?.setFillColor(color.cgColor)
context?.setBlendMode(.sourceAtop)
context?.fill(rect)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result!
}
}
|
0ade4cbd34a164d3e0e8ea7b6dca94b3
| 36.59434 | 130 | 0.679046 | false | false | false | false |
qichen0401/QCUtilitySwift
|
refs/heads/master
|
QCUtilitySwift/Classes/Common/CGRect+QC.swift
|
mit
|
1
|
//
// File.swift
// Pods
//
// Created by Qi Chen on 6/17/17.
//
//
import Foundation
extension CGRect {
public var center: CGPoint {
set {
self.origin = CGPoint(x: center.x - self.size.width/2, y: center.y - self.size.height/2)
}
get {
return CGPoint(x: self.origin.x + self.size.width/2, y: self.origin.y + self.size.height/2)
}
}
public init(center: CGPoint, size: CGSize) {
let origin = CGPoint(x: center.x - size.width / 2, y: center.y - size.height / 2)
self.init(origin: origin, size: size)
}
public func ellipseContains(_ point: CGPoint) -> Bool {
let x = point.x
let y = point.y
let h = self.center.x
let k = self.center.y
let a = self.width/2
let b = self.height/2
let result = (x - h)*(x - h)/(a*a) + (y-k)*(y-k)/(b*b)
return result <= 1
}
}
|
c630a9d97561b76659c6da61ac31a866
| 24.216216 | 103 | 0.525188 | false | false | false | false |
cocoaheadsru/server
|
refs/heads/develop
|
Sources/App/Models/Client/Client.swift
|
mit
|
1
|
import Vapor
import FluentProvider
import HTTP
// sourcery: AutoModelGeneratable
// sourcery: fromJSON, toJSON, Preparation, Updateable, ResponseRepresentable, Timestampable
final class Client: Model {
let storage = Storage()
var userId: Identifier?
var pushToken: String
init(pushToken: String, userId: Identifier?) {
self.pushToken = pushToken
self.userId = userId
}
// sourcery:inline:auto:Client.AutoModelGeneratable
init(row: Row) throws {
userId = try? row.get(Keys.userId)
pushToken = try row.get(Keys.pushToken)
}
func makeRow() throws -> Row {
var row = Row()
try? row.set(Keys.userId, userId)
try row.set(Keys.pushToken, pushToken)
return row
}
// sourcery:end
}
extension Client {
convenience init(request: Request) throws {
self.init(
pushToken: try request.json!.get(Keys.pushToken),
userId: try request.user().id
)
}
static func returnIfExists(request: Request) throws -> Client? {
return try Client.makeQuery()
.filter(Keys.userId, try request.user().id)
.first()
}
}
|
2aa38b0716708d96d828d2a2d1e8ca13
| 21.791667 | 92 | 0.680987 | false | false | false | false |
10686142/eChance
|
refs/heads/master
|
eChance/RegisterVC.swift
|
mit
|
1
|
//
// RegisterVC.swift
// Iraffle
//
// Created by Vasco Meerman on 03/05/2017.
// Copyright © 2017 Vasco Meerman. All rights reserved.
//
import Alamofire
import UIKit
class RegisterVC: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
// Outlets
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var genderTextField: UITextField!
@IBOutlet weak var dateOfBirthTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var confirmPasswordTextField: UITextField!
// Models
let user = UsersModel()
let date = TimerCall()
let datePicker = UIDatePicker()
// Constants and Variables
let defaults = UserDefaults.standard
let URL_USER_REGISTER = "https://echance.nl/SwiftToSQL_API/v1/register.php"
var dateSend: String!
var pickOption = ["", "Man", "Vrouw", "Onzijdig"]
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = UIPickerView()
pickerView.delegate = self
genderTextField.inputView = pickerView
createGenderPicker()
createDatePicker()
}
func createGenderPicker() {
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(doneGenderPickerPressed))
toolbar.setItems([doneButton], animated: false)
genderTextField.inputAccessoryView = toolbar
}
func createDatePicker() {
// Format datepicker to D M Y
datePicker.locale = NSLocale.init(localeIdentifier: "en_GB") as Locale
//Format for picker to date with years
datePicker.datePickerMode = .date
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(donePickerPressed))
toolbar.setItems([doneButton], animated: false)
dateOfBirthTextField.inputAccessoryView = toolbar
dateOfBirthTextField.inputView = datePicker
}
func doneGenderPickerPressed() {
self.view.endEditing(true)
}
func donePickerPressed() {
// format picker output to date with years
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .none
dateFormatter.dateFormat = "dd-MM-yyyy"
dateOfBirthTextField.text = dateFormatter.string(from: datePicker.date)
let dateCheck = datePicker.date
let eligebleAge = date.checkAgeUnder18(date: dateCheck)
if eligebleAge == true {
let dateFormatterSend = DateFormatter()
dateFormatterSend.dateStyle = .short
dateFormatterSend.timeStyle = .none
dateFormatterSend.dateFormat = "yyyy-MM-dd"
dateSend = dateFormatterSend.string(from: datePicker.date)
self.view.endEditing(true)
}
else{
self.registerErrorAlert(title: "Oeps!", message: "Je moet 18 jaar of ouder zijn om je in te schrijven..")
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
genderTextField.text = pickOption[row]
}
@IBAction func submitPressed(_ sender: Any) {
let userFName = firstNameTextField.text
let userLName = lastNameTextField.text
let userBDate = dateSend
let userGender = genderTextField.text
let userPassword = passwordTextField.text
let confirmPassword = confirmPasswordTextField.text
let userEmail = emailTextField.text
if userFName != "" && userLName != "" && userBDate != "" && userGender != "" && userPassword != "" && confirmPassword != "" && userEmail != ""{
let parameters: Parameters=[
"first_name":userFName!,
"last_name":userLName!,
"password":userPassword!,
"birth_date":userBDate!,
"email":userEmail!,
"gender":userGender!
]
Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
{
response in
//printing response
print(response)
if let result = response.result.value {
let jsonData = result as! NSDictionary
let message = jsonData.value(forKey: "message") as! String?
if message == "User already exist"{
self.registerErrorAlert(title: "Oeps!", message: "Deze email is al een keer geregistreerd")
self.emailTextField.text = ""
}
else{
// Save the userID from the registered user
let uid = jsonData.value(forKey: "uid") as! Int?
let userDict = ["userID": uid!, "userFN": userFName!, "userLN": userLName!, "userBD": userBDate!, "userE": userEmail!, "userP": userPassword!, "userG": userGender!] as [String : Any]
self.defaults.set(userDict, forKey: "user")
self.defaults.set("1", forKey: "fromRegister")
self.performSegue(withIdentifier: "toExplanation", sender: nil)
}
}
}
}
else{
self.registerErrorAlert(title: "Oeps!", message: "Zorg dat alle velden ingevuld zijn;)")
}
}
func registerErrorAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
}
|
e6a7fb16b37f019b10c1120f6f1a4056
| 36.048913 | 210 | 0.580167 | false | false | false | false |
chenyun122/StepIndicator
|
refs/heads/master
|
StepIndicatorDemo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// StepIndicator
//
// Created by Yun Chen on 2017/7/14.
// Copyright © 2017 Yun CHEN. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIScrollViewDelegate {
@IBOutlet weak var stepIndicatorView:StepIndicatorView!
@IBOutlet weak var scrollView:UIScrollView!
private var isScrollViewInitialized = false
override func viewDidLoad() {
super.viewDidLoad()
// In this demo, the customizations have been done in Storyboard.
// Customization by coding:
//self.stepIndicatorView.numberOfSteps = 5
//self.stepIndicatorView.currentStep = 0
//self.stepIndicatorView.circleColor = UIColor(red: 179.0/255.0, green: 189.0/255.0, blue: 194.0/255.0, alpha: 1.0)
//self.stepIndicatorView.circleTintColor = UIColor(red: 0.0/255.0, green: 180.0/255.0, blue: 124.0/255.0, alpha: 1.0)
//self.stepIndicatorView.circleStrokeWidth = 3.0
//self.stepIndicatorView.circleRadius = 10.0
//self.stepIndicatorView.lineColor = self.stepIndicatorView.circleColor
//self.stepIndicatorView.lineTintColor = self.stepIndicatorView.circleTintColor
//self.stepIndicatorView.lineMargin = 4.0
//self.stepIndicatorView.lineStrokeWidth = 2.0
//self.stepIndicatorView.displayNumbers = false //indicates if it displays numbers at the center instead of the core circle
//self.stepIndicatorView.direction = .leftToRight
//self.stepIndicatorView.showFlag = true
// Example for apply constraints programmatically, enable it for test.
//self.applyNewConstraints()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !isScrollViewInitialized {
isScrollViewInitialized = true
self.initScrollView()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func initScrollView() {
self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width * CGFloat(self.stepIndicatorView.numberOfSteps + 1), height: self.scrollView.frame.height)
let labelHeight = self.scrollView.frame.height / 2.0
let halfScrollViewWidth = self.scrollView.frame.width / 2.0
for i in 1 ... self.stepIndicatorView.numberOfSteps + 1 {
let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 100))
if i<=self.stepIndicatorView.numberOfSteps {
label.text = "\(i)"
}
else{
label.text = "You're done!"
}
label.textAlignment = NSTextAlignment.center
label.font = UIFont.systemFont(ofSize: 35)
label.textColor = UIColor.lightGray
label.center = CGPoint(x: halfScrollViewWidth * (CGFloat(i - 1) * 2.0 + 1.0), y:labelHeight)
self.scrollView.addSubview(label)
}
}
// MARK: - UIScrollViewDelegate
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageIndex = scrollView.contentOffset.x / scrollView.frame.size.width
stepIndicatorView.currentStep = Int(pageIndex)
}
// MARK: - More Examples
// Example for applying constraints programmatically
func applyNewConstraints() {
// Hold the weak object
guard let stepIndicatorView = self.stepIndicatorView else {
return
}
// Remove the constraints made in Storyboard before
stepIndicatorView.removeFromSuperview()
stepIndicatorView.removeConstraints(stepIndicatorView.constraints)
self.view.addSubview(stepIndicatorView)
// Add new constraints programmatically
stepIndicatorView.widthAnchor.constraint(equalToConstant: 263.0).isActive = true
stepIndicatorView.heightAnchor.constraint(equalToConstant: 80.0).isActive = true
stepIndicatorView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
stepIndicatorView.topAnchor.constraint(equalTo: self.view.layoutMarginsGuide.topAnchor, constant:30.0).isActive = true
self.scrollView.topAnchor.constraint(equalTo: stepIndicatorView.bottomAnchor, constant: 8.0).isActive = true
}
}
|
74e292f3b3aba65f8a0e7d2431c496d5
| 39.880734 | 170 | 0.665395 | false | false | false | false |
Zewo/SQL
|
refs/heads/master
|
Sources/SQL/Model/TableProtocol.swift
|
mit
|
2
|
public protocol TableField: RawRepresentable, Hashable, ParameterConvertible {
static var tableName: String { get }
}
public extension TableField {
public var sqlParameter: Parameter {
return .field(qualifiedField)
}
public var qualifiedField: QualifiedField {
return QualifiedField("\(Self.tableName).\(self.rawValue)")
}
}
public protocol TableProtocol {
associatedtype Field: TableField
}
public extension TableProtocol where Self.Field.RawValue == String {
public static func select(_ fields: Field...) -> Select {
return Select(fields.map { $0.qualifiedField }, from: [Field.tableName])
}
public static func select(where predicate: Predicate) -> Select {
return select.filtered(predicate)
}
public static var select: Select {
return Select("*", from: Field.tableName)
}
public static func update(_ dict: [Field: ValueConvertible?], where predicate: Predicate? = nil) -> Update {
var translated = [QualifiedField: ValueConvertible?]()
for (key, value) in dict {
translated[key.qualifiedField] = value
}
var update = Update(Field.tableName)
update.set(translated)
if let predicate = predicate {
update.filter(predicate)
}
return update
}
public static func insert(_ dict: [Field: ValueConvertible?]) -> Insert {
var translated = [QualifiedField: ValueConvertible?]()
for (key, value) in dict {
translated[key.qualifiedField] = value
}
return Insert(Field.tableName, values: translated)
}
public static func delete(where predicate: Predicate) -> Delete {
return Delete(from: Field.tableName).filtered(predicate)
}
public static var delete: Delete {
return Delete(from: Field.tableName)
}
}
|
0d52daf3b271214ac7b33989ac8d9431
| 26.617647 | 112 | 0.647497 | false | false | false | false |
lhx931119/DouYuTest
|
refs/heads/master
|
DouYu/DouYu/Classes/Home/View/RecommendGameView.swift
|
mit
|
1
|
//
// RecommendGameView.swift
// DouYu
//
// Created by 李宏鑫 on 17/1/19.
// Copyright © 2017年 hongxinli. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
private let kEdgeInsetMargin: CGFloat = -15
class RecommendGameView: UIView {
//控件属性
@IBOutlet weak var collectionView: UICollectionView!
//定义属性
var group: [AnchorGroup]?{
didSet{
//移除前两个
group?.removeFirst()
group?.removeFirst()
//添加更多
let moreGroup = AnchorGroup()
group?.append(moreGroup)
//刷新collectionView
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
//设置不随父空间拉伸而拉伸
autoresizingMask = .None
// 注册cell
collectionView.registerNib(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
//设置collectionView内边距
collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin)
}
}
// Mark:-快速创建的类方法
extension RecommendGameView{
class func recommendGameView() -> RecommendGameView{
return NSBundle.mainBundle().loadNibNamed("RecommendGameView", owner: nil, options: nil).first as! RecommendGameView
}
}
// Mark:-遵守collectionViewDataSource
extension RecommendGameView: UICollectionViewDataSource{
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return group?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(kGameCellID, forIndexPath: indexPath) as! CollectionGameCell
cell.group = group?[indexPath.item]
return cell
}
}
|
7854afcdd7cf00da9c738c6633c870f5
| 24.025316 | 133 | 0.657056 | false | false | false | false |
chquanquan/AreaPickerView_swift
|
refs/heads/master
|
AreaPickerViewDemo/AreaPickerViewDemo/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// test
//
// Created by quan on 2017/1/11.
// Copyright © 2017年 langxi.Co.Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
var areaPickerView: AreaPickerView?
override func viewDidLoad() {
super.viewDidLoad()
//初始化地址(如果有),方便弹出pickerView后能够主动选中,这时候还没有区域代码信息,但是只要一划动并确定就有了.理论上进入地址控制器时候,要么全部信息有,要么全部信息没有....我先赋值只是为了演示功能.
myLocate.province = "广东省"
myLocate.city = "广州市"
myLocate.area = "天河区"
setAreaText(locate: myLocate)
//areaPickerView.有控制器在的时候,不会被销毁.跟控制器时间销毁...没关系吧?
areaPickerView = AreaPickerView.picker(for: self, textField: textField)
textField.delegate = self //也个也最好实现.因为可以在将要显示PickerView的时候,主动选中一个地区.
//为了点击空白的时候能够退键盘
let tapGR = UITapGestureRecognizer(target: self, action: #selector(viewDidTap(tapGR:)))
tapGR.cancelsTouchesInView = false
view.addGestureRecognizer(tapGR)
}
func viewDidTap(tapGR: UITapGestureRecognizer) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - lazy
lazy var myLocate: Location = {
return Location()
}()
}
extension ViewController: UITextFieldDelegate {
//主动选择某一个地区,主动弹出某个区域以选中....
func textFieldDidBeginEditing(_ textField: UITextField) {
areaPickerView?.shouldSelected(proName: myLocate.province, cityName: myLocate.city, areaName: myLocate.area)
}
}
extension ViewController: AreaPickerDelegate {
internal func cancel(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
print("点击了取消")
//还原原来的值......
myLocate.decription()
setAreaText(locate: myLocate)
}
internal func sure(areaToolbar: AreaToolbar, textField: UITextField, locate: Location, item: UIBarButtonItem) {
print("点击了确定")
//当picker定住的时候,就有会值.**********但是******************
//picker还有转动的时候有些值是空的........取值前一定要判断是否为空.否则crash.....
//赋值新地址......
print("最后的值是\n")
locate.decription()
// myLocate = locate //不能直接赋值地址,这个是引用来的
myLocate.province = locate.province
myLocate.provinceCode = locate.provinceCode
myLocate.city = locate.city
myLocate.cityCode = locate.cityCode
myLocate.area = locate.area
myLocate.areaCode = locate.areaCode
}
internal func statusChanged(areaPickerView: AreaPickerView, pickerView: UIPickerView, textField: UITextField, locate: Location) {
//立即显示新值
print("转到的值:\n")
locate.decription()
if !locate.area.isEmpty {
textField.text = "\(locate.province) \(locate.city) \(locate.area)"
} else {
textField.text = "\(locate.province) \(locate.city)"
}
}
func setAreaText(locate: Location) {
var areaText = ""
if locate.city.isEmpty {
areaText = locate.province
} else if locate.area.isEmpty {
areaText = "\(locate.province) \(locate.city)"
} else {
areaText = "\(locate.province) \(locate.city) \(locate.area)"
}
textField.text = areaText
}
}
|
b15216a25643450687ba39bbe9dd3398
| 28.86087 | 133 | 0.624345 | false | false | false | false |
balafd/SAC_iOS
|
refs/heads/master
|
SAC/Pods/SwiftForms/SwiftForms/cells/FormLabelCell.swift
|
mit
|
1
|
//
// FormTextFieldCell.swift
// SwiftForms
//
// Created by Miguel Ángel Ortuño Ortuño on 20/08/14.
// Copyright (c) 2016 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
class FormLabelCell: FormValueCell {
/// MARK: FormBaseCell
override func configure() {
super.configure()
accessoryType = .none
titleLabel.translatesAutoresizingMaskIntoConstraints = false
valueLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
valueLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
valueLabel.textColor = UIColor.lightGray
valueLabel.textAlignment = .right
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel)
titleLabel.setContentHuggingPriority(UILayoutPriority(rawValue: 500), for: .horizontal)
titleLabel.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: .horizontal)
// apply constant constraints
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .height, relatedBy: .equal, toItem: contentView, attribute: .height, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
contentView.addConstraint(NSLayoutConstraint(item: valueLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1.0, constant: 0.0))
}
override func update() {
super.update()
titleLabel.text = rowDescriptor?.title
valueLabel.text = rowDescriptor?.configuration.cell.placeholder
}
}
|
42b810e2f29933c1229b07cb85486ac8
| 42.270833 | 185 | 0.702937 | false | true | false | false |
svdo/swift-SelfSignedCert
|
refs/heads/master
|
SelfSignedCert/CertificateName.swift
|
mit
|
1
|
// Copyright © 2016 Stefan van den Oord. All rights reserved.
import Foundation
class CertificateName : NSObject {
private(set) var components: [ Set<NSMutableArray> ]
var commonName: String {
get { return string(for: OID.commonName) }
set { setString(newValue, forOid:OID.commonName) }
}
var emailAddress: String {
get { return string(for: OID.email) }
set { setString(newValue, forOid:OID.email) }
}
override init() {
components = []
super.init()
}
func string(for oid:OID) -> String {
guard let pair = pair(for: oid), let str = pair[1] as? String else {
return ""
}
return str
}
func setString(_ string:String, forOid oid:OID) {
if let pair = pair(for: oid) {
pair[1] = string
}
else {
components.append([[oid, string]])
}
}
private func pair(for oid:OID) -> NSMutableArray? {
let filtered = components.filter { set in
guard let array = set.first, let filteredOid = array[0] as? OID else {
return false
}
return filteredOid == oid
}
if filtered.count == 1 {
return filtered[0].first
}
else {
return nil
}
}
}
|
46e206caa816bdcab3174bc5b0b90e8f
| 25.076923 | 82 | 0.525074 | false | false | false | false |
Tricertops/YAML
|
refs/heads/master
|
Sources/Utilities.swift
|
mit
|
1
|
//
// Utilities.swift
// YAML.framework
//
// Created by Martin Kiss on 14 May 2016.
// https://github.com/Tricertops/YAML
//
// The MIT License (MIT)
// Copyright © 2016 Martin Kiss
//
extension String {
/// Creates String from mutable libyaml char array.
init(_ string: UnsafeMutablePointer<yaml_char_t>?) {
guard let string = string else {
self.init()
return
}
let casted = UnsafePointer<CChar>(OpaquePointer(string))
self.init(cString: casted)
}
/// Convenience function for obtaining indexes.
func index(_ offset: Int) -> String.Index {
return self.index(self.startIndex, offsetBy: offset)
}
/// Convenience function for obtaining indexes from the end.
func index(backwards offset: Int) -> String.Index {
return self.index(self.endIndex, offsetBy: -offset)
}
/// Substring from a native String.Index.
func substring(from offset: Int) -> String {
return String(self[self.index(offset) ..< self.endIndex])
}
/// Substring to a native String.Index.
func substring(to offset: Int) -> String {
return String(self[self.startIndex ..< self.index(backwards: offset)])
}
/// Invoke block on the contents of this string, represented as a nul-terminated array of char, ensuring the array's lifetime until return.
func withMutableCString<Result>(_ block: @escaping (UnsafeMutablePointer<UInt8>) throws -> Result) rethrows -> Result {
var array = self.utf8CString
return try array.withUnsafeMutableBufferPointer { buffer in
let casted = UnsafeMutablePointer<UInt8>(OpaquePointer(buffer.baseAddress!))
return try block(casted)
}
}
}
extension Array {
/// Creates array from libyaml array of arbitrary type.
init(start: UnsafeMutablePointer<Element>?, end: UnsafeMutablePointer<Element>?) {
self.init()
guard let start = start else { return }
guard let end = end else { return }
var current = start
while current < end {
self.append(current.pointee)
current += 1
}
}
}
extension Int32 {
init(_ bool: Bool) {
self.init(bool ? 1 : 0)
}
}
|
1392f4b8cbf7a0aafca63119421ad242
| 26.411765 | 143 | 0.611588 | false | false | false | false |
johnno1962/Dynamo
|
refs/heads/master
|
Sources/Servers.swift
|
mit
|
1
|
//
// Servers.swift
// Dynamo
//
// Created by John Holdsworth on 11/06/2015.
// Copyright (c) 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/Dynamo/Sources/Servers.swift#24 $
//
// Repo: https://github.com/johnno1962/Dynamo
//
import Foundation
#if os(Linux)
import Dispatch
import Glibc
#endif
// MARK: Private queues and missing IP functions
let dynamoRequestQueue = DispatchQueue( label: "DynamoRequestThread", attributes: DispatchQueue.Attributes.concurrent )
// MARK: Basic http: Web server
/**
Basic http protocol web server running on the specified port. Requests are presented to each of a set
of swiftlets provided in a connecton thread until one is encountered that has processed the request.
*/
open class DynamoWebServer: _NSObject_ {
fileprivate let swiftlets: [DynamoSwiftlet]
fileprivate let serverSocket: Int32
/** port allocated for server if specified as 0 */
open var serverPort: UInt16 = 0
/** basic initialiser for Swift web server processing using array of swiftlets */
@objc public convenience init?( portNumber: UInt16, swiftlets: [DynamoSwiftlet], localhostOnly: Bool = false ) {
self.init( portNumber, swiftlets: swiftlets, localhostOnly: localhostOnly )
DispatchQueue.global(qos: .default).async(execute: {
self.runConnectionHandler( self.httpConnectionHandler )
} )
}
@objc init?( _ portNumber: UInt16, swiftlets: [DynamoSwiftlet], localhostOnly: Bool ) {
#if os(Linux)
signal( SIGPIPE, SIG_IGN )
#endif
self.swiftlets = swiftlets
var ip4addr = sockaddr_in()
#if !os(Linux)
ip4addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
#endif
ip4addr.sin_family = sa_family_t(AF_INET)
ip4addr.sin_port = htons( portNumber )
ip4addr.sin_addr = in_addr( s_addr: INADDR_ANY )
if localhostOnly {
inet_aton( "127.0.0.1", &ip4addr.sin_addr )
}
serverSocket = socket( Int32(ip4addr.sin_family), sockType, 0 )
var yes: u_int = 1, yeslen = socklen_t(MemoryLayout<u_int>.size)
var addrLen = socklen_t(MemoryLayout<sockaddr_in>.size)
super.init()
if serverSocket < 0 {
dynamoStrerror( "Could not get server socket" )
}
else if setsockopt( serverSocket, SOL_SOCKET, SO_REUSEADDR, &yes, yeslen ) < 0 {
dynamoStrerror( "Could not set SO_REUSEADDR" )
}
else if bind( serverSocket, sockaddr_cast(&ip4addr), addrLen ) < 0 {
dynamoStrerror( "Could not bind service socket on port \(portNumber)" )
}
else if listen( serverSocket, 100 ) < 0 {
dynamoStrerror( "Server socket would not listen" )
}
else if getsockname( serverSocket, sockaddr_cast(&ip4addr), &addrLen ) == 0 {
serverPort = ntohs( ip4addr.sin_port )
#if os(Linux)
let s = ""
#else
let s = type(of: self) === DynamoSSLWebServer.self ? "s" : ""
#endif
dynamoLog( "Server available on http\(s)://localhost:\(serverPort)" )
return
}
return nil
}
func runConnectionHandler( _ connectionHandler: @escaping (Int32) -> Void ) {
while self.serverSocket >= 0 {
let clientSocket = accept( self.serverSocket, nil, nil )
if clientSocket >= 0 {
dynamoRequestQueue.async(execute: {
connectionHandler( clientSocket )
} )
}
else {
Thread.sleep( forTimeInterval: 0.5 )
}
}
}
func wrapConnection( _ clientSocket: Int32 ) -> DynamoHTTPConnection? {
return DynamoHTTPConnection( clientSocket: clientSocket )
}
open func httpConnectionHandler( _ clientSocket: Int32 ) {
if let httpClient = wrapConnection( clientSocket ) {
while httpClient.readHeaders() {
var processed = false
for swiftlet in swiftlets {
switch swiftlet.present( httpClient: httpClient ) {
case .notProcessed:
continue
case .processed:
return
case .processedAndReusable:
httpClient.flush()
processed = true
}
break
}
if !processed {
httpClient.status = 400
httpClient.response( text: "Invalid request: \(httpClient.method) \(httpClient.path) \(httpClient.version)" )
return
}
}
}
}
}
#if os(Linux)
/**
Pre-forked worker model version e.g. https://github.com/kylef/Curassow
*/
public class DynamoWorkerServer : DynamoWebServer {
public init?( portNumber: UInt16, swiftlets: [DynamoSwiftlet], workers: Int, localhostOnly: Bool = false ) {
super.init( portNumber, swiftlets: swiftlets, localhostOnly: localhostOnly )
DispatchQueue.global(qos: .default).async {
var wcount = 0, status: Int32 = 0
while true {
if (wcount < workers || wait( &status ) != 0) && fork() == 0 {
self.runConnectionHandler( self.httpConnectionHandler )
}
wcount += 1
}
}
}
}
#else
// MARK: SSL https: Web Server
/**
Subclass of DynamoWebServer for accepting https: SSL encoded requests. Create a proxy on the provided
port to a surrogate DynamoWebServer on a random port on the localhost to actually process the requests.
*/
open class DynamoSSLWebServer: DynamoWebServer {
fileprivate let certs: [AnyObject]
/**
default initialiser for SSL server. Can proxy a "surrogate" non-SSL server given it's URL
*/
@objc public init?( portNumber: UInt16, swiftlets: [DynamoSwiftlet] = [], certs: [AnyObject], surrogate: String? = nil ) {
self.certs = certs
super.init( portNumber, swiftlets: swiftlets, localhostOnly: false )
DispatchQueue.global(qos: .default).async(execute: {
if surrogate == nil {
self.runConnectionHandler( self.httpConnectionHandler )
}
else if let surrogateURL = URL( string: surrogate! ) {
self.runConnectionHandler( {
(clientSocket: Int32) in
if let sslConnection = self.wrapConnection( clientSocket ),
let surrogateConnection = DynamoHTTPConnection( url: surrogateURL ) {
DynamoSelector.relay( "surrogate", from: sslConnection, to: surrogateConnection, dynamoTrace )
}
} )
}
else {
dynamoLog( "Invalid surrogate URL: \(String(describing: surrogate))" )
}
} )
}
override func wrapConnection( _ clientSocket: Int32 ) -> DynamoHTTPConnection? {
return DynamoSSLConnection( sslSocket: clientSocket, certs: certs )
}
}
class DynamoSSLConnection: DynamoHTTPConnection {
let inputStream: InputStream
let outputStream: OutputStream
init?( sslSocket: Int32, certs: [AnyObject]? ) {
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocket( nil, sslSocket, &readStream, &writeStream )
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
inputStream.open()
outputStream.open()
super.init(clientSocket: sslSocket,
readFP: funopen(readStream!.toOpaque(), {
(cookie, buffer, count) in
let inputStream = Unmanaged<InputStream>
.fromOpaque(cookie!).takeUnretainedValue()
// Swift.print("READ", count)
return Int32(inputStream.read( buffer!.withMemoryRebound(to: UInt8.self, capacity: Int(count)) {$0}, maxLength: Int(count) ))
}, nil, nil, {cookie -> Int32 in
Unmanaged<InputStream>.fromOpaque(cookie!)
.takeUnretainedValue().close()
return 0
}),
writeFP: funopen(writeStream!.toOpaque(), nil, {
(cookie, buffer, count) in
let outputStream = Unmanaged<OutputStream>
.fromOpaque(cookie!).takeUnretainedValue()
// Swift.print("WRITE", count)
return Int32(outputStream.write( buffer!.withMemoryRebound(to: UInt8.self, capacity: Int(count)) {$0}, maxLength: Int(count) ))
}, nil, {cookie -> Int32 in
Unmanaged<OutputStream>.fromOpaque(cookie!)
.takeUnretainedValue().close()
return 0
}))
if certs != nil {
let sslSettings: [NSString:AnyObject] = [
kCFStreamSSLIsServer: NSNumber(value: true as Bool),
kCFStreamSSLLevel: kCFStreamSSLLevel,
kCFStreamSSLCertificates: certs! as AnyObject
]
CFReadStreamSetProperty( inputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLSettings), sslSettings as CFTypeRef )
CFWriteStreamSetProperty( outputStream, CFStreamPropertyKey(rawValue: kCFStreamPropertySSLSettings), sslSettings as CFTypeRef )
}
}
override var hasBytesAvailable: Bool {
return inputStream.hasBytesAvailable
}
override func _read( buffer: UnsafeMutableRawPointer, count: Int ) -> Int {
return inputStream.read( buffer.assumingMemoryBound(to: UInt8.self), maxLength: count )
}
override func _write( buffer: UnsafeRawPointer, count: Int ) -> Int {
return outputStream.write( buffer.assumingMemoryBound(to: UInt8.self), maxLength: count )
}
override func receive( buffer: UnsafeMutableRawPointer, count: Int ) -> Int? {
return inputStream.hasBytesAvailable ? _read( buffer: buffer, count: count ) : nil
}
override func forward( buffer: UnsafeRawPointer, count: Int ) -> Int? {
return outputStream.hasSpaceAvailable ? _write( buffer: buffer, count: count ) : nil
}
}
#endif
|
ccb7e52536cbe0b48a76d4226f9a97bc
| 33.386667 | 139 | 0.599651 | false | false | false | false |
natemann/PlaidClient
|
refs/heads/master
|
PlaidClient/PlaidURL.swift
|
mit
|
1
|
//
// PlaidURL.swift
// PlaidClient
//
// Created by Nathan Mann on 8/14/16.
// Copyright © 2016 Nathan Mann. All rights reserved.
//
import Foundation
internal struct PlaidURL {
init(environment: Environment) {
switch environment {
case .development:
baseURL = "https://tartan.plaid.com"
case .production:
baseURL = "https://api.plaid.com"
}
}
let baseURL: String
func institutions(id: String? = nil) -> URLRequest {
var url = baseURL + "/institutions"
if let id = id {
url += "/\(id)"
}
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
return request
}
func intuit(clientID: String, secret: String, count: Int, skip: Int) -> URLRequest {
let bodyObject = ["client_id" : clientID,
"secret" : secret,
"count" : "\(count)",
"offset" : "\(skip)"]
return URLRequest("POST", url: URL(string: baseURL + "/institutions/longtail")!, body: bodyObject)
}
func connect(clientID: String, secret: String, institution: PlaidInstitution, username: String, password: String, pin: String? = nil) -> URLRequest {
let bodyObject = ["client_id" : clientID,
"secret" : secret,
"type" : institution.type,
"username" : username,
"password" : password,
"pin" : pin ?? "0"]
return URLRequest("POST", url: URL(string: baseURL + "/connect")!, body: bodyObject)
}
func step(clientID: String, secret: String, institution: PlaidInstitution, username: String, password: String, pin: String? = nil) -> URLRequest {
var request = connect(clientID: clientID, secret: secret, institution: institution, username: username, password: password)
request.url = request.url?.appendingPathComponent("/step")
return request
}
func mfaResponse(clientID: String, secret: String, institution: PlaidInstitution, accessToken: String, response: String) -> URLRequest {
let bodyObject = ["client_id" : "test_id",
"secret" : "test_secret",
"mfa" : response,
"type" : institution.type,
"access_token" : accessToken]
return URLRequest("POST", url: URL(string: baseURL + "/connect/step")!, body: bodyObject)
}
func patchConnect(clientID: String, secret: String, accessToken: String, username: String, password: String, pin: String? = nil) -> URLRequest {
let bodyObject = ["client_id" : clientID,
"secret" : secret,
"access_token" : accessToken,
"username" : username,
"password" : password,
"pin" : pin ?? "0"]
return URLRequest("PATCH", url: URL(string: baseURL + "/connect")!, body: bodyObject)
}
func patchMFAResponse(clientID: String, secret: String, accessToken: String, response: String) -> URLRequest {
let bodyObject = ["client_id" : "test_id",
"secret" : "test_secret",
"mfa" : response,
"access_token" : accessToken]
return URLRequest("PATCH", url: URL(string: baseURL + "/connect/step")!, body: bodyObject)
}
func transactions(clientID: String, secret: String, accessToken: String, accountID: String?, pending: Bool?, fromDate: Date?, toDate: Date?) -> URLRequest {
var options: [String : Any] = [:]
if let accountID = accountID {
options["account"] = accountID
}
if let pending = pending {
options["pending"] = pending
}
if let fromDate = fromDate {
options["gte"] = DateFormatter.plaidDate(fromDate)
}
if let toDate = toDate {
options["lte"] = DateFormatter.plaidDate(toDate)
}
let bodyObject: [String: Any] = ["client_id" : clientID,
"secret" : secret,
"access_token" : accessToken,
"options" : options]
return URLRequest("POST", url: URL(string: baseURL + "/connect/get")!, body: bodyObject)
}
}
fileprivate extension URLRequest {
init(_ method: String, url: URL, body: [String : Any]) {
self.init(url: url)
self.httpMethod = method
self.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
self.httpBody = try! JSONSerialization.data(withJSONObject: body, options: [])
}
}
|
54a47a7bf832a19c35c2cbdb72e10546
| 32.782313 | 160 | 0.529199 | false | false | false | false |
vrace/stdstr
|
refs/heads/master
|
stdstr/stdstr.swift
|
mit
|
1
|
//
// stdstr.wift -- C++ 98 std::string port to Swift
//
// Copyright (c) 2016 LIU YANG
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public extension String {
static let npos: Int = Int.max
func begin() -> Index {
return startIndex
}
func end() -> Index {
return endIndex
}
func size() -> Int {
return length()
}
func length() -> Int {
return characters.count
}
mutating func resize(n: Int) {
self = substr(0, n)
}
mutating func resize(n: size_t, _ c: Character) {
if length() >= n {
self = substr(0, n)
}
else {
append(n - length(), c)
}
}
mutating func reserve(n: Int = 0) {
reserveCapacity(n)
}
mutating func clear() {
removeAll()
}
func empty() -> Bool {
return isEmpty
}
subscript(pos: Int) -> Character {
get {
return at(pos)
}
set(newValue) {
replace(pos, 1, String(newValue))
}
}
func at(pos: Int) -> Character {
return self[startIndex.advancedBy(pos)]
}
mutating func append(str: String) -> String {
appendContentsOf(str)
return self
}
mutating func append(str: String, _ subpos: Int, _ sublen: Int) -> String {
return append(str.substr(subpos, sublen))
}
mutating func append(s: String, _ n: Int) -> String {
return append(s.substr(0, n))
}
mutating func append(n: Int, _ c: Character) -> String {
self.append(String(count: n, repeatedValue: c))
return self
}
mutating func push_back(c: Character) {
self.append(c)
}
mutating func assign(str: String) -> String {
self = str
return self
}
mutating func assign(str: String, _ subpos: Int, _ sublen: Int) -> String {
return assign(str.substr(subpos, sublen))
}
mutating func assign(s: String, _ n: Int) -> String {
return assign(s.substr(0, n))
}
mutating func assign(n: Int, _ c: Character) -> String {
clear()
return append(n, c)
}
mutating func insert(pos: Int, _ str: String) -> String {
insertContentsOf(str.characters, at: startIndex.advancedBy(pos))
return self
}
mutating func insert(pos: Int, _ str: String, _ subpos: Int, _ sublen: Int) -> String {
return insert(pos, str.substr(subpos, sublen))
}
mutating func insert(pos: Int, _ s: String, _ n: Int) -> String {
return insert(pos, s.substr(0, n))
}
mutating func insert(pos: Int, _ n: Int, _ c: Character) -> String {
return insert(pos, String(count: n, repeatedValue: c))
}
mutating func insert(p: Index, _ n: Int, _ c: Character) {
insertContentsOf(String(count: n, repeatedValue: c).characters, at: p)
}
mutating func insert(p: Index, _ c: Character) -> Index {
let distance = begin().distanceTo(p)
insert(c, atIndex: p)
return begin().advancedBy(distance)
}
mutating func erase(pos: Int = 0, _ len: Int = String.npos) -> String {
return replace(pos, len, "")
}
mutating func erase(p: Index) -> Index {
let distance = begin().distanceTo(p)
replace(p, p.advancedBy(1), "")
return begin().advancedBy(distance)
}
mutating func erase(first: Index, _ last: Index) -> Index {
let distance = begin().distanceTo(first)
replace(first, last, "")
return begin().advancedBy(distance)
}
mutating func replace(pos: Int, _ len: Int, _ str: String) -> String {
let end = Int(min(UInt(pos) + UInt(len), UInt(length())))
return replace(startIndex.advancedBy(pos), startIndex.advancedBy(end), str)
}
mutating func replace(i1: Index, _ i2: Index, _ str: String) -> String {
replaceRange(i1 ..< i2, with: str)
return self
}
mutating func replace(pos: Int, _ len: Int, _ str: String, _ subpos: Int, _ sublen: Int) -> String {
return replace(pos, len, str.substr(subpos, sublen))
}
mutating func replace(pos: Int, _ len: Int, _ s: String, _ n: Int) -> String {
return replace(pos, len, s.substr(0, n))
}
mutating func replace(i1: Index, _ i2: Index, _ s: String, _ n: Int) -> String {
return replace(i1, i2, s.substr(0, n))
}
mutating func replace(pos: Int, _ len: Int, _ n: Int, _ c: Character) -> String {
return replace(pos, len, String(count: n, repeatedValue: c))
}
mutating func replace(i1: Index, _ i2: Index, _ n: Int, _ c: Character) -> String {
return replace(i1, i2, String(count: n, repeatedValue: c))
}
mutating func swap(inout str: String) {
let temp = self
self = str
str = temp
}
func copy(inout s: String, _ len: Int, _ pos: Int = 0) -> Int {
s.assign(self, pos, len)
return s.length()
}
func find(str: String, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.substr($0, str.length()) == str
}
}
func find(s: String, _ pos: Int, _ n: Int) -> Int {
return find(s.substr(0, n), pos)
}
func find(c: Character, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.at($0) == c
}
}
func rfind(str: String, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
self.substr($0, str.length()) == str
}
}
func rfind(s: String, _ pos: Int, _ n: Int) -> Int {
return rfind(s.substr(0, n), pos)
}
func rfind(c: Character, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
self.at($0) == c
}
}
func find_first_of(str: String, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
str.find(self.at($0)) != String.npos
}
}
func find_first_of(s: String, _ pos: Int, _ n: Int) -> Int {
return find_first_of(s.substr(0, n), pos)
}
func find_first_of(c: Character, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.at($0) == c
}
}
func find_last_of(str: String, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
str.find(self.at($0)) != String.npos
}
}
func find_last_of(s: String, _ pos: Int, _ n: Int) -> Int {
return find_last_of(s.substr(0, n), pos)
}
func find_last_of(c: Character, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
self.at($0) == c
}
}
func find_first_not_of(str: String, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
str.find(self.at($0)) == String.npos
}
}
func find_first_not_of(s: String, _ pos: Int, n: Int) -> Int {
return find_first_not_of(s.substr(0, n), pos)
}
func find_first_not_of(c: Character, _ pos: Int = 0) -> Int {
return iterateForward(pos) {
self.at($0) != c
}
}
func find_last_not_of(str: String, _ pos: Int = String.npos) -> Int {
return iterateBackward(pos) {
str.find(self.at($0)) == String.npos
}
}
func find_last_not_of(s: String, _ pos: Int, n: Int) -> Int {
return find_last_not_of(s.substr(0, n), pos)
}
func find_last_not_of(c: Character, _ pos: Int = 0) -> Int {
return iterateBackward(pos) {
self.at($0) != c
}
}
func substr(pos: Int = 0, _ len: Int = String.npos) -> String {
let end = Int(min(UInt(pos) + UInt(len), UInt(length())))
return substringWithRange(startIndex.advancedBy(pos) ..< startIndex.advancedBy(end))
}
private func iterateForward(pos: Int, _ predicate: Int -> Bool) -> Int {
for index in pos.stride(to: length(), by: 1) {
if predicate(index) {
return index
}
}
return String.npos
}
private func iterateBackward(pos: Int, _ predicate: Int -> Bool) -> Int {
for index in min(length() - 1, pos).stride(through: 0, by: -1) {
if predicate(index) {
return index
}
}
return String.npos
}
}
// Not implemented methods
//
// Iterators
// =========
// reverse_iterator rbegin();
// const_reverse_iterator rbegin() const;
// reverse_iterator rend();
// const reverse_iterator rend() const;
//
// Capacity
// ========
// size_t max_size() const;
// size_t capacity() const;
//
// Element access
// ==============
// char& at(size_t pos);
//
// Modifiers
// =========
// template <class InputIterator> string& append(InputIterator first, InputIterator last);
// template <class InputIterator> string& assign(InputIterator first, InputIterator last);
// template <class InputIterator> void insert(iterator p, InputIterator first, InputIterator last);
// template <class InputIterator> string& replace(iterator i1, iterator i2, InputIterator first, InputIterator last);
//
// String operations
// =================
// const char* c_str() const;
// const char* data() const;
// allocator_type get_allocator() const;
// int compare(const string &str) const;
// int compare(size_t pos, size_t len, const string &str) const;
// int compare(size_t pos, size_t len, const string &str, size_t subpos, size_t sublen) const;
// int compare(const char *s) const;
// int compare(size_t pos, size_t len, const char *s) const;
// int compare(size_t pos, size_t len, const char *s, size_t n) const;
|
8a31c22d06a5c654d67df310d116feed
| 29.101928 | 117 | 0.560813 | false | false | false | false |
Sherlouk/monzo-vapor
|
refs/heads/master
|
Sources/JSON+AssertValue.swift
|
mit
|
1
|
import Foundation
import JSON
extension JSON {
/// Obtain the value for a given key, throws if the value can not be found and casted
func value<T>(forKey key: String) throws -> T {
if T.self is String.Type, let value = self[key]?.string as? T { return value }
if T.self is Bool.Type, let value = self[key]?.bool as? T { return value }
if T.self is URL.Type, let value = self[key]?.url as? T { return value }
if T.self is Date.Type, let value = self[key]?.date as? T { return value }
if T.self is Int.Type, let value = self[key]?.int as? T { return value }
if self[key] != nil {
throw MonzoJSONError.unsupportedType(String(describing: T.self))
}
throw MonzoJSONError.missingKey(key)
}
}
|
c436ae75d890f4c861085cdfb0bcdb8b
| 38.9 | 89 | 0.606516 | false | false | false | false |
open-telemetry/opentelemetry-swift
|
refs/heads/main
|
Examples/Simple Exporter/main.swift
|
apache-2.0
|
1
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
import JaegerExporter
import OpenTelemetryApi
import OpenTelemetrySdk
import ResourceExtension
import StdoutExporter
import ZipkinExporter
import SignPostIntegration
let sampleKey = "sampleKey"
let sampleValue = "sampleValue"
let resources = DefaultResources().get()
let instrumentationScopeName = "SimpleExporter"
let instrumentationScopeVersion = "semver:0.1.0"
var instrumentationScopeInfo = InstrumentationScopeInfo(name: instrumentationScopeName, version: instrumentationScopeVersion)
var tracer: TracerSdk
tracer = OpenTelemetrySDK.instance.tracerProvider.get(instrumentationName: instrumentationScopeName, instrumentationVersion: instrumentationScopeVersion) as! TracerSdk
func simpleSpan() {
let span = tracer.spanBuilder(spanName: "SimpleSpan").setSpanKind(spanKind: .client).startSpan()
span.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: 0.5)
span.end()
}
func childSpan() {
let span = tracer.spanBuilder(spanName: "parentSpan").setSpanKind(spanKind: .client).setActive(true).startSpan()
span.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: 0.2)
let childSpan = tracer.spanBuilder(spanName: "childSpan").setSpanKind(spanKind: .client).startSpan()
childSpan.setAttribute(key: sampleKey, value: sampleValue)
Thread.sleep(forTimeInterval: 0.5)
childSpan.end()
span.end()
}
let jaegerCollectorAdress = "localhost"
let jaegerExporter = JaegerSpanExporter(serviceName: "SimpleExporter", collectorAddress: jaegerCollectorAdress)
let stdoutExporter = StdoutExporter()
// let zipkinExporterOptions = ZipkinTraceExporterOptions()
// let zipkinExporter = ZipkinTraceExporter(options: zipkinExporterOptions)
let spanExporter = MultiSpanExporter(spanExporters: [jaegerExporter, stdoutExporter /* , zipkinExporter */ ])
let spanProcessor = SimpleSpanProcessor(spanExporter: spanExporter)
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(spanProcessor)
if #available(macOS 10.14, *) {
OpenTelemetrySDK.instance.tracerProvider.addSpanProcessor(SignPostIntegration())
}
simpleSpan()
sleep(1)
childSpan()
sleep(1)
|
7c09789b595ca1de1e1ccfc6a230c55e
| 33.584615 | 167 | 0.799822 | false | false | false | false |
2h4u/Async
|
refs/heads/master
|
Carthage/Checkouts/SwiftTask/Carthage/Checkouts/Async/AsyncTest/Tests/AsyncTests.swift
|
mit
|
2
|
//
// AsyncExample_iOSTests.swift
// AsyncExample iOSTests
//
// Created by Tobias DM on 15/07/14.
// Copyright (c) 2014 Tobias Due Munk. All rights reserved.
//
import Foundation
import XCTest
import Async
extension qos_class_t: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
class AsyncTests: 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()
}
// Typical testing time delay. Must be bigger than `timeMargin`
let timeDelay = 0.3
// Allowed error for timeDelay
let timeMargin = 0.2
/* GCD */
func testGCD() {
let expectation = self.expectation(description: "Expected after time")
let qos: DispatchQoS.QoSClass = .background
let queue = DispatchQueue.global(qos: qos)
queue.async {
XCTAssertEqual(qos_class_self(), qos.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
/* dispatch_async() */
func testAsyncMain() {
let expectation = self.expectation(description: "Expected on main queue")
var calledStuffAfterSinceAsync = false
Async.main {
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
XCTAssert(calledStuffAfterSinceAsync, "Should be async")
expectation.fulfill()
}
calledStuffAfterSinceAsync = true
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncUserInteractive() {
let expectation = self.expectation(description: "Expected on user interactive queue")
Async.userInteractive {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncUserInitiated() {
let expectation = self.expectation(description: "Expected on user initiated queue")
Async.userInitiated {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncUtility() {
let expectation = self.expectation(description: "Expected on utility queue")
Async.utility {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncBackground() {
let expectation = self.expectation(description: "Expected on background queue")
Async.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncCustomQueueConcurrent() {
let expectation = self.expectation(description: "Expected custom queue")
let label = "CustomQueueLabel"
let customQueue = DispatchQueue(label: label, attributes: [.concurrent])
let key = DispatchSpecificKey<String>()
customQueue.setSpecific(key: key, value: label)
Async.custom(queue: customQueue) {
XCTAssertEqual(DispatchQueue.getSpecific(key: key), label)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testAsyncCustomQueueSerial() {
let expectation = self.expectation(description: "Expected custom queue")
let label = "CustomQueueLabel"
let customQueue = DispatchQueue(label: label, attributes: [])
let key = DispatchSpecificKey<String>()
customQueue.setSpecific(key: key, value: label)
Async.custom(queue: customQueue) {
XCTAssertEqual(DispatchQueue.getSpecific(key: key), label)
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
/* Chaining */
func testAsyncBackgroundToMain() {
let expectation = self.expectation(description: "Expected on background to main queue")
var wasInBackground = false
Async.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
wasInBackground = true
}.main {
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
XCTAssert(wasInBackground, "Was in background first")
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin*2, handler: nil)
}
func testChaining() {
let expectation = self.expectation(description: "Expected On \(qos_class_self()) (expected \(DispatchQoS.QoSClass.userInitiated.rawValue))")
var id = 0
Async.main {
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
id += 1
XCTAssertEqual(id, 1, "Count main queue")
}.userInteractive {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
id += 1
XCTAssertEqual(id, 2, "Count user interactive queue")
}.userInitiated {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
id += 1
XCTAssertEqual(id, 3, "Count user initiated queue")
}.utility {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
id += 1
XCTAssertEqual(id, 4, "Count utility queue")
}.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
id += 1
XCTAssertEqual(id, 5, "Count background queue")
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin*5, handler: nil)
}
func testAsyncCustomQueueChaining() {
let expectation = self.expectation(description: "Expected custom queues")
var id = 0
let customQueue = DispatchQueue(label: "CustomQueueLabel", attributes: [.concurrent])
let otherCustomQueue = DispatchQueue(label: "OtherCustomQueueLabel", attributes: [])
Async.custom(queue: customQueue) {
id += 1
XCTAssertEqual(id, 1, "Count custom queue")
}.custom(queue: otherCustomQueue) {
id += 1
XCTAssertEqual(id, 2, "Count other custom queue")
expectation.fulfill()
}
waitForExpectations(timeout: timeMargin*2, handler: nil)
}
/* dispatch_after() */
func testAfterGCD() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
let time = DispatchTime.now() + timeDelay
let qos = DispatchQoS.QoSClass.background
let queue = DispatchQueue.global(qos: qos)
queue.asyncAfter(deadline: time) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), qos.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterMain() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.main(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterUserInteractive() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.userInteractive(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterUserInitated() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.userInitiated(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterUtility() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.utility(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterBackground() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let lowerTimeDelay = timeDelay - timeMargin
Async.background(after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterCustomQueue() {
let expectation = self.expectation(description: "Expected after time")
let date = Date()
let timeDelay = 1.0
let lowerTimeDelay = timeDelay - timeMargin
let label = "CustomQueueLabel"
let customQueue = DispatchQueue(label: label, attributes: [.concurrent])
let key = DispatchSpecificKey<String>()
customQueue.setSpecific(key: key, value: label)
Async.custom(queue: customQueue, after: timeDelay) {
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed >= lowerTimeDelay, "Should wait \(timePassed) >= \(lowerTimeDelay) seconds before firing")
XCTAssertEqual(DispatchQueue.getSpecific(key: key), label)
expectation.fulfill()
}
waitForExpectations(timeout: timeDelay + timeMargin, handler: nil)
}
func testAfterChainedMix() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.userInteractive(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
date2 = Date() // Update
}.utility(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
func testAfterChainedUserInteractive() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.userInteractive(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
date2 = Date() // Update
}.userInteractive(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
func testAfterChainedUserInitiated() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.userInitiated(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
date2 = Date() // Update
}.userInitiated(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
func testAfterChainedUtility() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.utility(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed)>=\(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
date2 = Date() // Update
}.utility(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) * 2, handler: nil)
}
func testAfterChainedBackground() {
let expectation = self.expectation(description: "Expected after time")
let date1 = Date()
var date2 = Date()
let timeDelay1 = timeDelay
let lowerTimeDelay1 = timeDelay1 - timeMargin
let upperTimeDelay1 = timeDelay1 + timeMargin
let timeDelay2 = timeDelay
let lowerTimeDelay2 = timeDelay2 - timeMargin
var id = 0
Async.background(after: timeDelay1) {
id += 1
XCTAssertEqual(id, 1, "First after")
let timePassed = Date().timeIntervalSince(date1)
XCTAssert(timePassed >= lowerTimeDelay1, "Should wait \(timePassed) >= \(lowerTimeDelay1) seconds before firing")
XCTAssert(timePassed < upperTimeDelay1, "Shouldn't wait \(timePassed), but <\(upperTimeDelay1) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
date2 = Date() // Update
}.background(after: timeDelay2) {
id += 1
XCTAssertEqual(id, 2, "Second after")
let timePassed = Date().timeIntervalSince(date2)
XCTAssert(timePassed >= lowerTimeDelay2, "Should wait \(timePassed) >= \(lowerTimeDelay2) seconds before firing")
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectation.fulfill()
}
waitForExpectations(timeout: (timeDelay1 + timeDelay2) + timeMargin*2, handler: nil)
}
/* dispatch_block_cancel() */
func testCancel() {
let expectation = self.expectation(description: "Block1 should run")
let block1 = Async.background {
// Some work
Thread.sleep(forTimeInterval: 0.2)
expectation.fulfill()
}
let block2 = block1.background {
XCTFail("Shouldn't be reached, since cancelled")
}
Async.main(after: 0.1) {
block1.cancel() // First block is _not_ cancelled
block2.cancel() // Second block _is_ cancelled
}
waitForExpectations(timeout: 0.2 + 0.1 + timeMargin*3, handler: nil)
}
/* dispatch_wait() */
func testWait() {
var id = 0
let block = Async.background {
// Some work
Thread.sleep(forTimeInterval: 0.1)
id += 1
XCTAssertEqual(id, 1, "")
}
XCTAssertEqual(id, 0, "")
block.wait()
id += 1
XCTAssertEqual(id, 2, "")
}
func testWaitMax() {
var id = 0
let date = Date()
let upperTimeDelay = timeDelay + timeMargin
let block = Async.background {
id += 1
XCTAssertEqual(id, 1, "The id should be 1") // A
// Some work that takes longer than we want to wait for
Thread.sleep(forTimeInterval: self.timeDelay + self.timeMargin)
id += 1 // C
}
let idCheck = id // XCTAssertEqual is experienced to behave as a wait
XCTAssertEqual(idCheck, 0, "The id should be 0, since block is send to background")
// Wait
block.wait(seconds: timeDelay)
id += 1
XCTAssertEqual(id, 2, "The id should be 2, since the block has begun running") // B
let timePassed = Date().timeIntervalSince(date)
XCTAssert(timePassed < upperTimeDelay, "Shouldn't wait \(upperTimeDelay) seconds before firing")
}
/* Generics */
func testGenericsChain() {
let expectationBackground = self.expectation(description: "Expected on background queue")
let expectationMain = self.expectation(description: "Expected on main queue")
let testValue = 10
Async.background {
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectationBackground.fulfill()
return testValue
}.main { (value: Int) in
#if (arch(i386) || arch(x86_64)) && (os(iOS) || os(tvOS)) // Simulator
XCTAssert(Thread.isMainThread, "Should be on main thread (simulator)")
#else
XCTAssertEqual(qos_class_self(), qos_class_main())
#endif
expectationMain.fulfill()
XCTAssertEqual(value, testValue)
return
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testGenericsWait() {
let asyncBlock = Async.background {
return 10
}.utility {
return "T\($0)"
}
asyncBlock.wait()
XCTAssertEqual(asyncBlock.output, Optional("T10"))
}
func testGenericsWaitMax() {
var complete1 = false
var complete2 = false
let asyncBlock = Async.background {
complete1 = true
// Some work that takes longer than we want to wait for
Thread.sleep(forTimeInterval: self.timeDelay + self.timeMargin)
complete2 = true
return 10
}.utility { (_: Int) -> Void in }
asyncBlock.wait(seconds: timeMargin)
XCTAssertNil(asyncBlock.output)
XCTAssert(complete1, "Should have been set in background block")
XCTAssertFalse(complete2, "Should not have been set/reached in background block")
}
/* dispatch_apply() */
func testApplyUserInteractive() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.userInteractive(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInteractive.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: timeMargin, handler: nil)
}
func testApplyUserInitiated() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.userInitiated(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.userInitiated.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyUtility() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.utility(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.utility.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyBackground() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
Apply.background(count) { i in
XCTAssertEqual(qos_class_self(), DispatchQoS.QoSClass.background.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyCustomQueueConcurrent() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
let label = "CustomQueueConcurrentLabel"
let customQueue = DispatchQueue(label: label, qos: .utility, attributes: [.concurrent])
Apply.custom(queue: customQueue, iterations: count) { i in
XCTAssertEqual(qos_class_self(), customQueue.qos.qosClass.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testApplyCustomQueueSerial() {
let count = 3
let iterations = 0..<count
let expectations = iterations.map { expectation(description: "\($0)") }
let label = "CustomQueueSerialLabel"
let customQueue = DispatchQueue(label: label, qos: .utility, attributes: [])
Apply.custom(queue: customQueue, iterations: count) { i in
XCTAssertEqual(qos_class_self(), customQueue.qos.qosClass.rawValue)
expectations[i].fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
}
|
7da177ddcffe38c3a6c2a63b4e61665b
| 39.72561 | 148 | 0.624644 | false | true | false | false |
ichu501/FBSimulatorControl
|
refs/heads/master
|
fbsimctl/FBSimulatorControlKit/Sources/iOSRunner.swift
|
bsd-3-clause
|
1
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import Foundation
import FBSimulatorControl
import FBDeviceControl
extension CommandResultRunner {
static func unimplementedActionRunner(_ action: Action, target: FBiOSTarget, format: FBiOSTargetFormat) -> Runner {
let (eventName, maybeSubject) = action.reportable
var actionMessage = eventName.rawValue
if let subject = maybeSubject {
actionMessage += " \(subject.description)"
}
let message = "Action \(actionMessage) is unimplemented for target \(format.format(target))"
return CommandResultRunner(result: CommandResult.failure(message))
}
}
struct iOSActionProvider {
let context: iOSRunnerContext<(Action, FBiOSTarget, iOSReporter)>
func makeRunner() -> Runner? {
let (action, target, reporter) = self.context.value
switch action {
case .diagnose(let query, let format):
return DiagnosticsRunner(reporter, query, query, format)
case .install(let appPath):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Install,
subject: ControlCoreSubject(appPath as NSString),
interaction: FBCommandInteractions.installApplication(withPath: appPath, command: target)
)
case .uninstall(let appBundleID):
return iOSTargetRunner(reporter, EventName.Uninstall,ControlCoreSubject(appBundleID as NSString)) {
try target.uninstallApplication(withBundleID: appBundleID)
}
case .launchApp(let appLaunch):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Launch,
subject: ControlCoreSubject(appLaunch),
interaction: FBCommandInteractions.launchApplication(appLaunch, command: target)
)
case .listApps:
return iOSTargetRunner(reporter, nil, ControlCoreSubject(target as! ControlCoreValue)) {
let subject = ControlCoreSubject(target.installedApplications().map { $0.jsonSerializableRepresentation() } as NSArray)
reporter.reporter.reportSimple(EventName.ListApps, EventType.Discrete, subject)
}
case .record(let start):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Record,
subject: start,
interaction: start ? FBCommandInteractions.startRecording(withCommand: target) : FBCommandInteractions.stopRecording(withCommand: target)
)
case .terminate(let bundleID):
return iOSTargetRunner(
reporter: reporter,
name: EventName.Terminate,
subject: ControlCoreSubject(bundleID as NSString),
interaction: FBCommandInteractions.killApplication(withBundleID: bundleID, command: target)
)
default:
return nil
}
}
}
struct iOSTargetRunner : Runner {
let reporter: iOSReporter
let name: EventName?
let subject: EventReporterSubject
let interaction: FBInteractionProtocol
init(reporter: iOSReporter, name: EventName?, subject: EventReporterSubject, interaction: FBInteractionProtocol) {
self.reporter = reporter
self.name = name
self.subject = subject
self.interaction = interaction
}
init(_ reporter: iOSReporter, _ name: EventName?, _ subject: EventReporterSubject, _ action: @escaping (Void) throws -> Void) {
self.init(reporter: reporter, name: name, subject: subject, interaction: Interaction(action))
}
func run() -> CommandResult {
do {
if let name = self.name {
self.reporter.report(name, EventType.Started, self.subject)
}
try self.interaction.perform()
if let name = self.name {
self.reporter.report(name, EventType.Ended, self.subject)
}
} catch let error as NSError {
return .failure(error.description)
} catch let error as JSONError {
return .failure(error.description)
} catch {
return .failure("Unknown Error")
}
return .success(nil)
}
}
private struct DiagnosticsRunner : Runner {
let reporter: iOSReporter
let subject: ControlCoreValue
let query: FBDiagnosticQuery
let format: DiagnosticFormat
init(_ reporter: iOSReporter, _ subject: ControlCoreValue, _ query: FBDiagnosticQuery, _ format: DiagnosticFormat) {
self.reporter = reporter
self.subject = subject
self.query = query
self.format = format
}
func run() -> CommandResult {
reporter.reportValue(EventName.Diagnose, EventType.Started, query)
let diagnostics = self.fetchDiagnostics()
reporter.reportValue(EventName.Diagnose, EventType.Ended, query)
let subjects: [EventReporterSubject] = diagnostics.map { diagnostic in
return SimpleSubject(
EventName.Diagnostic,
EventType.Discrete,
ControlCoreSubject(diagnostic)
)
}
return .success(CompositeSubject(subjects))
}
func fetchDiagnostics() -> [FBDiagnostic] {
let diagnostics = self.reporter.target.diagnostics
let format = self.format
return diagnostics.perform(query).map { diagnostic in
switch format {
case .CurrentFormat:
return diagnostic
case .Content:
return FBDiagnosticBuilder(diagnostic: diagnostic).readIntoMemory().build()
case .Path:
return FBDiagnosticBuilder(diagnostic: diagnostic).writeOutToFile().build()
}
}
}
}
|
a43d3811bad1f8fcee1d861ae5991bfa
| 33.772152 | 145 | 0.705497 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Kickstarter-iOS/Features/Discovery/Views/Cells/ActivitySampleFollowCell.swift
|
apache-2.0
|
1
|
import KsApi
import Library
import Prelude
import UIKit
internal protocol ActivitySampleFollowCellDelegate: AnyObject {
/// Call when should go to activity screen.
func goToActivity()
}
internal final class ActivitySampleFollowCell: UITableViewCell, ValueCell {
fileprivate let viewModel: ActivitySampleFollowCellViewModelType = ActivitySampleFollowCellViewModel()
internal weak var delegate: ActivitySampleFollowCellDelegate?
@IBOutlet fileprivate var activityStackView: UIStackView!
@IBOutlet fileprivate var activityTitleLabel: UILabel!
@IBOutlet fileprivate var cardView: UIView!
@IBOutlet fileprivate var friendFollowLabel: UILabel!
@IBOutlet fileprivate var friendImageAndFollowStackView: UIStackView!
@IBOutlet fileprivate var friendImageView: CircleAvatarImageView!
@IBOutlet fileprivate var seeAllActivityButton: UIButton!
internal override func awakeFromNib() {
super.awakeFromNib()
self.seeAllActivityButton.addTarget(
self,
action: #selector(self.seeAllActivityButtonTapped),
for: .touchUpInside
)
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> activitySampleCellStyle
|> \.backgroundColor .~ discoveryPageBackgroundColor()
_ = self.activityStackView
|> activitySampleStackViewStyle
_ = self.activityTitleLabel
|> activitySampleTitleLabelStyle
_ = self.cardView
|> dropShadowStyleMedium()
_ = self.friendFollowLabel
|> activitySampleFriendFollowLabelStyle
_ = self.friendImageAndFollowStackView
|> UIStackView.lens.spacing .~ Styles.grid(2)
_ = self.friendImageView
|> ignoresInvertColorsImageViewStyle
_ = self.seeAllActivityButton
|> activitySampleSeeAllActivityButtonStyle
}
internal override func bindViewModel() {
super.bindViewModel()
self.friendFollowLabel.rac.text = self.viewModel.outputs.friendFollowText
self.viewModel.outputs.friendImageURL
.observeForUI()
.on(event: { [weak self] _ in
self?.friendImageView.af.cancelImageRequest()
self?.friendImageView.image = nil
})
.skipNil()
.observeValues { [weak self] url in
self?.friendImageView.af.setImage(withURL: url)
}
self.viewModel.outputs.goToActivity
.observeForUI()
.observeValues { [weak self] _ in
self?.delegate?.goToActivity()
}
}
internal func configureWith(value: Activity) {
self.viewModel.inputs.configureWith(activity: value)
}
@objc fileprivate func seeAllActivityButtonTapped() {
self.viewModel.inputs.seeAllActivityTapped()
}
}
|
93f5f8b29eb42054322b2eb6a8be1e58
| 27.619565 | 104 | 0.729966 | false | false | false | false |
belatrix/iOSAllStars
|
refs/heads/master
|
AllStarsV2/AllStarsV2/CommonClasses/CoredataMedia/CDMKeyChain.swift
|
apache-2.0
|
1
|
//
// CDMKeyChain.swift
// InicioSesion
//
// Created by Kenyi Rodriguez on 6/01/17.
// Copyright © 2017 Core Data Media. All rights reserved.
//
import UIKit
public class CDMKeyChain: NSObject {
//MARK: - Público
public class func dataDesdeKeychainConCuenta(_ cuenta : String, conServicio servicio : String) -> Data? {
let tienePermiso = self.dispositivoCorrecto()
if tienePermiso == true {
let data = self.keychainDataConCuenta(cuenta, conServicio: servicio)
return data
}else{
exit(-1)
}
return nil
}
@discardableResult public class func guardarDataEnKeychain(_ data : Data, conCuenta cuenta : String, conServicio servicio : String) -> Bool {
let tienePermiso = self.dispositivoCorrecto()
if tienePermiso == true {
let guardado = self.guardarEnKeychain(data, conCuenta: cuenta, conServicio: servicio)
return guardado
}else{
exit(-1)
}
return false
}
public class func eliminarKeychain(){
let arrayElementosSeguridad = [kSecClassGenericPassword,
kSecClassInternetPassword,
kSecClassCertificate,
kSecClassKey,
kSecClassIdentity]
for elementoSeguridad in arrayElementosSeguridad{
let query = [kSecClass as String : elementoSeguridad]
SecItemDelete(query as CFDictionary)
}
}
//MARK: - Privado
private class func dispositivoCorrecto() -> Bool {
//Descomentar para producción, ya que en el simulador tampoco deja ejecutar para evitar injections en el código.
/*
if FileManager.default.fileExists(atPath: "/Applications/Cydia.app") || FileManager.default.fileExists(atPath: "/Library/MobileSubstrate/MobileSubstrate.dylib") || FileManager.default.fileExists(atPath: "/bin/bash") || FileManager.default.fileExists(atPath: "/usr/sbin/sshd") || FileManager.default.fileExists(atPath: "/etc/apt") {
return false
}else{
let texto = "1234567890"
do{
try texto.write(toFile: "/private/cache.txt", atomically: true, encoding: String.Encoding.utf8)
return false
}catch{
if UIApplication.shared.canOpenURL(URL(string: "cydia://package/com.example.package")!) {
return false
}else{
return true
}
}
}*/
return true
}
private class func keychainDataConCuenta(_ cuenta : String, conServicio servicio : String) -> Data? {
let query : [String : Any] = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : cuenta,
kSecAttrService as String : servicio,
kSecMatchCaseInsensitive as String : kCFBooleanTrue,
kSecReturnData as String : kCFBooleanTrue]
var resultado : AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &resultado)
if status == noErr && resultado != nil {
return resultado as? Data
}
return nil
}
private class func guardarEnKeychain(_ data : Data, conCuenta cuenta : String, conServicio servicio : String) -> Bool {
let keychainData = data as CFData
let query : [String : Any] = [kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : cuenta,
kSecAttrService as String : servicio,
kSecValueData as String : keychainData as Data,
kSecAttrAccessible as String : kSecAttrAccessibleWhenUnlocked as String]
var keychainError = noErr
keychainError = SecItemAdd(query as CFDictionary, nil)
return keychainError == noErr ? true : false
}
}
|
54b2ad85eb9a283c24dd5336f4a2fa6a
| 31.524138 | 339 | 0.511874 | false | false | false | false |
luisfcofv/rasgos-geometricos
|
refs/heads/master
|
rasgos-geometricos/Classes/Utilities/TanimotoDistance.swift
|
mit
|
1
|
//
// TanimotoDistance.swift
// rasgos-geometricos
//
// Created by Luis Flores on 3/7/15.
// Copyright (c) 2015 Luis Flores. All rights reserved.
//
import UIKit
class TanimotoDistance: NSObject {
class func tanimotoDistance(objectA:BinaryObject, objectB:BinaryObject) -> Double {
var sharedPixels = 0
var diff = Coordinate(x: objectB.centerOfMass.x - objectA.centerOfMass.x,
y: objectB.centerOfMass.y - objectA.centerOfMass.y)
for row in 0..<objectB.rows {
for col in 0..<objectB.columns {
if row - diff.y < 0 || row - diff.y >= objectA.rows
|| col - diff.x < 0 || col - diff.y >= objectA.columns {
continue
}
if objectA.grid[row - diff.y][col - diff.x] == 1
&& objectB.grid[row][col] == 1 {
sharedPixels++
}
}
}
var activePixels = objectA.activePixels + objectB.activePixels
return Double(activePixels - 2 * sharedPixels) / Double(activePixels - sharedPixels)
}
}
|
692846d07a35085f90153bc8b7ca989e
| 30.972222 | 92 | 0.538662 | false | false | false | false |
bluelinelabs/Junction
|
refs/heads/master
|
Junction/Junction/StringSetting.swift
|
mit
|
1
|
//
// StringSetting.swift
// Junction
//
// Created by Jimmy McDermott on 7/5/16.
// Copyright © 2016 BlueLine Labs. All rights reserved.
//
import Foundation
import UIKit
public final class StringSetting: Setting {
public var placeholder: String?
public var defaultValue: String?
public var value: String
public var key: String
public init(placeholder: String?, defaultValue: String?, key: String, value: String, title: String?) {
self.placeholder = placeholder
self.defaultValue = defaultValue
self.key = key
self.value = value
super.init()
self.title = title
}
public override func configureCell(tableViewCell: UITableViewCell) {
super.configureCell(tableViewCell)
tableViewCell.textLabel!.text = "\(tableViewCell.textLabel!.text!) \(value)"
}
override public func store() {
JunctionKeeper.sharedInstance.addValueForKey(key, value: value)
}
}
|
fa78d178eb14c331bdcfe1e2e8ff9c50
| 25.945946 | 106 | 0.654965 | false | true | false | false |
bingoogolapple/SwiftNote-PartTwo
|
refs/heads/master
|
CAAnimation-01基本动画/CAAnimation-01基本动画/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// CAAnimation-01基本动画
//
// Created by bingoogol on 14/10/25.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
/**
要实现简单动画,通过touchBegan方法来触发
1.平移动画
*/
class ViewController: UIViewController {
weak var myView:UIView!
override func viewDidLoad() {
super.viewDidLoad()
var myView = UIView(frame: CGRectMake(50, 50, 100, 100))
myView.backgroundColor = UIColor.redColor()
self.view.addSubview(myView)
self.myView = myView
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
var touch = touches.anyObject() as UITouch
var location = touch.locationInView(self.view)
// 将myView平移到手指触摸的目标点
// self.translationAnim(location)
if touch.view == self.myView {
println("点击myView")
}
// 苹果通过块代码封装后实现相同的效果
// UIView.animateWithDuration(1.0, animations: {
// self.myView.center = location
// },completion: { (finished:Bool) in
// println("结束动画 frame:\(self.myView.frame)")
// }
// )
}
///////////////////CABasic动画//////////////////
// 动画代理方法
// 动画开始(极少用)
override func animationDidStart(anim: CAAnimation!) {
println("开始动画")
}
// 动画结束(通常在动画结束后,做动画的后续处理)
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
var type = anim.valueForKey("animationType") as NSString
if type.isEqualToString("translationTo") {
// 通过键值取出需要移动到的目标点
var point = (anim.valueForKey("targetPoint") as NSValue).CGPointValue()
println("目标点:\(NSStringFromCGPoint(point))")
self.myView.center = point
}
println("结束动画 frame:\(self.myView.frame)")
}
// 平移动画到指定点
func translationAnim(point:CGPoint) {
// 1.实例化动画
// 注意:如果没有指定图层的锚点(定位点),position对应UIView的中心点
var anim = CABasicAnimation(keyPath: "position")
// 2.设置动画属性
// 1)fromValue(myView的当前坐标) & toValue
anim.toValue = NSValue(CGPoint: point)
// 2)动画的时长
anim.duration = 1.0
// 3)设置代理
anim.delegate = self
// 4)让动画停留在目标位置
/*
提示:通过设置动画在完成后不删除,以及向前填充,可以做到平移动画结束后
UIView看起来停留在目标位置,但是其本身的frame并不会发生变化
*/
// 5)注意:要修正坐标点的实际位置可以利用setValue方法,这里的key可以随意写
anim.setValue(NSValue(CGPoint: point), forKey: "targetPoint")
anim.setValue("translationTo", forKey: "animationType")
anim.removedOnCompletion = false
// forward逐渐逼近目标点
anim.fillMode = kCAFillModeForwards
// 3.将动画添加到图层
// 将动画添加到图层之后,系统会按照定义好的属性开始动画,通常程序员不在与动画进行交互
self.myView.layer.addAnimation(anim, forKey: nil)
}
}
|
d73232e876860150e35e425b49260cdb
| 28.309278 | 83 | 0.590781 | false | false | false | false |
jkolb/midnightbacon
|
refs/heads/master
|
MidnightBacon/Modules/Main/MainFlowController.swift
|
mit
|
1
|
//
// MainFlowController.swift
// MidnightBacon
//
// Copyright (c) 2015 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import Common
class MainFlowController : TabFlowController {
weak var factory: MainFactory!
var debugFlowController: DebugFlowController!
var subredditsFlowController: SubredditsFlowController!
var accountsFlowController: AccountsFlowController!
var messagesFlowController: MessagesFlowController!
var tabController: TabBarController!
override func loadViewController() {
tabController = TabBarController()
tabBarController = tabController // Fix this!
viewController = tabController
}
override func viewControllerDidLoad() {
tabBarController.delegate = self
tabBarController.viewControllers = [
startSubredditsFlow(),
startMessagesFlow(),
startAccountsFlow(),
]
}
func startSubredditsFlow() -> UIViewController {
subredditsFlowController = factory.subredditsFlowController()
let viewController = subredditsFlowController.start()
viewController.title = "Subreddits"
viewController.tabBarItem = UITabBarItem(title: "Subreddits", image: UIImage(named: "subreddits_unselected"), selectedImage: UIImage(named: "subreddits_selected"))
return viewController
}
func startAccountsFlow() -> UIViewController {
accountsFlowController = factory.accountsFlowController()
let viewController = accountsFlowController.start()
viewController.title = "Accounts"
viewController.tabBarItem = UITabBarItem(title: "Accounts", image: UIImage(named: "accounts_unselected"), selectedImage: UIImage(named: "accounts_selected"))
return viewController
}
func startMessagesFlow() -> UIViewController {
messagesFlowController = factory.messagesFlowController()
let viewController = messagesFlowController.start()
viewController.title = "Messages"
viewController.tabBarItem = UITabBarItem(title: "Messages", image: UIImage(named: "messages_unselected"), selectedImage: UIImage(named: "messages_selected"))
return viewController
}
}
extension MainFlowController : TabBarControllerDelegate {
func tabBarControllerDidDetectShake(tabBarController: TabBarController) {
if debugFlowController == nil {
debugFlowController = DebugFlowController()
debugFlowController.factory = factory
debugFlowController.delegate = self
}
if debugFlowController.canStart {
presentAndStartFlow(debugFlowController, animated: true, completion: nil)
}
}
}
extension MainFlowController : DebugFlowControllerDelegate {
func debugFlowControllerDidCancel(debugFlowController: DebugFlowController) {
debugFlowController.stopAnimated(true) { [weak self] in
self?.debugFlowController = nil
}
}
}
|
2e4b915ae3e99f860564851bf4be9e08
| 39.98 | 171 | 0.717423 | false | false | false | false |
mperovic/my41
|
refs/heads/master
|
my41/Classes/PreferencesMenu.swift
|
bsd-3-clause
|
1
|
//
// PreferencesMenu.swift
// my41
//
// Created by Miroslav Perovic on 11/16/14.
// Copyright (c) 2014 iPera. All rights reserved.
//
import Foundation
import Cocoa
class PreferencesMenuViewController: NSViewController {
var calculatorView: SelectedPreferencesView?
var modsView: SelectedPreferencesView?
var preferencesContainerViewController: PreferencesContainerViewController?
@IBOutlet weak var menuView: NSView!
override func viewWillAppear() {
}
override func viewDidLayout() {
if calculatorView != nil {
calculatorView?.removeFromSuperview()
}
calculatorView = SelectedPreferencesView(
frame: CGRect(
x: 0.0,
y: self.menuView.frame.height - 38.0,
width: 184.0,
height: 24.0
)
)
calculatorView?.text = "Calculator"
calculatorView?.selected = true
self.menuView.addSubview(calculatorView!)
if modsView != nil {
modsView?.removeFromSuperview()
}
modsView = SelectedPreferencesView(
frame: CGRect(
x: 0.0,
y: self.menuView.frame.height - 65.0,
width: 184.0,
height: 24.0
)
)
modsView?.text = "MODs"
modsView?.selected = false
self.menuView.addSubview(modsView!)
}
// MARK: Actions
@IBAction func selectCalculatorAction(sender: AnyObject) {
calculatorView?.selected = true
modsView?.selected = false
calculatorView!.setNeedsDisplay(calculatorView!.bounds)
modsView!.setNeedsDisplay(modsView!.bounds)
preferencesContainerViewController?.loadPreferencesCalculatorViewController()
}
@IBAction func selectModAction(sender: AnyObject) {
calculatorView?.selected = false
modsView?.selected = true
calculatorView!.setNeedsDisplay(calculatorView!.bounds)
modsView!.setNeedsDisplay(modsView!.bounds)
preferencesContainerViewController?.loadPreferencesModsViewController()
}
}
class PreferencesMenuView: NSView {
override func awakeFromNib() {
let viewLayer: CALayer = CALayer()
viewLayer.backgroundColor = CGColor(red: 0.9843, green: 0.9804, blue: 0.9725, alpha: 1.0)
self.wantsLayer = true
self.layer = viewLayer
}
}
//MARK: -
class PreferencesMenuLabelView: NSView {
override func awakeFromNib() {
let viewLayer: CALayer = CALayer()
viewLayer.backgroundColor = CGColor(red: 0.8843, green: 0.8804, blue: 0.8725, alpha: 1.0)
self.wantsLayer = true
self.layer = viewLayer
}
}
class SelectedPreferencesView: NSView {
var text: NSString?
var selected: Bool?
override func draw(_ dirtyRect: NSRect) {
//// Color Declarations
let backColor = NSColor(calibratedRed: 0.1569, green: 0.6157, blue: 0.8902, alpha: 0.95)
let textColor = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 1)
let font = NSFont(name: "Helvetica Bold", size: 14.0)
let textRect: NSRect = NSMakeRect(5, 3, 125, 18)
let textStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
textStyle.alignment = .left
if selected! {
//// Rectangle Drawing
let rectangleCornerRadius: CGFloat = 5
let rectangleRect = NSMakeRect(0, 0, 184, 24)
let rectangleInnerRect = NSInsetRect(rectangleRect, rectangleCornerRadius, rectangleCornerRadius)
let rectanglePath = NSBezierPath()
rectanglePath.move(to: NSMakePoint(NSMinX(rectangleRect), NSMinY(rectangleRect)))
rectanglePath.appendArc(
withCenter: NSMakePoint(NSMaxX(rectangleInnerRect), NSMinY(rectangleInnerRect)),
radius: rectangleCornerRadius,
startAngle: 270,
endAngle: 360
)
rectanglePath.appendArc(
withCenter: NSMakePoint(NSMaxX(rectangleInnerRect), NSMaxY(rectangleInnerRect)),
radius: rectangleCornerRadius,
startAngle: 0,
endAngle: 90
)
rectanglePath.line(to: NSMakePoint(NSMinX(rectangleRect), NSMaxY(rectangleRect)))
rectanglePath.close()
backColor.setFill()
rectanglePath.fill()
if let actualFont = font {
let textFontAttributes = [
NSAttributedString.Key.font: actualFont,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle: textStyle
]
text?.draw(in: NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}
} else {
if let actualFont = font {
let textFontAttributes = [
NSAttributedString.Key.font: actualFont,
NSAttributedString.Key.foregroundColor: backColor,
NSAttributedString.Key.paragraphStyle: textStyle
]
text?.draw(in: NSOffsetRect(textRect, 0, 1), withAttributes: textFontAttributes)
}
}
}
}
|
483dd94fdba062d819f89515d2fe5a3c
| 27.538462 | 100 | 0.728212 | false | false | false | false |
L3-DANT/findme-app
|
refs/heads/master
|
findme/Service/JsonSerializer.swift
|
mit
|
1
|
//
// JsonSerializer.swift
// findme
//
// Created by Maxime Signoret on 29/05/16.
// Copyright © 2016 Maxime Signoret. All rights reserved.
//
import Foundation
/// Handles Convertion from instances of objects to JSON strings. Also helps with casting strings of JSON to Arrays or Dictionaries.
public class JSONSerializer {
/**
Errors that indicates failures of JSONSerialization
- JsonIsNotDictionary: -
- JsonIsNotArray: -
- JsonIsNotValid: -
*/
public enum JSONSerializerError: ErrorType {
case JsonIsNotDictionary
case JsonIsNotArray
case JsonIsNotValid
}
//http://stackoverflow.com/questions/30480672/how-to-convert-a-json-string-to-a-dictionary
/**
Tries to convert a JSON string to a NSDictionary. NSDictionary can be easier to work with, and supports string bracket referencing. E.g. personDictionary["name"].
- parameter jsonString: JSON string to be converted to a NSDictionary.
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotDictionary. JsonIsNotDictionary will typically be thrown if you try to parse an array of JSON objects.
- returns: A NSDictionary representation of the JSON string.
*/
public static func toDictionary(jsonString: String) throws -> NSDictionary {
if let dictionary = try jsonToAnyObject(jsonString) as? NSDictionary {
return dictionary
} else {
throw JSONSerializerError.JsonIsNotDictionary
}
}
/**
Tries to convert a JSON string to a NSArray. NSArrays can be iterated and each item in the array can be converted to a NSDictionary.
- parameter jsonString: The JSON string to be converted to an NSArray
- throws: Throws error of type JSONSerializerError. Either JsonIsNotValid or JsonIsNotArray. JsonIsNotArray will typically be thrown if you try to parse a single JSON object.
- returns: NSArray representation of the JSON objects.
*/
public static func toArray(jsonString: String) throws -> NSArray {
if let array = try jsonToAnyObject(jsonString) as? NSArray {
return array
} else {
throw JSONSerializerError.JsonIsNotArray
}
}
/**
Tries to convert a JSON string to AnyObject. AnyObject can then be casted to either NSDictionary or NSArray.
- parameter jsonString: JSON string to be converted to AnyObject
- throws: Throws error of type JSONSerializerError.
- returns: Returns the JSON string as AnyObject
*/
private static func jsonToAnyObject(jsonString: String) throws -> AnyObject? {
var any: AnyObject?
if let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding) {
do {
any = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
}
catch let error as NSError {
let sError = String(error)
NSLog(sError)
throw JSONSerializerError.JsonIsNotValid
}
}
return any
}
/**
Generates the JSON representation given any custom object of any custom class. Inherited properties will also be represented.
- parameter object: The instantiation of any custom class to be represented as JSON.
- returns: A string JSON representation of the object.
*/
public static func toJson(object: Any) -> String {
var json = "{"
let mirror = Mirror(reflecting: object)
var children = [(label: String?, value: Any)]()
let mirrorChildrenCollection = AnyRandomAccessCollection(mirror.children)!
children += mirrorChildrenCollection
var currentMirror = mirror
while let superclassChildren = currentMirror.superclassMirror()?.children {
let randomCollection = AnyRandomAccessCollection(superclassChildren)!
children += randomCollection
currentMirror = currentMirror.superclassMirror()!
}
var filteredChildren = [(label: String?, value: Any)]()
for (optionalPropertyName, value) in children {
if !optionalPropertyName!.containsString("notMapped_") {
filteredChildren += [(optionalPropertyName, value)]
}
}
let size = filteredChildren.count
var index = 0
for (optionalPropertyName, value) in filteredChildren {
/*let type = value.dynamicType
let typeString = String(type)
print("SELF: \(type)")*/
let propertyName = optionalPropertyName!
let property = Mirror(reflecting: value)
var handledValue = String()
if value is Int || value is Double || value is Float || value is Bool {
handledValue = String(value ?? "null")
}
else if let array = value as? [Int?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Double?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Float?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [Bool?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? String(value!) : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [String?] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += value != nil ? "\"\(value!)\"" : "null"
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? [String] {
handledValue += "["
for (index, value) in array.enumerate() {
handledValue += "\"\(value)\""
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if let array = value as? NSArray {
handledValue += "["
for (index, value) in array.enumerate() {
if !(value is Int) && !(value is Double) && !(value is Float) && !(value is Bool) && !(value is String) {
handledValue += toJson(value)
}
else {
handledValue += "\(value)"
}
handledValue += (index < array.count-1 ? ", " : "")
}
handledValue += "]"
}
else if property.displayStyle == Mirror.DisplayStyle.Class {
handledValue = toJson(value)
}
else if property.displayStyle == Mirror.DisplayStyle.Optional {
let str = String(value)
if str != "nil" {
handledValue = String(str).substringWithRange(str.startIndex.advancedBy(9)..<str.endIndex.advancedBy(-1))
} else {
handledValue = "null"
}
}
else {
handledValue = String(value) != "nil" ? "\"\(value)\"" : "null"
}
json += "\"\(propertyName)\": \(handledValue)" + (index < size-1 ? ", " : "")
index += 1
}
json += "}"
return json
}
}
|
1eef7a487adf400c1b83fe32386c9339
| 41.253731 | 193 | 0.543099 | false | false | false | false |
safx/IIJMioKit
|
refs/heads/swift-2.0
|
IIJMioKitSample/PacketLogCell.swift
|
mit
|
1
|
//
// PacketLogCell.swift
// IIJMioKit
//
// Created by Safx Developer on 2015/05/16.
// Copyright (c) 2015年 Safx Developers. All rights reserved.
//
import UIKit
import IIJMioKit
class PacketLogCell: UITableViewCell {
@IBOutlet weak var date: UILabel!
@IBOutlet weak var withCoupon: UILabel!
@IBOutlet weak var withoutCoupon: UILabel!
private let dateFormatter = NSDateFormatter()
var model: MIOPacketLog? {
didSet { modelDidSet() }
}
private func modelDidSet() {
dateFormatter.dateFormat = "YYYY-MM-dd"
date!.text = dateFormatter.stringFromDate(model!.date)
let f = NSByteCountFormatter()
f.allowsNonnumericFormatting = false
f.allowedUnits = [.UseMB, .UseGB]
withCoupon!.text = f.stringFromByteCount(Int64(model!.withCoupon * 1000 * 1000))
withoutCoupon!.text = f.stringFromByteCount(Int64(model!.withoutCoupon * 1000 * 1000))
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
95314a97a1864da43fc003f080fbe3be
| 26.266667 | 94 | 0.667482 | false | false | false | false |
zxwWei/SwfitZeng
|
refs/heads/master
|
XWWeibo接收数据/XWWeibo/Classes/Model(模型)/NewFeature(新特性)/Controller/XWWelcomeVC.swift
|
apache-2.0
|
1
|
//
// XWWelcomeVC.swift
// XWWeibo
//
// Created by apple on 15/10/30.
// Copyright © 2015年 ZXW. All rights reserved.
//
import UIKit
import SDWebImage
class XWWelcomeVC: UIViewController {
// 定义底部约束
private var iconBottomConstriant: NSLayoutConstraint?
override func viewDidLoad() {
super.viewDidLoad()
prepareUI()
// 有值时进入
if let urlStr = XWUserAccount.loadAccount()?.avatar_large{
// MARK: - 未完成 从网上下载图片 从网络上获取图片资源
iconView.sd_setImageWithURL(NSURL(string: urlStr), placeholderImage: UIImage(named: "avatar_default_big"))
}
}
// MARK: - 当界面出现时,出现动画
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
iconBottomConstriant?.constant = -(UIScreen.mainScreen().bounds.height - 160)
// 有弹簧效果的动画
// usingSpringWithDamping: 值越小弹簧效果越明显 0 - 1
// initialSpringVelocity: 初速度
UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: { (_) -> Void in
UIView.animateWithDuration(1, animations: { () -> Void in
self.welcomeLabel.alpha = 1
}, completion: { (_) -> Void in
// MARK: - 当显示完成时做的事 进入访客视图
((UIApplication.sharedApplication().delegate) as! AppDelegate).switchRootController(true)
})
})
}
// MARK: - 布局UI
private func prepareUI() {
// 添加子控件
view.addSubview(bgView)
view.addSubview(iconView)
view.addSubview(welcomeLabel)
bgView.translatesAutoresizingMaskIntoConstraints = false
iconView.translatesAutoresizingMaskIntoConstraints = false
welcomeLabel.translatesAutoresizingMaskIntoConstraints = false
// 添加约束 这是数组
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : bgView]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[bkg]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bkg" : bgView]))
// 头像
view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85))
view.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 85))
// 垂直 底部160
iconBottomConstriant = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160)
view.addConstraint(iconBottomConstriant!)
// 欢迎归来
// H
view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: welcomeLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
}
// MARK: 准备界面元素
/// 背景图片
private lazy var bgView: UIImageView = UIImageView(image: UIImage(named: "ad_background"))
/// 欢迎归来
private lazy var welcomeLabel: UILabel = {
let welcomeLabel = UILabel()
welcomeLabel.text = "欢迎归来"
welcomeLabel.alpha = 0
return welcomeLabel
}()
/// 头像
private lazy var iconView: UIImageView = {
let iconView = UIImageView(image: UIImage(named: "avatar_default_big"))
iconView.layer.cornerRadius = 42.5
iconView.clipsToBounds = true
return iconView
}()
}
|
d94f46472dd989e588f0a8c6f4e7c97a
| 34.414815 | 223 | 0.618072 | false | false | false | false |
Magiic/FireMock
|
refs/heads/master
|
FireMock/FireMockDebug.swift
|
mit
|
1
|
//
// FireMockDebug.swift
// FireMock
//
// Created by Haithem Ben harzallah on 08/02/2017.
// Copyright © 2017 haithembenharzallah. All rights reserved.
//
import Foundation
/// Quantity information debug.
public enum FireMockDebugLevel {
case low
case high
}
struct FireMockDebug {
static var prefix: String?
static var level: FireMockDebugLevel = .high
static func debug(message: String, level: FireMockDebugLevel) {
if FireMock.debugIsEnabled, (self.level == level || self.level == .high) {
print("\(prefix ?? "FireMock ") - \(message)")
}
}
}
|
2cc69f655f9c72a402e39698f587de65
| 22.384615 | 82 | 0.657895 | false | false | false | false |
richardpiazza/SOSwift
|
refs/heads/master
|
Sources/SOSwift/Person.swift
|
mit
|
1
|
import Foundation
public class Person: Thing {
/// An additional name for a Person, can be used for a middle name.
public var additionalName: String?
/// Physical address of the item.
public var address: PostalAddressOrText?
/// An organization that this person is affiliated with. For example, a
/// school/university, a club, or a team.
public var affiliation: Organization?
/// An organization that the person is an alumni of.
/// - **Inverse property**: _alumni_
public var alumniOf: EducationalOrganizationOrOrganization?
/// An award won by or for this item.
public var awards: [String]?
/// Date of birth.
public var birthDate: DateOnly?
/// The place where the person was born.
public var birthPlace: Place?
/// The brand(s) associated with a product or service, or the brand(s)
/// maintained by an organization or business person.
public var brands: [BrandOrOrganization]?
/// A child of the person.
public var children: [Person]?
/// A colleague of the person.
public var colleagues: [PersonOrURL]?
/// A contact point for a person or organization.
public var contactPoints: [ContactPoint]?
/// Date of death.
public var deathDate: DateOnly?
/// The place where the person died.
public var deathPlace: Place?
/// The Dun & Bradstreet DUNS number for identifying an organization or
/// business person.
public var duns: String?
/// Email address.
public var email: String?
/// Family name. In the U.S., the last name of an Person. This can be used
/// along with givenName instead of the name property.
public var familyName: String?
/// The fax number.
public var faxNumber: String?
/// The most generic uni-directional social relation.
public var follows: [Person]?
/// A person or organization that supports (sponsors) something through some
/// kind of financial contribution.
public var funder: OrganizationOrPerson?
/// Gender of the person. While http://schema.org/Male and
/// http://schema.org/Female may be used, text strings are also acceptable
/// for people who do not identify as a binary gender.
public var gender: GenderOrText?
/// Given name. In the U.S., the first name of a Person. This can be used
/// along with familyName instead of the name property.
public var givenName: String?
/// The Global Location Number (GLN, sometimes also referred to as
/// International Location Number or ILN) of the respective organization,
/// person, or place. The GLN is a 13-digit number used to identify parties
/// and physical locations.
public var globalLocationNumber: String?
/// Indicates an OfferCatalog listing for this Organization, Person, or
/// Service.
public var offerCatalog: OfferCatalog?
/// Points-of-Sales operated by the organization or person.
public var pointsOfSales: [Place]?
/// The height of the item.
public var height: DistanceOrQuantitativeValue?
/// A contact location for a person's residence.
public var homeLocation: ContactPointOrPlace?
/// An honorific prefix preceding a Person's name such as Dr/Mrs/Mr.
public var honorificPrefix: String?
/// An honorific suffix preceding a Person's name such as M.D. /PhD/MSCSW.
public var honorificSuffix: String?
/// The International Standard of Industrial Classification of All Economic
/// Activities (ISIC), Revision 4 code for a particular organization,
/// business person, or place.
public var isicV4: String?
/// The job title of the person (for example, Financial Manager).
public var jobTitle: String?
/// The most generic bi-directional social/work relation.
public var knows: [Person]?
/// A pointer to products or services offered by the organization or person.
/// - **Inverse property**: _offeredBy_
public var makesOffer: [Offer]?
/// An Organization (or ProgramMembership) to which this Person or
/// Organization belongs.
/// - **Inverse property**: _member_
public var memberOf: [OrganizationOrProgramMembership]?
/// The North American Industry Classification System (NAICS) code for a
/// particular organization or business person.
public var naics: String?
/// Nationality of the person.
public var nationality: Country?
/// The total financial value of the person as calculated by subtracting
/// assets from liabilities.
public var netWorth: MonetaryAmountOrPriceSpecification?
/// The Person's occupation. For past professions, use Role for expressing
/// dates.
public var occupation: Occupation?
/// Products owned by the organization or person.
public var owns: [ProductOrService]?
/// A parent of this person.
public var parents: [Person]?
/// Event that this person is a performer or participant in.
public var performerIn: Event?
/// The publishingPrinciples property indicates (typically via URL) a
/// document describing the editorial principles of an Organization (or
/// individual e.g. a Person writing a blog) that relate to their activities
/// as a publisher, e.g. ethics or diversity policies. When applied to a
/// CreativeWork (e.g. NewsArticle) the principles are those of the party
/// primarily responsible for the creation of the CreativeWork.
/// While such policies are most typically expressed in natural language,
/// sometimes related information (e.g. indicating a funder) can be
/// expressed using schema.org terminology.
public var publishingPrinciples: CreativeWorkOrURL?
/// The most generic familial relation.
public var relatedTo: [Person]?
/// A pointer to products or services sought by the organization or person
/// (demand).
public var seeks: [Demand]?
/// A sibling of the person.
public var siblings: [Person]?
/// A person or organization that supports a thing through a pledge,
/// promise, or financial contribution. e.g. a sponsor of a Medical Study or
/// a corporate sponsor of an event.
public var sponsor: OrganizationOrPerson?
/// The person's spouse.
public var spouse: Person?
/// The Tax / Fiscal ID of the organization or person, e.g. the TIN in the
/// US or the CIF/NIF in Spain.
public var taxID: String?
/// The telephone number.
public var telephone: String?
/// The Value-added Tax ID of the organization or person.
public var vatID: String?
/// The weight of the product or person.
public var weight: QuantitativeValue?
/// A contact location for a person's place of work.
public var workLocation: ContactPointOrPlace?
/// Organizations that the person works for.
public var worksFor: [Organization]?
internal enum PersonCodingKeys: String, CodingKey {
case additionalName
case address
case affiliation
case alumniOf
case awards = "award"
case birthDate
case birthPlace
case brands = "brand"
case children
case colleagues = "colleague"
case contactPoints = "contactPoint"
case deathDate
case deathPlace
case duns
case email
case familyName
case faxNumber
case follows
case funder
case gender
case givenName
case globalLocationNumber
case offerCatalog = "hasOfferCatalog"
case pointsOfSales = "hasPOS"
case height
case homeLocation
case honorificPrefix
case honorificSuffix
case isicV4
case jobTitle
case knows
case makesOffer
case memberOf
case naics
case nationality
case netWorth
case occupation = "hasOccupation"
case owns
case parents = "parent"
case performerIn
case publishingPrinciples
case relatedTo
case seeks
case siblings = "sibling"
case sponsor
case spouse
case taxID
case telephone
case vatID
case weight
case workLocation
case worksFor
}
public override init() {
super.init()
}
public required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: PersonCodingKeys.self)
additionalName = try container.decodeIfPresent(String.self, forKey: .additionalName)
address = try container.decodeIfPresent(PostalAddressOrText.self, forKey: .address)
affiliation = try container.decodeIfPresent(Organization.self, forKey: .affiliation)
alumniOf = try container.decodeIfPresent(EducationalOrganizationOrOrganization.self, forKey: .alumniOf)
awards = try container.decodeIfPresent([String].self, forKey: .awards)
birthDate = try container.decodeIfPresent(DateOnly.self, forKey: .birthDate)
birthPlace = try container.decodeIfPresent(Place.self, forKey: .birthPlace)
brands = try container.decodeIfPresent([BrandOrOrganization].self, forKey: .brands)
children = try container.decodeIfPresent([Person].self, forKey: .children)
colleagues = try container.decodeIfPresent([PersonOrURL].self, forKey: .colleagues)
contactPoints = try container.decodeIfPresent([ContactPoint].self, forKey: .contactPoints)
deathDate = try container.decodeIfPresent(DateOnly.self, forKey: .deathDate)
deathPlace = try container.decodeIfPresent(Place.self, forKey: .deathPlace)
duns = try container.decodeIfPresent(String.self, forKey: .duns)
email = try container.decodeIfPresent(String.self, forKey: .email)
familyName = try container.decodeIfPresent(String.self, forKey: .familyName)
faxNumber = try container.decodeIfPresent(String.self, forKey: .faxNumber)
follows = try container.decodeIfPresent([Person].self, forKey: .follows)
funder = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .funder)
gender = try container.decodeIfPresent(GenderOrText.self, forKey: .gender)
givenName = try container.decodeIfPresent(String.self, forKey: .givenName)
globalLocationNumber = try container.decodeIfPresent(String.self, forKey: .globalLocationNumber)
offerCatalog = try container.decodeIfPresent(OfferCatalog.self, forKey: .offerCatalog)
pointsOfSales = try container.decodeIfPresent([Place].self, forKey: .pointsOfSales)
height = try container.decodeIfPresent(DistanceOrQuantitativeValue.self, forKey: .height)
homeLocation = try container.decodeIfPresent(ContactPointOrPlace.self, forKey: .homeLocation)
honorificPrefix = try container.decodeIfPresent(String.self, forKey: .honorificPrefix)
honorificSuffix = try container.decodeIfPresent(String.self, forKey: .honorificSuffix)
isicV4 = try container.decodeIfPresent(String.self, forKey: .isicV4)
jobTitle = try container.decodeIfPresent(String.self, forKey: .jobTitle)
knows = try container.decodeIfPresent([Person].self, forKey: .knows)
makesOffer = try container.decodeIfPresent([Offer].self, forKey: .makesOffer)
memberOf = try container.decodeIfPresent([OrganizationOrProgramMembership].self, forKey: .memberOf)
naics = try container.decodeIfPresent(String.self, forKey: .naics)
nationality = try container.decodeIfPresent(Country.self, forKey: .nationality)
netWorth = try container.decodeIfPresent(MonetaryAmountOrPriceSpecification.self, forKey: .netWorth)
occupation = try container.decodeIfPresent(Occupation.self, forKey: .occupation)
owns = try container.decodeIfPresent([ProductOrService].self, forKey: .owns)
parents = try container.decodeIfPresent([Person].self, forKey: .parents)
performerIn = try container.decodeIfPresent(Event.self, forKey: .performerIn)
publishingPrinciples = try container.decodeIfPresent(CreativeWorkOrURL.self, forKey: .publishingPrinciples)
relatedTo = try container.decodeIfPresent([Person].self, forKey: .relatedTo)
seeks = try container.decodeIfPresent([Demand].self, forKey: .seeks)
siblings = try container.decodeIfPresent([Person].self, forKey: .siblings)
sponsor = try container.decodeIfPresent(OrganizationOrPerson.self, forKey: .sponsor)
spouse = try container.decodeIfPresent(Person.self, forKey: .spouse)
taxID = try container.decodeIfPresent(String.self, forKey: .taxID)
telephone = try container.decodeIfPresent(String.self, forKey: .telephone)
vatID = try container.decodeIfPresent(String.self, forKey: .vatID)
weight = try container.decodeIfPresent(QuantitativeValue.self, forKey: .weight)
workLocation = try container.decodeIfPresent(ContactPointOrPlace.self, forKey: .workLocation)
worksFor = try container.decodeIfPresent([Organization].self, forKey: .worksFor)
}
public override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: PersonCodingKeys.self)
try container.encodeIfPresent(additionalName, forKey: .additionalName)
try container.encodeIfPresent(address, forKey: .address)
try container.encodeIfPresent(affiliation, forKey: .affiliation)
try container.encodeIfPresent(alumniOf, forKey: .alumniOf)
try container.encodeIfPresent(awards, forKey: .awards)
try container.encodeIfPresent(birthDate, forKey: .birthDate)
try container.encodeIfPresent(birthPlace, forKey: .birthPlace)
try container.encodeIfPresent(brands, forKey: .brands)
try container.encodeIfPresent(children, forKey: .children)
try container.encodeIfPresent(colleagues, forKey: .colleagues)
try container.encodeIfPresent(contactPoints, forKey: .contactPoints)
try container.encodeIfPresent(deathDate, forKey: .deathDate)
try container.encodeIfPresent(deathPlace, forKey: .deathPlace)
try container.encodeIfPresent(duns, forKey: .duns)
try container.encodeIfPresent(email, forKey: .email)
try container.encodeIfPresent(familyName, forKey: .familyName)
try container.encodeIfPresent(faxNumber, forKey: .faxNumber)
try container.encodeIfPresent(follows, forKey: .follows)
try container.encodeIfPresent(funder, forKey: .funder)
try container.encodeIfPresent(gender, forKey: .gender)
try container.encodeIfPresent(givenName, forKey: .givenName)
try container.encodeIfPresent(globalLocationNumber, forKey: .globalLocationNumber)
try container.encodeIfPresent(offerCatalog, forKey: .offerCatalog)
try container.encodeIfPresent(pointsOfSales, forKey: .pointsOfSales)
try container.encodeIfPresent(height, forKey: .height)
try container.encodeIfPresent(homeLocation, forKey: .homeLocation)
try container.encodeIfPresent(honorificPrefix, forKey: .honorificPrefix)
try container.encodeIfPresent(honorificSuffix, forKey: .honorificSuffix)
try container.encodeIfPresent(isicV4, forKey: .isicV4)
try container.encodeIfPresent(jobTitle, forKey: .jobTitle)
try container.encodeIfPresent(knows, forKey: .knows)
try container.encodeIfPresent(makesOffer, forKey: .makesOffer)
try container.encodeIfPresent(memberOf, forKey: .memberOf)
try container.encodeIfPresent(naics, forKey: .naics)
try container.encodeIfPresent(nationality, forKey: .nationality)
try container.encodeIfPresent(netWorth, forKey: .netWorth)
try container.encodeIfPresent(occupation, forKey: .occupation)
try container.encodeIfPresent(owns, forKey: .owns)
try container.encodeIfPresent(parents, forKey: .parents)
try container.encodeIfPresent(performerIn, forKey: .performerIn)
try container.encodeIfPresent(publishingPrinciples, forKey: .publishingPrinciples)
try container.encodeIfPresent(relatedTo, forKey: .relatedTo)
try container.encodeIfPresent(seeks, forKey: .seeks)
try container.encodeIfPresent(siblings, forKey: .siblings)
try container.encodeIfPresent(sponsor, forKey: .sponsor)
try container.encodeIfPresent(spouse, forKey: .spouse)
try container.encodeIfPresent(taxID, forKey: .taxID)
try container.encodeIfPresent(telephone, forKey: .telephone)
try container.encodeIfPresent(vatID, forKey: .vatID)
try container.encodeIfPresent(weight, forKey: .weight)
try container.encodeIfPresent(workLocation, forKey: .workLocation)
try container.encodeIfPresent(worksFor, forKey: .worksFor)
try super.encode(to: encoder)
}
}
|
05d8ae043c0370a20b9e2774e7ea128a
| 45.248649 | 115 | 0.695185 | false | false | false | false |
sunkanmi-akintoye/todayjournal
|
refs/heads/master
|
weather-journal/Controllers/CreatePostViewController.swift
|
mit
|
1
|
//
// CreatePostViewController.swift
// weather-journal
//
// Created by Luke Geiger on 6/29/15.
// Copyright (c) 2015 Luke J Geiger. All rights reserved.
//
import UIKit
class CreatePostViewController: UIViewController,UITextViewDelegate {
var post:Post!
private var textView:UITextView!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.setupInterface()
}
private func setupInterface(){
self.view.backgroundColor = UIColor.whiteColor()
if (self.post == nil){
self.post = Post()
self.post.creationDate = NSDate()
self.post.text = "";
}
else{
self.navigationItem.title = self.post.displayTitle()
}
self.fetchWeather(){
(result: WeatherCondition?) in
self.post.createdBy = PFUser.currentUser()!
if (result != nil){
self.post.temperatureF = result!.feelsLikeF as String
self.post.weather = result!.weather as String
}
else{
self.post.temperatureF = "-"
self.post.weather = "Unknown"
}
}
self.textView = UITextView(frame: CGRectMake(0, 0, self.view.width, self.view.height-216))
self.textView?.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth
self.textView?.delegate = self;
self.textView?.tintColor = UIColor.appBlueColor()
self.textView.font = UIFont.appFontOfSize(14)
self.textView.textColor = UIColor.appDarkGreyColor()
self.textView.text = self.post!.text;
self.view.addSubview(self.textView!)
self.switchToEditingMode(true)
}
// MARK: - Actions
override func viewWillDisappear(animated:Bool) {
var length = count(self.textView.text)
if (length > 0){
self.post.text = self.textView.text
self.dismissKeyboard()
self.post.pinInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// The object has been saved.
} else {
// There was a problem, check error.description
}
super.viewWillDisappear(animated)
}
self.post.saveEventually(nil)
}
}
private func switchToEditingMode(flag:Bool){
if (flag == true){
self.showKeyboard()
}
else{
self.dismissKeyboard()
}
}
func dismissKeyboard(){
self.view.endEditing(true)
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.frame = CGRectMake(0, 0, 20, 20)
button.setImage(UIImage(named:"icon-keyboard-up"), forState: UIControlState.Normal)
button.addTarget(self, action: "showKeyboard", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = rightBarButtonItem
}
func showKeyboard(){
self.textView.becomeFirstResponder()
let button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
button.frame = CGRectMake(0, 0, 20, 20)
button.setImage(UIImage(named:"icon-keyboard-down"), forState: UIControlState.Normal)
button.addTarget(self, action: "dismissKeyboard", forControlEvents: UIControlEvents.TouchUpInside)
var rightBarButtonItem: UIBarButtonItem = UIBarButtonItem(customView: button)
self.navigationItem.rightBarButtonItem = rightBarButtonItem
}
// MARK: - Wunderground API
private func fetchWeather(completion: (result: WeatherCondition?) -> Void){
PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in
let manager = AFHTTPRequestOperationManager()
var locationParams:NSDictionary = [
"lat" : NSString(format:"%f", geoPoint!.latitude),
"lng" : NSString(format:"%f", geoPoint!.longitude)
]
let endPoint = self.weatherUnderGroundGeolookupEndpoint(locationParams)
manager.GET(endPoint,
parameters: nil,
success: {
(operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
let geojsonResult:NSDictionary = responseObject as! NSDictionary
if ((geojsonResult.objectForKey("location") != nil)){
let locationDict = geojsonResult.objectForKey("location") as! NSDictionary
let weatherRequestURL = locationDict.objectForKey("requesturl") as! String
let weatherRequestURLJson = weatherRequestURL.stringByReplacingOccurrencesOfString(".html", withString: ".json", options: NSStringCompareOptions.LiteralSearch, range: nil)
let conditionsEndpoint = self.weatherUnderGroundConditionsEndpoint(weatherRequestURLJson)
manager.GET(conditionsEndpoint,
parameters: nil,
success: {
(operation: AFHTTPRequestOperation!,responseObject: AnyObject!) in
var conditionjsonResult:NSDictionary = responseObject as! NSDictionary
var currentObservationDict = conditionjsonResult.objectForKey("current_observation") as! NSDictionary
completion(result: WeatherCondition(jsonDict: currentObservationDict))
},
failure: {
(operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error:" + error.localizedDescription)
completion(result: nil)
})
}
else{
println("Could not get location:")
completion(result: nil)
}
},
failure: {
(operation: AFHTTPRequestOperation!,error: NSError!) in
println("Error:" + error.localizedDescription)
completion(result: nil)
})
}
}
private func weatherUnderGroundRootAPIString()->String{
return "http://api.wunderground.com/api/c8d9b1271b46e705/"
}
private func weatherUnderGroundConditionsEndpoint(cityEndpoint:String)->String{
return weatherUnderGroundRootAPIString() + "conditions/q/" + cityEndpoint
}
private func weatherUnderGroundGeolookupEndpoint(locationDict:NSDictionary)->String{
var latString = locationDict.objectForKey("lat") as! String
var lngString = locationDict.objectForKey("lng") as! String
return self.weatherUnderGroundRootAPIString() + "geolookup/q/" + latString + "," + lngString + ".json"
}
}
|
bd0cc4e6e0bf2e5843f22cfb87b32878
| 38.801075 | 195 | 0.574902 | false | false | false | false |
diiingdong/InnerShadowTest
|
refs/heads/master
|
InnerShadowTest/UIViewExtension.swift
|
mit
|
1
|
import UIKit
extension UIView
{
// different inner shadow styles
public enum innerShadowSide
{
case all, left, right, top, bottom, topAndLeft, topAndRight, bottomAndLeft, bottomAndRight, exceptLeft, exceptRight, exceptTop, exceptBottom
}
// define function to add inner shadow
public func addInnerShadow(onSide: innerShadowSide, shadowColor: UIColor, shadowSize: CGFloat, cornerRadius: CGFloat = 0.0, shadowOpacity: Float)
{
// define and set a shaow layer
let shadowLayer = CAShapeLayer()
shadowLayer.frame = bounds
shadowLayer.shadowColor = shadowColor.cgColor
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 0.0)
shadowLayer.shadowOpacity = shadowOpacity
shadowLayer.shadowRadius = shadowSize
shadowLayer.fillRule = kCAFillRuleEvenOdd
// define shadow path
let shadowPath = CGMutablePath()
// define outer rectangle to restrict drawing area
let insetRect = bounds.insetBy(dx: -shadowSize * 2.0, dy: -shadowSize * 2.0)
// define inner rectangle for mask
let innerFrame: CGRect = { () -> CGRect in
switch onSide
{
case .all:
return CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: frame.size.height)
case .left:
return CGRect(x: 0.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 4.0)
case .right:
return CGRect(x: -shadowSize * 2.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 4.0)
case .top:
return CGRect(x: -shadowSize * 2.0, y: 0.0, width: frame.size.width + shadowSize * 4.0, height: frame.size.height + shadowSize * 2.0)
case.bottom:
return CGRect(x: -shadowSize * 2.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 4.0, height: frame.size.height + shadowSize * 2.0)
case .topAndLeft:
return CGRect(x: 0.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0)
case .topAndRight:
return CGRect(x: -shadowSize * 2.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0)
case .bottomAndLeft:
return CGRect(x: 0.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0)
case .bottomAndRight:
return CGRect(x: -shadowSize * 2.0, y: -shadowSize * 2.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height + shadowSize * 2.0)
case .exceptLeft:
return CGRect(x: -shadowSize * 2.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height)
case .exceptRight:
return CGRect(x: 0.0, y: 0.0, width: frame.size.width + shadowSize * 2.0, height: frame.size.height)
case .exceptTop:
return CGRect(x: 0.0, y: -shadowSize * 2.0, width: frame.size.width, height: frame.size.height + shadowSize * 2.0)
case .exceptBottom:
return CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: frame.size.height + shadowSize * 2.0)
}
}()
// add outer and inner rectangle to shadow path
shadowPath.addRect(insetRect)
shadowPath.addRect(innerFrame)
// set shadow path as show layer's
shadowLayer.path = shadowPath
// add shadow layer as a sublayer
layer.addSublayer(shadowLayer)
// hide outside drawing area
clipsToBounds = true
}
}
|
f295d52fefefd0c7073c51ece0c9b0b1
| 51.026316 | 167 | 0.584977 | false | false | false | false |
richardxyx/Forecast
|
refs/heads/master
|
Forecast/SettingsViewController.swift
|
mit
|
1
|
//
// AboutViewController.swift
// Forecast
//
// Created by Kyle Bashour on 11/12/15.
// Copyright © 2015 Richard Neitzke. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
var delegate: WeatherViewController?
var reloadRequired = false
//Dismisses the view and reloads the WeatherViewController in case the unit preference changed
@IBAction func dismissPressed(sender: UIBarButtonItem) {
if reloadRequired {delegate?.refresh()}
dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var unitControl: UISegmentedControl!
//Changes the unit preference
@IBAction func unitControl(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0: defaults.setValue("us", forKey: "unit")
case 1: defaults.setValue("si", forKey: "unit")
default: defaults.setValue("auto", forKey: "unit")
}
reloadRequired = true
}
let defaults = NSUserDefaults.standardUserDefaults()
//Marks the current unit preference
override func viewWillAppear(animated: Bool) {
switch defaults.valueForKey("unit") as? String {
case "us"?: unitControl.selectedSegmentIndex = 0
case "si"?: unitControl.selectedSegmentIndex = 1
//Sets the current unit setting to auto in case the unit never changed
default:
defaults.setValue("auto", forKey: "unit")
unitControl.selectedSegmentIndex = 2
}
reloadRequired = false
}
//Makes Navigation Bar Transparent
override func viewDidLoad() {
let bar:UINavigationBar! = self.navigationController?.navigationBar
bar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
bar.shadowImage = UIImage()
bar.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0)
bar.barStyle = .BlackTranslucent
}
//Manages the text color of the headers
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = UIColor.whiteColor()
header.alpha = 0.5
}
//Opens the right link in Safari if a link is pressed
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath == NSIndexPath(forItem: 1, inSection: 1)
{ UIApplication.sharedApplication().openURL(NSURL(string:"https://github.com/richardxyx")!) }
if indexPath == NSIndexPath(forItem: 0, inSection: 2)
{ UIApplication.sharedApplication().openURL(NSURL(string:"http://forecast.io")!) }
if indexPath == NSIndexPath(forItem: 1, inSection: 2)
{ UIApplication.sharedApplication().openURL(NSURL(string:"http://weathericons.io")!) }
if indexPath == NSIndexPath(forItem: 2, inSection: 2)
{ UIApplication.sharedApplication().openURL(NSURL(string:"https://icons8.com")!) }
if indexPath == NSIndexPath(forItem: 0, inSection: 3)
{ UIApplication.sharedApplication().openURL(NSURL(string:"https://github.com/kylebshr")!) }
if indexPath == NSIndexPath(forItem: 1, inSection: 3)
{ UIApplication.sharedApplication().openURL(NSURL(string:"https://github.com/lapfelix")!) }
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
|
0714af7011f163f0bd92a9422fa5ee1d
| 38.108696 | 114 | 0.663424 | false | false | false | false |
HabitRPG/habitrpg-ios
|
refs/heads/develop
|
Habitica API Client/Habitica API Client/Models/User/APIUserItems.swift
|
gpl-3.0
|
1
|
//
// APIUserItems.swift
// Habitica API Client
//
// Created by Phillip Thelen on 09.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
public class APIUserItems: UserItemsProtocol, Decodable {
public var gear: UserGearProtocol?
public var currentMount: String?
public var currentPet: String?
public var ownedQuests: [OwnedItemProtocol]
public var ownedFood: [OwnedItemProtocol]
public var ownedHatchingPotions: [OwnedItemProtocol]
public var ownedEggs: [OwnedItemProtocol]
public var ownedSpecialItems: [OwnedItemProtocol]
public var ownedPets: [OwnedPetProtocol]
public var ownedMounts: [OwnedMountProtocol]
enum CodingKeys: String, CodingKey {
case gear
case currentMount
case currentPet
case ownedQuests = "quests"
case ownedFood = "food"
case ownedHatchingPotions = "hatchingPotions"
case ownedEggs = "eggs"
case ownedSpecialItems = "special"
case ownedPets = "pets"
case ownedMounts = "mounts"
}
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
gear = try? values.decode(APIUserGear.self, forKey: .gear)
currentPet = try? values.decode(String.self, forKey: .currentPet)
currentMount = try? values.decode(String.self, forKey: .currentMount)
let questsDict = try?values.decode([String: Int].self, forKey: .ownedQuests)
ownedQuests = (questsDict?.map({ (key, numberOwned) -> OwnedItemProtocol in
return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.quests.rawValue)
})) ?? []
let foodDict = try?values.decode([String: Int].self, forKey: .ownedFood)
ownedFood = (foodDict?.map({ (key, numberOwned) -> OwnedItemProtocol in
return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.food.rawValue)
})) ?? []
let hatchingPotionsDict = try?values.decode([String: Int].self, forKey: .ownedHatchingPotions)
ownedHatchingPotions = (hatchingPotionsDict?.map({ (key, numberOwned) -> OwnedItemProtocol in
return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.hatchingPotions.rawValue)
})) ?? []
let eggsDict = try? values.decode([String: Int].self, forKey: .ownedEggs)
ownedEggs = (eggsDict?.map({ (key, numberOwned) -> OwnedItemProtocol in
return APIOwnedItem(key: key, numberOwned: numberOwned, itemType: ItemType.eggs.rawValue)
})) ?? []
let specialDict = try? values.decode([String: Any].self, forKey: .ownedSpecialItems)
ownedSpecialItems = (specialDict?.filter({ (_, value) -> Bool in
return (value as? Int) != nil
}).map({ (key, numberOwned) -> OwnedItemProtocol in
return APIOwnedItem(key: key, numberOwned: numberOwned as? Int ?? 0, itemType: ItemType.special.rawValue)
})) ?? []
let petsDict = try?values.decode([String: Int?].self, forKey: .ownedPets)
ownedPets = (petsDict?.map({ (key, trained) -> OwnedPetProtocol in
return APIOwnedPet(key: key, trained: trained ?? 0)
})) ?? []
let mountsDict = try?values.decode([String: Bool?].self, forKey: .ownedMounts)
ownedMounts = (mountsDict?.map({ (key, owned) -> APIOwnedMount in
return APIOwnedMount(key: key, owned: owned ?? false)
})) ?? []
}
}
|
024717ea53d4638ce97dffc63f9ec0de
| 46.293333 | 117 | 0.656893 | false | false | false | false |
vkaramov/VKSplitViewController
|
refs/heads/master
|
SwiftDemo/SwiftDemo/SDDetailViewController.swift
|
mit
|
1
|
//
// SDDetailViewController.swift
// SwiftDemo
//
// Created by Viacheslav Karamov on 05.07.15.
// Copyright (c) 2015 Viacheslav Karamov. All rights reserved.
//
import UIKit
class SDDetailViewController: UIViewController
{
static let kNavigationStoryboardId = "DetailNavigationController";
private var splitController : VKSplitViewController?;
@IBOutlet private var colorView : UIView?;
override func viewDidLoad()
{
super.viewDidLoad();
splitController = UIApplication.sharedApplication().delegate?.window??.rootViewController as? VKSplitViewController;
}
func setBackgroundColor(color : UIColor)
{
colorView?.backgroundColor = color;
}
@IBAction func menuBarTapped(sender : UIBarButtonItem?)
{
if let splitController = splitController
{
let visible = splitController.masterViewControllerVisible;
self.navigationItem.leftBarButtonItem?.title? = visible ? "Show" : "Hide";
splitController.masterViewControllerVisible = !visible;
}
}
}
|
242059050895497b28554fcaeadf29d7
| 27.307692 | 124 | 0.677536 | false | false | false | false |
inkyfox/SwiftySQL
|
refs/heads/master
|
Tests/JoinTests.swift
|
mit
|
1
|
//
// JoinTests.swift
// SwiftySQLTests
//
// Created by Yongha Yoo (inkyfox) on 2016. 10. 27..
// Copyright © 2016년 Gen X Hippies Company. All rights reserved.
//
import XCTest
@testable import SwiftySQL
class JoinTests: XCTestCase {
override func setUp() {
super.setUp()
student = Student()
teature = Teature()
lecture = Lecture()
attending = Attending()
}
override func tearDown() {
super.tearDown()
student = nil
teature = nil
lecture = nil
attending = nil
}
func testJoin() {
XCTAssertSQL(student.join(attending),
"student AS stu JOIN user.attending AS atd")
XCTAssertSQL(student.join(attending, on: student.id == attending.studentID),
"student AS stu JOIN user.attending AS atd ON stu.id = atd.student_id")
}
func testLeftJoin() {
XCTAssertSQL(student.leftJoin(attending),
"student AS stu LEFT JOIN user.attending AS atd")
XCTAssertSQL(student.leftJoin(attending, on: student.id == attending.studentID),
"student AS stu LEFT JOIN user.attending AS atd ON stu.id = atd.student_id")
XCTAssertSQL(student.leftOuterJoin(attending),
"student AS stu LEFT JOIN user.attending AS atd")
XCTAssertSQL(student.leftOuterJoin(attending, on: student.id == attending.studentID),
"student AS stu LEFT JOIN user.attending AS atd ON stu.id = atd.student_id")
}
func testCrossJoin() {
XCTAssertSQL(student.crossJoin(attending),
"student AS stu CROSS JOIN user.attending AS atd")
XCTAssertSQL(student.crossJoin(attending, on: student.id == attending.studentID),
"student AS stu CROSS JOIN user.attending AS atd ON stu.id = atd.student_id")
}
func testNaturalJoin() {
XCTAssertSQL(student.naturalJoin(attending),
"student AS stu NATURAL JOIN user.attending AS atd")
XCTAssertSQL(student.naturalJoin(attending, on: student.id == attending.studentID),
"student AS stu NATURAL JOIN user.attending AS atd ON stu.id = atd.student_id")
}
func testNaturalLeftJoin() {
XCTAssertSQL(student.naturalLeftJoin(attending),
"student AS stu NATURAL LEFT JOIN user.attending AS atd")
XCTAssertSQL(student.naturalLeftJoin(attending,
on: student.id == attending.studentID),
"student AS stu NATURAL LEFT JOIN user.attending AS atd ON stu.id = atd.student_id")
}
func testMultipleJoin() {
XCTAssertSQL(
student
.join(attending, on: student.id == attending.studentID)
.join(lecture, on: lecture.id == attending.lectureID)
,
"student AS stu " +
"JOIN user.attending AS atd ON stu.id = atd.student_id " +
"JOIN lecture AS lec ON lec.id = atd.lecture_id")
}
}
|
b8094c323bcc55bd741e9431cd407040
| 35.717647 | 105 | 0.590516 | false | true | false | false |
4faramita/TweeBox
|
refs/heads/master
|
TweeBox/TwitterUser.swift
|
mit
|
1
|
//
// TwitterUser.swift
// TweeBox
//
// Created by 4faramita on 2017/7/28.
// Copyright © 2017年 4faramita. All rights reserved.
//
import Foundation
import SwiftyJSON
struct TwitterUser {
public var id: String
public var location: String?
public var name: String // not the @ one, that's the "screen_name"
public var screenName: String
public var url: URL?
// A URL provided by the user in association with their profile.
public var createdAt: String
public var defaultProfile: Bool
// When true, indicates that the user has not altered the theme or background of their user profile.
public var defaultProfileImage: Bool
public var description: String?
public var entities: Entity
// Entities which have been parsed out of the url or description fields defined by the user.
public var verified: Bool
public var favouritesCount: Int
public var followRequestSent: Bool?
// When true, indicates that the authenticating user has issued a follow request to this protected user account
public var following: Bool?
public var followersCount: Int
public var followingCount: Int // friends_count
public var geoEnabled: Bool
// When true, indicates that the user has enabled the possibility of geotagging their Tweets.
// This field must be true for the current user to attach geographic data when using POST statuses / update .
public var isTranslator: Bool
// When true, indicates that the user is a participant in Twitter’s translator community .
public var lang: String
public var listedCount: Int
// The number of public lists that this user is a member of.
public var notifications: Bool?
// Indicates whether the authenticated user has chosen to receive this user’s Tweets by SMS.
public var profileBackgroundColor: String
// The hexadecimal color chosen by the user for their background.
public var profileBackgroundImageURLHTTP: URL? // profile_background_image_url
public var profileBackgroundImageURL: URL? // profile_background_image_url_https
public var profileBackgroundTile: Bool
// When true, indicates that the user’s profile_background_image_url should be tiled when displayed.
public var profileBannerURL: URL?
// By adding a final path element of the URL,
// it is possible to obtain different image sizes optimized for specific displays.
public var profileImageURLHTTP: URL? // profile_image_url
public var profileImageURL: URL? // profile_image_url_https
public var profileUseBackgroundImage: Bool
// public var profile_link_color: String
// public var profile_sidebar_border_color: String
// public var profile_sidebar_fill_color: String
// public var profile_text_color: String
public var protected: Bool
public var status: Tweet?
public var statusesCount: Int
// The number of Tweets (including retweets) issued by the user.
public var timeZone: String?
public var utcOffset: Int?
// The offset from GMT/UTC in seconds.
// public var withheld_in_countries: String?
// public var withheld_scope: String?
init(with userJSON: JSON) {
id = userJSON["id_str"].stringValue
location = userJSON["location"].string
name = userJSON["name"].stringValue
screenName = userJSON["screen_name"].stringValue
url = URL(string: userJSON["url"].stringValue)
createdAt = userJSON["created_at"].stringValue
defaultProfile = userJSON["default_profile"].bool ?? true
defaultProfileImage = userJSON["default_profile_image"].bool ?? true
description = userJSON["description"].string
entities = Entity(with: userJSON["entities"], and: JSON.null) // ((userJSON["entities"].null == nil) ? (Entity(with: userJSON["entities"])) : nil)
verified = userJSON["verified"].bool ?? false
favouritesCount = userJSON["favourites_count"].int ?? 0
followRequestSent = userJSON["follow_request_sent"].bool
following = userJSON["following"].bool
followersCount = userJSON["followers_count"].int ?? 0
followingCount = userJSON["friends_count"].int ?? 0
geoEnabled = userJSON["geo_enabled"].bool ?? false
isTranslator = userJSON["is_translator"].bool ?? false
lang = userJSON["lang"].stringValue
listedCount = userJSON["listed_count"].int ?? 0
notifications = userJSON["notifications"].bool
profileBackgroundColor = userJSON["profile_background_color"].stringValue
profileBackgroundImageURLHTTP = URL(string: userJSON["profile_background_image_url"].stringValue)
profileBackgroundImageURL = URL(string: userJSON["profile_background_image_url_https"].stringValue)
profileBackgroundTile = userJSON["profile_background_tile"].bool ?? false
profileBannerURL = URL(string: userJSON["profile_banner_url"].stringValue)
profileImageURLHTTP = URL(string: userJSON["profile_image_url"].stringValue)
profileImageURL = URL(string: userJSON["profile_image_url_https"].stringValue, quality: .max)
profileUseBackgroundImage = userJSON["profile_use_background_image"].bool ?? true
protected = userJSON["protected"].bool ?? false
status = ((userJSON["status"].null == nil) ? (Tweet(with: userJSON["status"])) : nil)
statusesCount = userJSON["statuses_count"].int ?? 0
timeZone = userJSON["time_zone"].string
utcOffset = userJSON["utc_offset"].int
}
}
|
446e2cd1197ad88ff0ff41a88720aaf7
| 47.645669 | 176 | 0.62933 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Representables/SharingPicker.swift
|
mit
|
1
|
//
// SharingPicker.swift
// RedditOs
//
// Created by Thomas Ricouard on 12/08/2020.
//
import Foundation
import AppKit
import SwiftUI
struct SharingsPicker: NSViewRepresentable {
@Binding var isPresented: Bool
var sharingItems: [Any] = []
func makeNSView(context: Context) -> NSView {
let view = NSView()
return view
}
func updateNSView(_ nsView: NSView, context: Context) {
if isPresented {
let picker = NSSharingServicePicker(items: sharingItems)
picker.delegate = context.coordinator
DispatchQueue.main.async {
picker.show(relativeTo: .zero, of: nsView, preferredEdge: .minY)
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator(owner: self)
}
class Coordinator: NSObject, NSSharingServicePickerDelegate {
let owner: SharingsPicker
init(owner: SharingsPicker) {
self.owner = owner
}
func sharingServicePicker(_ sharingServicePicker: NSSharingServicePicker, didChoose service: NSSharingService?) {
sharingServicePicker.delegate = nil
self.owner.isPresented = false
}
}
}
|
2cc55d3256db0461d9a32d95c463091e
| 25.446809 | 121 | 0.613033 | false | false | false | false |
Camvergence/AssetFlow
|
refs/heads/master
|
PhotosPlusTests/PhotosPlusTests.swift
|
mit
|
3
|
//
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import XCTest
@testable import PhotosPlus
class PhotosPlusTests: XCTestCase {
var cameraNames: [String] = [String]()
func testCameras() {
let cameraTypes: [CameraModel.Type] = [
Canon10D.self,
Canon5D.self,
Canon6D.self,
CanonEOS1D.self,
CanonEOS1DC.self,
CanonEOS1DMarkII.self,
CanonEOS1DMarkIII.self,
CanonEOS1DMarkIIN.self,
CanonEOS1DMarkIV.self,
CanonEOS1Ds.self,
CanonEOS1DsMarkII.self,
CanonEOS1DsMarkIII.self,
CanonEOS1DX.self,
CanonEOS1DXMarkII.self,
CanonEOS20D.self,
CanonEOS30D.self,
CanonEOS40D.self,
CanonEOS50D.self,
CanonEOS5DMarkII.self,
CanonEOS5DMarkIII.self,
CanonEOS5DMarkIV.self,
CanonEOS5DS.self,
CanonEOS5DSR.self,
CanonEOS60D.self,
CanonEOS70D.self,
CanonEOS7D.self,
CanonEOS7DMarkII.self,
CanonEOS80D.self,
CanonEOSD30.self,
CanonEOSD60.self,
CanonEOSDigitalRebel.self,
CanonEOSDigitalRebelXS.self,
CanonEOSDigitalRebelXSi.self,
CanonEOSDigitalRebelXT.self,
CanonEOSDigitalRebelXTi.self,
CanonEOSM.self,
CanonEOSM10.self,
CanonEOSM2.self,
CanonEOSM3.self,
CanonEOSM5.self,
CanonEOSRebelSL1.self,
CanonEOSRebelT1i.self,
CanonEOSRebelT2i.self,
CanonEOSRebelT3.self,
CanonEOSRebelT3i.self,
CanonEOSRebelT4i.self,
CanonEOSRebelT5.self,
CanonEOSRebelT5i.self,
CanonEOSRebelT6.self,
CanonEOSRebelT6i.self,
CanonEOSRebelT6s.self,
CanonPowerShotG10.self,
CanonPowerShotG11.self,
CanonPowerShotG12.self,
CanonPowerShotG15.self,
CanonPowerShotG16.self,
CanonPowerShotG1X.self,
CanonPowerShotG1XMarkII.self,
CanonPowerShotG3X.self,
CanonPowerShotG5.self,
CanonPowerShotG5X.self,
CanonPowerShotG6.self,
CanonPowerShotG7X.self,
CanonPowerShotG7XMarkII.self,
CanonPowerShotG9.self,
CanonPowerShotG9X.self,
CanonPowerShotPro1.self,
CanonPowerShotS100.self,
CanonPowerShotS110.self,
CanonPowerShotS120.self,
CanonPowerShotS60.self,
CanonPowerShotS70.self,
CanonPowerShotS90.self,
CanonPowerShotS95.self,
CanonPowerShotSX1IS.self,
CanonPowerShotSX50HS.self,
CanonPowerShotSX60HS.self,
DJIMavicPro.self,
DxOOne.self,
EpsonRD1.self,
EpsonRD1s.self,
EpsonRD1x.self,
FujifilmFinePixS2Pro.self,
FujifilmFinePixS3Pro.self,
FujifilmFinePixS5Pro.self,
FujifilmFinePixX100.self,
FujifilmX100S.self,
FujifilmX100t.self,
FujifilmX20.self,
FujifilmX30.self,
FujifilmX70.self,
FujifilmXA1.self,
FujifilmXA2.self,
FujifilmXE1.self,
FujifilmXE2.self,
FujifilmXE2S.self,
FujifilmXM1.self,
FujifilmXPro1.self,
FujifilmXPro2.self,
FujifilmXQ1.self,
FujifilmXQ2.self,
FujifilmXT1.self,
FujifilmXT10.self,
FujifilmXT2.self,
GooglePixelXL.self,
HasselbladCF22.self,
HasselbladCF39.self,
HasselbladCFV16.self,
HasselbladCFV50c.self,
HasselbladH3D31.self,
HasselbladH3D31II.self,
HasselbladH3DII50.self,
HasselbladH4D40.self,
HasselbladH5D50c.self,
HasselbladLunar.self,
HasselbladX1D.self,
KodakDCSProSLR.self,
KodakPixproS1.self,
KonicaMinoltaALPHA5DIGITAL.self,
KonicaMinoltaALPHA7DIGITAL.self,
KonicaMinoltaALPHASWEETDIGITAL.self,
KonicaMinoltaDiMAGEA200.self,
KonicaMinoltaDYNAX5D.self,
KonicaMinoltaDYNAX7D.self,
KonicaMinoltaMAXXUM5D.self,
KonicaMinoltaMAXXUM7D.self,
LeafAFi5.self,
LeafAFi6.self,
LeafAFi7.self,
LeafAFiII6.self,
LeafAFiII7.self,
LeafAptus17.self,
LeafAptus22.self,
LeafAptus54S.self,
LeafAptus65.self,
LeafAptus65S.self,
LeafAptus75.self,
LeafAptus75s.self,
LeafAptusII6.self,
LeafAptusII7.self,
LeafValeo11.self,
LeafValeo17.self,
LeafValeo22.self,
LeicaCTyp112.self,
LeicaDIGILUX2.self,
LeicaDIGILUX3.self,
LeicaDLuxTyp109.self,
LeicaDLux2.self,
LeicaDLux3.self,
LeicaDLux4.self,
LeicaDLux5.self,
LeicaDLux6.self,
LeicaM.self,
LeicaM8dot2.self,
LeicaM8.self,
LeicaM9.self,
LeicaME.self,
LeicaMMonochromTyp246.self,
LeicaMMonochrom.self,
LeicaQ.self,
LeicaSTyp007.self,
LeicaS2.self,
LeicaSLTyp601.self,
LeicaVLuxTyp114.self,
LeicaVLux1.self,
LeicaVLux2.self,
LeicaVLux4.self,
LeicaXTyp113.self,
LeicaX1.self,
LeicaX2.self,
LeicaXUTyp113.self,
LeicaXVarioTyp107.self,
MinoltaDiMAGEA1.self,
MinoltaDiMAGEA2.self,
Nikon1AW1.self,
Nikon1J1.self,
Nikon1J2.self,
Nikon1J3.self,
Nikon1J4.self,
Nikon1J5.self,
Nikon1S1.self,
Nikon1S2.self,
Nikon1V1.self,
Nikon1V2.self,
Nikon1V3.self,
NikonCOOLPIXA.self,
NikonCOOLPIXP330.self,
NikonCOOLPIXP340.self,
NikonCOOLPIXP6000.self,
NikonCOOLPIXP7000.self,
NikonCOOLPIXP7100.self,
NikonCOOLPIXP7700.self,
NikonCOOLPIXP7800.self,
NikonD1.self,
NikonD100.self,
NikonD1H.self,
NikonD1X.self,
NikonD200.self,
NikonD2H.self,
NikonD2Hs.self,
NikonD2X.self,
NikonD2Xs.self,
NikonD3.self,
NikonD300.self,
NikonD3000.self,
NikonD300S.self,
NikonD3100.self,
NikonD3200.self,
NikonD3300.self,
NikonD3400.self,
NikonD3S.self,
NikonD3X.self,
NikonD4.self,
NikonD40.self,
NikonD40X.self,
NikonD4S.self,
NikonD5.self,
NikonD50.self,
NikonD500.self,
NikonD5000.self,
NikonD5100.self,
NikonD5200.self,
NikonD5300.self,
NikonD5500.self,
NikonD60.self,
NikonD600.self,
NikonD610.self,
NikonD70.self,
NikonD700.self,
NikonD7000.self,
NikonD70s.self,
NikonD7100.self,
NikonD7200.self,
NikonD750.self,
NikonD80.self,
NikonD800.self,
NikonD800E.self,
NikonD810.self,
NikonD810A.self,
NikonD90.self,
NikonDf.self,
NikonE8400.self,
NikonE8700.self,
NikonE8800.self,
OlympusC7000Z.self,
OlympusC7070WZ.self,
OlympusC70Z.self,
OlympusC8080WZ.self,
OlympusE1.self,
OlympusE3.self,
OlympusE30.self,
OlympusE300.self,
OlympusE330.self,
OlympusE400.self,
OlympusE410.self,
OlympusE450.self,
OlympusE5.self,
OlympusE500.self,
OlympusE510.self,
OlympusE600.self,
OlympusE620.self,
OlympusEM1.self,
OlympusEM1MarkII.self,
OlympusEP5.self,
OlympusEVOLTE420.self,
OlympusEVOLTE520.self,
OlympusOMDEM10.self,
OlympusOMDEM10MarkII.self,
OlympusOMDEM5.self,
OlympusOMDEM5MarkII.self,
OlympusPENEP1.self,
OlympusPENEP2.self,
OlympusPENEP3.self,
OlympusPENEPL1.self,
OlympusPENEPL1s.self,
OlympusPENEPL2.self,
OlympusPENEPL3.self,
OlympusPENEPL5.self,
OlympusPENEPL7.self,
OlympusPENEPM1.self,
OlympusPENEPM2.self,
OlympusPENF.self,
OlympusPENLiteEPL6.self,
OlympusSP570UZ.self,
OlympusSTYLUS1.self,
OlympusSTYLUSSH2.self,
OlympusSTYLUSXZ2.self,
OlympusTG4.self,
OlympusXZ1.self,
PanasonicLUMIXCM1.self,
PanasonicLUMIXDMCFZ100.self,
PanasonicLUMIXDMCFZ1000.self,
PanasonicLUMIXDMCFZ150.self,
PanasonicLUMIXDMCFZ200.self,
PanasonicLUMIXDMCF25000.self,
PanasonicLumixDMCFZ300.self,
PanasonicLUMIXDMCFZ330.self,
PanasonicLUMIXDMCFZ35.self,
PanasonicLUMIXDMCFZ38.self,
PanasonicLUMIXDMCFZ50.self,
PanasonicLUMIXDMCFZ70.self,
PanasonicLUMIXDMCFZ72.self,
PanasonicLUMIXDMCG1.self,
PanasonicLUMIXDMCG10.self,
PanasonicLUMIXDMCG2.self,
PanasonicLUMIXDMCG3.self,
PanasonicLUMIXDMCG5.self,
PanasonicLUMIXDMCG6.self,
PanasonicLUMIXDMCG7.self,
PanasonicLUMIXDMCGF1.self,
PanasonicLUMIXDMCGF2.self,
PanasonicLUMIXDMCGF3.self,
PanasonicLUMIXDMCGF5.self,
PanasonicLUMIXDMCGF6.self,
PanasonicLUMIXDMCGF7.self,
PanasonicLUMIXDMCGF8.self,
PanasonicLUMIXDMCGH1.self,
PanasonicLUMIXDMCGH2.self,
PanasonicLUMIXDMCGH3.self,
PanasonicLUMIXDMCGH4.self,
PanasonicLUMIXDMCGM1.self,
PanasonicLUMIXDMCGM5.self,
PanasonicLUMIXDMCGX1.self,
PanasonicLumixDMCGX7.self,
PanasonicLumixDMCGX8.self,
PanasonicLUMIXDMCL1.self,
PanasonicLUMIXDMCLC1.self,
PanasonicLUMIXDMCLF1.self,
PanasonicLUMIXDMCLX1.self,
PanasonicLUMIXDMCLX10.self,
PanasonicLUMIXDMCLX100.self,
PanasonicLUMIXDMCLX2.self,
PanasonicLUMIXDMCLX3.self,
PanasonicLUMIXDMCLX5.self,
PanasonicLUMIXDMCLX7.self,
PanasonicLUMIXDMCTZ60.self,
PanasonicLUMIXDMCTZ61.self,
PanasonicLUMIXDMCTZ70.self,
PanasonicLUMIXDMCTZ71.self,
PanasonicLUMIXDMCZS100.self,
PanasonicLUMIXDMCZS40.self,
PanasonicLUMIXDMCZS50.self,
PanasonicLumixG85.self,
PanasonicLumixZS60.self,
PentaxIstD.self,
PentaxIstDL.self,
PentaxIstDL2.self,
PentaxIstDS.self,
PentaxIstDS2.self,
Pentax645D.self,
Pentax645Z.self,
PentaxK1.self,
PentaxK100D.self,
PentaxK100DSuper.self,
PentaxK10D.self,
PentaxK110D.self,
PentaxK2000.self,
PentaxK200D.self,
PentaxK20D.self,
PentaxK3.self,
PentaxK30.self,
PentaxK3II.self,
PentaxK5.self,
PentaxK50.self,
PentaxK5II.self,
PentaxK5IIs.self,
PentaxK7.self,
PentaxK70.self,
PentaxKm.self,
PentaxKr.self,
PentaxKS1.self,
PentaxKS2.self,
PentaxKx.self,
PentaxMX1.self,
PentaxQ.self,
RicohGRII.self,
SamsungGalaxyNX.self,
SamsungGX10.self,
SamsungGX1L.self,
SamsungGX1S.self,
SamsungGX20.self,
SamsungNX1.self,
SamsungNX10.self,
SamsungNX100.self,
SamsungNX1000.self,
SamsungNX11.self,
SamsungNX1100.self,
SamsungNX20.self,
SamsungNX200.self,
SamsungNX2000.self,
SamsungNX210.self,
SamsungNX30.self,
SamsungNX300.self,
SamsungNX5.self,
SamsungNX500.self,
SonyAlphaDSLRA200.self,
SonyAlphaDSLRA230.self,
SonyAlphaDSLRA290.self,
SonyAlphaDSLRA300.self,
SonyAlphaDSLRA330.self,
SonyAlphaDSLRA350.self,
SonyAlphaDSLRA380.self,
SonyAlphaDSLRA390.self,
SonyAlphaDSLRA450.self,
SonyAlphaDSLRA500.self,
SonyAlphaDSLRA550.self,
SonyAlphaDSLRA560.self,
SonyAlphaDSLRA580.self,
SonyAlphaDSLRA850.self,
SonyAlphaDSLRA900.self,
SonyAlphaILCE3000.self,
SonyAlphaILCE5000.self,
SonyA5100.self,
SonyAlphaILCE6000.self,
SonyA6300.self,
SonyA6500.self,
SonyA7.self,
SonyA7II.self,
SonyAlphaILCE7R.self,
SonyA7rII.self,
SonyA7s.self,
SonyAlphaILCE7SII.self,
SonyAlphaNEX3N.self,
SonyAlphaNEX5.self,
SonyAlphaNEX5N.self,
SonyAlphaNEX5R.self,
SonyAlphaNEX5T.self,
SonyAlphaNEX6.self,
SonyAlphaNEX7.self,
SonyAlphaNEXC3.self,
SonyAlphaNEXF3.self,
SonyAlphaSLTA33.self,
SonyAlphaSLTA35.self,
SonyAlphaSLTA37.self,
SonyAlphaSLTA55.self,
SonyAlphaSLTA57.self,
SonyAlphaSLTA58.self,
SonyAlphaSLTA65.self,
SonyAlphaSLTA68.self,
SonyAlphaSLTA77.self,
SonyAlphaSLTA77II.self,
SonyAlphaSLTA99.self,
SonyCybershotDSCRX1.self,
SonyCybershotDSCRX10.self,
SonyCybershotDSCRX100.self,
SonyCybershotDSCRX100II.self,
SonyCybershotDSCRX100III.self,
SonyCybershotDSCRX100IV.self,
SonyCybershotDSCRX10II.self,
SonyCybershotDSCRX10III.self,
SonyCybershotDSCRX1R.self,
SonyCybershotRX1RII.self,
SonyDSCF828.self,
SonyDSCR1.self,
SonyDSCV3.self,
SonyA100.self,
SonyA700.self,
SonyNEX3.self,
SonyNEXVG20.self,
SonyRX100MarkV.self,
YIM1.self,
]
for cameraType in cameraTypes {
assert(check(camera: cameraType.init()), String(describing: cameraType))
}
}
func check(camera: CameraModel) -> Bool {
if cameraNames.contains(camera.name) {
return false
} else {
cameraNames.append(camera.name)
}
if camera.manufacturer.defaultRawUti == "" {
return false
}
if camera.rawUti == "" {
return false
}
return true
}
}
|
8b3f6034602279514d90c7641da21b8a
| 30.908 | 84 | 0.543563 | false | false | false | false |
ByteriX/BxInputController
|
refs/heads/master
|
BxInputController/Sources/Controller/BxInputController+InputAccessoryView.swift
|
mit
|
1
|
/**
* @file BxInputController+InputAccessoryView.swift
* @namespace BxInputController
*
* @details Working with panel abouve keyboard in BxInputController
* @date 23.01.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
/// Working with panel abouve keyboard in BxInputController
extension BxInputController
{
/// Class of panel abouve keyboard
open class InputAccessoryView : UIToolbar
{
internal(set) public var backNextControl: UISegmentedControl
internal(set) public var doneButtonItem: UIBarButtonItem
init(parent: BxInputController) {
var items : [String] = []
let settings = parent.settings
items.append(settings.backButtonTitle)
items.append(settings.nextButtonTitle)
backNextControl = UISegmentedControl(items: items)
backNextControl.frame = CGRect(x: 0, y: 0, width: 140, height: 30)
backNextControl.isMomentary = true
backNextControl.addTarget(parent, action: #selector(backNextButtonClick), for: .valueChanged)
doneButtonItem = UIBarButtonItem(title: settings.doneButtonTitle, style: .done, target: parent, action: #selector(doneButtonClick))
super.init(frame: CGRect(x: 0, y: 0, width: 320, height: 44))
self.barStyle = .blackTranslucent
self.items = [UIBarButtonItem(customView: backNextControl), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), doneButtonItem]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
/// refresh commonInputAccessoryView for using this as panel as abouve keyboard
open func updateInputAccessory()
{
if isShowingInputAccessoryView {
commonInputAccessoryView = InputAccessoryView(parent: self)
updateCommonInputAccessory()
} else {
commonInputAccessoryView = nil
}
}
/// update content of panel as abouve keyboard
open func updateCommonInputAccessory()
{
guard let commonInputAccessoryView = commonInputAccessoryView,
let activeRow = activeRow else
{
return
}
commonInputAccessoryView.backNextControl.setEnabled(getDecrementRow(from: activeRow) != nil, forSegmentAt: 0)
commonInputAccessoryView.backNextControl.setEnabled(getIncrementRow(from: activeRow) != nil, forSegmentAt: 1)
}
/// set and update panel abouve keyboard for activeControl
open func updateInputAccessory(activeControl: UIView?)
{
if let activeControl = activeControl as? UITextField {
activeControl.inputAccessoryView = commonInputAccessoryView
} else if let activeControl = activeControl as? UITextView {
activeControl.inputAccessoryView = commonInputAccessoryView
}
updateCommonInputAccessory()
}
/// event when user click back or next row
@objc open func backNextButtonClick(control: UISegmentedControl) {
guard let activeRow = activeRow else {
activeControl?.resignFirstResponder()
return
}
var row: BxInputRow? = nil
if control.selectedSegmentIndex == 0 {
row = getDecrementRow(from: activeRow)
} else {
row = getIncrementRow(from: activeRow)
}
if let row = row {
//
DispatchQueue.main.async {[weak self] () in
self?.selectRow(row)
self?.updateCommonInputAccessory()
}
} else {
activeControl?.resignFirstResponder()
}
}
/// event when user click done
@objc open func doneButtonClick() {
activeControl?.resignFirstResponder()
}
/// return true if row can get focus
open func checkedForGettingRow(_ row: BxInputRow) -> Bool{
if row is BxInputChildSelectorRow {
return false
}
return row.isEnabled
}
/// return a row after current row. If not found then return nil
open func getIncrementRow(from row: BxInputRow) -> BxInputRow?
{
if let indexPath = getIndex(for: row) {
var sectionIndex = indexPath.section
var rowIndex = indexPath.row + 1
while sectionIndex < sections.count {
let rowBinders = sections[sectionIndex].rowBinders
while rowIndex < rowBinders.count {
let result = rowBinders[rowIndex].rowData
if checkedForGettingRow(result) {
return result
}
rowIndex = rowIndex + 1
}
rowIndex = 0
sectionIndex = sectionIndex + 1
}
}
return nil
}
/// return a row before current row. If not found then return nil
open func getDecrementRow(from row: BxInputRow) -> BxInputRow?
{
if let indexPath = getIndex(for: row) {
var sectionIndex = indexPath.section
var rowIndex = indexPath.row - 1
while sectionIndex > -1 {
let rowBinders = sections[sectionIndex].rowBinders
while rowIndex > -1 {
let result = rowBinders[rowIndex].rowData
if checkedForGettingRow(result) {
return result
}
rowIndex = rowIndex - 1
}
sectionIndex = sectionIndex - 1
if sectionIndex > -1 {
rowIndex = sections[sectionIndex].rowBinders.count - 1
}
}
}
return nil
}
}
|
5af2d4a789bf97b1409bf19439112fef
| 35.792683 | 167 | 0.60126 | false | false | false | false |
Bargetor/beak
|
refs/heads/master
|
Beak/Beak/view/UIAnimation.swift
|
mit
|
1
|
//
// UIAnimation.swift
// Beak
//
// Created by 马进 on 2017/1/6.
// Copyright © 2017年 马进. All rights reserved.
//
import Foundation
//
// EAAnimationFuture.swift
//
// Created by Marin Todorov on 5/26/15.
// Copyright (c) 2015-2016 Underplot ltd. 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 UIKit
/**
A class that is used behind the scene to chain and/or delay animations.
You do not need to create instances directly - they are created automatically when you use
animateWithDuration:animation: and the like.
*/
public class UIAnimationFuture: Equatable, CustomStringConvertible {
/* debug helpers */
private var debug: Bool = false
private var debugNumber: Int = 0
static private var debugCount: Int = 0
/* animation properties */
var duration: CFTimeInterval = 0.0
var delay: CFTimeInterval = 0.0
var options: UIView.AnimationOptions = []
var animations: (() -> Void)?
var completion: ((Bool) -> Void)?
var identifier: String
var springDamping: CGFloat = 0.0
var springVelocity: CGFloat = 0.0
private var loopsChain = false
private static var cancelCompletions: [String: ()->Void] = [:]
/* animation chain links */
var prevDelayedAnimation: UIAnimationFuture? {
didSet {
if let prev = prevDelayedAnimation {
identifier = prev.identifier
}
}
}
var nextDelayedAnimation: UIAnimationFuture?
//MARK: - Animation lifecycle
init() {
UIAnimationFuture.debugCount += 1
self.debugNumber = UIAnimationFuture.debugCount
if debug {
print("animation #\(self.debugNumber)")
}
self.identifier = UUID().uuidString
}
deinit {
if debug {
print("deinit \(self)")
}
}
/**
An array of all "root" animations for all currently animating chains. I.e. this array contains
the first link in each currently animating chain. Handy if you want to cancel all chains - just
loop over `animations` and call `cancelAnimationChain` on each one.
*/
public static var animations: [UIAnimationFuture] = []
//MARK: Animation methods
@discardableResult
public func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void) -> UIAnimationFuture {
return animate(withDuration: duration, animations: animations, completion: completion)
}
@discardableResult
public func animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture {
return animate(withDuration: duration, delay: delay, options: [], animations: animations, completion: completion)
}
@discardableResult
public func animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture {
return animateAndChain(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion)
}
@discardableResult
public func animate(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture {
let anim = animateAndChain(withDuration: duration, delay: delay, options: options, animations: animations, completion: completion)
self.springDamping = dampingRatio
self.springVelocity = velocity
return anim
}
@discardableResult
public func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture {
var options = options
if options.contains(.repeat) {
options.remove(.repeat)
loopsChain = true
}
self.duration = duration
self.delay = delay
self.options = options
self.animations = animations
self.completion = completion
nextDelayedAnimation = UIAnimationFuture()
nextDelayedAnimation!.prevDelayedAnimation = self
return nextDelayedAnimation!
}
//MARK: - Animation control methods
/**
A method to cancel the animation chain of the current animation.
This method cancels and removes all animations that are chained to each other in one chain.
The animations will not stop immediately - the currently running animation will finish and then
the complete chain will be stopped and removed.
:param: completion completion closure
*/
public func cancelAnimationChain(_ completion: (()->Void)? = nil) {
UIAnimationFuture.cancelCompletions[identifier] = completion
var link = self
while link.nextDelayedAnimation != nil {
link = link.nextDelayedAnimation!
}
link.detachFromChain()
if debug {
print("cancelled top animation: \(link)")
}
}
private func detachFromChain() {
self.nextDelayedAnimation = nil
if let previous = self.prevDelayedAnimation {
if debug {
print("dettach \(self)")
}
previous.nextDelayedAnimation = nil
previous.detachFromChain()
} else {
if let index = UIAnimationFuture.animations.index(of: self) {
if debug {
print("cancel root animation #\(UIAnimationFuture.animations[index])")
}
UIAnimationFuture.animations.remove(at: index)
}
}
self.prevDelayedAnimation = nil
}
func run() {
if debug {
print("run animation #\(debugNumber)")
}
//TODO: Check if layer-only animations fire a proper completion block
if let animations = animations {
options.insert(.beginFromCurrentState)
let animationDelay = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * self.delay )) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: animationDelay) {
if self.springDamping > 0.0 {
//spring animation
UIView.animate(withDuration: self.duration, delay: 0, usingSpringWithDamping: self.springDamping, initialSpringVelocity: self.springVelocity, options: self.options, animations: animations, completion: self.animationCompleted)
} else {
//basic animation
UIView.animate(withDuration: self.duration, delay: 0, options: self.options, animations: animations, completion: self.animationCompleted)
}
}
}
}
private func animationCompleted(_ finished: Bool) {
//animation's own completion
self.completion?(finished)
//chain has been cancelled
if let cancelCompletion = UIAnimationFuture.cancelCompletions[identifier] {
if debug {
print("run chain cancel completion")
}
cancelCompletion()
detachFromChain()
return
}
//check for .Repeat
if finished && self.loopsChain {
//find first animation in the chain and run it next
var link = self
while link.prevDelayedAnimation != nil {
link = link.prevDelayedAnimation!
}
if debug {
print("loop to \(link)")
}
link.run()
return
}
//run next or destroy chain
if self.nextDelayedAnimation?.animations != nil {
self.nextDelayedAnimation?.run()
} else {
//last animation in the chain
self.detachFromChain()
}
}
public var description: String {
get {
if debug {
return "animation #\(self.debugNumber) [\(self.identifier)] prev: \(self.prevDelayedAnimation?.debugNumber ?? 0) next: \(self.nextDelayedAnimation?.debugNumber ?? 0)"
} else {
return "<EADelayedAnimation>"
}
}
}
}
public func == (lhs: UIAnimationFuture , rhs: UIAnimationFuture) -> Bool {
return lhs === rhs
}
extension UIView{
// MARK: chain animations
/**
Creates and runs an animation which allows other animations to be chained to it and to each other.
:param: duration The animation duration in seconds
:param: delay The delay before the animation starts
:param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info)
:param: animations Animation closure
:param: completion Completion closure of type (Bool)->Void
:returns: The created request.
*/
public class func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture {
let currentAnimation = UIAnimationFuture()
currentAnimation.duration = duration
currentAnimation.delay = delay
currentAnimation.options = options
currentAnimation.animations = animations
currentAnimation.completion = completion
currentAnimation.nextDelayedAnimation = UIAnimationFuture()
currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation
currentAnimation.run()
UIAnimationFuture.animations.append(currentAnimation)
return currentAnimation.nextDelayedAnimation!
}
/**
Creates and runs an animation which allows other animations to be chained to it and to each other.
:param: duration The animation duration in seconds
:param: delay The delay before the animation starts
:param: usingSpringWithDamping the spring damping
:param: initialSpringVelocity initial velocity of the animation
:param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info)
:param: animations Animation closure
:param: completion Completion closure of type (Bool)->Void
:returns: The created request.
*/
public class func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> UIAnimationFuture {
let currentAnimation = UIAnimationFuture()
currentAnimation.duration = duration
currentAnimation.delay = delay
currentAnimation.options = options
currentAnimation.animations = animations
currentAnimation.completion = completion
currentAnimation.springDamping = dampingRatio
currentAnimation.springVelocity = velocity
currentAnimation.nextDelayedAnimation = UIAnimationFuture()
currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation
currentAnimation.run()
UIAnimationFuture.animations.append(currentAnimation)
return currentAnimation.nextDelayedAnimation!
}
/**
Creates and runs an animation which allows other animations to be chained to it and to each other.
:param: duration The animation duration in seconds
:param: timing A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info)
:param: animations Animation closure
:param: completion Completion closure of type (Bool)->Void
:returns: The created request.
*/
public class func animate(withDuration duration: TimeInterval, timingFunction: CAMediaTimingFunction, animations: @escaping () -> Void, completion: (() -> Void)?) -> Void {
UIView.beginAnimations(nil, context: nil)
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setAnimationTimingFunction(timingFunction)
CATransaction.setCompletionBlock(completion)
animations()
CATransaction.commit()
UIView.commitAnimations()
}
}
|
e8262fcc84d2b63f673cd2c847a77614
| 38.295455 | 304 | 0.655654 | false | false | false | false |
albinekcom/BitBay-Ticker-iOS
|
refs/heads/master
|
Codebase/Common/ReviewController.swift
|
mit
|
1
|
import StoreKit
final class ReviewController {
private let storeReviewController: SKStoreReviewController.Type
private let userDefaults: UserDefaults
private let counterMaximum = 10
private let counterKey = "counter"
private var counter: Int {
get {
userDefaults.integer(forKey: counterKey)
}
set {
userDefaults.set(newValue, forKey: counterKey)
}
}
init(storeReviewController: SKStoreReviewController.Type = SKStoreReviewController.self,
userDefaults: UserDefaults = .standard) {
self.storeReviewController = storeReviewController
self.userDefaults = userDefaults
}
func tryToDisplay(in activeScene: UIWindowScene) {
counter += 1
if counter >= counterMaximum {
counter = 0
// storeReviewController.requestReview(in: activeScene) // TODO: Uncomment before shipping
AnalyticsService.shared.trackReviewRequested()
}
}
}
|
e95af3a0b2a665ea5b8de8d065d6e287
| 27.621622 | 101 | 0.629839 | false | false | false | false |
lemberg/obd2-swift-lib
|
refs/heads/master
|
OBD2-Swift/Classes/Model/Response.swift
|
mit
|
1
|
//
// Response.swift
// OBD2Swift
//
// Created by Max Vitruk on 5/25/17.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
public struct Response : Hashable, Equatable {
var timestamp : Date
var mode : Mode = .none
var pid : UInt8 = 0
var data : Data?
var rawData : [UInt8] = []
public var strigDescriptor : String?
init() {
self.timestamp = Date()
}
public var hashValue: Int {
return Int(mode.rawValue ^ pid)
}
public static func ==(lhs: Response, rhs: Response) -> Bool {
return false
}
public var hasData : Bool {
return data == nil
}
}
|
2cb97e896d19ac522082b49ea552d40f
| 16.942857 | 63 | 0.617834 | false | false | false | false |
joalbright/Gameboard
|
refs/heads/master
|
Gameboards.playground/Sources/Boards/Checkers.swift
|
apache-2.0
|
1
|
import UIKit
public struct Checkers {
public enum PieceType: String {
case none = " "
case checker1 = "●"
case checker2 = "○"
case king1 = "◉"
case king2 = "◎"
}
public static var board: Grid {
return Grid([
8 ✕ (EmptyPiece %% "●"),
8 ✕ ("●" %% EmptyPiece),
8 ✕ (EmptyPiece %% "●"),
8 ✕ EmptyPiece,
8 ✕ EmptyPiece,
8 ✕ ("○" %% EmptyPiece),
8 ✕ (EmptyPiece %% "○"),
8 ✕ ("○" %% EmptyPiece)
])
}
public static let playerPieces = ["●◉","○◎"]
public static func validateJump(_ s1: Square, _ s2: Square, _ p1: Piece, _ p2: Piece, _ grid: Grid, _ hint: Bool = false) -> Bool {
let m1 = s2.0 - s1.0
let m2 = s2.1 - s1.1
let e1 = s1.0 + m1 / 2
let e2 = s1.1 + m2 / 2
guard let jumpedPieceType: PieceType = PieceType(rawValue: grid[e1,e2]), jumpedPieceType != .none else { return false }
switch PieceType(rawValue: p1) ?? .none {
case .checker1:
guard m1 == 2 && abs(m2) == 2 else { return false }
guard jumpedPieceType != .checker1, jumpedPieceType != .king1 else { return false }
case .checker2:
guard m1 == -2 && abs(m2) == 2 else { return false }
guard jumpedPieceType != .checker2, jumpedPieceType != .king2 else { return false }
case .king1:
guard abs(m1) == 2 && abs(m2) == 2 else { return false }
guard jumpedPieceType != .checker1, jumpedPieceType != .king1 else { return false }
case .king2:
guard abs(m1) == 2 && abs(m2) == 2 else { return false }
guard jumpedPieceType != .checker2, jumpedPieceType != .king2 else { return false }
case .none: return false
}
guard !hint else { return true }
grid[e1,e2] = EmptyPiece // remove other player piece
return true
}
public static func validateMove(_ s1: Square, _ s2: Square, _ p1: Piece, _ p2: Piece, _ grid: Grid, _ hint: Bool = false) throws -> Piece? {
let m1 = s2.0 - s1.0
let m2 = s2.1 - s1.1
var kingPiece: PieceType?
guard p2 == EmptyPiece else { throw MoveError.invalidmove }
switch PieceType(rawValue: p1) ?? .none {
case .checker1:
guard (m1 == 1 && abs(m2) == 1) || validateJump(s1, s2, p1, p2, grid, hint) else { throw MoveError.invalidmove }
if s2.c == grid.content.count - 1 { kingPiece = .king1 }
case .checker2:
guard (m1 == -1 && abs(m2) == 1) || validateJump(s1, s2, p1, p2, grid, hint) else { throw MoveError.invalidmove }
if s2.c == 0 { kingPiece = .king2 }
case .king1, .king2:
guard (abs(m1) == 1 && abs(m2) == 1) || validateJump(s1, s2, p1, p2, grid, hint) else { throw MoveError.invalidmove }
case .none: throw MoveError.incorrectpiece
}
guard !hint else { return nil }
let piece = grid[s2.0,s2.1]
grid[s2.0,s2.1] = kingPiece?.rawValue ?? p1 // place my piece in target square
grid[s1.0,s1.1] = EmptyPiece // remove my piece from original square
return piece
}
}
extension Grid {
public func checker(_ rect: CGRect, highlights: [Square], selected: Square?) -> UIView {
let view = UIView(frame: rect)
let w = rect.width / content.count
let h = rect.height / content.count
view.backgroundColor = colors.background
view.layer.cornerRadius = 10
view.layer.masksToBounds = true
for (r,row) in content.enumerated() {
for (c,item) in row.enumerated() {
var piece = "\(item)"
let holder = UIView(frame: CGRect(x: c * w, y: r * h, width: w, height: h))
holder.backgroundColor = (c + r) % 2 == 0 ? colors.background : colors.foreground
let label = HintLabel(frame: CGRect(x: 0, y: 0, width: w, height: h))
label.backgroundColor = .clear
label.textColor = player(piece) == 0 ? colors.player1 : colors.player2
label.highlightColor = colors.highlight
if player(piece) == 1 {
if let index = playerPieces[1].array().index(of: piece) { piece = playerPieces[0].array()[index] }
}
if let selected = selected, selected.0 == r && selected.1 == c { label.textColor = colors.selected }
for highlight in highlights { label.highlight = label.highlight ? true : highlight.0 == r && highlight.1 == c }
label.text = piece
label.textAlignment = .center
label.font = UIFont(name: "Apple Symbols", size: (w + h) / 2 - 10)
holder.addSubview(label)
view.addSubview(holder)
}
}
return view
}
}
|
1f9d5228ca872a8e2fb02453ebf8731d
| 30.448864 | 144 | 0.475339 | false | false | false | false |
giangbvnbgit128/AnViet
|
refs/heads/master
|
AnViet/Class/ViewControllers/TutorialViewController/AVTutorialViewController.swift
|
apache-2.0
|
1
|
//
// AVTutorialViewController.swift
// AnViet
//
// Created by Bui Giang on 5/25/17.
// Copyright © 2017 Bui Giang. All rights reserved.
//
import UIKit
class AVTutorialViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var btnRegis: UIButton!
@IBOutlet weak var btnLogin: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
let arrayImage:[String] = ["tutorial1","tutorial1","tutorial2","tutorial3",
"tutorial4","tutorial1","tutorial1","tutorial0"]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.registerNib(AVTutorialCollectionViewCell.self)
self.automaticallyAdjustsScrollViewInsets = false
self.pageControl.currentPage = 0
self.btnLogin.layer.cornerRadius = 4
self.btnRegis.layer.cornerRadius = 4
self.pageControl.numberOfPages = arrayImage.count
navigationController?.navigationBar.isTranslucent = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func movePageControlWithScroll () {
let pageWidth = collectionView.frame.width
let page = Int(floor((collectionView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
if pageControl.currentPage != page {
self.pageControl.currentPage = page
}
}
@IBAction func actionLogin(_ sender: AnyObject) {
let logicVC = AVLoginViewController()
navigationController?.pushViewController(logicVC, animated: true)
}
@IBAction func actionRegis(_ sender: AnyObject) {
let regisVC = AVRegisterAccountAccountViewController()
navigationController?.pushViewController(regisVC, animated: true)
}
}
extension AVTutorialViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrayImage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue(AVTutorialCollectionViewCell.self, forIndexPath: indexPath) as AVTutorialCollectionViewCell
cell.ConfigCell(nameImage: self.arrayImage[indexPath.row])
return cell
}
}
extension AVTutorialViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return UIScreen.main.bounds.size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.1
}
}
extension AVTutorialViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
movePageControlWithScroll()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
movePageControlWithScroll()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("====Scroll \(scrollView.contentOffset.x) prin y = \(scrollView.contentOffset.y)")
}
}
|
3cdb13ccf63d110959d7830975c82551
| 37.548077 | 133 | 0.700923 | false | false | false | false |
Anish-kumar-dev/instagram-swift
|
refs/heads/master
|
instagram-swift/instagram-swift/instagram-swift/Login/SLLoginViewController.swift
|
mit
|
2
|
//
// SLLoginViewController.swift
// instagram-swift
//
// Created by Dimas Gabriel on 10/21/14.
// Copyright (c) 2014 Swift Libs. All rights reserved.
//
import UIKit
protocol SLLoginViewControllerDelegate {
func loginViewControllerDidCancel(vc: SLLoginViewController)
func loginViewControllerDidLogin(accesToken: String)
func loginViewControllerDidError(error : NSError)
}
class SLLoginViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var mainWebView: UIWebView!
var delegate: SLLoginViewControllerDelegate?
var redirectURI : String?
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: "SLLoginViewController", bundle: nibBundleOrNil)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.mainWebView.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancelButtonTap(sender: UIBarButtonItem) {
self.delegate?.loginViewControllerDidCancel(self)
self.dismissViewControllerAnimated(true, completion: nil)
}
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
if (self.redirectURI != nil){
var urlStr = request.URL.absoluteString
if (urlStr?.hasPrefix(self.redirectURI!) == true) {
urlStr = urlStr!.stringByReplacingOccurrencesOfString("?", withString: "", options:nil, range:nil)
urlStr = urlStr!.stringByReplacingOccurrencesOfString("#", withString: "", options:nil, range:nil)
let urlResources = urlStr!.componentsSeparatedByString("/")
let urlParameters = urlResources.last
let parameters = urlParameters?.componentsSeparatedByString("&")
if parameters?.count == 1 {
let keyValue = parameters![0]
let keyValueArray = keyValue.componentsSeparatedByString("=")
let key = keyValueArray[0]
if key == "access_token" {
self.delegate?.loginViewControllerDidLogin(keyValueArray[1])
self.dismissViewControllerAnimated(true, completion: nil)
}
}else {
// We have an error
let errorString = "Authorization not granted"
let error = NSError(domain: kSLInstagramEngineErrorDomain,
code: kSLInstagramEngineErrorCodeAccessNotGranted,
userInfo: [NSLocalizedDescriptionKey : errorString])
self.delegate?.loginViewControllerDidError(error)
}
return false
}
}
return true
}
}
|
495628bcf72ceeca6a7522b9495e126c
| 36.114943 | 139 | 0.594302 | false | false | false | false |
lanit-tercom-school/grouplock
|
refs/heads/master
|
GroupLockiOS/GroupLock/Scenes/Home_Stack/ProvideKeyScene/ProvideKeyRouter.swift
|
apache-2.0
|
1
|
//
// ProvideKeyRouter.swift
// GroupLock
//
// Created by Sergej Jaskiewicz on 18.07.16.
// Copyright (c) 2016 Lanit-Tercom School. All rights reserved.
//
import UIKit
protocol ProvideKeyRouterInput {
}
class ProvideKeyRouter: ProvideKeyRouterInput {
weak var viewController: ProvideKeyViewController!
// MARK: - Navigation
// MARK: - Communication
func passDataToNextScene(_ segue: UIStoryboardSegue) {
if segue.identifier == "ProcessedFile" {
passDataToProcessedFileScene(segue)
}
}
func passDataToProcessedFileScene(_ segue: UIStoryboardSegue) {
// swiftlint:disable:next force_cast (since the destination is known)
let processedFileViewController = segue.destination as! ProcessedFileViewController
processedFileViewController.output.files = viewController.output.files
processedFileViewController.output.cryptographicKey = viewController.output.keys
processedFileViewController.output.isEncryption = true
}
}
|
659fa37a0fa9ea97bc71d522eb8977a1
| 24.725 | 91 | 0.724976 | false | false | false | false |
Sajjon/ViewComposer
|
refs/heads/master
|
Source/Classes/ViewAttribute/AttributedValues/DataSourceOwner.swift
|
mit
|
1
|
//
// DataSourceOwner.swift
// ViewComposer
//
// Created by Alexander Cyon on 2017-06-11.
//
//
import Foundation
protocol DataSourceOwner: class {
var dataSourceProxy: NSObjectProtocol? { get set }
}
internal extension DataSourceOwner {
func apply(_ style: ViewStyle) {
style.attributes.forEach {
switch $0 {
case .dataSource(let dataSource):
dataSourceProxy = dataSource
case .dataSourceDelegate(let dataSource):
dataSourceProxy = dataSource
default:
break
}
}
}
}
extension UITableView: DataSourceOwner {
var dataSourceProxy: NSObjectProtocol? {
get { return self.dataSource }
set {
guard let specificDataSource = newValue as? UITableViewDataSource else { return }
self.dataSource = specificDataSource
}
}
}
extension UICollectionView: DataSourceOwner {
var dataSourceProxy: NSObjectProtocol? {
get { return self.dataSource }
set {
guard let specificDataSource = newValue as? UICollectionViewDataSource else { return }
self.dataSource = specificDataSource
}
}
}
extension UIPickerView: DataSourceOwner {
var dataSourceProxy: NSObjectProtocol? {
get { return self.dataSource }
set {
guard let specificDataSource = newValue as? UIPickerViewDataSource else { return }
self.dataSource = specificDataSource
}
}
}
|
abb3511d58297c6673d77e11b5c37529
| 25.293103 | 98 | 0.622951 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
utils/benchmark/Graph/prims.swift
|
apache-2.0
|
9
|
//===--- prims.swift - Implementation of Prims MST algorithm --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
@_silgen_name("mach_absolute_time") func __mach_absolute_time__() -> UInt64
struct Node {
var id : Int
var adjList : Array<Int>
init(i : Int) {
id = i
adjList = Array<Int>()
}
}
struct NodeCost {
var nodeId : Int
var cost : Double
}
func getLeftChildIndex(index : Int) -> Int {
return index*2 + 1
}
func getRightChildIndex(index : Int) -> Int {
return (index + 1)*2
}
func getParentIndex(childIndex : Int) -> Int {
return (childIndex - 1)/2
}
class PriorityQueue {
var heap : Array<NodeCost?>
var graphIndexToHeapIndexMap : Array<Int?>
init() {
heap = Array<NodeCost?>()
graphIndexToHeapIndexMap = Array<Int?>()
}
// This should only be called when initializing an uninitialized queue.
func append(n : NodeCost?) {
heap.append(n)
graphIndexToHeapIndexMap.append(n!.nodeId)
}
func dumpDebug() {
print("QUEUE")
for nodeCost in heap {
let nodeId : Int = nodeCost!.nodeId
let cost : Double = nodeCost!.cost
print("(\(nodeId), \(cost))")
}
}
func contains(i : Int) -> Bool {
for nodeCost in heap {
if nodeCost!.nodeId == i {
return true
}
}
return false
}
func checkInvariants(graph : Array<Node>) {
// If the heap is empty, skip everything.
if heap.isEmpty {
return
}
var s = Array<Int>()
s.append(0)
while !s.isEmpty {
let index = s.popLast();
let leftChild = getLeftChildIndex(index);
let rightChild = getRightChildIndex(index);
if (leftChild < heap.count) {
if heap[leftChild]!.cost < heap[index]!.cost {
print("Left: \(heap[leftChild]!.cost); Parent: \(heap[index]!.cost)")
}
assert(heap[leftChild]!.cost >= heap[index]!.cost);
s.append(leftChild);
}
if (rightChild < heap.count) {
if heap[rightChild]!.cost < heap[index]!.cost {
print("Right: \(heap[rightChild]!.cost); Parent: \(heap[index]!.cost)")
}
assert(heap[rightChild]!.cost >= heap[index]!.cost);
s.append(rightChild);
}
}
// Make sure that each element in the graph that is not in the heap has
// its index set to .None
for i in 0..graph.count {
if contains(i) {
assert(graphIndexToHeapIndexMap[i] != .None,
"All items contained in the heap must have an index assigned in map.")
} else {
assert(graphIndexToHeapIndexMap[i] == .None,
"All items not in heap must not have an index assigned in map.")
}
}
}
// Pop off the smallest cost element, updating all data structures along the
// way.
func popHeap() -> NodeCost {
// If we only have one element, just return it.
if heap.count == 1 {
return heap.popLast()!
}
// Otherwise swap the heap head with the last element of the heap and pop
// the heap.
swap(&heap[0], &heap[heap.count-1])
let result = heap.popLast()
// Invalidate the graph index of our old head and update the graph index of
// the new head value.
graphIndexToHeapIndexMap[heap[0]!.nodeId] = .Some(0)
graphIndexToHeapIndexMap[result!.nodeId] = .None
// Re-establish the heap property.
var heapIndex = 0
var smallestIndex : Int
while true {
smallestIndex = updateHeapAtIndex(heapIndex)
if smallestIndex == heapIndex {
break
}
heapIndex = smallestIndex
}
// Return result.
return result!
}
func updateCostIfLessThan(graphIndex : Int, newCost : Double) -> Bool {
// Look up the heap index corresponding to the input graph index.
var heapIndex : Int? = graphIndexToHeapIndexMap[graphIndex]
// If the graph index is not in the heap, return false.
if heapIndex == .None {
return false
}
// Otherwise, look up the cost of the node.
let nodeCost = heap[heapIndex!]
// If newCost >= nodeCost.1, don't update anything and return false.
if newCost >= nodeCost!.cost {
return false
}
// Ok, we know that newCost < nodeCost.1 so replace nodeCost.1 with
// newCost and update all relevant data structures. Return true.
heap[heapIndex!] = .Some(NodeCost(nodeCost!.nodeId, newCost))
while heapIndex != .None && heapIndex! > 0 {
heapIndex = .Some(getParentIndex(heapIndex!))
updateHeapAtIndex(heapIndex!)
}
return true
}
func updateHeapAtIndex(index : Int) -> Int {
let leftChildIndex : Int = getLeftChildIndex(index)
let rightChildIndex : Int = getRightChildIndex(index)
var smallestIndex : Int = 0
if leftChildIndex < heap.count &&
heap[leftChildIndex]!.cost < heap[index]!.cost {
smallestIndex = leftChildIndex
} else {
smallestIndex = index
}
if rightChildIndex < heap.count &&
heap[rightChildIndex]!.cost < heap[smallestIndex]!.cost {
smallestIndex = rightChildIndex
}
if smallestIndex != index {
swap(&graphIndexToHeapIndexMap[heap[index]!.nodeId],
&graphIndexToHeapIndexMap[heap[smallestIndex]!.nodeId])
swap(&heap[index], &heap[smallestIndex])
}
return smallestIndex
}
func isEmpty() -> Bool {
return heap.isEmpty
}
}
func prim(
graph : Array<Node>,
fun : (Int, Int) -> Double) -> Array<Int?> {
var treeEdges = Array<Int?>()
// Create our queue, selecting the first element of the grpah as the root of
// our tree for simplciity.
var queue = PriorityQueue()
queue.append(.Some(NodeCost(0, 0.0)))
// Make the minimum spanning tree root its own parent for simplicity.
treeEdges.append(.Some(0))
// Create the graph.
for i in 1..graph.count {
queue.append(.Some(NodeCost(i, Double.inf())))
treeEdges.append(.None)
}
while !queue.isEmpty() {
let e = queue.popHeap()
let nodeId = e.nodeId
for adjNodeIndex in graph[nodeId].adjList {
if queue.updateCostIfLessThan(adjNodeIndex, fun(graph[nodeId].id,
graph[adjNodeIndex].id)) {
treeEdges[adjNodeIndex] = .Some(nodeId)
}
}
}
return treeEdges
}
struct Edge : Equatable {
var start : Int
var end : Int
}
func ==(lhs: Edge, rhs: Edge) -> Bool {
return lhs.start == rhs.start && lhs.end == rhs.end
}
extension Edge : Hashable {
func hashValue() -> Int {
return start.hashValue() ^ end.hashValue()
}
}
func benchPrimsInternal(iterations: Int) {
for i in 0..iterations {
var graph = Array<Node>()
var nodes : Int[] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 97, 98, 99 ]
var edges : (Int, Int, Double)[] = [
(26, 47, 921),
(20, 25, 971),
(92, 59, 250),
(33, 55, 1391),
(78, 39, 313),
(7, 25, 637),
(18, 19, 1817),
(33, 41, 993),
(64, 41, 926),
(88, 86, 574),
(93, 15, 1462),
(86, 33, 1649),
(37, 35, 841),
(98, 51, 1160),
(15, 30, 1125),
(65, 78, 1052),
(58, 12, 1273),
(12, 17, 285),
(45, 61, 1608),
(75, 53, 545),
(99, 48, 410),
(97, 0, 1303),
(48, 17, 1807),
(1, 54, 1491),
(15, 34, 807),
(94, 98, 646),
(12, 69, 136),
(65, 11, 983),
(63, 83, 1604),
(78, 89, 1828),
(61, 63, 845),
(18, 36, 1626),
(68, 52, 1324),
(14, 50, 690),
(3, 11, 943),
(21, 68, 914),
(19, 44, 1762),
(85, 80, 270),
(59, 92, 250),
(86, 84, 1431),
(19, 18, 1817),
(52, 68, 1324),
(16, 29, 1108),
(36, 80, 395),
(67, 18, 803),
(63, 88, 1717),
(68, 21, 914),
(75, 82, 306),
(49, 82, 1292),
(73, 45, 1876),
(89, 82, 409),
(45, 47, 272),
(22, 83, 597),
(61, 12, 1791),
(44, 68, 1229),
(50, 51, 917),
(14, 53, 355),
(77, 41, 138),
(54, 21, 1870),
(93, 70, 1582),
(76, 2, 1658),
(83, 73, 1162),
(6, 1, 482),
(11, 65, 983),
(81, 90, 1024),
(19, 1, 970),
(8, 58, 1131),
(60, 42, 477),
(86, 29, 258),
(69, 59, 903),
(34, 15, 807),
(37, 2, 1451),
(7, 73, 754),
(47, 86, 184),
(67, 17, 449),
(18, 67, 803),
(25, 4, 595),
(3, 31, 1337),
(64, 31, 1928),
(9, 43, 237),
(83, 63, 1604),
(47, 45, 272),
(86, 88, 574),
(87, 74, 934),
(98, 94, 646),
(20, 1, 642),
(26, 92, 1344),
(18, 17, 565),
(47, 11, 595),
(10, 59, 1558),
(2, 76, 1658),
(77, 74, 1277),
(42, 60, 477),
(80, 36, 395),
(35, 23, 589),
(50, 37, 203),
(6, 96, 481),
(78, 65, 1052),
(1, 52, 127),
(65, 23, 1932),
(46, 51, 213),
(59, 89, 89),
(15, 93, 1462),
(69, 3, 1305),
(17, 37, 1177),
(30, 3, 193),
(9, 15, 818),
(75, 95, 977),
(86, 47, 184),
(10, 12, 1736),
(80, 27, 1010),
(12, 10, 1736),
(86, 1, 1958),
(60, 12, 1240),
(43, 71, 683),
(91, 65, 1519),
(33, 86, 1649),
(62, 26, 1773),
(1, 13, 1187),
(2, 10, 1018),
(91, 29, 351),
(69, 12, 136),
(43, 9, 237),
(29, 86, 258),
(17, 48, 1807),
(31, 64, 1928),
(68, 61, 1936),
(76, 38, 1724),
(1, 6, 482),
(53, 14, 355),
(51, 50, 917),
(54, 13, 815),
(19, 29, 883),
(35, 87, 974),
(70, 96, 511),
(23, 35, 589),
(39, 69, 1588),
(93, 73, 1093),
(13, 73, 435),
(5, 60, 1619),
(42, 41, 1523),
(66, 58, 1596),
(1, 67, 431),
(17, 67, 449),
(30, 95, 906),
(71, 43, 683),
(5, 87, 190),
(12, 78, 891),
(30, 97, 402),
(28, 17, 1131),
(7, 97, 1356),
(58, 66, 1596),
(20, 37, 1294),
(73, 76, 514),
(54, 8, 613),
(68, 35, 1252),
(92, 32, 701),
(3, 90, 652),
(99, 46, 1576),
(13, 54, 815),
(20, 87, 1390),
(36, 18, 1626),
(51, 26, 1146),
(2, 23, 581),
(29, 7, 1558),
(88, 59, 173),
(17, 1, 1071),
(37, 49, 1011),
(18, 6, 696),
(88, 33, 225),
(58, 38, 802),
(87, 50, 1744),
(29, 91, 351),
(6, 71, 1053),
(45, 24, 1720),
(65, 91, 1519),
(37, 50, 203),
(11, 3, 943),
(72, 65, 1330),
(45, 50, 339),
(25, 20, 971),
(15, 9, 818),
(14, 54, 1353),
(69, 95, 393),
(8, 66, 1213),
(52, 2, 1608),
(50, 14, 690),
(50, 45, 339),
(1, 37, 1273),
(45, 93, 1650),
(39, 78, 313),
(1, 86, 1958),
(17, 28, 1131),
(35, 33, 1667),
(23, 2, 581),
(51, 66, 245),
(17, 54, 924),
(41, 49, 1629),
(60, 5, 1619),
(56, 93, 1110),
(96, 13, 461),
(25, 7, 637),
(11, 69, 370),
(90, 3, 652),
(39, 71, 1485),
(65, 51, 1529),
(20, 6, 1414),
(80, 85, 270),
(73, 83, 1162),
(0, 97, 1303),
(13, 33, 826),
(29, 71, 1788),
(33, 12, 461),
(12, 58, 1273),
(69, 39, 1588),
(67, 75, 1504),
(87, 20, 1390),
(88, 97, 526),
(33, 88, 225),
(95, 69, 393),
(2, 52, 1608),
(5, 25, 719),
(34, 78, 510),
(53, 99, 1074),
(33, 35, 1667),
(57, 30, 361),
(87, 58, 1574),
(13, 90, 1030),
(79, 74, 91),
(4, 86, 1107),
(64, 94, 1609),
(11, 12, 167),
(30, 45, 272),
(47, 91, 561),
(37, 17, 1177),
(77, 49, 883),
(88, 23, 1747),
(70, 80, 995),
(62, 77, 907),
(18, 4, 371),
(73, 93, 1093),
(11, 47, 595),
(44, 23, 1990),
(20, 0, 512),
(3, 69, 1305),
(82, 3, 1815),
(20, 88, 368),
(44, 45, 364),
(26, 51, 1146),
(7, 65, 349),
(71, 39, 1485),
(56, 88, 1954),
(94, 69, 1397),
(12, 28, 544),
(95, 75, 977),
(32, 90, 789),
(53, 1, 772),
(54, 14, 1353),
(49, 77, 883),
(92, 26, 1344),
(17, 18, 565),
(97, 88, 526),
(48, 80, 1203),
(90, 32, 789),
(71, 6, 1053),
(87, 35, 974),
(55, 90, 1808),
(12, 61, 1791),
(1, 96, 328),
(63, 10, 1681),
(76, 34, 871),
(41, 64, 926),
(42, 97, 482),
(25, 5, 719),
(23, 65, 1932),
(54, 1, 1491),
(28, 12, 544),
(89, 10, 108),
(27, 33, 143),
(67, 1, 431),
(32, 45, 52),
(79, 33, 1871),
(6, 55, 717),
(10, 58, 459),
(67, 39, 393),
(10, 4, 1808),
(96, 6, 481),
(1, 19, 970),
(97, 7, 1356),
(29, 16, 1108),
(1, 53, 772),
(30, 15, 1125),
(4, 6, 634),
(6, 20, 1414),
(88, 56, 1954),
(87, 64, 1950),
(34, 76, 871),
(17, 12, 285),
(55, 59, 321),
(61, 68, 1936),
(50, 87, 1744),
(84, 44, 952),
(41, 33, 993),
(59, 18, 1352),
(33, 27, 143),
(38, 32, 1210),
(55, 70, 1264),
(38, 58, 802),
(1, 20, 642),
(73, 13, 435),
(80, 48, 1203),
(94, 64, 1609),
(38, 28, 414),
(73, 23, 1113),
(78, 12, 891),
(26, 62, 1773),
(87, 43, 579),
(53, 6, 95),
(59, 95, 285),
(88, 63, 1717),
(17, 5, 633),
(66, 8, 1213),
(41, 42, 1523),
(83, 22, 597),
(95, 30, 906),
(51, 65, 1529),
(17, 49, 1727),
(64, 87, 1950),
(86, 4, 1107),
(37, 98, 1102),
(32, 92, 701),
(60, 94, 198),
(73, 98, 1749),
(4, 18, 371),
(96, 70, 511),
(7, 29, 1558),
(35, 37, 841),
(27, 64, 384),
(12, 33, 461),
(36, 38, 529),
(69, 16, 1183),
(91, 47, 561),
(85, 29, 1676),
(3, 82, 1815),
(69, 58, 1579),
(93, 45, 1650),
(97, 42, 482),
(37, 1, 1273),
(61, 4, 543),
(96, 1, 328),
(26, 0, 1993),
(70, 64, 878),
(3, 30, 193),
(58, 69, 1579),
(4, 25, 595),
(31, 3, 1337),
(55, 6, 717),
(39, 67, 393),
(78, 34, 510),
(75, 67, 1504),
(6, 53, 95),
(51, 79, 175),
(28, 91, 1040),
(89, 78, 1828),
(74, 93, 1587),
(45, 32, 52),
(10, 2, 1018),
(49, 37, 1011),
(63, 61, 845),
(0, 20, 512),
(1, 17, 1071),
(99, 53, 1074),
(37, 20, 1294),
(10, 89, 108),
(33, 92, 946),
(23, 73, 1113),
(23, 88, 1747),
(49, 17, 1727),
(88, 20, 368),
(21, 54, 1870),
(70, 93, 1582),
(59, 88, 173),
(32, 38, 1210),
(89, 59, 89),
(23, 44, 1990),
(38, 76, 1724),
(30, 57, 361),
(94, 60, 198),
(59, 10, 1558),
(55, 64, 1996),
(12, 11, 167),
(36, 24, 1801),
(97, 30, 402),
(52, 1, 127),
(58, 87, 1574),
(54, 17, 924),
(93, 74, 1587),
(24, 36, 1801),
(2, 37, 1451),
(91, 28, 1040),
(59, 55, 321),
(69, 11, 370),
(8, 54, 613),
(29, 85, 1676),
(44, 19, 1762),
(74, 79, 91),
(93, 56, 1110),
(58, 10, 459),
(41, 50, 1559),
(66, 51, 245),
(80, 19, 1838),
(33, 79, 1871),
(76, 73, 514),
(98, 37, 1102),
(45, 44, 364),
(16, 69, 1183),
(49, 41, 1629),
(19, 80, 1838),
(71, 57, 500),
(6, 4, 634),
(64, 27, 384),
(84, 86, 1431),
(5, 17, 633),
(96, 88, 334),
(87, 5, 190),
(70, 21, 1619),
(55, 33, 1391),
(10, 63, 1681),
(11, 62, 1339),
(33, 13, 826),
(64, 70, 878),
(65, 72, 1330),
(70, 55, 1264),
(64, 55, 1996),
(50, 41, 1559),
(46, 99, 1576),
(88, 96, 334),
(51, 20, 868),
(73, 7, 754),
(80, 70, 995),
(44, 84, 952),
(29, 19, 883),
(59, 69, 903),
(57, 53, 1575),
(90, 13, 1030),
(28, 38, 414),
(12, 60, 1240),
(85, 58, 573),
(90, 55, 1808),
(4, 10, 1808),
(68, 44, 1229),
(92, 33, 946),
(90, 81, 1024),
(53, 75, 545),
(45, 30, 272),
(41, 77, 138),
(21, 70, 1619),
(45, 73, 1876),
(35, 68, 1252),
(13, 96, 461),
(53, 57, 1575),
(82, 89, 409),
(28, 61, 449),
(58, 61, 78),
(27, 80, 1010),
(61, 58, 78),
(38, 36, 529),
(80, 30, 397),
(18, 59, 1352),
(62, 11, 1339),
(95, 59, 285),
(51, 98, 1160),
(6, 18, 696),
(30, 80, 397),
(69, 94, 1397),
(58, 85, 573),
(48, 99, 410),
(51, 46, 213),
(57, 71, 500),
(91, 30, 104),
(65, 7, 349),
(79, 51, 175),
(47, 26, 921),
(4, 61, 543),
(98, 73, 1749),
(74, 77, 1277),
(61, 28, 449),
(58, 8, 1131),
(61, 45, 1608),
(74, 87, 934),
(71, 29, 1788),
(30, 91, 104),
(13, 1, 1187),
(0, 26, 1993),
(82, 49, 1292),
(43, 87, 579),
(24, 45, 1720),
(20, 51, 868),
(77, 62, 907),
(82, 75, 306),
]
for n in nodes {
graph.append(Node(n))
}
var map = Dictionary<Edge, Double>()
for tup in edges {
map.add(Edge(tup.0, tup.1), tup.2)
graph[tup.0].adjList.append(tup.1)
}
let treeEdges = prim(graph, { (start: Int, end: Int) in
return map[Edge(start, end)]
})
//for i in 0...treeEdges.count {
// print("Node: \(i). Parent: \(treeEdges[i]!)")
//}
}
}
func benchPrims() {
let start = __mach_absolute_time__()
benchPrimsInternal(100)
let delta = __mach_absolute_time__() - start
print("\(delta) nanoseconds.")
}
benchPrims()
|
3f86e51f7635a141979ff43d9278b988
| 22.276119 | 81 | 0.454419 | false | false | false | false |
tangplin/JSON2Anything
|
refs/heads/master
|
JSON2Anything/Source/Extensions/Swift+J2A.swift
|
mit
|
1
|
//
// Swift+J2A.swift
//
// Copyright (c) 2014 Pinglin Tang.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
extension Int: Anything {
static func anythingWithJSON(argumentJSON:[AnyObject]) -> Int? {
if argumentJSON.count != 1 {
return nil
}
let o : AnyObject = argumentJSON[0]
if let o_n = o as? NSNumber {
return o_n.integerValue
} else if let o_s = o as? NSString {
return o_s.integerValue
} else {
return nil
}
}
}
extension Float: Anything {
static func anythingWithJSON(argumentJSON:[AnyObject]) -> Float? {
if argumentJSON.count != 1 {
return nil
}
let o : AnyObject = argumentJSON[0]
if let o_n = o as? NSNumber {
return o_n.floatValue
} else if let o_s = o as? NSString {
return o_s.floatValue
} else {
return nil
}
}
}
extension Double: Anything {
static func anythingWithJSON(argumentJSON:[AnyObject]) -> Double? {
if argumentJSON.count != 1 {
return nil
}
let o : AnyObject = argumentJSON[0]
if let o_n = o as? NSNumber {
return o_n.doubleValue
} else if let o_s = o as? NSString {
return o_s.doubleValue
} else {
return nil
}
}
}
extension Bool: Anything {
static func anythingWithJSON(argumentJSON:[AnyObject]) -> Bool? {
if argumentJSON.count != 1 {
return nil
}
let o : AnyObject = argumentJSON[0]
if let o_n = o as? NSNumber {
return o_n.boolValue
} else if let o_s = o as? NSString {
return o_s.boolValue
} else {
return nil
}
}
}
|
a6f5d92d70b03ecc5a5bb43fcadcd9ab
| 27.627451 | 80 | 0.594724 | false | false | false | false |
podverse/podverse-ios
|
refs/heads/master
|
Podverse/DeletingPodcasts.swift
|
agpl-3.0
|
1
|
//
// DeletingPodcasts.swift
// Podverse
//
// Created by Mitchell Downey on 11/19/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import Foundation
final class DeletingPodcasts {
static let shared = DeletingPodcasts()
var podcastKeys = [String]()
func addPodcast(podcastId:String?, feedUrl:String?) {
if let podcastId = podcastId {
if self.podcastKeys.filter({$0 == podcastId}).count < 1 {
self.podcastKeys.append(podcastId)
}
} else if let feedUrl = feedUrl {
if self.podcastKeys.filter({$0 == feedUrl}).count < 1 {
self.podcastKeys.append(feedUrl)
}
}
}
func removePodcast(podcastId:String?, feedUrl:String?) {
if let podcastId = podcastId, let index = self.podcastKeys.index(of: podcastId) {
self.podcastKeys.remove(at: index)
} else if let feedUrl = feedUrl, let index = self.podcastKeys.index(of: feedUrl) {
self.podcastKeys.remove(at: index)
}
}
func hasMatchingId(podcastId:String) -> Bool {
if let _ = self.podcastKeys.index(of: podcastId) {
return true
}
return false
}
func hasMatchingUrl(feedUrl:String) -> Bool {
if let _ = self.podcastKeys.index(of: feedUrl) {
return true
}
return false
}
}
|
b7ef44681426f898cef6f7be082d7a9d
| 27.098039 | 90 | 0.573622 | false | false | false | false |
ScoutHarris/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Cells/WPReusableTableViewCells.swift
|
gpl-2.0
|
2
|
import Foundation
import UIKit
import WordPressShared.WPTableViewCell
class WPReusableTableViewCell: WPTableViewCell {
override func prepareForReuse() {
super.prepareForReuse()
textLabel?.text = nil
textLabel?.textAlignment = .natural
textLabel?.adjustsFontSizeToFitWidth = false
detailTextLabel?.text = nil
detailTextLabel?.textColor = UIColor.black
imageView?.image = nil
accessoryType = .none
accessoryView = nil
selectionStyle = .default
accessibilityLabel = nil
}
}
class WPTableViewCellDefault: WPReusableTableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class WPTableViewCellSubtitle: WPReusableTableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class WPTableViewCellValue1: WPReusableTableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class WPTableViewCellValue2: WPReusableTableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .value2, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class WPTableViewCellBadge: WPTableViewCellDefault {
var badgeCount: Int = 0 {
didSet {
if badgeCount > 0 {
badgeLabel.text = String(badgeCount)
accessoryView = badgeLabel
accessoryType = .none
} else {
accessoryView = nil
}
}
}
fileprivate lazy var badgeLabel: UILabel = {
let label = UILabel(frame: CGRect(origin: CGPoint.zero, size: WPTableViewCellBadge.badgeSize))
label.layer.masksToBounds = true
label.layer.cornerRadius = WPTableViewCellBadge.badgeCornerRadius
label.textAlignment = .center
label.backgroundColor = WPStyleGuide.newKidOnTheBlockBlue()
label.textColor = UIColor.white
return label
}()
fileprivate static let badgeSize = CGSize(width: 50, height: 30)
fileprivate static var badgeCornerRadius: CGFloat {
return badgeSize.height / 2
}
}
|
16b93528afc83642332fe5507cd82bd3
| 29.344444 | 102 | 0.672281 | false | false | false | false |
nurv/CSSwift
|
refs/heads/master
|
CSSwift/searching.swift
|
cc0-1.0
|
1
|
//
// searching.swift
// CSSwift
//
// Created by Artur Ventura on 19/08/14.
// Copyright (c) 2014 Artur Ventura. All rights reserved.
//
import Foundation
// Sequential Search
// Best: O(1), Avg: O(n), Worst: O(n)
func sequentialSearch<T: Equatable> (array:[T], object:T) -> Bool{
for i in array{
if i == object{
return true
}
}
return false;
}
// Binary Search
// Best: O(1), Avg: O(log n), Worst: O(log n)
func binarySearch<T: Comparable> (array:[T], object:T) -> Bool{
var low = 0
var high = array.count - 1
while low <= high {
println(array[low...high])
var ix = (low + high) / 2
if object == array[ix] {
return true
} else if object < array[ix] {
high = ix - 1
} else {
low = ix + 1
}
}
return false
}
// Hash-based Search
// Best: O(1), Avg: O(1), Worst: O(n)
func loadTable<T: Comparable>(size:Int, C:[T], hash: (T)->Int) -> Array<LinkedList<T>?>{
var array = Array<LinkedList<T>?>(count: size, repeatedValue: nil)
for(var i = 0; i<C.count-1; i++){
var h = hash(C[i])
if array[h] == nil{
array[h] = LinkedList<T>()
}
array[h]!.add(array[h]!.length, object: C[i]);
}
return array
}
func hashSearch<T: Comparable>(C:[T], hash: (T)->Int, object:T) -> Bool{
var array = loadTable(C.count, C, hash)
var h = hash(object)
if let list = array[h]{
return list.find(object)
}else{
return false
}
}
|
e39ec570de17990f890d62925efdd0ba
| 20.849315 | 88 | 0.516614 | false | false | false | false |
shirai/SwiftLearning
|
refs/heads/master
|
playground/配列.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
/*
*
*宣言
*
*/
//型を指定して配列を作成
let party: [String] = ["勇者", "戦士", "魔法使い", "僧侶"]
print(party[2]) //インデックスで要素を参照する。
print("パーティの人数は、\(party.count)人です。") //要素数をcountプロパティで取得する。
//初期値で型を推測して配列を作成
var お弁当 = ["おにぎり", "玉子焼き", "ミニトマト", "アスパラ"]
//初期値に同じ数字を入れて配列を作成。
let point = Array(repeating: 100, count: 4) //repeatedValueではなくrepeating
print(point)
//空の配列を作成する。(データ型の指定が必須)
var box : [UInt] = []
var box2 = [UInt] ()
var box3 : Array<UInt> = []
//配列が空かどうかをisEmptyプロパティで調べる
if box.isEmpty {
print("配列は空です。")
}
//初期化の時に異なる型の要素を含める。Any又はAnyObject
var a: Array<Any> = [100, 123.4, "文字列"] // 異なる型の要素
print(50 + (a[0] as! Int)) // 計算等する場合はキャスト(型変換)が必要(なぜかasの後に!が必要)
//関数を配列要素にする。
let add = { (a: Double, b: Double) -> Double in return a + b } //二つDouble型の値を受け取ったら、足し算して返す
let sub = { (a: Double, b: Double) -> Double in return a - b }
let mul = { (a: Double, b: Double) -> Double in return a * b }
let div = { (a: Double, b: Double) -> Double in return a / b }
var ope: [(Double, Double) -> Double] //[(関数の引数) -> 関数の戻り値]
ope = [add, sub, mul, div]
ope[2](10, 20)
/*
*
*要素の追加
*
*/
お弁当.append("タコさんウインナー")
お弁当 += ["ブロッコリー","りんご"]
print(お弁当)
//宣言時の値と異なる型の値を混在はできない
//お弁当.append(100) //エラーになる
//定数の配列は、要素を変更したり追加することはできない。
//party.append("盗賊") // エラーになる
//要素を指定位置に挿入する
//お弁当.insert("キウイ", atIndex : 2)
お弁当.insert("キウイ", at : 2)
print(お弁当)
/*
*
*要素の変更
*
*/
お弁当[0] = "おむすび"
print(お弁当)
//お弁当[10] = "ふりかけ"// インデックス範囲外を指定すると実行時エラーになる
//お弁当[0] = 10 // 配列の宣言時と異なる値を代入するとコンパイル時エラーになる
// インデックス1の値(インデックス2は含めない)を変更
お弁当[1..<2] = ["ゆで卵", "肉巻き"]
print(お弁当)
// インデックス0の値(インデックス2は含めない)を変更
お弁当[0...2] = ["サンドイッチ", "オムレツ"]
print(お弁当)
/*
*
*要素の削除
*
*/
//指定したインデックスの要素を削除
お弁当.remove(at: 2)
print(お弁当)
//配列の最後の要素を削除
お弁当.removeLast()
print(お弁当)
//初期化
お弁当 = []
print(お弁当)
/*
*
*イティレーション
*
*/
//for文を使って繰り返し処理
var book = ["こころ", "山椒魚", "檸檬", "細雪"]
for chara in book{
print(chara)
}
//インデックスも使いたい場合
//for (index, chara) in enumerate(party) {
for(index, chara) in book.enumerated(){
print("\(index + 1): \(chara)")
}
/*
*
*配列のコピー
*
*/
var book2 = book
book2[1] = "蟹工船"
print(book)
print(book2)
|
ba8e72b5e99088309bed7d707886ced1
| 17.125 | 91 | 0.627126 | false | false | false | false |
mtransitapps/mtransit-for-ios
|
refs/heads/master
|
MonTransit/Source/SQL/SQLHelper/ServiceDateDataProvider.swift
|
apache-2.0
|
1
|
//
// ServiceDateDataProvider.swift
// MonTransit
//
// Created by Thibault on 16-01-07.
// Copyright © 2016 Thibault. All rights reserved.
//
import UIKit
import SQLite
class ServiceDateDataProvider {
private let service_dates = Table("service_dates")
private let service_id = Expression<String>("service_id")
private let date = Expression<Int>("date")
init()
{
}
func createServiceDate(iAgency:Agency, iSqlCOnnection:Connection) -> Bool
{
do {
let wServiceRawType = iAgency.getMainFilePath()
let wFileText = iAgency.getZipData().getDataFileFromZip(iAgency.mGtfsServiceDate, iDocumentName: wServiceRawType)
if wFileText != ""
{
let wServices = wFileText.stringByReplacingOccurrencesOfString("'", withString: "").componentsSeparatedByString("\n")
let docsTrans = try! iSqlCOnnection.prepare("INSERT INTO service_dates (service_id, date) VALUES (?,?)")
try iSqlCOnnection.transaction {
for wService in wServices
{
let wServiceFormated = wService.componentsSeparatedByString(",")
if wServiceFormated.count == 2{
try docsTrans.run(wServiceFormated[0], Int(wServiceFormated[1])!)
}
}
}
}
return true
}
catch {
print("insertion failed: \(error)")
return false
}
}
func retrieveCurrentService(iId:Int) -> [String]
{
// get the user's calendar
let userCalendar = NSCalendar.currentCalendar()
// choose which date and time components are needed
let requestedComponents: NSCalendarUnit = [
NSCalendarUnit.Year,
NSCalendarUnit.Month,
NSCalendarUnit.Day ]
// get the components
let dateTimeComponents = userCalendar.components(requestedComponents, fromDate: NSDate())
let wYear = dateTimeComponents.year
let wMonth = dateTimeComponents.month
let wDay = dateTimeComponents.day
//Verify if the current date is in DB
let wDate = getDatesLimit(iId)
let wTimeString = String(format: "%04d", wYear) + String(format: "%02d", wMonth) + String(format: "%02d", wDay)
var wTimeInt = Int(wTimeString)!
if wDate.max.getNSDate().getDateToInt() < wTimeInt{
wTimeInt = wDate.max.getNSDate().getDateToInt()
}
let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates.filter(date == wTimeInt))
var wCurrentService = [String]()
for wService in wServices
{
wCurrentService.append(wService.get(service_id))
}
return wCurrentService
}
func retrieveCurrentServiceByDate(iDate:Int, iId:Int) -> [String]
{
let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates.filter(date == iDate))
var wCurrentServices = [String]()
for wService in wServices
{
wCurrentServices.append(wService.get(service_id))
}
return wCurrentServices
}
func getDatesLimit(iId:Int) ->(min:GTFSTimeObject, max:GTFSTimeObject){
var min:GTFSTimeObject!
var max:GTFSTimeObject!
var wGtfsList:[GTFSTimeObject] = []
let wServices = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(service_dates)
for wService in wServices{
wGtfsList.append(GTFSTimeObject(iGtfsDate: wService[date]))
}
min = wGtfsList.first
max = wGtfsList.last
return (min,max)
}
}
|
d46e83bdb9485babb019872db8a3f7dc
| 31.491803 | 133 | 0.575322 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Money/Tests/MoneyKitTests/Balance/CryptoFormatterTests.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import XCTest
// swiftlint:disable type_body_length
class CryptoFormatterTests: XCTestCase {
private var englishLocale: Locale!
private var btcFormatter: CryptoFormatter!
private var ethFormatter: CryptoFormatter!
private var bchFormatter: CryptoFormatter!
private var xlmFormatter: CryptoFormatter!
override func setUp() {
super.setUp()
englishLocale = Locale(identifier: "en_US")
btcFormatter = CryptoFormatter(
locale: englishLocale,
cryptoCurrency: .bitcoin,
minFractionDigits: 1,
withPrecision: .short
)
ethFormatter = CryptoFormatter(
locale: englishLocale,
cryptoCurrency: .ethereum,
minFractionDigits: 1,
withPrecision: .short
)
bchFormatter = CryptoFormatter(
locale: englishLocale,
cryptoCurrency: .bitcoinCash,
minFractionDigits: 1,
withPrecision: .short
)
xlmFormatter = CryptoFormatter(
locale: englishLocale,
cryptoCurrency: .stellar,
minFractionDigits: 1,
withPrecision: .short
)
}
override func tearDown() {
englishLocale = nil
btcFormatter = nil
ethFormatter = nil
bchFormatter = nil
xlmFormatter = nil
super.tearDown()
}
func testFormatWithoutSymbolBtc() {
XCTAssertEqual(
"0.00000001",
btcFormatter.format(minor: 1)
)
XCTAssertEqual(
"0.1",
btcFormatter.format(major: 0.1)
)
XCTAssertEqual(
"0.0",
btcFormatter.format(major: 0)
)
XCTAssertEqual(
"1.0",
btcFormatter.format(major: 1)
)
XCTAssertEqual(
"1,000.0",
btcFormatter.format(major: 1000)
)
XCTAssertEqual(
"1,000,000.0",
btcFormatter.format(major: 1000000)
)
}
func testFormatWithSymbolBtc() {
XCTAssertEqual(
"0.00000001 BTC",
btcFormatter.format(minor: 1, includeSymbol: true)
)
XCTAssertEqual(
"0.1 BTC",
btcFormatter.format(major: 0.1, includeSymbol: true)
)
XCTAssertEqual(
"0.0 BTC",
btcFormatter.format(major: 0, includeSymbol: true)
)
XCTAssertEqual(
"1.0 BTC",
btcFormatter.format(major: 1, includeSymbol: true)
)
XCTAssertEqual(
"1,000.0 BTC",
btcFormatter.format(major: 1000, includeSymbol: true)
)
XCTAssertEqual(
"1,000,000.0 BTC",
btcFormatter.format(major: 1000000, includeSymbol: true)
)
}
func testFormatEthShortPrecision() {
XCTAssertEqual(
"0.0 ETH",
ethFormatter.format(minor: 1, includeSymbol: true)
)
XCTAssertEqual(
"0.0 ETH",
ethFormatter.format(minor: 1000, includeSymbol: true)
)
XCTAssertEqual(
"0.0 ETH",
ethFormatter.format(minor: 1000000, includeSymbol: true)
)
XCTAssertEqual(
"0.0 ETH",
ethFormatter.format(minor: 1000000000, includeSymbol: true)
)
}
func testFormatEthLongPrecision() {
let formatter = CryptoFormatter(
locale: englishLocale,
cryptoCurrency: .ethereum,
minFractionDigits: 1,
withPrecision: .long
)
XCTAssertEqual(
"0.000000000000000001 ETH",
formatter.format(minor: 1, includeSymbol: true)
)
XCTAssertEqual(
"0.000000000000001 ETH",
formatter.format(minor: 1000, includeSymbol: true)
)
XCTAssertEqual(
"0.000000000001 ETH",
formatter.format(minor: 1000000, includeSymbol: true)
)
XCTAssertEqual(
"0.000000001 ETH",
formatter.format(minor: 1000000000, includeSymbol: true)
)
}
func testFormatWithoutSymbolEth() {
XCTAssertEqual(
"0.00000001",
ethFormatter.format(minor: 10000000000)
)
XCTAssertEqual(
"0.00001",
ethFormatter.format(minor: 10000000000000)
)
XCTAssertEqual(
"0.1",
ethFormatter.format(minor: 100000000000000000)
)
XCTAssertEqual(
"1.0",
ethFormatter.format(minor: 1000000000000000000)
)
XCTAssertEqual(
"10.0",
ethFormatter.format(major: 10)
)
XCTAssertEqual(
"100.0",
ethFormatter.format(major: 100)
)
XCTAssertEqual(
"1,000.0",
ethFormatter.format(major: 1000)
)
XCTAssertEqual(
"1.213333",
ethFormatter.format(major: 1.213333)
)
XCTAssertEqual(
"1.12345678",
ethFormatter.format(major: 1.123456789)
)
}
func testFormatWithSymbolEth() {
XCTAssertEqual(
"0.00000001 ETH",
ethFormatter.format(minor: 10000000000, includeSymbol: true)
)
XCTAssertEqual(
"0.00001 ETH",
ethFormatter.format(minor: 10000000000000, includeSymbol: true)
)
XCTAssertEqual(
"0.1 ETH",
ethFormatter.format(minor: 100000000000000000, includeSymbol: true)
)
XCTAssertEqual(
"1.213333 ETH",
ethFormatter.format(major: 1.213333, includeSymbol: true)
)
XCTAssertEqual(
"1.12345678 ETH",
ethFormatter.format(major: 1.123456789, includeSymbol: true)
)
XCTAssertEqual(
"1.12345678 ETH",
ethFormatter.format(minor: 1123456789333222111, includeSymbol: true)
)
}
func testFormatWithoutSymbolBch() {
XCTAssertEqual(
"0.00000001",
bchFormatter.format(minor: 1)
)
XCTAssertEqual(
"0.1",
bchFormatter.format(major: 0.1)
)
XCTAssertEqual(
"0.0",
bchFormatter.format(major: 0)
)
XCTAssertEqual(
"1.0",
bchFormatter.format(major: 1)
)
XCTAssertEqual(
"1,000.0",
bchFormatter.format(major: 1000)
)
XCTAssertEqual(
"1,000,000.0",
bchFormatter.format(major: 1000000)
)
}
func testFormatWithSymbolBch() {
XCTAssertEqual(
"0.00000001 BCH",
bchFormatter.format(minor: 1, includeSymbol: true)
)
XCTAssertEqual(
"0.1 BCH",
bchFormatter.format(major: 0.1, includeSymbol: true)
)
XCTAssertEqual(
"0.0 BCH",
bchFormatter.format(major: 0, includeSymbol: true)
)
XCTAssertEqual(
"1.0 BCH",
bchFormatter.format(major: 1, includeSymbol: true)
)
XCTAssertEqual(
"1,000.0 BCH",
bchFormatter.format(major: 1000, includeSymbol: true)
)
XCTAssertEqual(
"1,000,000.0 BCH",
bchFormatter.format(major: 1000000, includeSymbol: true)
)
}
func testFormatWithoutSymbolXlm() {
XCTAssertEqual(
"0.0000001",
xlmFormatter.format(minor: 1)
)
XCTAssertEqual(
"0.1",
xlmFormatter.format(major: 0.1)
)
XCTAssertEqual(
"0.0",
xlmFormatter.format(major: 0)
)
XCTAssertEqual(
"1.0",
xlmFormatter.format(major: 1)
)
XCTAssertEqual(
"1,000.0",
xlmFormatter.format(major: 1000)
)
XCTAssertEqual(
"1,000,000.0",
xlmFormatter.format(major: 1000000)
)
}
func testFormatWithSymbolXlm() {
XCTAssertEqual(
"0.0000001 XLM",
xlmFormatter.format(minor: 1, includeSymbol: true)
)
XCTAssertEqual(
"0.1 XLM",
xlmFormatter.format(major: 0.1, includeSymbol: true)
)
XCTAssertEqual(
"0.0 XLM",
xlmFormatter.format(major: 0, includeSymbol: true)
)
XCTAssertEqual(
"1.0 XLM",
xlmFormatter.format(major: 1, includeSymbol: true)
)
XCTAssertEqual(
"1,000.0 XLM",
xlmFormatter.format(major: 1000, includeSymbol: true)
)
XCTAssertEqual(
"1,000,000.0 XLM",
xlmFormatter.format(major: 1000000, includeSymbol: true)
)
}
func testItalyLocaleFormattingBtc() {
let italyLocale = Locale(identifier: "it_IT")
let formatter = CryptoFormatter(
locale: italyLocale,
cryptoCurrency: .bitcoin,
minFractionDigits: 1,
withPrecision: .long
)
XCTAssertEqual(
"0,00000001",
formatter.format(minor: 1)
)
XCTAssertEqual(
"0,1",
formatter.format(major: 0.1)
)
XCTAssertEqual(
"0,0",
formatter.format(major: 0)
)
XCTAssertEqual(
"1,0",
formatter.format(major: 1)
)
XCTAssertEqual(
"1.000,0",
formatter.format(major: 1000)
)
XCTAssertEqual(
"1.000.000,0",
formatter.format(major: 1000000)
)
}
}
|
2ee2111ffffdd4ed501d77d29efbf2d8
| 26.520891 | 80 | 0.520951 | false | false | false | false |
couchbits/iOSToolbox
|
refs/heads/master
|
Sources/Extensions/UIKit/UILongPressGestureRecognizerExtensions.swift
|
mit
|
1
|
//
// UILongTapGestureRecognizerExtension.swift
// Alamofire
//
// Created by Dominik Gauggel on 10.04.18.
//
import Foundation
import UIKit
private var LongPressBlockHandlerKey: UInt8 = 0
extension UILongPressGestureRecognizer {
public convenience init(longPress: ((UILongPressGestureRecognizer) -> Void)? = nil) {
self.init()
initializeHandler(longPress)
}
public var longPress: ((UILongPressGestureRecognizer) -> Void)? {
get {
return blockHandler?.blockHandler
}
set {
initializeHandler(newValue)
}
}
internal var blockHandler: GenericBlockHandler<UILongPressGestureRecognizer>? {
get { return getAssociated(associativeKey: &LongPressBlockHandlerKey) }
set { setAssociated(value: newValue, associativeKey: &LongPressBlockHandlerKey) }
}
internal func initializeHandler(_ handler: ((UILongPressGestureRecognizer) -> Void)?) {
if let handler = blockHandler {
removeTarget(handler, action: GenericBlockHandlerAction)
}
if let handler = handler {
blockHandler = GenericBlockHandler(object: self, blockHandler: handler)
if let blockHandler = blockHandler {
addTarget(blockHandler, action: GenericBlockHandlerAction)
}
}
}
}
|
cf9731a1049bfea812b5627dd3ab4242
| 28.977778 | 91 | 0.661972 | false | false | false | false |
ustwo/formvalidator-swift
|
refs/heads/master
|
Tests/Unit Tests/Conditions/PresentConditionTests.swift
|
mit
|
1
|
//
// PresentConditionTests.swift
// FormValidatorSwift
//
// Created by Aaron McTavish on 13/01/2016.
// Copyright © 2016 ustwo. All rights reserved.
//
import XCTest
@testable import FormValidatorSwift
final class PresentConditionTests: XCTestCase {
// MARK: - Properties
let condition = PresentCondition()
// MARK: - Test Success
func testPresentCondition_Success() {
// Given
let testInput = "Foo"
let expectedResult = true
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
// MARK: - Test Failure
func testPresentCondition_Empty_Failure() {
// Given
let testInput = ""
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
func testPresentCondition_Nil_Failure() {
// Given
let testInput: String? = nil
let expectedResult = false
// Test
AssertCondition(condition, testInput: testInput, expectedResult: expectedResult)
}
}
|
3a6e8bb4f1d9c65b33446a8bc75fadb5
| 21.314815 | 88 | 0.59668 | false | true | false | false |
orcudy/archive
|
refs/heads/master
|
ios/razzle/circle-indicator/COIndicatorCircle/COIndicatorCircle.swift
|
gpl-3.0
|
1
|
//
// Circle.swift
// COIndicatorCircle
//
// Created by Chris Orcutt on 8/24/15.
// Copyright (c) 2015 Chris Orcutt. All rights reserved.
//
import UIKit
import QuartzCore
class COIndicatorCircle: UIView {
@IBOutlet var view: UIView!
var radius: Float!
let thickness: Float = 5
let foregroundCircleColor: UIColor = UIColor.blackColor()
let backgroundCircleColor: UIColor = UIColor.whiteColor()
private var backgroundCircleLayer: CAShapeLayer!
private var foregroundCircleLayer: CAShapeLayer!
private var backgroundPath: UIBezierPath!
private var foregroundPath: UIBezierPath!
//MARK: Initialization
func baseInit() {
NSBundle.mainBundle().loadNibNamed("COIndicatorCircle", owner: self, options: nil)
if frame.width > frame.height {
radius = Float(frame.height) / 2.0
} else {
radius = Float(frame.width) / 2.0
}
let x = center.x / 2
let y = center.y / 2
let width = radius * 2
let height = radius * 2
let arcCenter = CGPoint(x: CGFloat(radius), y: CGFloat(radius))
self.backgroundPath = UIBezierPath(arcCenter: arcCenter, radius: CGFloat(radius - (thickness / 2)), startAngle: 0, endAngle: 2 * pi, clockwise: true)
self.foregroundPath = UIBezierPath(arcCenter: arcCenter, radius: CGFloat(radius - (thickness / 2)), startAngle: 0, endAngle: 0.83 * 2 * pi, clockwise: true)
self.backgroundCircleLayer = createCircleLayer(view.bounds, path: backgroundPath.CGPath, lineWidth: CGFloat(thickness), strokeColor: backgroundCircleColor.CGColor, fillColor: UIColor.clearColor().CGColor, backgroundColor: UIColor.clearColor().CGColor)
self.view.layer.addSublayer(backgroundCircleLayer)
self.foregroundCircleLayer = createCircleLayer(view.bounds, path: foregroundPath.CGPath, lineWidth: CGFloat(thickness), strokeColor: foregroundCircleColor.CGColor, fillColor: UIColor.clearColor().CGColor, backgroundColor: UIColor.clearColor().CGColor)
self.view.layer.addSublayer(foregroundCircleLayer)
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = 2.0
animation.repeatCount = 1.0
animation.fromValue = 0.0
animation.toValue = 1.0
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
foregroundCircleLayer.addAnimation(animation, forKey: "foreGroundCircleAnimation")
backgroundColor = UIColor.clearColor()
self.view.frame = CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))
self.view.center = CGPoint(x: frame.size.width / 2, y: frame.size.height / 2)
self.addSubview(self.view)
}
func createCircleLayer(frame: CGRect, path: CGPath, lineWidth: CGFloat, strokeColor: CGColor, fillColor: CGColor, backgroundColor: CGColor) -> CAShapeLayer {
let circleLayer = CAShapeLayer()
circleLayer.frame = frame
circleLayer.path = path
circleLayer.lineWidth = lineWidth
circleLayer.strokeColor = strokeColor
circleLayer.fillColor = fillColor
circleLayer.backgroundColor = backgroundColor
return circleLayer
}
override init(frame: CGRect) {
super.init(frame: frame)
baseInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
baseInit()
}
}
|
17ad4f5e2a4e38ac8d1ac91ab9114e91
| 40.152941 | 259 | 0.677816 | false | false | false | false |
rmannion/RMCore
|
refs/heads/master
|
RMCore/Table Manager/Models/RMTableSection.swift
|
mit
|
1
|
//
// RMTableSection.swift
// RMCore
//
// Created by Ryan Mannion on 4/29/16.
// Copyright © 2016 Ryan Mannion. All rights reserved.
//
import Foundation
import ReactiveKit
public class RMTableSection {
public var rows: [RMTableRow] = []
public var headerClass: RMTableSectionView.Type?
public weak var headerDelegate: RMTableSectionViewDelegate?
public var headerText: String?
public var headerHeight: CGFloat = 0
public var footerClass: RMTableSectionView.Type?
public var footerHeight: CGFloat = 0
public var userInfo: Any?
public var closed: Property<Bool> = Property(false)
public var section: Int = 0
public var indexTitle: String?
public init(rows: [RMTableRow] = []) {
self.rows = rows
}
public var selectedRows: [RMTableRow] {
return rows.filter { $0.isSelected.value }
}
}
|
97a764cfcacd57143a250c39b2411ec9
| 26.25 | 63 | 0.68578 | false | false | false | false |
Chaosspeeder/YourGoals
|
refs/heads/master
|
YourGoals/Utility/Date+DateRange.swift
|
lgpl-3.0
|
1
|
//
// Date+DateRange.swift
// YourGoals
//
// Created by André Claaßen on 17.12.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
// this extension is based on ideas of
// http://adampreble.net/blog/2014/09/iterating-over-range-of-dates-swift/
extension Calendar {
/// create a range from start date to end date. default is stepping a day with interval 1
///
/// - Parameters:
/// - startDate: start date
/// - endDate: end date
/// - stepUnits: step in days
/// - stepValue: 1
/// - Returns: a range
func dateRange(startDate: Date, endDate: Date, stepComponent: Calendar.Component = .day, stepValue: Int = 1) -> DateRange {
let dateRange = DateRange(calendar: self, startDate: startDate, endDate: endDate,
stepComponent: stepComponent, stepValue: stepValue, multiplier: 0)
return dateRange
}
/// create a range of dates with a start date and a number of steps (eg. days)
///
/// - Parameters:
/// - startDate: start date of the range
/// - steps: number of steps
/// - stepComponent: component eg. day
/// - stepValue: increment
/// - Returns: a daterange of nil
func dateRange(startDate: Date, steps:Int, stepComponent: Calendar.Component = .day, stepValue: Int = 1) -> DateRange? {
guard let endDate = self.date(byAdding: stepComponent, value: stepValue * steps, to: startDate) else {
return nil
}
let dateRange = DateRange(calendar: self, startDate: startDate, endDate: endDate,
stepComponent: stepComponent, stepValue: stepValue, multiplier: 0)
return dateRange
}
}
/// the date range is sequence for iterating easier over a range of dates
struct DateRange:Sequence {
var calendar: Calendar
var startDate: Date
var endDate: Date
var stepComponent: Calendar.Component
var stepValue: Int
fileprivate var multiplier: Int
// MARK: - Sequence Protocol
func makeIterator() -> DateRange.Iterator {
return Iterator(range: self)
}
// Mark: - Iterator
struct Iterator: IteratorProtocol {
var range: DateRange
mutating func next() -> Date? {
guard let nextDate = range.calendar.date(byAdding: Calendar.Component.day, value: range.stepValue * range.multiplier, to: range.startDate) else {
return nil
}
if nextDate > range.endDate {
return nil
}
else {
range.multiplier += 1
return nextDate
}
}
}
}
|
f61324d3af349d98b99251ba5f8281d5
| 31.388235 | 157 | 0.593534 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.