repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Kicksort/KSSwipeStack | KSSwipeStack/Classes/SwipeOptions.swift | 1 | 750 | //
// SwipeOptions.swift
// KSSwipeStack
//
// Created by Simon Arneson on 2017-03-24.
// Copyright © 2017 Kicksort Consulting AB. All rights reserved.
//
import UIKit
public struct SwipeOptions {
public var throwingThreshold = Float(800)
public var snapDuration = 0.1
public var allowHorizontalSwipes = true
public var allowVerticalSwipes = false
public var horizontalPanThreshold = CGFloat(0.5)
public var verticalPanThreshold = CGFloat(0.5)
public var visibleImageOrigin = CGPoint(x: 0, y: 0)
public var allowUndo = true
public var maxRenderedCards = 5
public var refillThreshold = 10
public var dismissAnimationDuration = 0.25
public var freezeWhenDismissing = false
public init() {}
}
| mit | 6cc691f21c440aa2cfbbc9bddd016864 | 27.807692 | 65 | 0.719626 | 4.115385 | false | false | false | false |
grandiere/box | box/Firebase/Database/Model/FDbAlgoItem.swift | 1 | 1318 | import Foundation
class FDbAlgoItem:FDbProtocol
{
static let latitude:String = "latitude"
static let longitude:String = "longitude"
static let created:String = "created"
let latitude:Double
let longitude:Double
let created:TimeInterval
init(
latitude:Double,
longitude:Double,
created:TimeInterval)
{
self.latitude = latitude
self.longitude = longitude
self.created = created
}
//MARK: node protocol
required init?(snapshot:Any)
{
guard
let snapshotDict:[String:Any] = snapshot as? [String:Any],
let latitude:Double = snapshotDict[FDbAlgoItem.latitude] as? Double,
let longitude:Double = snapshotDict[FDbAlgoItem.longitude] as? Double,
let created:TimeInterval = snapshotDict[FDbAlgoItem.created] as? TimeInterval
else
{
return nil
}
self.latitude = latitude
self.longitude = longitude
self.created = created
}
func json() -> Any?
{
let json:[String:Any] = [
FDbAlgoItem.latitude:latitude,
FDbAlgoItem.longitude:longitude,
FDbAlgoItem.created:created]
return json
}
}
| mit | 0178bf13e6222b1c6804e3a7603ac22d | 23.867925 | 89 | 0.578907 | 5.030534 | false | false | false | false |
qbalsdon/br.cd | brcd/Pods/RSBarcodes_Swift/Source/RSUnifiedCodeGenerator.swift | 1 | 4026 | //
// RSUnifiedCodeGenerator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/10/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import Foundation
import UIKit
import AVFoundation
public class RSUnifiedCodeGenerator: RSCodeGenerator {
public var isBuiltInCode128GeneratorSelected = false
public var fillColor: UIColor = UIColor.whiteColor()
public var strokeColor: UIColor = UIColor.blackColor()
public class var shared: RSUnifiedCodeGenerator {
return UnifiedCodeGeneratorSharedInstance
}
// MARK: RSCodeGenerator
public func generateCode(contents: String, inputCorrectionLevel:InputCorrectionLevel, machineReadableCodeObjectType: String) -> UIImage? {
var codeGenerator: RSCodeGenerator?
switch machineReadableCodeObjectType {
case AVMetadataObjectTypeQRCode, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode:
return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType))
case AVMetadataObjectTypeCode39Code:
codeGenerator = RSCode39Generator()
case AVMetadataObjectTypeCode39Mod43Code:
codeGenerator = RSCode39Mod43Generator()
case AVMetadataObjectTypeEAN8Code:
codeGenerator = RSEAN8Generator()
case AVMetadataObjectTypeEAN13Code:
codeGenerator = RSEAN13Generator()
case AVMetadataObjectTypeInterleaved2of5Code:
codeGenerator = RSITFGenerator()
case AVMetadataObjectTypeITF14Code:
codeGenerator = RSITF14Generator()
case AVMetadataObjectTypeUPCECode:
codeGenerator = RSUPCEGenerator()
case AVMetadataObjectTypeCode93Code:
codeGenerator = RSCode93Generator()
// iOS 8 included, but my implementation's performance is better :)
case AVMetadataObjectTypeCode128Code:
if self.isBuiltInCode128GeneratorSelected {
return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType))
} else {
codeGenerator = RSCode128Generator()
}
case AVMetadataObjectTypeDataMatrixCode:
codeGenerator = RSCodeDataMatrixGenerator()
case RSBarcodesTypeISBN13Code:
codeGenerator = RSISBN13Generator()
case RSBarcodesTypeISSN13Code:
codeGenerator = RSISSN13Generator()
case RSBarcodesTypeExtendedCode39Code:
codeGenerator = RSExtendedCode39Generator()
default:
print("No code generator selected.")
}
if codeGenerator != nil {
codeGenerator!.fillColor = self.fillColor
codeGenerator!.strokeColor = self.strokeColor
return codeGenerator!.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObjectType)
} else {
return nil
}
}
public func generateCode(contents: String, machineReadableCodeObjectType: String) -> UIImage? {
return self.generateCode(contents, inputCorrectionLevel: .Medium, machineReadableCodeObjectType: machineReadableCodeObjectType)
}
public func generateCode(machineReadableCodeObject: AVMetadataMachineReadableCodeObject, inputCorrectionLevel: InputCorrectionLevel) -> UIImage? {
return self.generateCode(machineReadableCodeObject.stringValue, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObject.type)
}
public func generateCode(machineReadableCodeObject: AVMetadataMachineReadableCodeObject) -> UIImage? {
return self.generateCode(machineReadableCodeObject, inputCorrectionLevel: .Medium)
}
}
let UnifiedCodeGeneratorSharedInstance = RSUnifiedCodeGenerator()
| mit | 4cff7c586dfb56a0a94f367fb9f5a40d | 45.275862 | 192 | 0.730253 | 6.71 | false | false | false | false |
alexktchen/ExchangeRate | ExchangeRate/SettingViewController.swift | 1 | 5529 | //
// SettingViewController.swift
// ExchangeRate
//
// Created by Alex Chen on 2015/10/3.
// Copyright © 2015 AlexChen. All rights reserved.
//
import UIKit
class SettingViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "setting_view_title".localized
//self.tableView.tableFooterView = UIView(frame: CGRectZero)
self.tableView.backgroundColor = UIColor.whiteColor()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewWillAppear(animated: Bool) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 2
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let sectionHeaderHeight: CGFloat = 40
if scrollView.contentOffset.y <= sectionHeaderHeight&&scrollView.contentOffset.y >= 0 {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
} else if scrollView.contentOffset.y >= sectionHeaderHeight {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0)
}
}
override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let view = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
view.frame = CGRectMake(0, 0, self.tableView.frame.size.width, 30.0)
if section == 0 {
let margin = self.tableView.frame.size.width / 2 / 2
let label = UILabel(frame: CGRectMake(20, 0, self.tableView.frame.size.width - margin, 30))
view.contentView.addSubview(label)
label.numberOfLines = 0
label.textColor = UIColor.lightGrayColor()
label.userInteractionEnabled = true
label.textAlignment = NSTextAlignment.Left
label.font = UIFont(name: label.font.fontName, size: 12)
label.text = "開啟當地貨幣或依據您的地理位置資訊來顯示所處的國家貨幣."
} else {
let label = UILabel(frame: CGRectMake(10, 0, self.tableView.frame.size.width, 30))
view.contentView.addSubview(label)
label.numberOfLines = 0
label.textColor = UIColor.lightGrayColor()
label.userInteractionEnabled = true
label.textAlignment = NSTextAlignment.Center
label.font = UIFont(name: label.font.fontName, size: 12)
label.text = "資料來源為 Yahoo Finance."
}
return view
}
override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
return 80
} else {
return 200
}
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 3317d64e06149d0ef766847f3fa41508 | 34.454545 | 157 | 0.676374 | 5.069638 | false | false | false | false |
michalziman/mz-location-picker | MZLocationPicker/Classes/MZLocationPickerView.swift | 1 | 7381 | //
// MZLocationPickerView.swift
// Pods
//
// Created by Michal Ziman on 27/07/2017.
//
//
import UIKit
import MapKit
fileprivate struct Constants {
static let shadowOpacity: Float = 0.3
static let bottomShadowOffset: CGSize = CGSize(width: 0, height: -3)
static let topShadowOffset: CGSize = CGSize(width: 0, height: 3)
static let shadowRadius: CGFloat = 2
static let animationDuration: TimeInterval = 0.15
}
class MZLocationPickerView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var navigationBar: UINavigationBar!
@IBOutlet weak var navigationItem: UINavigationItem!
@IBOutlet weak var cancelButton: UIBarButtonItem!
@IBOutlet weak var cancelCrossButton: UIButton!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var searchView: UIView!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var chosenLocationView: UIView!
@IBOutlet weak var chosenLocationLabel: UILabel!
@IBOutlet weak var useButton: UIButton!
@IBOutlet var showCancelSearchConstraint: NSLayoutConstraint!
@IBOutlet var showSearchConstraint: NSLayoutConstraint!
@IBOutlet var showChosenLocationConstraint: NSLayoutConstraint!
weak var searchResultsView: UIView? = nil {
willSet {
if let oldSrv = searchResultsView {
oldSrv.removeFromSuperview()
}
}
didSet {
if let newSrv = searchResultsView {
addToSearchView(view: newSrv)
newSrv.isHidden = !isShowingSearchResults
}
}
}
weak var recentLocationsView: UIView? = nil {
willSet {
if let oldRlv = recentLocationsView {
oldRlv.removeFromSuperview()
}
}
didSet {
if let newRlv = recentLocationsView {
addToSearchView(view: newRlv)
newRlv.isHidden = isShowingSearchResults
}
}
}
func addToSearchView(view:UIView) {
var newFrame = searchView.frame
newFrame.origin.y = searchBar.frame.height
newFrame.size.height = searchView.frame.height - searchBar.frame.height
view.frame = newFrame
view.translatesAutoresizingMaskIntoConstraints = false
searchView.addSubview(view)
searchView.addConstraints([
NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: searchBar, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: searchView, attribute: .bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: view, attribute: .leading, relatedBy: .equal, toItem: searchView, attribute: .leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: searchView, attribute: .trailing, multiplier: 1, constant: 0)
])
}
var chosenLocation: CLLocation? = nil {
didSet {
guard let cl = chosenLocation else {
return
}
// Replace annotation with new one
mapView.removeAnnotations(mapView.annotations)
let annotation = MKPointAnnotation()
annotation.coordinate = cl.coordinate
mapView.addAnnotation(annotation)
}
}
var chosenLocationName: String? = nil {
didSet {
chosenLocationLabel.text = chosenLocationName
showChosenLocationConstraint.isActive = true
UIView.animate(withDuration: Constants.animationDuration) {
self.layoutIfNeeded()
}
}
}
var isShowingLocateMe: Bool {
set {
navigationItem.leftBarButtonItem = newValue ? MKUserTrackingBarButtonItem(mapView: mapView) : nil
}
get {
return (navigationItem.leftBarButtonItem != nil)
}
}
var isShowingSearch: Bool {
set {
showSearchConstraint.isActive = newValue
showCancelSearchConstraint.isActive = newValue
UIView.animate(withDuration: Constants.animationDuration) {
self.layoutIfNeeded()
}
}
get {
return showSearchConstraint.isActive
}
}
var isShowingSearchResults: Bool = false {
didSet {
if isShowingSearchResults {
if let srv = searchResultsView {
srv.isHidden = false
}
if let rlv = recentLocationsView {
rlv.isHidden = true
}
} else {
if let srv = searchResultsView {
srv.isHidden = true
}
if let rlv = recentLocationsView {
rlv.isHidden = false
}
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initSubviews()
}
func initSubviews() {
// Load from nib
let nib = UINib(nibName: "MZLocationPickerView", bundle: Bundle(for: type(of:self)))
nib.instantiate(withOwner: self, options: nil)
contentView.frame = bounds
addSubview(contentView)
searchView.layer.masksToBounds = false
searchView.layer.shadowColor = UIColor.black.cgColor
searchView.layer.shadowOpacity = Constants.shadowOpacity
searchView.layer.shadowOffset = Constants.topShadowOffset
searchView.layer.shadowRadius = Constants.shadowRadius
chosenLocationView.layer.masksToBounds = false
chosenLocationView.layer.shadowColor = UIColor.black.cgColor
chosenLocationView.layer.shadowOpacity = Constants.shadowOpacity
chosenLocationView.layer.shadowOffset = Constants.bottomShadowOffset
chosenLocationView.layer.shadowRadius = Constants.shadowRadius
translatesAutoresizingMaskIntoConstraints = false
showCancelSearchConstraint.isActive = false
showSearchConstraint.isActive = false
showChosenLocationConstraint.isActive = false
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
}
func keyboardWillShow(_ notification:Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
showSearchConstraint.constant = keyboardRectangle.height
}
}
func setTranslations(from tranlsator:MZLocationPickerTranslator) {
navigationItem.title = tranlsator.locationPickerTitleText
cancelButton.title = tranlsator.locationPickerCancelText
searchBar.placeholder = tranlsator.locationPickerSearchText
useButton.setTitle(tranlsator.locationPickerUseText, for: .normal)
}
@IBAction func hideSearch(_ sender: Any) {
endEditing(true)
isShowingSearch = false
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mit | 0b281f00130c79eaa762fb70b3bf0d19 | 35.181373 | 153 | 0.629996 | 5.532984 | false | false | false | false |
soulfly/guinea-pig-smart-bot | node_modules/quickblox/samples/cordova/video_chat/plugins/cordova-plugin-iosrtc/src/PluginMediaStreamTrack.swift | 4 | 3492 | import Foundation
class PluginMediaStreamTrack : NSObject, RTCMediaStreamTrackDelegate {
var rtcMediaStreamTrack: RTCMediaStreamTrack
var id: String
var kind: String
var eventListener: ((data: NSDictionary) -> Void)?
var eventListenerForEnded: (() -> Void)?
var lostStates = Array<String>()
init(rtcMediaStreamTrack: RTCMediaStreamTrack) {
NSLog("PluginMediaStreamTrack#init()")
self.rtcMediaStreamTrack = rtcMediaStreamTrack
self.id = rtcMediaStreamTrack.label // NOTE: No "id" property provided.
self.kind = rtcMediaStreamTrack.kind
}
deinit {
NSLog("PluginMediaStreamTrack#deinit()")
}
func run() {
NSLog("PluginMediaStreamTrack#run() [kind:%@, id:%@]", String(self.kind), String(self.id))
self.rtcMediaStreamTrack.delegate = self
}
func getJSON() -> NSDictionary {
return [
"id": self.id,
"kind": self.kind,
"label": self.rtcMediaStreamTrack.label,
"enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false,
"readyState": PluginRTCTypes.mediaStreamTrackStates[self.rtcMediaStreamTrack.state().rawValue] as String!
]
}
func setListener(
eventListener: (data: NSDictionary) -> Void,
eventListenerForEnded: () -> Void
) {
NSLog("PluginMediaStreamTrack#setListener() [kind:%@, id:%@]", String(self.kind), String(self.id))
self.eventListener = eventListener
self.eventListenerForEnded = eventListenerForEnded
for readyState in self.lostStates {
self.eventListener!(data: [
"type": "statechange",
"readyState": readyState,
"enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false
])
if readyState == "ended" {
self.eventListenerForEnded!()
}
}
self.lostStates.removeAll()
}
func setEnabled(value: Bool) {
NSLog("PluginMediaStreamTrack#setEnabled() [kind:%@, id:%@, value:%@]",
String(self.kind), String(self.id), String(value))
self.rtcMediaStreamTrack.setEnabled(value)
}
// TODO: No way to stop the track.
// Check https://github.com/eface2face/cordova-plugin-iosrtc/issues/140
func stop() {
NSLog("PluginMediaStreamTrack#stop() [kind:%@, id:%@]", String(self.kind), String(self.id))
NSLog("PluginMediaStreamTrack#stop() | stop() not implemented (see: https://github.com/eface2face/cordova-plugin-iosrtc/issues/140")
// NOTE: There is no setState() anymore
// self.rtcMediaStreamTrack.setState(RTCTrackStateEnded)
// Let's try setEnabled(false), but it also fails.
self.rtcMediaStreamTrack.setEnabled(false)
}
/**
* Methods inherited from RTCMediaStreamTrackDelegate.
*/
func mediaStreamTrackDidChange(rtcMediaStreamTrack: RTCMediaStreamTrack!) {
let state_str = PluginRTCTypes.mediaStreamTrackStates[self.rtcMediaStreamTrack.state().rawValue] as String!
NSLog("PluginMediaStreamTrack | state changed [kind:%@, id:%@, state:%@, enabled:%@]",
String(self.kind), String(self.id), String(state_str), String(self.rtcMediaStreamTrack.isEnabled()))
if self.eventListener != nil {
self.eventListener!(data: [
"type": "statechange",
"readyState": state_str,
"enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false
])
if self.rtcMediaStreamTrack.state().rawValue == RTCTrackStateEnded.rawValue {
self.eventListenerForEnded!()
}
} else {
// It may happen that the eventListener is not yet set, so store the lost states.
self.lostStates.append(state_str)
}
}
}
| apache-2.0 | 2950a308d51d576efa80b2286ff46f71 | 27.59322 | 134 | 0.690149 | 3.990857 | false | false | false | false |
qtds8810/RxSamples_Pod | RxSamples_Pod/TwoWayBind/ShipmentDeal/ProductInfoModel.swift | 1 | 1090 | //
// ProductInfoModel.swift
// RxSamples_Pod
//
// Created by 左得胜 on 2017/8/31.
// Copyright © 2017年 zds. All rights reserved.
//
import Foundation
struct ProductInfoModel {
let id: Int
let name: String
let unitPrice: Int
let count: Variable<Int>
}
extension ProductInfoModel: IdentifiableType, Equatable, Hashable {
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
var hashValue: Int {
return id.hashValue
}
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func ==(lhs: ProductInfoModel, rhs: ProductInfoModel) -> Bool {
return lhs.id == rhs.id
}
var identity: Int {
return id
}
}
| mit | 8b1bf47d0f1adcb25785227ec41cc395 | 24.139535 | 81 | 0.618871 | 4.048689 | false | false | false | false |
lplotni/xconf_swift_example | test/test/GameScene.swift | 1 | 1002 | import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!";
myLabel.fontSize = 65;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func mouseDown(theEvent: NSEvent) {
/* Called when a mouse click occurs */
let location = theEvent.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.position = location;
sprite.setScale(0.5)
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
| mit | 398e490e4e87c5b0bb9dfc0e865392c6 | 30.3125 | 93 | 0.620758 | 4.911765 | false | false | false | false |
XLsn0w/XLsn0wKit_swift | XLsn0wKit/Extensions/UILable+Extensions.swift | 1 | 809 |
import UIKit
extension UILabel {
/// UILable遍历构造器
///
/// - Parameters:
/// - title: 文字
/// - textColor: 文字颜色
/// - fontSize: 文字大小
/// - numOfLines: 文字行数
/// - alignment: 对齐方式
convenience init(title: String?,
textColor: UIColor = UIColor.darkGray,
fontSize: CGFloat = 14,
numOfLines: Int = 0,
alignment: NSTextAlignment = .left){
self.init()
self.text = title
self.textColor = textColor
self.font = UIFont(name: "DINCond-Bold", size: fontSize)
self.numberOfLines = numOfLines
self.textAlignment = alignment
self.sizeToFit()
}
}
| mit | d4f4cf50b5dd17064b005b1ea2d2dd74 | 22.84375 | 64 | 0.49017 | 4.709877 | false | false | false | false |
velvetroom/columbus | Source/View/Settings/VSettingsListCellDetailLevelListCell.swift | 1 | 1815 | import UIKit
final class VSettingsListCellDetailLevelListCell:UICollectionViewCell
{
private weak var labelTitle:UILabel!
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let labelTitle:UILabel = UILabel()
labelTitle.isUserInteractionEnabled = false
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.font = UIFont.medium(size:VSettingsListCellDetailLevelListCell.Constants.titleFontSize)
labelTitle.textColor = UIColor.colourBackgroundDark
self.labelTitle = labelTitle
addSubview(labelTitle)
NSLayoutConstraint.equalsVertical(
view:labelTitle,
toView:self)
NSLayoutConstraint.leftToLeft(
view:labelTitle,
toView:self,
constant:VSettingsListCellDetailLevelListCell.Constants.titleLeft)
NSLayoutConstraint.rightToRight(
view:labelTitle,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
labelTitle.textColor = UIColor.white
}
else
{
labelTitle.textColor = UIColor(white:0, alpha:0.3)
}
}
//MARK: internal
func config(model:MSettingsDetailLevelProtocol)
{
labelTitle.text = model.title
hover()
}
}
| mit | 03a759a83230008370321e68f2eda9b1 | 22.571429 | 106 | 0.591185 | 5.619195 | false | false | false | false |
britez/sdk-ios | Example/Tests/Tests.swift | 1 | 7821 | // https://github.com/Quick/Quick
import Quick
import Nimble
import sdk_ios_v2
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("tests for decidir 2.0 API") {
it("when payment data is ok") {
let paymentTokenApi = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741", isSandbox: true)
let pti = PaymentTokenInfo()
pti.cardNumber = "44213211231"
pti.cardExpirationMonth = "12"
pti.cardExpirationYear = "20"
pti.cardHolderName = "OSCAR CAMPOS"
pti.securityCode = "123"
let holder = CardHolderIdentification()
holder.type = "dni"
holder.number = "123123123"
pti.cardHolderIdentification = holder
paymentTokenApi.createPaymentToken(paymentTokenInfo: pti) { (paymentToken, error) in
expect(error).to(beNil())
if let paymentToken = paymentToken {
expect(paymentToken.id) != ""
}
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
done()
}
}
it("when payment data is ok") {
let paymentTokenApi = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741", isSandbox: true)
let pti = PaymentTokenInfo()
pti.cardNumber = "44213211231"
pti.cardExpirationMonth = "12"
pti.cardExpirationYear = "20"
pti.cardHolderName = "OSCAR CAMPOS"
pti.securityCode = "123"
let holder = CardHolderIdentification()
holder.type = "dni"
holder.number = "123123123"
pti.cardHolderIdentification = holder
paymentTokenApi.createPaymentToken(paymentTokenInfo: pti) { (paymentToken, error) in
expect(error).to(beNil())
if let paymentToken = paymentToken {
expect(paymentToken.id) != ""
}
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
done()
}
}
it("when apiKey is wrong") {
let paymentTokenApi = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741")
let pti = PaymentTokenInfo()
pti.cardNumber = "44213211231"
pti.cardExpirationMonth = "12"
pti.cardExpirationYear = "20"
pti.cardHolderName = "OSCAR CAMPOS"
pti.securityCode = "123"
let holder = CardHolderIdentification()
holder.type = "dni"
holder.number = "123123123"
pti.cardHolderIdentification = holder
paymentTokenApi.createPaymentToken(paymentTokenInfo: pti) { (paymentToken, error) in
expect(paymentToken).to(beNil())
guard error == nil else {
if case let ErrorResponse.Error(statusCode, _, _) = error! {
expect(403) == statusCode
}
return
}
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
done()
}
}
it("when cardNumer is expired") {
let paymentTokenApi = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741", isSandbox: true)
let pti = PaymentTokenInfo()
pti.cardNumber = "44213211231"
pti.cardExpirationMonth = "12"
pti.cardExpirationYear = "12"
pti.cardHolderName = "OSCAR CAMPOS"
pti.securityCode = "123"
let holder = CardHolderIdentification()
holder.type = "dni"
holder.number = "123123123"
pti.cardHolderIdentification = holder
paymentTokenApi.createPaymentToken(paymentTokenInfo: pti) { (paymentToken, error) in
expect(paymentToken).to(beNil())
guard error == nil else {
if case let ErrorResponse.Error(_, _, dec as ModelError) = error! {
expect("invalid_request_error") == dec.errorType
expect(dec.validationErrors?.count) == 1
let validationError = dec.validationErrors?.popLast()
expect(validationError?.code) == "CardData"
expect(validationError?.param) == "expired card"
}
return
}
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
done()
}
}
it("when create payment with wrong card token") {
let paymentTokenApi = PaymentsTokenAPI(publicKey: "e9cdb99fff374b5f91da4480c8dca741", isSandbox: true)
let pti = PaymentTokenInfoWithCardToken()
pti.token = "someToken"
pti.securityCode = "123"
paymentTokenApi.createPaymentTokenWithCardToken(paymentTokenInfoWithCardToken: pti) { (paymentToken, error) in
expect(paymentToken).to(beNil())
guard error == nil else {
if case let ErrorResponse.Error(_, _, dec as ModelError) = error! {
expect("invalid_request_error") == dec.errorType
expect(dec.validationErrors?.count) == 1
let validationError = dec.validationErrors?.popLast()
expect(validationError?.code) == "invalid_param"
expect(validationError?.param) == "token"
}
return
}
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
done()
}
}
}
}
}
| mit | c750b33d734086e77a8862dbd834b277 | 36.421053 | 126 | 0.399437 | 6.86655 | false | false | false | false |
geeven/EveryWeekSwiftDemo | DrawingBoard/DrawingBoard/ViewController.swift | 1 | 2489 | //
// ViewController.swift
// DrawingBoard
//
// Created by Geeven on 16/3/6.
// Copyright © 2016年 Geeven. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
//MARK: - 生命周期方法
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK: - 私有控件
/// 画布
private lazy var printView: GDDrawingView! = GDDrawingView()
}
// MARK: - 设置事件
extension ViewController {
/// 清屏
@IBAction func clearnScreen(sender: AnyObject) {
printView.clearnScreen()
}
/// 上一退
@IBAction func undo(sender: AnyObject) {
printView.undo()
}
/// 橡皮
@IBAction func eraser(sender: AnyObject) {
printView.erase()
}
/// 选择图片
@IBAction func choosePicture(sender: AnyObject) {
let pickVc = UIImagePickerController()
pickVc.sourceType = .SavedPhotosAlbum
pickVc.delegate = self
presentViewController(pickVc, animated: true, completion: nil)
}
/// 设置色彩
@IBAction func chooseColor(sender: AnyObject) {
}
/// 设置线宽
@IBAction func setLineWidth(sender: AnyObject) {
}
/// 保存图片到相册
@IBAction func saveDrawing(sender: AnyObject) {
printView.saveDrawing()
let alertVc = UIAlertController(title: "操作提示", message: "成功保存到相册", preferredStyle: .Alert)
let action:UIAlertAction = UIAlertAction(title: "确定", style:.Default, handler: nil)
alertVc.addAction(action)
presentViewController(alertVc, animated: true, completion: nil)
}
}
//MARK: - UIImagePickerControllerDelegate
extension ViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print(info)
let image = info["UIImagePickerControllerOriginalImage"]
}
}
extension ViewController {
private func setUpUI() {
view.addSubview(printView)
printView.frame = CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64)
}
} | mit | 4de44d328505e4a074cc5ffccc813d72 | 22.534653 | 123 | 0.609848 | 4.829268 | false | false | false | false |
CosmicMind/Material | Sources/iOS/Data/DataSourceItem.swift | 3 | 1876 | /*
* The MIT License (MIT)
*
* Copyright (C) 2019, CosmicMind, Inc. <http://cosmicmind.com>.
* 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
public struct DataSourceItem {
/// Stores an the data for the item.
public var data: Any?
/// Width for horizontal scroll direction.
public var width: CGFloat?
/// Height for vertical scroll direction.
public var height: CGFloat?
/**
Initializer.
- Parameter data: A reference to an Any that is associated
with a width or height.
- Parameter width: The width for the horizontal scroll direction.
- Parameter height: The height for the vertical scroll direction.
*/
public init(data: Any? = nil, width: CGFloat? = nil, height: CGFloat? = nil) {
self.data = data
self.width = width
self.height = height
}
}
| mit | f46495a90aed1b4be8fc22833554b581 | 36.52 | 80 | 0.726546 | 4.393443 | false | false | false | false |
akuraru/PureViewIcon | PureViewIcon/Views/PVISearch.swift | 1 | 2327 | //
// PVISearch.swift
//
// Created by akuraru on 2017/02/11.
//
import UIKit
import SnapKit
extension PVIView {
func makeSearchConstraints() {
base.snp.updateConstraints { (make) in
make.width.equalToSuperview()
make.height.equalToSuperview()
make.center.equalToSuperview()
}
base.transform = resetTransform()
before.setup(width: 2)
main.setup(width: 2)
after.setup(width: 2)
// before
before.top.alpha = 0
before.left.alpha = 1
before.right.alpha = 1
before.bottom.alpha = 0
before.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().multipliedBy(8 / 17.0)
make.centerY.equalToSuperview().multipliedBy(26 / 17.0)
make.width.equalToSuperview().multipliedBy(4 / 34.0)
make.height.equalToSuperview().multipliedBy(11 / 34.0)
}
before.view.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI_4))
// main
main.top.alpha = 0
main.left.alpha = 0
main.right.alpha = 0
main.bottom.alpha = 0
main.view.snp.makeConstraints { (make) in
make.centerX.equalToSuperview().multipliedBy(19 / 17.0)
make.centerY.equalToSuperview().multipliedBy(15 / 17.0)
make.width.equalToSuperview().multipliedBy(22 / 34.0)
make.height.equalToSuperview().multipliedBy(22 / 34.0)
}
main.view.transform = resetTransform()
// after
after.top.alpha = 0
after.left.alpha = 0
after.right.alpha = 0
after.bottom.alpha = 0
after.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.width.equalToSuperview()
make.height.equalToSuperview()
}
after.view.transform = resetTransform()
}
func searchLayoutSubviews() {
before.view.layer.borderWidth = 0
before.view.layer.cornerRadius = 0
main.view.layer.borderWidth = self.frame.width * 2.0 / 34
main.view.layer.cornerRadius = self.frame.width * 11 / 34
after.view.layer.borderWidth = 0
after.view.layer.cornerRadius = 0
}
}
| mit | a11df81d69ca5c1d5c169a62625ccf97 | 30.445946 | 81 | 0.579287 | 4.365854 | false | false | false | false |
ruslanskorb/CoreStore | Sources/ListSnapshot.swift | 1 | 24181 | //
// ListSnapshot.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - ListSnapshot
/**
A `ListSnapshot` holds a stable list of `DynamicObject` identifiers. This is typically created by a `ListPublisher` and are designed to work well with `DiffableDataSource.TableView`s and `DiffableDataSource.CollectionView`s. For detailed examples, see the documentation on `DiffableDataSource.TableView` and `DiffableDataSource.CollectionView`.
While the `ListSnapshot` stores only object identifiers, all accessors to its items return `ObjectPublisher`s, which are lazily created. For more details, see the documentation on `ListObject`.
Since `ListSnapshot` is a value type, you can freely modify its items.
*/
public struct ListSnapshot<O: DynamicObject>: RandomAccessCollection, Hashable {
// MARK: Public (Accessors)
/**
The `DynamicObject` type associated with this list
*/
public typealias ObjectType = O
/**
The type for the section IDs
*/
public typealias SectionID = String
/**
The type for the item IDs
*/
public typealias ItemID = O.ObjectID
/**
Returns the object at the given index.
- parameter index: the index of the object. Using an index above the valid range will raise an exception.
- returns: the `ObjectPublisher<O>` interfacing the object at the specified index
*/
public subscript(index: Index) -> ObjectPublisher<O> {
let context = self.context!
let itemID = self.diffableSnapshot.itemIdentifiers[index]
return context.objectPublisher(objectID: itemID)
}
/**
Returns the object at the given index, or `nil` if out of bounds.
- parameter index: the index for the object. Using an index above the valid range will return `nil`.
- returns: the `ObjectPublisher<O>` interfacing the object at the specified index, or `nil` if out of bounds
*/
public subscript(safeIndex index: Index) -> ObjectPublisher<O>? {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers
guard itemIDs.indices.contains(index) else {
return nil
}
let itemID = itemIDs[index]
return context.objectPublisher(objectID: itemID)
}
/**
Returns the object at the given `sectionIndex` and `itemIndex`.
- parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will raise an exception.
- parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will raise an exception.
- returns: the `ObjectPublisher<O>` interfacing the object at the specified section and item index
*/
public subscript(sectionIndex: Int, itemIndex: Int) -> ObjectPublisher<O> {
let context = self.context!
let snapshot = self.diffableSnapshot
let sectionID = snapshot.sectionIdentifiers[sectionIndex]
let itemID = snapshot.itemIdentifiers(inSection: sectionID)[itemIndex]
return context.objectPublisher(objectID: itemID)
}
/**
Returns the object at the given section and item index, or `nil` if out of bounds.
- parameter sectionIndex: the section index for the object. Using a `sectionIndex` with an invalid range will return `nil`.
- parameter itemIndex: the index for the object within the section. Using an `itemIndex` with an invalid range will return `nil`.
- returns: the `ObjectPublisher<O>` interfacing the object at the specified section and item index, or `nil` if out of bounds
*/
public subscript(safeSectionIndex sectionIndex: Int, safeItemIndex itemIndex: Int) -> ObjectPublisher<O>? {
let context = self.context!
let snapshot = self.diffableSnapshot
let sectionIDs = snapshot.sectionIdentifiers
guard sectionIDs.indices.contains(sectionIndex) else {
return nil
}
let sectionID = sectionIDs[sectionIndex]
let itemIDs = snapshot.itemIdentifiers(inSection: sectionID)
guard itemIDs.indices.contains(itemIndex) else {
return nil
}
let itemID = itemIDs[itemIndex]
return context.objectPublisher(objectID: itemID)
}
/**
Returns the object at the given `IndexPath`.
- parameter indexPath: the `IndexPath` for the object. Using an `indexPath` with an invalid range will raise an exception.
- returns: the `ObjectPublisher<O>` interfacing the object at the specified index path
*/
public subscript(indexPath: IndexPath) -> ObjectPublisher<O> {
return self[indexPath[0], indexPath[1]]
}
/**
Returns the object at the given `IndexPath`, or `nil` if out of bounds.
- parameter indexPath: the `IndexPath` for the object. Using an `indexPath` with an invalid range will return `nil`.
- returns: the `ObjectPublisher<O>` interfacing the object at the specified index path, or `nil` if out of bounds
*/
public subscript(safeIndexPath indexPath: IndexPath) -> ObjectPublisher<O>? {
return self[
safeSectionIndex: indexPath[0],
safeItemIndex: indexPath[1]
]
}
/**
Checks if the `ListSnapshot` has at least one section
- returns: `true` if at least one section exists, `false` otherwise
*/
public func hasSections() -> Bool {
return self.diffableSnapshot.numberOfSections > 0
}
/**
Checks if the `ListSnapshot` has at least one object in any section.
- returns: `true` if at least one object in any section exists, `false` otherwise
*/
public func hasItems() -> Bool {
return self.diffableSnapshot.numberOfItems > 0
}
/**
Checks if the `ListSnapshot` has at least one object in the specified section.
- parameter sectionIndex: the section index. Using an index outside the valid range will return `false`.
- returns: `true` if at least one object in the specified section exists, `false` otherwise
*/
public func hasItems(inSectionIndex sectionIndex: Int) -> Bool {
let snapshot = self.diffableSnapshot
let sectionIDs = snapshot.sectionIdentifiers
guard sectionIDs.indices.contains(sectionIndex) else {
return false
}
let sectionID = sectionIDs[sectionIndex]
return snapshot.numberOfItems(inSection: sectionID) > 0
}
/**
Checks if the `ListSnapshot` has at least one object the specified section.
- parameter sectionID: the section identifier. Using an index outside the valid range will return `false`.
- returns: `true` if at least one object in the specified section exists, `false` otherwise
*/
public func hasItems(inSectionWithID sectionID: SectionID) -> Bool {
let snapshot = self.diffableSnapshot
guard snapshot.sectionIdentifiers.contains(sectionID) else {
return false
}
return snapshot.numberOfItems(inSection: sectionID) > 0
}
/**
The number of items in all sections in the `ListSnapshot`
*/
public var numberOfItems: Int {
return self.diffableSnapshot.numberOfItems
}
/**
The number of sections in the `ListSnapshot`
*/
public var numberOfSections: Int {
return self.diffableSnapshot.numberOfSections
}
/**
Returns the number of items for the specified `SectionID`.
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- returns: The number of items in the given `SectionID`
*/
public func numberOfItems(inSectionWithID sectionID: SectionID) -> Int {
return self.diffableSnapshot.numberOfItems(inSection: sectionID)
}
/**
Returns the number of items at the specified section index.
- parameter sectionIndex: the index of the section. Specifying an invalid value will raise an exception.
- returns: The number of items in the given `SectionID`
*/
public func numberOfItems(inSectionIndex sectionIndex: Int) -> Int {
let snapshot = self.diffableSnapshot
let sectionID = snapshot.sectionIdentifiers[sectionIndex]
return snapshot.numberOfItems(inSection: sectionID)
}
/**
All section identifiers in the `ListSnapshot`
*/
public var sectionIDs: [SectionID] {
return self.diffableSnapshot.sectionIdentifiers
}
/**
Returns the `SectionID` that the specified `ItemID` belongs to, or `nil` if it is not in the list.
- parameter itemID: the `ItemID`
- returns: the `SectionID` that the specified `ItemID` belongs to, or `nil` if it is not in the list
*/
public func sectionID(containingItemWithID itemID: ItemID) -> SectionID? {
return self.diffableSnapshot.sectionIdentifier(containingItem: itemID)
}
/**
All object identifiers in the `ListSnapshot`
*/
public var itemIDs: [ItemID] {
return self.diffableSnapshot.itemIdentifiers
}
/**
Returns the item identifiers belonging to the specified `SectionID`.
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- returns: the `ItemID` array belonging to the given `SectionID`
*/
public func itemIDs(inSectionWithID sectionID: SectionID) -> [ItemID] {
return self.diffableSnapshot.itemIdentifiers(inSection: sectionID)
}
/**
Returns the item identifiers belonging to the specified `SectionID` and a `Sequence` of item indices.
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- parameter indices: the positions of the itemIDs to return. Specifying an invalid value will raise an exception.
- returns: the `ItemID` array belonging to the given `SectionID` at the specified indices
*/
public func itemIDs<S: Sequence>(inSectionWithID sectionID: SectionID, atIndices indices: S) -> [ItemID] where S.Element == Int {
let itemIDs = self.diffableSnapshot.itemIdentifiers(inSection: sectionID)
return indices.map({ itemIDs[$0] })
}
/**
Returns the index of the specified `ItemID` in the whole list, or `nil` if it is not in the list.
- parameter itemID: the `ItemID`
- returns: the index of the specified `ItemID`, or `nil` if it is not in the list
*/
public func indexOfItem(withID itemID: ItemID) -> Index? {
return self.diffableSnapshot.indexOfItem(itemID)
}
/**
Returns the index of the specified `SectionID`, or `nil` if it is not in the list.
- parameter sectionID: the `SectionID`
- returns: the index of the specified `SectionID`, or `nil` if it is not in the list
*/
public func indexOfSection(withID sectionID: SectionID) -> Int? {
return self.diffableSnapshot.indexOfSection(sectionID)
}
/**
Returns an array of `ObjectPublisher`s for the items at the specified indices
- parameter indices: the positions of items. Specifying an invalid value will raise an exception.
- returns: an array of `ObjectPublisher`s for the items at the specified indices
*/
public func items<S: Sequence>(atIndices indices: S) -> [ObjectPublisher<O>] where S.Element == Index {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers
return indices.map { position in
let itemID = itemIDs[position]
return ObjectPublisher<O>(objectID: itemID, context: context)
}
}
/**
Returns an array of `ObjectPublisher`s for the items in the specified `SectionID`
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- returns: an array of `ObjectPublisher`s for the items in the specified `SectionID`
*/
public func items(inSectionWithID sectionID: SectionID) -> [ObjectPublisher<O>] {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers(inSection: sectionID)
return itemIDs.map {
return ObjectPublisher<O>(objectID: $0, context: context)
}
}
/**
Returns an array of `ObjectPublisher`s for the items in the specified `SectionID` and indices
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- parameter itemIndices: the positions of items within the section. Specifying an invalid value will raise an exception.
- returns: an array of `ObjectPublisher`s for the items in the specified `SectionID` and indices
*/
public func items<S: Sequence>(inSectionWithID sectionID: SectionID, atIndices itemIndices: S) -> [ObjectPublisher<O>] where S.Element == Int {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers(inSection: sectionID)
return itemIndices.map { position in
let itemID = itemIDs[position]
return ObjectPublisher<O>(objectID: itemID, context: context)
}
}
/**
Returns a lazy sequence of `ObjectPublisher`s for the items at the specified indices
- parameter indices: the positions of items. Specifying an invalid value will raise an exception.
- returns: a lazy sequence of `ObjectPublisher`s for the items at the specified indices
*/
public func lazy<S: Sequence>(atIndices indices: S) -> LazyMapSequence<S, ObjectPublisher<O>> where S.Element == Index {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers
return indices.lazy.map { position in
let itemID = itemIDs[position]
return ObjectPublisher<O>(objectID: itemID, context: context)
}
}
/**
Returns a lazy sequence of `ObjectPublisher`s for the items in the specified `SectionID`
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- returns: a lazy sequence of `ObjectPublisher`s for the items in the specified `SectionID`
*/
public func lazy(inSectionWithID sectionID: SectionID) -> LazyMapSequence<[NSManagedObjectID], ObjectPublisher<O>> {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers(inSection: sectionID)
return itemIDs.lazy.map {
return ObjectPublisher<O>(objectID: $0, context: context)
}
}
/**
Returns a lazy sequence of `ObjectPublisher`s for the items in the specified `SectionID` and indices
- parameter sectionID: the `SectionID`. Specifying an invalid value will raise an exception.
- parameter itemIndices: the positions of items within the section. Specifying an invalid value will raise an exception.
- returns: a lazy sequence of `ObjectPublisher`s for the items in the specified `SectionID` and indices
*/
public func lazy<S: Sequence>(inSectionWithID sectionID: SectionID, atIndices itemIndices: S) -> LazyMapSequence<S, ObjectPublisher<O>> where S.Element == Int {
let context = self.context!
let itemIDs = self.diffableSnapshot.itemIdentifiers(inSection: sectionID)
return itemIndices.lazy.map { position in
let itemID = itemIDs[position]
return ObjectPublisher<O>(objectID: itemID, context: context)
}
}
// MARK: Public (Mutators)
/**
Appends extra items to the specified section
- parameter itemIDs: the object identifiers for the objects to append
- parameter sectionID: the section to append the items to
*/
public mutating func appendItems(withIDs itemIDs: [ItemID], toSectionWithID sectionID: SectionID? = nil) {
self.diffableSnapshot.appendItems(itemIDs, toSection: sectionID)
}
/**
Inserts extra items before a specified item
- parameter itemIDs: the object identifiers for the objects to insert
- parameter beforeItemID: an existing identifier to insert items before of. Specifying an invalid value will raise an exception.
*/
public mutating func insertItems(withIDs itemIDs: [ItemID], beforeItemID: ItemID) {
self.diffableSnapshot.insertItems(itemIDs, beforeItem: beforeItemID)
}
/**
Inserts extra items after a specified item
- parameter itemIDs: the object identifiers for the objects to insert
- parameter beforeItemID: an existing identifier to insert items after of. Specifying an invalid value will raise an exception.
*/
public mutating func insertItems(withIDs itemIDs: [ItemID], afterItemID: ItemID) {
self.diffableSnapshot.insertItems(itemIDs, afterItem: afterItemID)
}
/**
Deletes the specified items
- parameter itemIDs: the object identifiers for the objects to delete
*/
public mutating func deleteItems(withIDs itemIDs: [ItemID]) {
self.diffableSnapshot.deleteItems(itemIDs)
}
/**
Deletes all items
*/
public mutating func deleteAllItems() {
self.diffableSnapshot.deleteAllItems()
}
/**
Moves an item before another specified item
- parameter itemID: an object identifier in the list to move. Specifying an invalid value will raise an exception.
- parameter beforeItemID: another identifier to move the item before of. Specifying an invalid value will raise an exception.
*/
public mutating func moveItem(withID itemID: ItemID, beforeItemID: ItemID) {
self.diffableSnapshot.moveItem(itemID, beforeItem: beforeItemID)
}
/**
Moves an item after another specified item
- parameter itemID: an object identifier in the list to move. Specifying an invalid value will raise an exception.
- parameter beforeItemID: another identifier to move the item after of. Specifying an invalid value will raise an exception.
*/
public mutating func moveItem(withID itemID: ItemID, afterItemID: ItemID) {
self.diffableSnapshot.moveItem(itemID, afterItem: afterItemID)
}
/**
Marks the specified items as reloaded
- parameter itemIDs: the object identifiers to reload
*/
public mutating func reloadItems(withIDs itemIDs: [ItemID]) {
self.diffableSnapshot.reloadItems(itemIDs)
}
/**
Appends new section identifiers to the end of the list
- parameter sectionIDs: the sections to append
*/
public mutating func appendSections(withIDs sectionIDs: [SectionID]) {
self.diffableSnapshot.appendSections(sectionIDs)
}
/**
Inserts new sections before an existing section
- parameter sectionIDs: the section identifiers for the sections to insert
- parameter beforeSectionID: an existing identifier to insert items before of. Specifying an invalid value will raise an exception.
*/
public mutating func insertSections(withIDs sectionIDs: [SectionID], beforeSectionID: SectionID) {
self.diffableSnapshot.insertSections(sectionIDs, beforeSection: beforeSectionID)
}
/**
Inserts new sections after an existing section
- parameter sectionIDs: the section identifiers for the sections to insert
- parameter beforeSectionID: an existing identifier to insert items after of. Specifying an invalid value will raise an exception.
*/
public mutating func insertSections(withIDs sectionIDs: [SectionID], afterSectionID: SectionID) {
self.diffableSnapshot.insertSections(sectionIDs, afterSection: afterSectionID)
}
/**
Deletes the specified sections
- parameter sectionIDs: the section identifiers for the sections to delete
*/
public mutating func deleteSections(withIDs sectionIDs: [SectionID]) {
self.diffableSnapshot.deleteSections(sectionIDs)
}
/**
Moves a section before another specified section
- parameter sectionID: a section identifier in the list to move. Specifying an invalid value will raise an exception.
- parameter beforeSectionID: another identifier to move the section before of. Specifying an invalid value will raise an exception.
*/
public mutating func moveSection(withID sectionID: SectionID, beforeSectionID: SectionID) {
self.diffableSnapshot.moveSection(sectionID, beforeSection: beforeSectionID)
}
/**
Moves a section after another specified section
- parameter sectionID: a section identifier in the list to move. Specifying an invalid value will raise an exception.
- parameter afterSectionID: another identifier to move the section after of. Specifying an invalid value will raise an exception.
*/
public mutating func moveSection(withID sectionID: SectionID, afterSectionID: SectionID) {
self.diffableSnapshot.moveSection(sectionID, afterSection: afterSectionID)
}
/**
Marks the specified sections as reloaded
- parameter sectionIDs: the section identifiers to reload
*/
public mutating func reloadSections(withIDs sectionIDs: [SectionID]) {
self.diffableSnapshot.reloadSections(sectionIDs)
}
// MARK: RandomAccessCollection
public var startIndex: Index {
return self.diffableSnapshot.itemIdentifiers.startIndex
}
public var endIndex: Index {
return self.diffableSnapshot.itemIdentifiers.endIndex
}
// MARK: Sequence
public typealias Element = ObjectPublisher<O>
public typealias Index = Int
// MARK: Equatable
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
return lhs.id == rhs.id
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
// MARK: Internal
internal private(set) var diffableSnapshot: DiffableDataSourceSnapshotProtocol
internal init() {
// if #available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *) {
//
// self.diffableSnapshot = NSDiffableDataSourceSnapshot<String, NSManagedObjectID>()
// }
// else {
self.diffableSnapshot = Internals.DiffableDataSourceSnapshot()
// }
self.context = nil
}
// @available(iOS 13.0, tvOS 13.0, watchOS 6.0, macOS 10.15, *)
// internal init(diffableSnapshot: NSDiffableDataSourceSnapshot<String, NSManagedObjectID>, context: NSManagedObjectContext) {
//
// self.diffableSnapshot = diffableSnapshot
// self.context = context
// }
internal init(diffableSnapshot: Internals.DiffableDataSourceSnapshot, context: NSManagedObjectContext) {
self.diffableSnapshot = diffableSnapshot
self.context = context
}
// MARK: Private
private let id: UUID = .init()
private let context: NSManagedObjectContext?
}
| mit | b616e280a03a8d7b2e795650df7048a5 | 35.306306 | 345 | 0.689247 | 5.078765 | false | false | false | false |
allenngn/firefox-ios | Client/Frontend/Browser/LoginsHelper.swift | 12 | 13655 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
import WebKit
private let log = XCGLogger.defaultInstance()
private let SaveButtonTitle = NSLocalizedString("Save", comment: "Button to save the user's password")
private let NotNowButtonTitle = NSLocalizedString("Not now", comment: "Button to not save the user's password")
private let UpdateButtonTitle = NSLocalizedString("Update", comment: "Button to update the user's password")
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Authentication prompt cancel button")
private let LogInButtonTitle = NSLocalizedString("Log in", comment: "Authentication prompt log in button")
class LoginsHelper: BrowserHelper {
private weak var browser: Browser?
private let profile: Profile
private var snackBar: SnackBar?
private static let MaxAuthenticationAttempts = 3
class func name() -> String {
return "LoginsHelper"
}
required init(browser: Browser, profile: Profile) {
self.browser = browser
self.profile = profile
if let path = NSBundle.mainBundle().pathForResource("LoginsHelper", ofType: "js") {
if let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as? String {
var userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
}
func scriptMessageHandlerName() -> String? {
return "loginsManagerMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
var res = message.body as! [String: String]
let type = res["type"]
if let url = browser?.url {
if type == "request" {
res["username"] = ""
res["password"] = ""
let login = Login.fromScript(url, script: res)
requestLogins(login, requestId: res["requestId"]!)
} else if type == "submit" {
setCredentials(Login.fromScript(url, script: res))
}
}
}
class func replace(base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in enumerate(keys) {
let replace = replacements[index]
let range = string.rangeOfString(key,
options: NSStringCompareOptions.LiteralSearch,
range: nil,
locale: nil)!
string.replaceRange(range, with: replace)
let nsRange = NSMakeRange(distance(string.startIndex, range.startIndex),
count(replace))
ranges.append(nsRange)
}
var attributes = [NSObject: AnyObject]()
attributes[NSFontAttributeName] = UIFont.systemFontOfSize(13, weight: UIFontWeightRegular)
attributes[NSForegroundColorAttributeName] = UIColor.darkGrayColor()
var attr = NSMutableAttributedString(string: string, attributes: attributes)
for (index, range) in enumerate(ranges) {
attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(13, weight: UIFontWeightMedium), range: range)
}
return attr
}
private func setCredentials(login: LoginData) {
if login.password.isEmpty {
log.debug("Empty password")
return
}
profile.logins
.getLoginsForProtectionSpace(login.protectionSpace, withUsername: login.username)
.uponQueue(dispatch_get_main_queue()) { res in
if let data = res.successValue {
log.debug("Found \(data.count) logins.")
for saved in data {
if let saved = saved {
if saved.password == login.password {
self.profile.logins.addUseOfLoginByGUID(saved.guid)
return
}
self.promptUpdateFromLogin(login: saved, toLogin: login)
return
}
}
}
self.promptSave(login)
}
}
private func promptSave(login: LoginData) {
let promptMessage: NSAttributedString
if let username = login.username {
let promptStringFormat = NSLocalizedString("Do you want to save the password for %@ on %@?", comment: "Prompt for saving a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
promptMessage = NSAttributedString(string: String(format: promptStringFormat, username, login.hostname))
} else {
let promptStringFormat = NSLocalizedString("Do you want to save the password on %@?", comment: "Prompt for saving a password with no username. The parameter is the hostname of the site.")
promptMessage = NSAttributedString(string: String(format: promptStringFormat, login.hostname))
}
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = CountdownSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: SaveButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.addLogin(login)
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func promptUpdateFromLogin(login old: LoginData, toLogin new: LoginData) {
let guid = old.guid
let formatted: String
if let username = new.username {
let promptStringFormat = NSLocalizedString("Do you want to update the password for %@ on %@?", comment: "Prompt for updating a password. The first parameter is the username being saved. The second parameter is the hostname of the site.")
formatted = String(format: promptStringFormat, username, new.hostname)
} else {
let promptStringFormat = NSLocalizedString("Do you want to update the password on %@?", comment: "Prompt for updating a password with on username. The parameter is the hostname of the site.")
formatted = String(format: promptStringFormat, new.hostname)
}
let promptMessage = NSAttributedString(string: formatted)
if snackBar != nil {
browser?.removeSnackbar(snackBar!)
}
snackBar = CountdownSnackBar(attrText: promptMessage,
img: UIImage(named: "lock_verified"),
buttons: [
SnackButton(title: UpdateButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
self.profile.logins.updateLoginByGUID(guid, new: new,
significant: new.isSignificantlyDifferentFrom(old))
}),
SnackButton(title: NotNowButtonTitle, callback: { (bar: SnackBar) -> Void in
self.browser?.removeSnackbar(bar)
self.snackBar = nil
return
})
])
browser?.addSnackbar(snackBar!)
}
private func requestLogins(login: LoginData, requestId: String) {
profile.logins.getLoginsForProtectionSpace(login.protectionSpace).uponQueue(dispatch_get_main_queue()) { res in
var jsonObj = [String: AnyObject]()
if let cursor = res.successValue {
log.debug("Found \(cursor.count) logins.")
jsonObj["requestId"] = requestId
jsonObj["name"] = "RemoteLogins:loginsFound"
jsonObj["logins"] = map(cursor, { $0!.toDict() })
}
let json = JSON(jsonObj)
let src = "window.__firefox__.logins.inject(\(json.toString()))"
self.browser?.webView?.evaluateJavaScript(src, completionHandler: { (obj, err) -> Void in
})
}
}
func handleAuthRequest(viewController: UIViewController, challenge: NSURLAuthenticationChallenge) -> Deferred<Result<LoginData>> {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= LoginsHelper.MaxAuthenticationAttempts {
return deferResult(LoginDataError(description: "Too many attempts to open site"))
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
return deferResult(Login.createWithCredential(credential!, protectionSpace: challenge.protectionSpace))
}
} else {
credential = nil
}
}
if let credential = credential {
// If we have some credentials, we'll show a prompt with them.
return promptForUsernamePassword(viewController, credentials: credential, protectionSpace: challenge.protectionSpace)
}
// Otherwise, try to look one up
let options = QueryOptions(filter: challenge.protectionSpace.host, filterType: .None, sort: .None)
return profile.logins.getLoginsForProtectionSpace(challenge.protectionSpace).bindQueue(dispatch_get_main_queue()) { res in
let credentials = res.successValue?[0]?.credentials
return self.promptForUsernamePassword(viewController, credentials: credentials, protectionSpace: challenge.protectionSpace)
}
}
private func promptForUsernamePassword(viewController: UIViewController, credentials: NSURLCredential?, protectionSpace: NSURLProtectionSpace) -> Deferred<Result<LoginData>> {
if protectionSpace.host.isEmpty {
println("Unable to show a password prompt without a hostname")
return deferResult(LoginDataError(description: "Unable to show a password prompt without a hostname"))
}
let deferred = Deferred<Result<LoginData>>()
let alert: UIAlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !(protectionSpace.realm?.isEmpty ?? true) {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg, protectionSpace.host, protectionSpace.realm ?? "") as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg, protectionSpace.host) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: UIAlertControllerStyle.Alert)
}
// Add a button to log in.
let action = UIAlertAction(title: LogInButtonTitle,
style: UIAlertActionStyle.Default) { (action) -> Void in
let user = (alert.textFields?[0] as! UITextField).text
let pass = (alert.textFields?[1] as! UITextField).text
let login = Login.createWithCredential(NSURLCredential(user: user, password: pass, persistence: .ForSession), protectionSpace: protectionSpace)
deferred.fill(Result(success: login))
self.setCredentials(login)
}
alert.addAction(action)
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: UIAlertActionStyle.Cancel) { (action) -> Void in
deferred.fill(Result(failure: LoginDataError(description: "Save password cancelled")))
}
alert.addAction(cancel)
// Add a username textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = credentials?.user
}
// Add a password textfield.
alert.addTextFieldWithConfigurationHandler { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.secureTextEntry = true
textfield.text = credentials?.password
}
viewController.presentViewController(alert, animated: true) { () -> Void in }
return deferred
}
}
| mpl-2.0 | aed7e759c56a0c86d60749c8bca15a68 | 47.250883 | 249 | 0.63149 | 5.503829 | false | false | false | false |
wagnersouz4/replay | Replay/Replay/Source/Models/Movie.swift | 1 | 2909 | //
// Movie.swift
// Replay
//
// Created by Wagner Souza on 24/03/17.
// Copyright © 2017 Wagner Souza. All rights reserved.
//
import Foundation
struct Movie {
var movieId: Int
var genres: [String]
var title: String
var overview: String
var releaseDate: Date
/// Not every movie has a posterPath
var posterPath: String?
var videos: [YoutubeVideo]
/// Array of backdrops images sorted by its rating.
var backdropImagesPath: [String]
var runtime: Int
}
// MARK: Conforming to JSONable
extension Movie: JSONable {
init?(json: JSONDictionary) {
guard let genresList = json["genres"] as? [JSONDictionary],
let genres: [String] = JsonHelper.generateList(using: genresList, key: "name") else { return nil }
guard let videosList = json["videos"] as? JSONDictionary,
let videosResult = videosList["results"] as? [JSONDictionary],
let videos: [YoutubeVideo] = JsonHelper.generateList(using: videosResult) else { return nil }
guard let images = json["images"] as? JSONDictionary,
let backdropImages = images["backdrops"] as? [JSONDictionary],
let backdropImagesPath: [String] = JsonHelper.generateList(using: backdropImages,
key: "file_path")
else { return nil }
guard let movieId = json["id"] as? Int,
let title = json["original_title"] as? String,
let overview = json["overview"] as? String,
let poster = json["poster_path"] as? String,
let releaseDateString = json["release_date"] as? String,
let runtime = json["runtime"] as? Int else { return nil }
let posterPath = (poster == "N/A") ? nil : poster
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-d"
guard let releaseDate = formatter.date(from: releaseDateString) else {
fatalError("Invalid date format")
}
self.init(movieId: movieId,
genres: genres,
title: title,
overview: overview,
releaseDate: releaseDate,
posterPath: posterPath,
videos: videos,
backdropImagesPath: backdropImagesPath,
runtime: runtime)
}
}
// MARK: Conforming to GriddableContent
extension Movie: GriddableContent {
var identifier: Any? {
return movieId
}
var gridPortraitImageUrl: URL? {
guard let imagePath = posterPath else { return nil }
return TMDbHelper.createImageURL(using: imagePath)
}
var gridLandscapeImageUrl: URL? {
guard !backdropImagesPath.isEmpty else { return nil }
return TMDbHelper.createImageURL(using: backdropImagesPath[0])
}
var gridTitle: String {
return title
}
}
| mit | af2f46c6cdb1eb3dcf5083b56c9fdca9 | 31.311111 | 110 | 0.601788 | 4.68277 | false | false | false | false |
justin999/gitap | gitap/GitHubAPIManager.swift | 1 | 10885 | //
// GitHubAPIManager.swift
// gitap
//
// Created by Koichi Sato on 1/4/17.
// Copyright © 2017 Koichi Sato. All rights reserved.
//
import Foundation
import Alamofire
import Locksmith
let githubBaseURLString = "https://api.github.com"
enum GitHubAPIManagerError: Error {
case network(error: Error)
case apiProvidedError(reason: String)
case authCouldNot(reason: String)
case authLost(reason: String)
case objectSerialization(reason: String)
}
protocol ResultProtocol {
init?(json: [String: Any])
}
let kKeyChainGitHub = "github"
let kMessageFailToObtainToken: String = "Could not obtain an OAuth token"
class GitHubAPIManager {
static let shared = GitHubAPIManager()
var isLoadingOAuthToken: Bool = false
var OAuthTokenCompletionHandler:((Error?) -> Void)?
var OAuthToken: String? {
set {
guard let newValue = newValue else {
let _ = try? Locksmith.deleteDataForUserAccount(userAccount: kKeyChainGitHub)
Utils.setDefaultsValue(value: nil, key: "githubAuthToken")
return
}
Utils.setDefaultsValue(value: newValue, key: "githubAuthToken")
guard let _ = try? Locksmith.updateData(data: ["token": newValue], forUserAccount: kKeyChainGitHub) else {
let _ = try? Locksmith.deleteDataForUserAccount(userAccount: kKeyChainGitHub)
return
}
}
get {
// try to load from keychain
let dictionary = Locksmith.loadDataForUserAccount(userAccount: kKeyChainGitHub)
return dictionary?["token"] as? String
}
}
let clientID: String = Configs.github.clientId
let clientSecret: String = Configs.github.clientSecret
func clearCache() -> Void {
let cache = URLCache.shared
cache.removeAllCachedResponses()
}
func hasOAuthToken() -> Bool {
if let token = self.OAuthToken {
return !token.isEmpty
}
return false
}
func clearOAuthToken() {
if let _ = self.OAuthToken {
self.OAuthToken = nil
self.clearCache()
}
}
// MARK: - OAuth flow
func URLToStartOAuth2Login() -> URL? {
// TODO: change the state for production
let authPath: String = "https://github.com/login/oauth/authorize" +
"?client_id=\(clientID)&scope=user%20repo%20gist"
return URL(string: authPath)
}
func processOAuthStep1Response(_ url: URL) {
// extract the code from the URL
guard let code = extrctCodeFromOauthStep1Response(url) else {
self.isLoadingOAuthToken = false
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
return
}
swapAuthCodeForToken(code: code)
}
func swapAuthCodeForToken(code: String) {
let getTokenPath: String = "https://github.com/login/oauth/access_token"
let tokenParams = ["client_id": clientID, "client_secret": clientSecret, "code": code]
let jsonHeader = ["Accept": "application/json"]
Alamofire.request(getTokenPath, method: .post, parameters: tokenParams, encoding: URLEncoding.default, headers: jsonHeader)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
self.isLoadingOAuthToken = false
let errorMessage = response.result.error?.localizedDescription ?? kMessageFailToObtainToken
let error = GitHubAPIManagerError.authCouldNot(reason: errorMessage)
self.OAuthTokenCompletionHandler?(error)
return
}
guard let value = response.result.value else {
print("no string received in response when swapping oauth code for token")
self.isLoadingOAuthToken = false
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
return
}
guard let jsonResult = value as? [String: String] else {
print("no data received or data not JSON")
self.isLoadingOAuthToken = false
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
return
}
self.OAuthToken = self.parseOAuthTokenResponse(jsonResult)
self.isLoadingOAuthToken = false
if (self.hasOAuthToken()) {
self.OAuthTokenCompletionHandler?(nil)
} else {
let error = GitHubAPIManagerError.authCouldNot(reason: kMessageFailToObtainToken)
self.OAuthTokenCompletionHandler?(error)
}
}
}
func extrctCodeFromOauthStep1Response(_ url: URL) -> String? {
let components = URLComponents(url: url, resolvingAgainstBaseURL: false)
var code: String?
guard let queryItems = components?.queryItems else {
return nil
}
for queryItem in queryItems {
if (queryItem.name.lowercased() == "code") {
code = queryItem.value
break
}
}
return code
}
func parseOAuthTokenResponse(_ json: [String: String]) -> String? {
var token: String?
for (key, value) in json {
switch key {
case "access_token":
token = value
print("Got Token: \(token ?? "no token")")
case "scope":
// TODO: verify scope
print("SET SCOPE")
print("key: \(key), scope: \(value)")
case "token_type":
// TODO: verify is bearer
print("CHECK IF BEARER")
default:
print("got more than I expected from the OAuth token exchange")
print(key)
}
}
return token
}
// MARK: - API Calls
// MARK: fundamental
func fetch<T: ResultProtocol>(_ urlRequest: URLRequestConvertible, completionHandler: @escaping (Result<[T]>, String?) -> Void) {
Alamofire.request(urlRequest)
.responseJSON { response in
if let urlResponse = response.response,
let authError = self.checkUnauthorized(urlResponse: urlResponse) {
completionHandler(.failure(authError), nil)
return
}
let result: Result<[T]> = self.arrayFromResponse(response: response)
let next = self.parseNextPageFromHeaders(response: response.response)
completionHandler(result, next)
}
}
private func arrayFromResponse<T: ResultProtocol>(response: DataResponse<Any>) -> Result<[T]> {
guard response.result.error == nil else {
return .failure(GitHubAPIManagerError.network(error: response.result.error!))
}
// make sure we got JSON and it's an array
if let jsonArray = response.result.value as? [[String: Any]] {
var datas = [T]()
for item in jsonArray {
if let data = T(json: item) {
datas.append(data)
}
}
return .success(datas)
} else if let jsonData = response.result.value as? [String: Any], let data: T = T(json: jsonData) {
return .success([data])
} else if let jsonDictionary = response.result.value as? [String: Any],
let errorMessage = jsonDictionary["message"] as? String { return .failure(GitHubAPIManagerError.apiProvidedError(reason: errorMessage))
} else {
return .failure(GitHubAPIManagerError.apiProvidedError(reason: "something went wrong"))
}
}
// MARK: - Helpers
// func isAPIOnline(completionHandler: @escaping (Bool) -> Void) {
// Alamofire.request(GistRouter.baseURLString)
// .validate(statusCode: 200 ..< 300)
// .response { response in
// guard response.error == nil else {
// // no internet connection or GitHub API is down
// completionHandler(false)
// return
// }
// completionHandler(true)
// }
// }
func checkUnauthorized(urlResponse: HTTPURLResponse) -> (Error?) {
if (urlResponse.statusCode == 401) {
self.OAuthToken = nil
return GitHubAPIManagerError.authLost(reason: "Not Logged In")
} else if (urlResponse.statusCode == 404) {
return GitHubAPIManagerError.authLost(reason: "Not Found")
} else if (urlResponse.statusCode >= 400 && urlResponse.statusCode < 500) { // TODO: describe this reason more kindly
return GitHubAPIManagerError.apiProvidedError(reason: "400 error")
}
return nil
}
// MARK: - Pagination
private func parseNextPageFromHeaders(response: HTTPURLResponse?) -> String? {
guard let linkHeader = response?.allHeaderFields["Link"] as? String else {
return nil
}
/* looks like: <https://...?page=2>; rel="next", <https://...?page=6>; rel="last" */
// so split on ","
let components = linkHeader.characters.split { $0 == "," }.map { String($0) }
// now we have 2 lines like '<https://...?page=2>; rel="next"'
for item in components {
// see if it's "next"
let rangeOfNext = item.range(of: "rel=\"next\"", options: [])
guard rangeOfNext != nil else {
continue
}
// this is the "next" item, extract the URL
let rangeOfPaddedURL = item.range(of: "<(.*)>;",
options: .regularExpression,
range: nil,
locale: nil)
guard let range = rangeOfPaddedURL else {
return nil
}
let nextURL = item.substring(with: range)
// strip off the < and >;
let start = nextURL.index(range.lowerBound, offsetBy: 1)
let end = nextURL.index(range.upperBound, offsetBy: -2)
let trimmedRange = start ..< end
return nextURL.substring(with: trimmedRange)
}
return nil
}
}
| mit | 1a926afe8f1208a17a5bf8ea28aa9d02 | 38.434783 | 147 | 0.563947 | 5.173004 | false | false | false | false |
dtartaglia/Apex | Apex/URLCommand.swift | 1 | 1158 | //
// URLCommand.swift
// Apex
//
// Created by Daniel Tartaglia on 12/17/17.
// Copyright © 2017 Daniel Tartaglia. MIT License
//
public
struct URLCommand: Command, Equatable {
public
init(session: URLSession, request: URLRequest, action: URLCommandActionCreator?) {
self.session = session
self.request = request
self.action = action
}
public
func execute(dispatcher: Dispatcher) {
session.dataTask(with: request) { (data, response, error) in
if let action = self.action {
if let data = data, let response = response {
dispatcher.dispatch(action: action(.success(data, response)))
}
else {
dispatcher.dispatch(action: action(.failure(error ?? UnknownError())))
}
}
}.resume()
}
public
static func ==(lhs: URLCommand, rhs: URLCommand) -> Bool {
return lhs.request == rhs.request
}
private let session: URLSession
private let request: URLRequest
private let action: URLCommandActionCreator?
}
public
typealias URLCommandActionCreator = (URLCommandUpdate) -> Action
public
enum URLCommandUpdate {
case success(Data, URLResponse)
case failure(Error)
}
public
struct UnknownError: Error { }
| mit | eb176fc432caae05ada155bbd0f10e48 | 20.830189 | 83 | 0.710458 | 3.708333 | false | false | false | false |
openhab/openhab.ios | openHAB/OpenHABClientCertificatesViewController.swift | 1 | 2297 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import OpenHABCore
import os.log
import UIKit
class OpenHABClientCertificatesViewController: UITableViewController {
static let tableViewCellIdentifier = "ClientCertificatesCell"
var clientCertificates: [SecIdentity] = []
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("client_certificates", comment: "")
os_log("OpenHABClientCertificatesViewController viewDidLoad", log: .default, type: .info)
tableView.tableFooterView = UIView()
tableView.allowsMultipleSelectionDuringEditing = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
NetworkConnection.shared.clientCertificateManager.clientIdentities.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: OpenHABClientCertificatesViewController.tableViewCellIdentifier, for: indexPath)
cell.textLabel?.text = NetworkConnection.shared.clientCertificateManager.getIdentityName(index: indexPath.row)
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete {
let status = NetworkConnection.shared.clientCertificateManager.deleteFromKeychain(index: indexPath.row)
if status == noErr {
tableView.deleteRows(at: [indexPath], with: .fade)
}
}
}
}
| epl-1.0 | c376fb00ee0c0ce7887199daada965c9 | 37.932203 | 162 | 0.724859 | 5.208617 | false | false | false | false |
griotspeak/PathMath | Sources/PathMath/CGRect.swift | 1 | 3183 | //
// CGRect.swift
// PathMath
//
// Created by TJ Usiyan on 12/12/15.
// Copyright © 2015 Buttons and Lights LLC. All rights reserved.
//
import QuartzCore
extension CGRect {
public typealias EdgeDescription = (top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat)
func edgeDescription(_ originLocation: OriginLocation = OriginLocation.defaultPlatformLocation) -> EdgeDescription {
let value: EdgeDescription
value.left = minX
value.right = maxX
switch originLocation {
case .lowerLeft:
value.bottom = minY
value.top = maxY
case .upperLeft:
value.bottom = maxY
value.top = minY
}
return value
}
public typealias CornerDescription = (topLeft: CGPoint, topRight: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint)
func corners(_ originLocation: OriginLocation = OriginLocation.defaultPlatformLocation) -> CornerDescription {
let edges = edgeDescription(originLocation)
return (
topLeft: CGPoint(x: edges.left, y: edges.top),
topRight: CGPoint(x: edges.right, y: edges.top),
bottomLeft: CGPoint(x: edges.left, y: edges.bottom),
bottomRight: CGPoint(x: edges.right, y: edges.bottom)
)
}
}
extension CGRect {
public var center: CGPoint {
CGPoint(x: origin.x + (size.width * 0.5), y: origin.y + (size.height * 0.5))
}
public init(center: CGPoint, size: CGSize) {
let origin = CGPoint(x: center.x - size.width * 0.5, y: center.y - size.height * 0.5)
self.init(origin: origin, size: size)
}
public init(size innerSize: CGSize, centeredInRect outerRect: CGRect) {
self.init(center: outerRect.center, size: innerSize)
}
public init(size innerSize: CGSize, centeredInSize outerSize: CGSize) {
self.init(size: innerSize, centeredInRect: CGRect(origin: CGPoint.zero, size: outerSize))
}
public init(top: CGFloat, right: CGFloat, bottom: CGFloat, left: CGFloat, originLocation: OriginLocation = .defaultPlatformLocation) {
let width = right - left
let height: CGFloat
let originY: CGFloat
switch originLocation {
case .lowerLeft:
height = top - bottom
originY = bottom
case .upperLeft:
height = bottom - top
originY = top
}
self.init(origin: CGPoint(x: left,
y: originY),
size: CGSize(width: width,
height: height))
}
public init(edges: EdgeDescription, originLocation: OriginLocation = .defaultPlatformLocation) {
let originX = edges.left
let originY: CGFloat
let height: CGFloat
let width = edges.right - edges.left
switch originLocation {
case .lowerLeft:
originY = edges.bottom
height = edges.top - edges.bottom
case .upperLeft:
originY = edges.top
height = edges.bottom - edges.top
}
self.init(x: originX, y: originY, width: width, height: height)
}
}
| mit | 8120ccef62f667e0fd1b284815e688ee | 32.145833 | 138 | 0.604965 | 4.444134 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Model/Search/MSearchEntryNumber.swift | 1 | 3565 | import UIKit
class MSearchEntryNumber
{
private static let kBreak:String = "\n"
private static let kSeparator:String = ", "
private static let kKeyEntries:String = "entries"
private static let kKeyGrammaticalFeatures:String = "grammaticalFeatures"
private static let kKeyType:String = "type"
private static let kKeyText:String = "text"
private static let kTypeNumber:String = "Number"
private static let kNumberFontSize:CGFloat = 14
class func parse(json:Any) -> NSAttributedString?
{
guard
let jsonMap:[String:Any] = json as? [String:Any],
let jsonEntries:[Any] = jsonMap[kKeyEntries] as? [Any]
else
{
return nil
}
var numbers:[String] = []
let mutableString:NSMutableAttributedString = NSMutableAttributedString()
let attributes:[String:AnyObject] = [
NSFontAttributeName:UIFont.regular(size:kNumberFontSize),
NSForegroundColorAttributeName:UIColor.black]
let stringBreak:NSAttributedString = NSAttributedString(
string:kBreak,
attributes:attributes)
let stringSeparator:NSAttributedString = NSAttributedString(
string:kSeparator,
attributes:attributes)
for jsonEntry:Any in jsonEntries
{
guard
let jsonEntryMap:[String:Any] = jsonEntry as? [String:Any],
let jsonFeatures:[Any] = jsonEntryMap[
kKeyGrammaticalFeatures] as? [Any]
else
{
continue
}
for jsonFeature:Any in jsonFeatures
{
guard
let featureMap:[String:Any] = jsonFeature as? [String:Any],
let featureMapType:String = featureMap[kKeyType] as? String,
let featureMapText:String = featureMap[kKeyText] as? String
else
{
continue
}
if featureMapType == kTypeNumber
{
let numberLowerCase:String = featureMapText.lowercased()
var append:Bool = true
for number:String in numbers
{
if number == numberLowerCase
{
append = false
break
}
}
if append
{
numbers.append(numberLowerCase)
if mutableString.string.isEmpty
{
mutableString.append(stringBreak)
}
else
{
mutableString.append(stringSeparator)
}
let numberString:NSAttributedString = NSAttributedString(
string:numberLowerCase,
attributes:attributes)
mutableString.append(numberString)
}
}
}
}
return mutableString
}
}
| mit | c8eb79c17117887594330e12a90d5b8e | 32.952381 | 81 | 0.453857 | 6.84261 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Helpers/Coding/Date/KeyedEncodingContainer+DateFormat.swift | 1 | 725 | //
// KeyedEncodingContainer+DateFormat.swift
//
//
// Created by Vladislav Fitc on 29/05/2020.
//
import Foundation
extension KeyedEncodingContainer {
mutating func encode(_ date: Date, forKey key: K, dateFormat: String) throws {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let rawDate = dateFormatter.string(from: date)
try encode(rawDate, forKey: key)
}
mutating func encodeIfPresent(_ date: Date?, forKey key: K, dateFormat: String) throws {
guard let date = date else { return }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let rawDate = dateFormatter.string(from: date)
try encode(rawDate, forKey: key)
}
}
| mit | f8be7d3e0a9435316044dcaa44cd0b9c | 25.851852 | 90 | 0.710345 | 4.341317 | false | false | false | false |
dvor/Antidote | Antidote/NotificationObject.swift | 2 | 2764 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
enum NotificationAction {
case openChat(chatUniqueIdentifier: String)
case openRequest(requestUniqueIdentifier: String)
case answerIncomingCall(userInfo: String)
}
extension NotificationAction {
fileprivate struct Constants {
static let ValueKey = "ValueKey"
static let ArgumentKey = "ArgumentKey"
static let OpenChatValue = "OpenChatValue"
static let OpenRequestValue = "OpenRequestValue"
static let AnswerIncomingCallValue = "AnswerIncomingCallValue"
}
init?(dictionary: [String: String]) {
guard let value = dictionary[Constants.ValueKey] else {
return nil
}
switch value {
case Constants.OpenChatValue:
guard let argument = dictionary[Constants.ArgumentKey] else {
return nil
}
self = .openChat(chatUniqueIdentifier: argument)
case Constants.OpenRequestValue:
guard let argument = dictionary[Constants.ArgumentKey] else {
return nil
}
self = .openRequest(requestUniqueIdentifier: argument)
case Constants.AnswerIncomingCallValue:
guard let argument = dictionary[Constants.ArgumentKey] else {
return nil
}
self = .answerIncomingCall(userInfo: argument)
default:
return nil
}
}
func archive() -> [String: String] {
switch self {
case .openChat(let identifier):
return [
Constants.ValueKey: Constants.OpenChatValue,
Constants.ArgumentKey: identifier,
]
case .openRequest(let identifier):
return [
Constants.ValueKey: Constants.OpenRequestValue,
Constants.ArgumentKey: identifier,
]
case .answerIncomingCall(let userInfo):
return [
Constants.ValueKey: Constants.AnswerIncomingCallValue,
Constants.ArgumentKey: userInfo,
]
}
}
}
struct NotificationObject {
/// Title of notification
let title: String
/// Body text of notification
let body: String
/// Action to be fired when user interacts with notification
let action: NotificationAction
/// Sound to play when notification is fired. Valid only for local notifications.
let soundName: String
}
| mit | acd10990b468360f58fd2b68eceba643 | 32.707317 | 85 | 0.594428 | 5.640816 | false | false | false | false |
chrisamanse/UsbongKit | UsbongKit/Usbong/PlayableTree.swift | 2 | 10783 | //
// PlayableTree.swift
// UsbongKit
//
// Created by Chris Amanse on 1/12/16.
// Copyright © 2016 Usbong Social Systems, Inc. All rights reserved.
//
import Foundation
import AVFoundation
public protocol PlayableTree: class {
var nodeView: NodeView! { get set }
var tree: UsbongTree? { get set }
var voiceOverOn: Bool { get set }
var speechSynthesizer: AVSpeechSynthesizer { get set }
var backgroundAudioPlayer: AVAudioPlayer? { get set }
var voiceOverAudioPlayer: AVAudioPlayer? { get set }
// Node
func reloadNode()
func transitionToPreviousNode()
func transitionToNextNode()
// View controllers
func showAvailableActions(_ sender: AnyObject?)
func showChooseLanguageScreen()
// Background audio
func loadBackgroundAudio()
// Voice-over
func startVoiceOver()
func stopVoiceOver()
func startVoiceOverAudio() -> Bool
func stopVoiceOverAudio()
func startTextToSpeech()
func stopTextToSpeech()
// Dismiss
/// If `true`, receiver is dismissed if next node is end state, otherwise, it shows end state.
var shouldDismissWhenNextNodeIsEndState: Bool { get }
}
public extension PlayableTree where Self: UIViewController {
// MARK: Transitioning nodes
func transitionToPreviousNode() {
guard let tree = self.tree else {
return
}
if !tree.previousNodeIsAvailable {
dismiss(animated: true, completion: nil)
return
}
tree.transitionToPreviousNode()
reloadNode()
}
func transitionToNextNode() {
guard let tree = self.tree else {
return
}
// Do not transition if tree prevents it
if tree.shouldPreventTransitionToNextTaskNode {
// Present no selection alert
let alertController = UIAlertController(title: "No Selection", message: "Please select one of the choices", preferredStyle: .alert)
let okayAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okayAction)
present(alertController, animated: true, completion: nil)
return
}
// Dismiss if next node is end state and if PlayableTree says it should dismiss when next node is end state
if tree.nextNodeIsEndState && shouldDismissWhenNextNodeIsEndState {
// Save state of last node
tree.saveStateOfLastNode()
dismiss(animated: true, completion: nil)
return
}
// Dismiss if next node is not available
if !tree.nextNodeIsAvailable {
// Save state of last node
tree.saveStateOfLastNode()
dismiss(animated: true, completion: nil)
return
}
tree.transitionToNextNode()
reloadNode()
}
func showAvailableActions(_ sender: AnyObject?) {
let actionController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// Voice-over
let speechText = "Speech " + (voiceOverOn ? "Off" : "On")
let speechAction = UIAlertAction(title: speechText, style: .default) { (action) -> Void in
self.voiceOverOn = !self.voiceOverOn
}
actionController.addAction(speechAction)
// Auto-play
if let autoPlayableTree = self as? AutoPlayableTree {
let autoPlayText = "Auto-play " + (autoPlayableTree.autoPlay ? "Off" : "On")
let autoPlayAction = UIAlertAction(title: autoPlayText, style: .default, handler: { action in
autoPlayableTree.autoPlay = !autoPlayableTree.autoPlay
})
actionController.addAction(autoPlayAction)
}
// Set Language
let setLanguageAction = UIAlertAction(title: "Set Language", style: .default) { (action) -> Void in
self.showChooseLanguageScreen()
}
actionController.addAction(setLanguageAction)
// Cancel
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
actionController.addAction(cancelAction)
// For iPad action sheet behavior (similar to a popover)
if let popover = actionController.popoverPresentationController {
if let barButtonItem = sender as? UIBarButtonItem {
popover.barButtonItem = barButtonItem
} else if let view = sender as? UIView {
popover.sourceView = view
}
}
present(actionController, animated: true, completion: nil)
}
func showChooseLanguageScreen() {
if let tree = self.tree {
let languagesTableVC = LanguagesTableViewController()
let navVC = UINavigationController(rootViewController: languagesTableVC)
languagesTableVC.languages = tree.availableLanguages
languagesTableVC.selectedLanguage = tree.currentLanguage
languagesTableVC.didSelectLanguageCompletion = { selectedLanguage in
tree.currentLanguage = selectedLanguage
self.reloadNode()
}
navVC.modalPresentationStyle = .formSheet
present(navVC, animated: true, completion: nil)
}
}
}
public extension PlayableTree {
var voiceOverOn: Bool {
get {
// Default to true if not yet set
let standardUserDefaults = UserDefaults.standard
if standardUserDefaults.object(forKey: "SpeechOn") == nil {
standardUserDefaults.set(true, forKey: "SpeechOn")
}
return standardUserDefaults.bool(forKey: "SpeechOn")
}
set {
UserDefaults.standard.set(newValue, forKey: "SpeechOn")
// If toggled to on, start voice-over, else, stop
if newValue {
self.startVoiceOver()
} else {
self.stopVoiceOver()
}
}
}
func reloadNode() {
guard let tree = self.tree else {
return
}
guard let node = tree.currentNode else {
return
}
stopVoiceOver()
nodeView.node = node
nodeView.hintsDictionary = tree.hintsDictionary
if let delegate = self as? HintsTextViewDelegate {
nodeView.hintsTextViewDelegate = delegate
}
// Background image
if let backgroundImagePath = tree.backgroundImageURL?.path {
nodeView.backgroundImage = UIImage(contentsOfFile: backgroundImagePath)
}
// Background audio - change only if not empty and different
if let currentURL = backgroundAudioPlayer?.url {
if let newURL = tree.backgroundAudioURL {
if newURL as URL != currentURL {
backgroundAudioPlayer?.stop()
backgroundAudioPlayer = nil
loadBackgroundAudio()
}
}
} else {
// If current URL is empty, attempt load
loadBackgroundAudio()
}
// Voice-over
if voiceOverOn {
startVoiceOver()
}
}
// MARK: Background audio
func loadBackgroundAudio() {
guard let url = tree?.backgroundAudioURL else {
return
}
do {
let audioPlayer = try AVAudioPlayer(contentsOf: url as URL)
audioPlayer.numberOfLoops = -1
audioPlayer.prepareToPlay()
audioPlayer.play()
audioPlayer.volume = 0.4
backgroundAudioPlayer = audioPlayer
} catch let error {
print("Error loading background audio: \(error)")
}
}
// MARK: Voice-over
func startVoiceOver() {
// Attempt to play speech from audio file, if failed, resort to text-to-speech
if !startVoiceOverAudio() {
// Start text-to-speech instead
startTextToSpeech()
}
}
func stopVoiceOver() {
stopVoiceOverAudio()
stopTextToSpeech()
}
func startVoiceOverAudio() -> Bool {
guard let voiceOverAudioURL = tree?.currentVoiceOverAudioURL else {
return false
}
do {
let audioPlayer = try AVAudioPlayer(contentsOf: voiceOverAudioURL as URL)
// Get coordingator if playable
let coordinator = (self as? AutoPlayableTree)?.voiceOverCoordinator
coordinator?.delegate = self as? VoiceOverCoordinatorDelegate
// Set audio player delegate
audioPlayer.delegate = coordinator
// Play
audioPlayer.prepareToPlay()
audioPlayer.play()
voiceOverAudioPlayer = audioPlayer
return true
} catch let error {
print("Error loading voice-over audio: \(error)")
return false
}
}
func stopVoiceOverAudio() {
guard let audioPlayer = voiceOverAudioPlayer else {
return
}
if audioPlayer.isPlaying {
audioPlayer.stop()
}
}
func startTextToSpeech() {
guard let node = tree?.currentNode else {
return
}
// Get coordinator if AutoPlayable
let coordinator = (self as? AutoPlayableTree)?.voiceOverCoordinator
coordinator?.delegate = self as? VoiceOverCoordinatorDelegate
// Set speech synthesizer delegate to coordinator
speechSynthesizer.delegate = coordinator
for module in node.modules where module is SpeakableTextTypeModule {
let texts = (module as! SpeakableTextTypeModule).speakableTexts
for text in texts {
let utterance = AVSpeechUtterance(string: text)
utterance.voice = AVSpeechSynthesisVoice(language: "en-EN")
coordinator?.lastSpeechUtterance = utterance
// Speak
speechSynthesizer.speak(utterance)
}
}
}
func stopTextToSpeech() {
if speechSynthesizer.isSpeaking {
speechSynthesizer.stopSpeaking(at: .immediate)
}
}
var shouldDismissWhenNextNodeIsEndState: Bool {
return true
}
}
| apache-2.0 | 9f09542defb61e4649b2eb51c2976184 | 31.475904 | 143 | 0.575311 | 5.741214 | false | false | false | false |
pandazheng/Spiral | Spiral/Rope.swift | 2 | 1013 | //
// Rope.swift
// Spiral
//
// Created by 杨萧玉 on 14-10-11.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import SpriteKit
class Rope: SKSpriteNode {
let maxLength:CGFloat
let fixWidth:CGFloat = 5
init(length:CGFloat){
let texture = SKTexture(imageNamed: "rope")
maxLength = texture.size().height / (texture.size().width / fixWidth)
let size = CGSize(width: fixWidth, height: min(length,maxLength))
super.init(texture: SKTexture(rect: CGRect(origin: CGPointZero, size: CGSize(width: 1, height: min(length / maxLength, 1))), inTexture: texture),color:SKColor.clearColor(), size: size)
// normalTexture = texture?.textureByGeneratingNormalMapWithSmoothness(0.5, contrast: 0.5)
// lightingBitMask = playerLightCategory|killerLightCategory|scoreLightCategory|shieldLightCategory|reaperLightCategory
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 5c3d8cab6a088cb0507a60920f62403a | 36 | 192 | 0.688689 | 3.98008 | false | false | false | false |
omochi/numsw | Sources/numsw/NDArray/NDArrayTransformation.swift | 1 | 1696 |
extension NDArray {
public func reshaped(_ newShape: [Int]) -> NDArray<T> {
precondition(newShape.filter({ $0 == -1 }).count <= 1, "Invalid shape.")
var newShape = newShape
if let autoIndex = newShape.index(of: -1) {
let prod = -newShape.reduce(1, *)
newShape[autoIndex] = elements.count / prod
}
return NDArray(shape: newShape, elements: self.elements)
}
public func raveled() -> NDArray<T> {
return NDArray(shape: [elements.count], elements: elements)
}
}
extension NDArray {
public func transposed() -> NDArray<T> {
let axes: [Int] = (0..<shape.count).reversed()
return transposed(axes)
}
public func transposed(_ axes: [Int]) -> NDArray<T> {
precondition(axes.count == shape.count, "Number of `axes` and number of dimensions must correspond.")
precondition(Set(axes) == Set(0..<shape.count), "Argument `axes` must contain each axis.")
let outShape = axes.map { self.shape[$0] }
let outPointer = UnsafeMutablePointer<T>.allocate(capacity: self.elements.count)
defer { outPointer.deallocate(capacity: elements.count) }
let inIndices = calculateIndices(formatIndicesInAxes(shape, []))
for i in inIndices {
let oIndex = calculateIndex(outShape, axes.map { i[$0] })
outPointer.advanced(by: oIndex).pointee = getElement(self, i)
}
let elements = Array(UnsafeBufferPointer(start: outPointer, count: self.elements.count))
return NDArray(shape: outShape, elements: elements)
}
}
| mit | d0732dd44da1e07f22bfd2475812b9d2 | 34.333333 | 109 | 0.590802 | 4.27204 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Player/PlayerTimerCoordinator.swift | 1 | 1777 | //
// PlayerTimerCoordinator.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/26/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import RxSwift
protocol PlayerTimerCoordinator {
func presentTimer(in controller: UIViewController, time: Int?) -> Observable<Int?>
}
class MAPlayerTimerCoordinator: NSObject, PlayerTimerCoordinator {
func presentTimer(in controller: UIViewController, time: Int?) -> Observable<Int?> {
let destinationController = UIStoryboard.player.controller(of: PlayerTimerViewController.self)
let timeObservable = destinationController.timeOutput
if let time = time {
destinationController.currentTime = time
destinationController.timerEnabled = true
}
destinationController.transitioningDelegate = self
destinationController.modalPresentationStyle = .custom
controller.present(destinationController, animated: true, completion: nil)
return timeObservable
}
}
extension MAPlayerTimerCoordinator: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil
}
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return PlayerTimerPresentationController(presentedViewController: presented, presenting: presenting)
}
}
| mit | ea9a3777efb7f4c212500fa8b0419d84 | 32.433962 | 170 | 0.725169 | 6.174216 | false | false | false | false |
mohamede1945/quran-ios | Quran/TranslationPageLayout.swift | 1 | 1878 | //
// TranslationPageLayout.swift
// Quran
//
// Created by Mohamed Afifi on 4/1/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
struct LongTranslationTextLayout {
let textContainer: NSTextContainer
let numberOfGlyphs: Int
}
struct TranslationTextLayout: Hashable {
let text: TranslationText
let size: CGSize
let longTextLayout: LongTranslationTextLayout?
let translatorSize: CGSize
var hashValue: Int {
return text.text.hashValue ^ size.width.hashValue ^ text.translation.id.hashValue
}
static func == (lhs: TranslationTextLayout, rhs: TranslationTextLayout) -> Bool {
return
lhs.text.translation.id == rhs.text.translation.id &&
lhs.size.width == rhs.size.width &&
lhs.text.text == rhs.text.text
}
}
struct TranslationArabicTextLayout {
let arabicText: String
let size: CGSize
}
struct TranslationVerseLayout {
let ayah: AyahNumber
let arabicTextLayout: TranslationArabicTextLayout
let translationLayouts: [TranslationTextLayout]
let arabicPrefixLayouts: [TranslationArabicTextLayout]
let arabicSuffixLayouts: [TranslationArabicTextLayout]
}
struct TranslationPageLayout {
let pageNumber: Int
let verseLayouts: [TranslationVerseLayout]
}
| gpl-3.0 | 9ba6ecf27d200ac80f40f07ae27e6baa | 28.809524 | 89 | 0.71672 | 4.347222 | false | false | false | false |
vanyaland/Popular-Movies | iOS/PopularMovies/PopularMovies/MovieDetailScrollView.swift | 1 | 1975 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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
// MARK: MovieDetailScrollView: UIScrollView
final class MovieDetailScrollView: UIScrollView {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var posterImageView: UIImageView!
@IBOutlet weak var releaseDateLabel: UILabel!
@IBOutlet weak var ratingLabel: UILabel!
@IBOutlet weak var overviewLabel: UILabel!
func configure(with viewModel: MovieDetailViewModel) {
titleLabel.text = viewModel.titleText
posterImageView.af_setImage(withURL: viewModel.imageUrl)
releaseDateLabel.text = viewModel.releaseDateText
ratingLabel.text = viewModel.ratingText
overviewLabel.attributedText = viewModel.overviewAttributedText
titleLabel.textColor = viewModel.primaryTextColor
releaseDateLabel.textColor = viewModel.secondaryTextColor
ratingLabel.textColor = viewModel.secondaryTextColor
}
}
| mit | 93d7ba7e8e60eee3b0b69133ca242ef6 | 41.021277 | 80 | 0.772152 | 4.925187 | false | false | false | false |
DSanzh/ios_nanodegree | 2_ud788_UIKit_Fundamentals/Other subtasks/Roshambo/Roshambo/ViewController.swift | 1 | 1343 | //
// ViewController.swift
// Roshambo
//
// Created by Sanzhar on 6/13/17.
// Copyright © 2017 Sanzhar D. All rights reserved.
//
import UIKit
// MARK: - ViewControler : UIViewController
class ViewController: UIViewController {
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: Actions
@IBAction func rockButton(_ sender: UIButton) {
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "RoshamboResultViewController") as? RoshamboResultViewController {
vc.userChoice = Shape.Rock
present(vc, animated: true, completion: nil)
}
}
@IBAction func scissorsButton(_ sender: UIButton) {
performSegue(withIdentifier: "playRoshambo", sender: sender)
}
// MARK: Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "playRoshambo" {
if let controller = segue.destination as? RoshamboResultViewController {
controller.userChoice = getUserChoice(sender as! UIButton)
}
}
}
// MARK: Utilities
private func getUserChoice(_ sender: UIButton) -> Shape {
let title = sender.title(for: .normal)!
return Shape(rawValue: title)!
}
}
| mit | f2b0920d964627bdc4f967110ad5a268 | 24.807692 | 145 | 0.624441 | 4.611684 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/HandyJSON/Source/NominalType.swift | 3 | 3654 | /*
* Copyright 1999-2101 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Created by zhouzhuo on 07/01/2017.
//
protocol NominalType : MetadataType {
var nominalTypeDescriptorOffsetLocation: Int { get }
}
extension NominalType {
var nominalTypeDescriptor: NominalTypeDescriptor? {
let pointer = UnsafePointer<Int>(self.pointer)
let base = pointer.advanced(by: nominalTypeDescriptorOffsetLocation)
if base.pointee == 0 {
// swift class created dynamically in objc-runtime didn't have valid nominalTypeDescriptor
return nil
}
#if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
return NominalTypeDescriptor(pointer: relativePointer(base: base, offset: base.pointee - base.hashValue))
#else
return NominalTypeDescriptor(pointer: relativePointer(base: base, offset: base.pointee))
#endif
}
var fieldTypes: [Any.Type]? {
guard let nominalTypeDescriptor = self.nominalTypeDescriptor else {
return nil
}
guard let function = nominalTypeDescriptor.fieldTypesAccessor else { return nil }
return (0..<nominalTypeDescriptor.numberOfFields).map {
return unsafeBitCast(function(UnsafePointer<Int>(pointer)).advanced(by: $0).pointee, to: Any.Type.self)
}
}
var fieldOffsets: [Int]? {
guard let nominalTypeDescriptor = self.nominalTypeDescriptor else {
return nil
}
let vectorOffset = nominalTypeDescriptor.fieldOffsetVector
guard vectorOffset != 0 else {
return nil
}
return (0..<nominalTypeDescriptor.numberOfFields).map {
return UnsafePointer<Int>(pointer)[vectorOffset + $0]
}
}
}
struct NominalTypeDescriptor : PointerType {
public var pointer: UnsafePointer<_NominalTypeDescriptor>
var mangledName: String {
return String(cString: relativePointer(base: pointer, offset: pointer.pointee.mangledName) as UnsafePointer<CChar>)
}
var numberOfFields: Int {
return Int(pointer.pointee.numberOfFields)
}
var fieldOffsetVector: Int {
return Int(pointer.pointee.fieldOffsetVector)
}
var fieldNames: [String] {
let p = UnsafePointer<Int32>(self.pointer)
return Array(utf8Strings: relativePointer(base: p.advanced(by: 3), offset: self.pointer.pointee.fieldNames))
}
typealias FieldsTypeAccessor = @convention(c) (UnsafePointer<Int>) -> UnsafePointer<UnsafePointer<Int>>
var fieldTypesAccessor: FieldsTypeAccessor? {
let offset = pointer.pointee.fieldTypesAccessor
guard offset != 0 else {
return nil
}
let p = UnsafePointer<Int32>(self.pointer)
let offsetPointer: UnsafePointer<Int> = relativePointer(base: p.advanced(by: 4), offset: offset)
return unsafeBitCast(offsetPointer, to: FieldsTypeAccessor.self)
}
}
struct _NominalTypeDescriptor {
var mangledName: Int32
var numberOfFields: Int32
var fieldOffsetVector: Int32
var fieldNames: Int32
var fieldTypesAccessor: Int32
}
| mit | 3789285b2d0fa9c52e29793c3c44c239 | 34.134615 | 123 | 0.681171 | 4.648855 | false | false | false | false |
zxwWei/SwfitZeng | XWWeibo接收数据/XWWeibo/Classes/Tool(工具)/XWAFNTool.swift | 1 | 8090 | //
// XWAFNTool.swift
// XWWeibo
//
// Created by apple on 15/10/28.
// Copyright © 2015年 ZXW. All rights reserved.
//
// MARK : - ios9中的网络请求需配key
// MARK : - 进一步封装
import Foundation
import AFNetworking
// MARK: - 网络枚举错误
enum XWNetWorkError: Int {
case emptyToken = -1
case emptyUid = -2
// 枚举里面可以有属性
var description: String {
get {
// 根据枚举的类型返回对应的错误
switch self {
case XWNetWorkError.emptyToken:
return "accecc token 为空"
case XWNetWorkError.emptyUid:
return "uid 为空"
}
}
}
// 枚举可以定义方法
func error() -> NSError {
return NSError(domain: "cn.itcast.error.network", code: rawValue, userInfo: ["errorDescription" : description])
}
}
//class XWNetworkTool: AFHTTPSessionManager {
class XWNetworkTool: NSObject {
/// 闭包宏定义 类型别名
typealias NetWorkFinishedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
/// 属性 afnManager
private var afnManager: AFHTTPSessionManager
// MARK: - 1.创建单例 继续自本类
static let shareInstance: XWNetworkTool = XWNetworkTool()
// MARK: - 重写XWNetworkTool()构造方法
override init(){
let urlStr = "https://api.weibo.com/"
afnManager = AFHTTPSessionManager(baseURL: NSURL(string: urlStr))
afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
}
// MARK: - 2 Oauth授权url 注意参数不要复制出错
// 2.参数
// 申请时应用时分配的APPKey
private let client_id = "1369851949"
// 回调地址
let redirect_uri = "http://www.baidu.com/"
/// 请求的类型,填写authorization_code
private let grant_type = "authorization_code"
// 应用的secert
private let client_secret = "abc9cd7b14e70a7b26ad4e1cfa147e0e"
// MARK: - 3.OAthURL地址 Oauth授权url
func oauthURL() -> NSURL {
// 拼接
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
return NSURL(string: urlString)!
}
// MARK: - /// 判断access token是否有值,没有值返回nil,如果有值生成一个字典
func assTokenDict() -> [String: AnyObject]? {
if XWUserAccount.loadAccount()?.access_token == nil {
return nil
}
return ["access_token": XWUserAccount.loadAccount()!.access_token!]
}
// MARK: - 4.加载AssesToken
func loadAssesToken(code: String , finished: NetWorkFinishedCallBack){
let urlString = "https://api.weibo.com/oauth2/access_token"
// 参数
let parameters = [
//"code" : code
"client_id" : client_id ,
"client_secret": client_secret,
"grant_type": grant_type,
"code": code,
"redirect_uri": redirect_uri
]
// MARK: - 网络请求 让调用者获取信息
afnManager.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
// 成功时告诉调用闭包者得到result
finished(result: result as? [String: AnyObject] , error: nil)
}) { (_, error) -> Void in
// 失败时告诉调用闭包者得到error
finished(result: nil, error: error)
}
}
// finished: (result: [String: AnyObject]? ,error: NSError?) -> () NSError?
// MARK: - 获取用户信息
func loadUserinfo(finished:NetWorkFinishedCallBack) {
print("asscess_token:\(XWUserAccount.loadAccount()?.access_token)")
if XWUserAccount.loadAccount()?.access_token == nil {
let error = XWNetWorkError.emptyToken.error()
finished(result: nil, error: error)
//print("没有acces_token")
return
}
// 判断uid
if XWUserAccount.loadAccount()?.uid == nil{
//print("没有uid")
let error = XWNetWorkError.emptyUid.error()
finished(result: nil, error: error)
return
}
// url
let urlString = "2/users/show.json"
// MARK: -------------------- 参数 字典参数是-------------------
let parameters = [
"access_token" : XWUserAccount.loadAccount()!.access_token!,
"uid" : XWUserAccount.loadAccount()!.uid!
]
// 把结果告诉调用者
requestGETGET(urlString, parameters: parameters, finished: finished)
}
///MARK: 获取微博信息 发送网络请求的方法
func getblogInfo(since_id: Int, max_id: Int,finished: NetWorkFinishedCallBack){
let uslStr = "2/statuses/home_timeline.json"
guard var parmeters = assTokenDict() else {
// 没有值的时候进入
finished(result: nil, error: XWNetWorkError.emptyToken.error())
return
}
// - parameter since_id: 加载大于since_id大的微博, 默认为0
// - parameter max_id: 加载小于或等于max_id的微博, 默认为0
//
//print(assTokenDict() )
//
// var parmeters = [
//
// "access_token" : XWUserAccount.loadAccount()!.access_token!
// ]
if (since_id > 0){
parmeters["since_id"] = since_id
}
else if (max_id > 0){
parmeters["max_id"] = max_id - 1
}
// parmeters["max_id"] = max_id
//
requestGETGET(uslStr, parameters: parmeters, finished: finished)
}
//
// func getblogInfo(since_id: Int, max_id: Int,finished:NetWorkFinishedCallBack) {
// // 获取路径
// let path = NSBundle.mainBundle().pathForResource("statuses", ofType: "json")
//
// // 加载文件数据
// let data = NSData(contentsOfFile: path!)
//
// // 转成json
// do {
// let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0))
// // 有数据
// finished(result: json as? [String : AnyObject], error: nil)
// } catch {
// print("出异常了")
// }
// }
//
//
// MARK: - 发布微博
func sendStatus(status: String,finished: NetWorkFinishedCallBack){
let urlStr = "2/statuses/update.json"
guard var parmerters = assTokenDict() else{
// 没有值的时候进入
finished(result: nil, error: XWNetWorkError.emptyToken.error())
return
}
parmerters["status"] = status
afnManager.POST(urlStr, parameters: parmerters, success: { (_ , result) -> Void in
finished(result: result as? [String: AnyObject], error: nil)
}) { (_ , error ) -> Void in
finished(result: nil, error: error )
}
}
// MARK: - 封装 GET
func requestGETGET(URLString: String, parameters: AnyObject?, finished: NetWorkFinishedCallBack){
afnManager.GET(URLString, parameters: parameters, success: { (_, result) -> Void in
finished(result: result as? [String: AnyObject], error: nil)
//print("成功:result\(result)")
}) { (_, error ) -> Void in
finished(result: nil, error: error )
// print("失败:error\(error)")
}
}
}
| apache-2.0 | c448b5426d2621164b7440506e5fc5a9 | 26.155797 | 119 | 0.519013 | 4.370262 | false | false | false | false |
cliqz-oss/jsengine | jsengine-ios/jsengine/SystemLoader.swift | 1 | 6325 | //
// SystemLoader.swift
// jsengine
//
// Created by Ghadir Eraisha on 12/19/16.
// Copyright © 2016 Cliqz GmbH. All rights reserved.
//
import Foundation
class SystemLoader {
private weak var jsContext: JSContext? = nil
private var assetsRoot: String
private var buildRoot: String
private var bundle: NSBundle
private var moduleCache: [String:JSValue] = [String:JSValue]()
init(context: JSContext, assetsRoot: String, buildRoot: String, bundle: NSBundle) {
self.jsContext = context
self.assetsRoot = assetsRoot
self.buildRoot = buildRoot
self.bundle = bundle
let loadSubScript: @convention(block) (String) -> () = {[weak self] assetPath in
self?.loadSubScript(assetPath)
}
context.setObject(unsafeBitCast(loadSubScript, AnyObject.self), forKeyedSubscript: "loadSubScript")
// Load Module
loadJavascriptSource("timers")
if #available(iOS 10, *) {
} else {
loadJavascriptSource("/build/modules/bower_components/es6-promise/es6-promise")
context.evaluateScript("Promise = ES6Promise")
}
// create dummy exports object for polyfill to be added
context.evaluateScript("var exports = {}")
self.loadJavascriptSource("system-polyfill.js")
context.evaluateScript("var System = exports.System;");
// some custom modules for the App: system and promise
context.evaluateScript("System.set('system', { default: System });");
context.evaluateScript("System.set('promise', { default: Promise });");
}
func readSourceFile(assetPath: String, buildPath: String, fileExtension: String) -> String? {
var content: String? = nil
let (sourceName, directory) = getSourceMetaData(assetPath, buildPath: buildPath)
if let path = self.bundle.pathForResource(sourceName, ofType: fileExtension, inDirectory: directory){
content = try? NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String
} else {
DebugLogger.log("<< Script not found: \(assetPath)")
}
return content
}
func loadModule(moduleName: String) throws -> JSValue {
//check for cached modules
if let module = self.moduleCache[moduleName] {
return module
}
return try loadModuleInternal(moduleName)
}
func callVoidFunctionOnModule(modulePath: String, functionName: String, arguments: [AnyObject]? = nil) throws {
let module = try loadModule(modulePath)
module.invokeMethod(functionName, withArguments: arguments)
}
func callFunctionOnModule(modulePath: String, functionName: String, arguments: [AnyObject]? = nil) throws -> JSValue? {
let module = try loadModule(modulePath)
return try callFunctionOnObject(module, functionName: functionName, arguments: arguments)
}
func callFunctionOnModuleAttribute(modulePath: String, attribute: [String], functionName: String, arguments: [AnyObject]? = nil) throws -> JSValue? {
let depth = attribute.count
var attributeStack = [JSValue?](count:depth+1, repeatedValue: nil)
let module = try loadModuleInternal(modulePath)
attributeStack[0] = module
for index in 0...depth-1 {
attributeStack[index+1] = attributeStack[index]?.valueForProperty(attribute[index])
}
return try callFunctionOnObject(attributeStack[depth]!, functionName: functionName, arguments: arguments)
}
private func callFunctionOnObject(obj: AnyObject, functionName: String, arguments: [AnyObject]? = nil) throws -> JSValue? {
let fnResult = obj.invokeMethod(functionName, withArguments: arguments)
return fnResult
}
private func loadModuleInternal(moduleName: String) throws -> JSValue {
let promise = jsContext?.evaluateScript("System.import(\"\(moduleName)\")")
let promiseCallBack = PromiseCallback(promise:promise!)
let module = try promiseCallBack.get()
moduleCache[moduleName] = module
return module!
}
func loadSubScript(assetPath: String) {
if let content = readSourceFile(assetPath, buildPath: self.buildRoot, fileExtension: "js") {
self.jsContext?.evaluateScript(content)
} else {
DebugLogger.log("<< Could not load file: \(assetPath)")
}
}
private func loadJavascriptSource(assetPath: String) {
if let content = readSourceFile(assetPath, buildPath: "", fileExtension: "js") {
self.jsContext?.evaluateScript(content)
} else {
DebugLogger.log("<< Could not load file: \(assetPath)")
}
}
private func getSourceMetaData(assetPath: String, buildPath: String) -> (String, String) {
var sourceName: String
var directory: String
// seperate the folder path and the file name of the asset
if assetPath.rangeOfString("/") != nil {
var pathComponents = assetPath.componentsSeparatedByString("/")
sourceName = pathComponents.last!
pathComponents.removeLast()
directory = self.assetsRoot + buildPath + pathComponents.joinWithSeparator("/")
} else {
sourceName = assetPath
directory = self.assetsRoot + buildPath
}
// remove file extension
if SystemLoader.endsWith(sourceName, suffix:".js") {
sourceName = sourceName.stringByReplacingOccurrencesOfString(".js", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
}
return (sourceName, directory)
}
private static func endsWith(string: String, suffix: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if suffix.isEmpty {
return true
}
if let range = string.rangeOfString(suffix,
options: [NSStringCompareOptions.AnchoredSearch, NSStringCompareOptions.BackwardsSearch]) {
return range.endIndex == string.endIndex
}
return false
}
}
| mpl-2.0 | 2b3031b1adba64d84373d0fd9f33a28a | 39.280255 | 154 | 0.640259 | 5.104116 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Core/Shared/LoggingObserver.swift | 2 | 4724 | //
// LoggingObserver.swift
// Operations
//
// Created by Daniel Thorpe on 24/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
/**
Attach a `LoggingObserver to an operation to log when the operation
start, produces new operation and finsihed.
Any produced `Operation` instances will automatically get their
own logger attached.
*/
@available(iOS, deprecated=9, message="Use the log property of Operation directly.")
@available(OSX, deprecated=10.11, message="Use the log property of Operation directly.")
public struct LoggingObserver: OperationObserver {
public typealias LoggerBlockType = (message: String) -> Void
let logger: LoggerBlockType
let queue: dispatch_queue_t
/**
Create a logging observer. Accepts as the final argument a block which receives a
`String` message to be logged. By default this just uses `print()`, but construct
with a custom block to send logs to other systems. The block is executed on a
dispatch queue.
- parameter queue: a queue, by detault it uses it's own serial queue.
- parameter logger: a logging block. By detault the logger uses `println`
however, for custom loggers provide a block which receives a `String`.
*/
public init(queue: dispatch_queue_t = Queue.Initiated.serial("me.danthorpe.Operations.Logger"), logger: LoggerBlockType = { print($0) }) {
self.queue = queue
self.logger = logger
}
/**
Conforms to `OperationObserver`. The logger is sent a string which uses the
`name` parameter of the operation if provived.
"My Operation: did start."
- parameter operation: the `Operation` which has started.
*/
public func didStartOperation(operation: Operation) {
log("\(operation.operationName): did start.")
}
/**
Conforms to `OperationObserver`. The logger is sent a string which uses the
`name` parameter of the operation if provived.
"My Operation: did cancel."
- parameter operation: the `Operation` which has started.
*/
public func didCancelOperation(operation: Operation) {
log("\(operation.operationName): did cancel.")
}
/**
Conforms to `OperationObserver`. The logger is sent a string which uses the
`name` parameter of the operation if provived.
"My Operation: did produce operation: My Other Operation."
If the produced operation is an `Operation`, then a new `LoggingObserver` with
same queue and logger will be attached to it as an observer. Meaning that when
the produced operation starts/produces/finishes, it will also generate log
output.
- parameter operation: the `Operation` producer.
- parameter newOperation: the `Operation` which has been produced.
*/
public func operation(operation: Operation, didProduceOperation newOperation: NSOperation) {
let detail = newOperation.operationName
if let newOperation = newOperation as? Operation {
newOperation.addObserver(LoggingObserver(queue: queue, logger: logger))
}
log("\(operation.operationName): did produce operation: \(detail).")
}
/**
Conforms to `OperationObserver`. The logger is sent a string which uses the
`name` parameter of the operation if provived. If there were errors, output
looks like
"My Operation: finsihed with error(s): [My Operation Error]."
or if no errors:
"My Operation: finsihed with no errors."
- parameter operation: the `Operation` that finished.
- parameter errors: an array of `ErrorType`, not that these will be printed out.
*/
public func willFinishOperation(operation: Operation, errors: [ErrorType]) {
let detail = errors.count > 0 ? "error(s): \(errors)" : "no errors"
log("\(operation.operationName): will finish with \(detail).")
}
/**
Conforms to `OperationObserver`. The logger is sent a string which uses the
`name` parameter of the operation if provived. If there were errors, output
looks like
"My Operation: finsihed with error(s): [My Operation Error]."
or if no errors:
"My Operation: finsihed with no errors."
- parameter operation: the `Operation` that finished.
- parameter errors: an array of `ErrorType`, not that these will be printed out.
*/
public func didFinishOperation(operation: Operation, errors: [ErrorType]) {
let detail = errors.count > 0 ? "error(s): \(errors)" : "no errors"
log("\(operation.operationName): did finish with \(detail).")
}
private func log(message: String) {
dispatch_async(queue) {
self.logger(message: message)
}
}
}
| gpl-3.0 | a232d38896218aa368d03bd018b8a2e6 | 34.787879 | 142 | 0.684801 | 4.555448 | false | false | false | false |
PJayRushton/stats | Stats/UpdateTrophies.swift | 1 | 2551 | //
// UpdateTrophies.swift
// Stats
//
// Created by Parker Rushton on 8/30/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import Foundation
struct TrophySectionsUpdated: Event {
var sections: [TrophySection]
var gameId: String
init(_ sections: [TrophySection], gameId: String) {
self.sections = sections
self.gameId = gameId
}
}
struct UpdateTrophies: Command {
var game: Game?
init(for game: Game? = nil) {
self.game = game
}
func execute(state: AppState, core: Core<AppState>) {
DispatchQueue.global().async {
let objectId = self.game?.id ?? state.seasonState.currentSeasonId
guard let id = objectId else { return }
let sections = Trophy.allValues.compactMap { trophy -> TrophySection? in
let trophyStats = state.statState.stats(for: id, ofType: trophy.statType)
let isWorst = trophy == Trophy.worseBattingAverage
let winners = self.winningStats(from: trophyStats, isWorst: isWorst)
guard let winner = winners.first else { return nil }
return TrophySection(trophy: trophy, firstStat: winner, secondStat: winners.second)
}
guard !sections.isEmpty else { return }
core.fire(event: TrophySectionsUpdated(sections, gameId: id))
}
}
}
// MARK - Private
extension UpdateTrophies {
func winningStats(from stats: [Stat], isWorst: Bool = false) -> (first: Stat?, second: Stat?) {
guard !stats.isEmpty, let currentTeam = App.core.state.teamState.currentTeam else { return (nil, nil) }
var allStats = isWorst ? stats.sorted() : stats.sorted().reversed()
let winnerStat = allStats.removeFirst()
guard winnerStat.value > 0 else { return (nil, nil) }
guard stats.count > 1 else { return (winnerStat, nil) }
var secondStat: Stat?
if currentTeam.isCoed {
var otherGenderStats = stats.filter { $0.player?.gender != winnerStat.player?.gender }
otherGenderStats = isWorst ? otherGenderStats.sorted() : otherGenderStats.sorted().reversed()
secondStat = otherGenderStats.first
} else {
secondStat = allStats.first
}
if !isWorst {
guard let second = secondStat, second.value > 0 else { return (winnerStat, nil) }
}
return (first: winnerStat, second: secondStat)
}
}
| mit | aaee79f4e2a98cda049c29925c55e2de | 31.692308 | 111 | 0.601569 | 4.358974 | false | false | false | false |
huonw/swift | validation-test/compiler_crashers_fixed/00086-std-function-func-swift-type-subst.swift | 65 | 569 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
struct h<t, j: v where t.h == j
| apache-2.0 | 8bfb13bb29d1e0c8bc7bbdef9536fe20 | 27.45 | 79 | 0.650264 | 3.126374 | false | false | false | false |
Eunryu/EDToolKit | EDToolKit/Classes/MakeUIButtonKit.swift | 1 | 7962 | //
// MakeUIButtonKit.swift
// Pods
//
// Created by 은아월 on 2017. 4. 13..
//
//
import Foundation
import UIKit
public class MakeUIButtonKit {
public static let shared = MakeUIButtonKit()
public init() {
}
// MARK : 2017.04.26 Size(CGRect) -> Size(CGSize) 로 변경
open func makeButton(title: String, size: CGSize, addView: AnyObject) -> UIButton {
let mainButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
buttonBasicWork(button: mainButton)
mainButton.setTitle(title, for: .normal)
addView.addSubview(mainButton)
return mainButton
}
open func makeButton(titleImage: UIImage, size: CGSize, addView: AnyObject) -> UIButton {
let mainButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
buttonBasicWork(button: mainButton)
mainButton.setImage(titleImage, for: .normal)
addView.addSubview(mainButton)
return mainButton
}
//-----------------
// MARK : 2017.04.26 Image 버튼의 추가
open func makeButton(nImage: UIImage, pImage: UIImage, size: CGSize, addView: AnyObject) -> UIButton {
let mainButton: UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
buttonBasicWork(button: mainButton)
mainButton.setImage(nImage, for: .normal)
mainButton.setImage(pImage, for: .highlighted)
addView.addSubview(mainButton)
return mainButton
}
// -----------
open func textDecoration(button: UIButton, fontName: String?, fontSize: CGFloat?, color: UIColor?, pressColor: UIColor?) {
if fontSize != nil && fontName != nil {
button.titleLabel!.font = UIFont(name: fontName!, size: fontSize!)
} else {
if fontSize != nil {
button.titleLabel!.font = UIFont(name: "Helvetica", size: fontSize!)
} else if fontName != nil {
button.titleLabel!.font = UIFont(name: fontName!, size: 14.0)
}
}
if color != nil {
button.setTitleColor(color!, for: .normal)
}
if pressColor != nil {
button.setTitleColor(pressColor!, for: .highlighted)
}
}
open func containerDecoration(button: UIButton, layerColor: UIColor?, layerWidth: CGFloat?, bgColor: UIColor?, corner: CGFloat?) {
if layerColor != nil && layerWidth != nil {
button.layer.borderColor = layerColor!.cgColor
button.layer.borderWidth = layerWidth!
} else {
if layerColor != nil {
button.layer.borderColor = layerColor!.cgColor
} else if layerWidth != nil {
button.layer.borderWidth = layerWidth!
}
}
if bgColor != nil {
button.backgroundColor = bgColor!
}
if corner != nil {
button.layer.cornerRadius = corner!
}
}
// MARK : CustomButton Decoration
open func customButtonBasicSetting(customBtn: AnyObject, mainBg: UIColor?, pressBg: UIColor?, mainLayer: UIColor?, pressLayer: UIColor?, mainTxt: UIColor?, pressTxt: UIColor?) {
if customBtn is ClickBgEffectButton {
if mainBg != nil {
(customBtn as! ClickBgEffectButton).mainColor = mainBg!
}
if pressBg != nil {
(customBtn as! ClickBgEffectButton).pressColor = pressBg!
}
return
}
if customBtn is ClickLayerEffectButton {
if mainLayer != nil {
(customBtn as! ClickLayerEffectButton).mainBorderLayer = mainLayer!
}
if pressLayer != nil {
(customBtn as! ClickLayerEffectButton).pressBorderLayer = pressLayer!
}
return
}
if customBtn is ClickBgAndTextEffectButton {
if mainBg != nil {
(customBtn as! ClickBgAndTextEffectButton).mainBgColor = mainBg!
}
if pressBg != nil {
(customBtn as! ClickBgAndTextEffectButton).pressBgColor = pressBg!
}
if mainTxt != nil {
(customBtn as! ClickBgAndTextEffectButton).mainTextColor = mainTxt!
}
if pressTxt != nil {
(customBtn as! ClickBgAndTextEffectButton).pressTextColor = pressTxt!
}
return
}
if customBtn is ClickLayerAndTextEffectButton {
if mainLayer != nil {
(customBtn as! ClickLayerAndTextEffectButton).mainLayerColor = mainLayer!
}
if pressLayer != nil {
(customBtn as! ClickLayerAndTextEffectButton).pressLayerColor = pressLayer!
}
if mainTxt != nil {
(customBtn as! ClickLayerAndTextEffectButton).mainTextColor = mainTxt!
}
if pressTxt != nil {
(customBtn as! ClickLayerAndTextEffectButton).pressTextColor = pressTxt!
}
return
}
//ClickMultiEffectButton
// MARK : 2017.04.25 MultiEffectButton 으로 되어있지 않던것들에 대해 수정.
if mainBg != nil {
(customBtn as! ClickMultiEffectButton).mainBgColor = mainBg!
}
if pressBg != nil {
(customBtn as! ClickMultiEffectButton).pressBgColor = pressBg!
}
if mainLayer != nil {
(customBtn as! ClickMultiEffectButton).mainLayerColor = mainLayer!
}
if pressLayer != nil {
(customBtn as! ClickMultiEffectButton).pressLayerColor = pressLayer!
}
if mainTxt != nil {
(customBtn as! ClickMultiEffectButton).mainTextColor = mainTxt!
}
if pressTxt != nil {
(customBtn as! ClickMultiEffectButton).pressTextColor = pressTxt!
}
}
// MARK : Make Button basic
func buttonBasicWork(button: UIButton) {
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitleColor(UIColor.black, for: .normal)
button.titleLabel?.font = UIFont(name: "Helvetica".localized, size: 14)
}
}
extension UIButton {
// 2017.06.14 - 버튼 함수의 익스텐션화, 텍스트 꾸미기
func textDecoration(fontName: String?, fontSize: CGFloat?, color: UIColor?, pressColor: UIColor?) {
if fontSize != nil && fontName != nil {
self.titleLabel!.font = UIFont(name: fontName!, size: fontSize!)
} else {
if fontSize != nil {
self.titleLabel!.font = UIFont(name: "Helvetica", size: fontSize!)
} else if fontName != nil {
self.titleLabel!.font = UIFont(name: fontName!, size: 14.0)
}
}
if color != nil {
self.setTitleColor(color!, for: .normal)
}
if pressColor != nil {
self.setTitleColor(pressColor!, for: .highlighted)
}
}
func containerDecoration(layerColor: UIColor?, layerWidth: CGFloat?, bgColor: UIColor?, corner: CGFloat?) {
if layerColor != nil && layerWidth != nil {
self.layer.borderColor = layerColor!.cgColor
self.layer.borderWidth = layerWidth!
} else {
if layerColor != nil {
self.layer.borderColor = layerColor!.cgColor
} else if layerWidth != nil {
self.layer.borderWidth = layerWidth!
}
}
if bgColor != nil {
self.backgroundColor = bgColor!
}
if corner != nil {
self.layer.cornerRadius = corner!
}
}
}
| mit | 0446ce66d8275ba17e920379d8c80aea | 32.381356 | 181 | 0.55801 | 5.056483 | false | false | false | false |
CaryZheng/ZTabsView | ZTabsViewDemo/ZTabsViewDemo/ViewController.swift | 1 | 1648 | //
// ViewController.swift
// ZTabsViewDemo
//
// Created by CaryZheng on 15/6/27.
// Copyright (c) 2015年 CaryZheng. All rights reserved.
//
import UIKit
class ViewController: UIViewController, IZTabsView {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initTabsView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initTabsView()
{
let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height
let parentWidth = self.view.bounds.size.width
let parentHeight = self.view.bounds.size.height
let tabsView = ZTabsView()
tabsView.delegate = self
tabsView.frame = CGRectMake(0, statusBarHeight, parentWidth, parentHeight)
let tabTitles = ["Tab1", "Tab2", "Tab3"]
let view1 = UIView()
view1.backgroundColor = UIColor.redColor()
let view2 = UIView()
view2.backgroundColor = UIColor.yellowColor()
let view3 = UIView()
view3.backgroundColor = UIColor.blueColor()
let contentViews = [view1, view2, view3]
tabsView.initView(tabTitles, contentViews: contentViews)
self.view.addSubview(tabsView)
}
func onTabChanged(currentTabIndex: Int, lastTabIndex: Int)
{
ZLog.d("onTabChanged currentTabIndex = \(currentTabIndex), lastTabIndex = \(lastTabIndex)")
}
}
| mit | f9af02f0a79ee2d1efec7c8f63145b51 | 26.898305 | 99 | 0.625152 | 4.702857 | false | false | false | false |
Tj3n/TVNExtensions | UIKit/AVAudioSession.swift | 1 | 2196 | //
// AVAudioSession+Extension.swift
// TVNExtensions
//
// Created by Tien Nhat Vu on 2/2/18.
//
import Foundation
import AVFoundation
extension AVAudioSession {
public static var isHeadphonesConnected: Bool {
return sharedInstance().isHeadphonesConnected
}
public var isHeadphonesConnected: Bool {
return !currentRoute.outputs.filter { $0.isHeadphones }.isEmpty
}
//No way to do for lower iOS, have to use Obj-C
@available(iOS 10.0, *)
public class func mixWithBackgroundMusic() {
_ = try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
}
}
extension AVAudioSessionPortDescription {
public var isHeadphones: Bool {
return portType == .headphones
}
}
public class AudioDetection {
var callback: ((_ isConnected: Bool)->())?
public init(callback: @escaping ((_ isConnected: Bool)->())) {
self.callback = callback;
self.listenForNotifications()
}
deinit {
callback = nil
NotificationCenter.default.removeObserver(self)
}
func listenForNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(handleRouteChange(_:)), name: AVAudioSession.routeChangeNotification, object: nil)
}
@objc func handleRouteChange(_ notification: Notification) {
guard
let userInfo = notification.userInfo,
let reasonRaw = userInfo[AVAudioSessionRouteChangeReasonKey] as? NSNumber,
let reason = AVAudioSession.RouteChangeReason(rawValue: reasonRaw.uintValue)
else { fatalError("Strange... could not get routeChange") }
switch reason {
case .oldDeviceUnavailable:
callback?(false)
case .newDeviceAvailable:
print("newDeviceAvailable")
if AVAudioSession.isHeadphonesConnected {
callback?(true)
}
case .routeConfigurationChange:
print("routeConfigurationChange")
case .categoryChange:
print("categoryChange")
default:
print("not handling reason")
}
}
}
| mit | 8b094cb2ad58f632cbc0b36d41ec62cf | 29.5 | 155 | 0.643443 | 4.979592 | false | false | false | false |
chunkyguy/Cocos2dSwift | Cocos2dSwift/Classes/HelloWorldScene.swift | 1 | 2727 |
//
// HelloWorldScene.swift
// TapSoccer
//
// Created by Sid on 24/06/14.
// Copyright (c) 2014 whackylabs. All rights reserved.
//
import Foundation
/**
* The main scene
*/
class HelloWorldScene : CCScene {
let _sprite:CCSprite?
init()
{
super.init()
// Enable touch handling on scene node
userInteractionEnabled = true
// Create a colored background (Dark Grey)
var background:CCNodeColor = CCNodeColor(color: CCColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0))
addChild(background)
// Add a sprite
_sprite = CCSprite(imageNamed: "Icon-72.png")
_sprite!.position = CGPoint(x: self.contentSize.width/2, y: self.contentSize.height/2)
addChild(_sprite)
// Animate sprite with action
let actionSpin:CCActionRotateBy = CCActionRotateBy(duration: 1.5, angle: 360)
_sprite?.runAction(actionSpin)
// Create a back button
let backButton:CCButton = CCButton(title: "[ Menu ]", fontName: "Verdana-Bold", fontSize: 18.0)
backButton.positionType = CCPositionType.Normalized
// CCPositionTypeMake(CCPositionUnit.Normalized, CCPositionUnit.Normalized, CCPositionReferenceCorner.BottomLeft)
backButton.position = CGPoint(x: 0.85, y: 0.95) // Top Right of screen
backButton.setTarget(self, selector: "onBackClicked:")
addChild(backButton)
}
deinit
{
// clean up code goes here
}
override func onEnter()
{
// always call super onEnter first
super.onEnter()
// In pre-v3, touch enable and scheduleUpdate was called here
// In v3, touch is enabled by setting userInterActionEnabled for the individual nodes
// Per frame update is automatically enabled, if update is overridden
}
override func onExit()
{
// always call super onExit last
super.onExit()
}
override func touchBegan(touch: UITouch!, withEvent event: UIEvent!)
{
let touchLoc:CGPoint = touch.locationInNode(self)
// Log touch location
println("Move sprite to \(NSStringFromCGPoint(touchLoc))")
// Move our sprite to touch location
let actionMove:CCActionMoveTo = CCActionMoveTo(duration: 1.0, position: touchLoc)
_sprite!.runAction(actionMove)
}
func onBackClicked(sender:AnyObject)
{
// back to intro scene with transition
CCDirector.sharedDirector().replaceScene(IntroScene(), withTransition: CCTransition(pushWithDirection: CCTransitionDirection.Right, duration: 1.0))
}
} | mit | 8cdac71c7b06f1539685e005dcbaaf1a | 29.651685 | 155 | 0.625596 | 4.492586 | false | false | false | false |
JerrySir/YCOA | YCOA/Main/DetailPage/View/DetailPageTableVC_DeleteTableViewCell.swift | 1 | 3612 | //
// DetailPageTableVC_DeleteTableViewCell.swift
// YCOA
//
// Created by Jerry on 2017/2/1.
// Copyright © 2017年 com.baochunsteel. All rights reserved.
//
// 删除Cell
import UIKit
class DetailPageTableVC_DeleteTableViewCell: UITableViewCell {
private var deleteButton: UIButton!
private var infoStringTextView: UITextView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.contentView.backgroundColor = UIColor.groupTableViewBackground
let titleLabel = UILabel()
titleLabel.text = "单据删除"
titleLabel.textColor = UIColor.darkText
titleLabel.font = UIFont.systemFont(ofSize: 22)
self.contentView.addSubview(titleLabel)
let bgView = UIView()
bgView.backgroundColor = UIColor.white
self.contentView.addSubview(bgView)
let infoStringLabel = UILabel()
infoStringLabel.text = "说明:"
infoStringLabel.font = UIFont.systemFont(ofSize: 17)
infoStringLabel.textColor = UIColor.lightGray
bgView.addSubview(infoStringLabel)
self.infoStringTextView = UITextView()
self.infoStringTextView.layer.masksToBounds = true
self.infoStringTextView.layer.borderColor = UIColor.lightGray.cgColor
self.infoStringTextView.layer.borderWidth = 1
self.infoStringTextView.layer.cornerRadius = 0.1
bgView.addSubview(self.infoStringTextView)
self.deleteButton = UIButton(type: .system)
self.deleteButton.setTitle("删除单据", for: .normal)
self.deleteButton.backgroundColor = UIColor.red
self.deleteButton.setTitleColor(UIColor.white, for: .normal)
bgView.addSubview(self.deleteButton)
//AutoLayout
titleLabel.snp.makeConstraints { (make) in
make.left.top.equalTo(8)
}
bgView.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.right.bottom.equalTo(-8)
make.bottom.equalTo(-8)
}
infoStringLabel.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.centerY.equalTo(infoStringTextView.snp.centerY)
}
self.infoStringTextView.snp.makeConstraints { (make) in
make.left.equalTo(infoStringLabel.snp.right).offset(8)
make.top.equalTo(8)
make.right.equalTo(-8)
make.height.equalTo(55)
}
self.deleteButton.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(infoStringTextView.snp.bottom).offset(8)
make.right.bottom.equalTo(-8)
make.height.equalTo(50)
}
}
open func configure(didDeletedTap: @escaping (String)->Swift.Void) {
self.deleteButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (_) in
didDeletedTap(self.infoStringTextView.text)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
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
}
}
| mit | 82f091809e87a66157073df4cfbfb476 | 33.471154 | 124 | 0.639888 | 4.735799 | false | false | false | false |
chrisjmendez/swift-exercises | GUI/TipView/TipView/ViewController.swift | 1 | 1633 | //
// ViewController.swift
// TipView
//
// Created by Chris on 1/16/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var easyTipPreferences = EasyTipView.Preferences()
@IBOutlet weak var tip1: UIButton!
@IBOutlet weak var tip2: UIButton!
@IBAction func onTap2(sender: AnyObject) {
EasyTipView.showAnimated(true,
forView: self.tip2,
withinSuperview: self.navigationController?.view,
text: "Tip view inside the navigation controller's view. Tap to dismiss!",
preferences: easyTipPreferences,
delegate: self)
}
@IBOutlet weak var tip3: UIButton!
func onLoad(){
easyTipPreferences.drawing.font = UIFont(name: "Helvetica", size: 13)!
easyTipPreferences.drawing.foregroundColor = UIColor.blackColor()
easyTipPreferences.drawing.backgroundColor = UIColor(hue:0.46, saturation:0.99, brightness:0.6, alpha:1)
easyTipPreferences.drawing.arrowPosition = EasyTipView.ArrowPosition.Top
EasyTipView.globalPreferences = easyTipPreferences
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController:EasyTipViewDelegate{
func easyTipViewDidDismiss(tipView : EasyTipView){
print("tipView")
}
} | mit | 4947b91fa33cddf9db75bd742484c44a | 27.649123 | 112 | 0.664216 | 5.052632 | false | false | false | false |
amraboelela/swift | test/TypeDecoder/typealias.swift | 1 | 2108 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-executable %s -g -o %t/typealias -emit-module
// RUN: sed -ne '/\/\/ *DEMANGLE: /s/\/\/ *DEMANGLE: *//p' < %s > %t/input
// RUN: %lldb-moduleimport-test %t/typealias -type-from-mangled=%t/input | %FileCheck %s
typealias Alias = Int
struct Outer {
typealias Alias = Int
struct Inner {
typealias Alias = Int
}
}
struct GenericOuter<T> {
typealias Alias = Int
struct Inner {
typealias Alias = Int
}
}
protocol Proto {
typealias Alias = Int
}
extension Proto {
typealias OtherAlias = Int
}
extension GenericOuter where T : Proto {
typealias ConditionalAlias = Int
}
struct Conforms : Proto {}
func blackHole(_: Any...) {}
do {
let x1: Alias = 0
let x2: Outer.Alias = 0
let x3: Outer.Inner.Alias = 0
blackHole(x1, x2, x3)
}
do {
let x1: GenericOuter<Int>.Alias = 0
let x2: GenericOuter<Int>.Inner.Alias = 0
blackHole(x1, x2)
}
do {
// Note that the first two are not sugared because of representational issues.
let x1: Proto.Alias = 0
let x2: Proto.OtherAlias = 0
let x3: Conforms.Alias = 0
let x4: Conforms.OtherAlias = 0
blackHole(x1, x2, x3, x4)
}
func generic<T : Proto>(_: T) {
let x1: T.Alias = 0
let x2: T.OtherAlias = 0
blackHole(x1, x2)
}
do {
let x1: GenericOuter<Conforms>.ConditionalAlias = 0
blackHole(x1)
}
// DEMANGLE: $s9typealias5AliasaD
// DEMANGLE: $s9typealias5OuterV5AliasaD
// DEMANGLE: $s9typealias5OuterV5InnerV5AliasaD
// CHECK: Alias
// CHECK: Outer.Alias
// CHECK: Outer.Inner.Alias
// DEMANGLE: $s9typealias12GenericOuterV5AliasaySi_GD
// DEMANGLE: $s9typealias12GenericOuterV5InnerV5AliasaySi__GD
// CHECK: GenericOuter<Int>.Alias
// CHECK: GenericOuter<Int>.Inner.Alias
// DEMANGLE: $s9typealias5ProtoP5AliasayAA8ConformsV_GD
// DEMANGLE: $s9typealias5ProtoPAAE10OtherAliasayAA8ConformsV_GD
// DEMANGLE: $s9typealias5ProtoP5Aliasayx_GD
// DEMANGLE: $s9typealias5ProtoPAAE10OtherAliasayx_GD
// DEMANGLE: $s9typealias12GenericOuterVA2A5ProtoRzlE16ConditionalAliasayAA8ConformsV_GD
// CHECK: GenericOuter<Conforms>.ConditionalAlias
| apache-2.0 | 7e4af1cb2077835eabd19687652cc994 | 19.871287 | 88 | 0.708729 | 3.198786 | false | false | false | false |
mcjcloud/Show-And-Sell | Show And Sell/StaggeredLayout.swift | 1 | 3463 | //
// StaggeredLayout.swift
// Show And Sell
//
// Created by Brayden Cloud on 2/14/17.
// Copyright © 2017 Brayden Cloud. All rights reserved.
//
import UIKit
// MARK: Delegate protocol
protocol StaggeredLayoutDelegate {
func collectionView(_ collectionView: UICollectionView, heightForCellAt indexPath: IndexPath, with width: CGFloat) -> CGFloat
}
class StaggeredLayout: UICollectionViewLayout {
// delegate for layout
var delegate: StaggeredLayoutDelegate!
// properties
var numberOfColumns = 2
var cellPadding: CGFloat = 3.0
// layout attributes
var cache = [UICollectionViewLayoutAttributes]()
// size
private var contentHeight: CGFloat = 0.0
private var contentWidth: CGFloat {
let insets = collectionView!.contentInset
return collectionView!.bounds.width - (insets.left + insets.right) // return the width of the view minus the insets
}
// override content size variable
override var collectionViewContentSize: CGSize {
return CGSize(width: contentWidth, height: contentHeight)
}
// MARK: Layout functions
override func prepare() {
// if there are no attribtes
if cache.isEmpty {
let columnWidth = contentWidth / CGFloat(numberOfColumns)
var xOffset = [CGFloat]()
// build the offset array from the left axis per cell
for column in 0..<numberOfColumns {
xOffset.append(CGFloat(column) * columnWidth)
}
var column = 0
var yOffset = [CGFloat](repeating: 0, count: numberOfColumns)
// create the y offsets
for item in 0..<collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: item, section: 0)
let width = columnWidth - (cellPadding * 2)
let cellHeight = delegate.collectionView(collectionView!, heightForCellAt: indexPath, with: width)
let height = cellHeight + cellPadding
// create the Cell frame
let frame = CGRect(x: xOffset[column], y: yOffset[column], width: columnWidth, height: height)
let insetFrame = frame.insetBy(dx: cellPadding, dy: cellPadding)
// get attributes
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attributes.frame = insetFrame
cache.append(attributes)
contentHeight = max(contentHeight, frame.maxY)
yOffset[column] += height
column = column >= (numberOfColumns - 1) ? 0 : column + 1
}
}
}
// override functions that gets the layout for elements in a given rect
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
// loop through the attributes in cache
for attributes in cache {
// if the attributes in cache is being displayed
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes) // add the attributes from cache to the resultant array
}
}
// return the attributes
return layoutAttributes
}
}
| apache-2.0 | adddd270aaa671e8436f55b2c8eba6de | 36.225806 | 129 | 0.607163 | 5.629268 | false | false | false | false |
PixarAnimationStudios/depot3 | d3RepoMan/d3RepoMan/AppDelegate.swift | 1 | 3597 | //
// AppDelegate.swift
// d3ExpirationMonitor
//
// Created by Chris Lasell on 7/18/15.
// Copyright (c) 2016 Pixar Animation Studios. All rights reserved.
//
//### Copyright 2018 Pixar
//###
//### Licensed under the Apache License, Version 2.0 (the "Apache License")
//### with the following modification; you may not use this file except in
//### compliance with the Apache License and the following modification to it:
//### Section 6. Trademarks. is deleted and replaced with:
//###
//### 6. Trademarks. This License does not grant permission to use the trade
//### names, trademarks, service marks, or product names of the Licensor
//### and its affiliates, except as required to comply with Section 4(c) of
//### the License and to reproduce the content of the NOTICE file.
//###
//### You may obtain a copy of the Apache License at
//###
//### http://www.apache.org/licenses/LICENSE-2.0
//###
//### Unless required by applicable law or agreed to in writing, software
//### distributed under the Apache License with the above modification is
//### distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
//### KIND, either express or implied. See the Apache License for the specific
//### language governing permissions and limitations under the Apache License.
//###
//###
import Cocoa
import CoreFoundation
import Foundation
import AppKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// the current user
let currentUser = NSUserName()
// filesystem access...
let fileManager = NSFileManager.defaultManager()
// the d3 support folder
let d3SupportFolder = "/Library/Application Support/d3"
// The folder where we collect the data per-user
// this folder needs to exist and be root:wheel, 0733
let d3UsageFolder = "\(d3SupportFolder)/Usage"
// the live plist
let plistPath = "\(d3UsageFolder)/\(currentUser).plist"
// the usage data
var monitorPlistData = NSMutableDictionary()
// if the live plist exists, load it
if fileManager.fileExistsAtPath(plistPath) {
monitorPlistData = NSMutableDictionary(contentsOfFile: plistPath)!
} else {
monitorPlistData.writeToFile(plistPath, atomically: false)
} // if fileManager...
// set the plist to mode 600, (decimal 384)
try! fileManager.setAttributes(["NSFilePosixPermissions": 384], ofItemAtPath: plistPath)
// the NSWorksace that will send notifications to us.
let workspace = NSWorkspace.sharedWorkspace()
// the notification center in that worksapce
let notifCtr = workspace.notificationCenter
// add our observer for when apps come to the foreground
// the block just adds or updates the plist key for the app with the current
// timestamp, then writes out the plist.
notifCtr.addObserverForName( NSWorkspaceDidActivateApplicationNotification,
object: nil,
queue: nil,
usingBlock: {(notification: NSNotification) -> Void in
var userInfo = notification.userInfo
let runningApp: NSRunningApplication = userInfo![NSWorkspaceApplicationKey] as! NSRunningApplication
let appExecPath = runningApp.executableURL!.path as String!
let now = NSDate()
monitorPlistData[appExecPath] = now
monitorPlistData.writeToFile(plistPath, atomically: false)
} // usingBlock
) // notifCtr.addObserverForName
} // func applicationDidFinishLaunching
} // class AppDelegate
| apache-2.0 | b892f8fb90bfbb62cda8a5d92b1a7037 | 35.333333 | 108 | 0.704754 | 4.854251 | false | false | false | false |
KarlWarfel/nutshell-ios | Nutshell/DataModel/CoreData/CommonData.swift | 1 | 3970 | //
// CommonData.swift
// Nutshell
//
// Created by Brian King on 9/15/15.
// Copyright © 2015 Tidepool. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
class CommonData: NSManagedObject {
// TODO: add code to download "meal" and "workout" items from service once they are supported and we upload them
class func fromJSON(json: JSON, moc: NSManagedObjectContext) -> CommonData? {
// The type of object we create is based on the "type" field
var newObject: CommonData? = nil
if let type = json["type"].string {
switch type {
case "activity": newObject = Activity.fromJSON(json, moc: moc)
case "basal": newObject = Basal.fromJSON(json, moc: moc)
case "bolus": newObject = Bolus.fromJSON(json, moc: moc)
case "cbg": newObject = ContinuousGlucose.fromJSON(json, moc: moc)
// The documentation indicates "deviceMeta", but the actual JSON shows "deviceEvent"
case "deviceEvent", "deviceMeta": newObject = DeviceMetadata.fromJSON(json, moc: moc)
case "food": newObject = Food.fromJSON(json, moc: moc)
case "grabbag": newObject = GrabBag.fromJSON(json, moc: moc)
case "bloodKetone": newObject = BloodKetone.fromJSON(json, moc: moc)
case "urineKetone": newObject = UrineKetone.fromJSON(json, moc: moc)
case "note": newObject = Note.fromJSON(json, moc: moc)
case "smbg": newObject = SelfMonitoringGlucose.fromJSON(json, moc: moc)
case "settings": newObject = Settings.fromJSON(json, moc: moc)
case "upload": newObject = Upload.fromJSON(json, moc: moc)
case "wizard": newObject = Wizard.fromJSON(json, moc: moc)
default: print("CommonData: Unknown type \(type)")
}
// If we got an object, set the common properties on it
if let newObject = newObject {
if let id = json["id"].string {
newObject.id = id
} else {
print("skipped record of type \(type) missing id")
return nil
}
newObject.type = type
if let timeString = json["time"].string {
if let time = NutUtils.dateFromJSON(timeString) {
newObject.time = time
} else {
print("skipped record of type \(type) with unknown time format: \(timeString)")
return nil
}
} else {
print("skipped record of type \(type) with missing time field")
return nil
}
newObject.time = NutUtils.dateFromJSON(json["time"].string)
newObject.deviceId = json["deviceId"].string
newObject.uploadId = json["uploadId"].string
newObject.previous = json["previous"].string
newObject.timezoneOffset = json["timezoneOffset"].number
newObject.deviceTime = NutUtils.dateFromJSON(json["deviceTime"].string)
newObject.units = json["units"].string
newObject.createdTime = NutUtils.dateFromJSON(json["createdTime"].string)
newObject.modifiedTime = NutUtils.dateFromJSON(json["modifiedTime"].string)
newObject.payload = json["payload"].string
newObject.annotations = json["annotations"].string
}
}
return newObject
}
}
| bsd-2-clause | 2fb02bab3e9c14724c9b37d2767b19bd | 47.402439 | 116 | 0.51877 | 5.392663 | false | false | false | false |
apple/swift-llbuild | experimental/cevobuild/Sources/CevoCore/Engine.swift | 1 | 4984 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
import Foundation
import Crypto
import NIO
import NIOConcurrencyHelpers
public protocol Key: Codable {}
public protocol Value : Codable {}
extension Key {
public typealias KeyHash = Data
public var stableHash: KeyHash {
// Not super happy about this implementation, but this will get replaced anyways by the mechanism that will
// translate between Keys and CAS IDs.
// An important note here is that we need to encode the type as well, otherwise we might get 2 different keys
// that contain the same fields and values, but actually represent different values.
var hash = SHA256()
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
encoder.dateEncodingStrategy = .iso8601
let data = try! encoder.encode(["key": self])
hash.update(data: data)
var digest = [UInt8]()
hash.finalize().withUnsafeBytes { pointer in
digest.append(contentsOf: pointer)
}
return KeyHash(digest)
}
}
public struct Result {
let changedAt: Int
let value: Value
let dependencies: [Key]
}
public class FunctionInterface {
let engine: Engine
public let group: EventLoopGroup
init(group: EventLoopGroup, engine: Engine) {
self.engine = engine
self.group = group
}
public func request(_ key: Key) -> EventLoopFuture<Value> {
return engine.buildKey(key: key)
}
public func request<V: Value>(_ key: Key, as type: V.Type = V.self) -> EventLoopFuture<V> {
return engine.buildKey(key: key, as: type)
}
// FIXME - implement these
// func spawn<T>(action: ()->T) -> EventLoopFuture<T>
// func spawn(args: [String], env: [String: String]) -> EventLoopFuture<ProcessResult...>
}
public protocol Function {
func compute(key: Key, _ fi: FunctionInterface) -> EventLoopFuture<Value>
}
public protocol EngineDelegate {
func lookupFunction(forKey: Key, group: EventLoopGroup) -> EventLoopFuture<Function>
}
public enum EngineError: Error {
case invalidValueType(String)
}
public class Engine {
public let group: EventLoopGroup
fileprivate let lock = NIOConcurrencyHelpers.Lock()
fileprivate let delegate: EngineDelegate
fileprivate var pendingResults: [Key.KeyHash: EventLoopFuture<Value>] = [:]
public enum Error: Swift.Error {
case noPendingTask
case missingBuildResult
}
public init(
group: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount),
delegate: EngineDelegate
) {
self.group = group
self.delegate = delegate
}
public func build(key: Key, inputs: [Key.KeyHash: Value]? = nil) -> EventLoopFuture<Value> {
// Set static input results if needed
if let inputs = inputs {
lock.withLockVoid {
for (k, v) in inputs {
self.pendingResults[k] = self.group.next().makeSucceededFuture(v)
}
}
}
// Build the key
return buildKey(key: key)
}
func buildKey(key: Key) -> EventLoopFuture<Value> {
return lock.withLock {
let keyID = key.stableHash
if let value = pendingResults[keyID] {
return value
}
// Create a promise to execute the body outside of the lock
let promise = group.next().makePromise(of: Value.self)
group.next().flatSubmit {
return self.delegate.lookupFunction(forKey: key, group: self.group).flatMap { function in
let fi = FunctionInterface(group: self.group, engine: self)
return function.compute(key: key, fi)
}
}.cascade(to: promise)
pendingResults[keyID] = promise.futureResult
return promise.futureResult
}
}
}
extension Engine {
public func build<V: Value>(key: Key, inputs: [Key.KeyHash: Value]? = nil, as: V.Type) -> EventLoopFuture<V> {
return self.build(key: key, inputs: inputs).flatMapThrowing {
guard let value = $0 as? V else {
throw EngineError.invalidValueType("Expected value of type \(V.self)")
}
return value
}
}
func buildKey<V: Value>(key: Key, as: V.Type) -> EventLoopFuture<V> {
return self.buildKey(key: key).flatMapThrowing {
guard let value = $0 as? V else {
throw EngineError.invalidValueType("Expected value of type \(V.self)")
}
return value
}
}
}
| apache-2.0 | 1b1e8f9165b475dddedf0d5bc3c00602 | 29.576687 | 117 | 0.625201 | 4.498195 | false | false | false | false |
tranhieutt/Swiftz | Swiftz/OptionalExt.swift | 1 | 4280 | //
// OptionalExt.swift
// Swiftz
//
// Created by Maxwell Swadling on 4/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
extension Optional {
/// Case analysis for the Optional type. Given a maybe, a default value in case it is None, and
/// a function, maps the function over the value in the Maybe.
public func maybe<B>(def : B, onSome : Wrapped -> B) -> B {
switch self {
case .None:
return def
case let .Some(x):
return onSome(x)
}
}
/// Given an Optional and a default value returns the value of the Optional when it is Some, else
/// this function returns the default value.
public func getOrElse(def : Wrapped) -> Wrapped {
switch self {
case .None:
return def
case let .Some(x):
return x
}
}
}
/// MARK: Instances
extension Optional : Functor {
public typealias A = Wrapped
public typealias B = Any
public typealias FB = Optional<B>
public func fmap<B>(f : Wrapped -> B) -> Optional<B> {
return self.map(f)
}
}
extension Optional /*: Pointed*/ {
public static func pure(x : Wrapped) -> Optional<Wrapped> {
return .Some(x)
}
}
extension Optional : Applicative {
public typealias FA = Optional<A>
public typealias FAB = Optional<A -> B>
public func ap<B>(f : Optional<A -> B>) -> Optional<B> {
return f <*> self
}
}
extension Optional : ApplicativeOps {
public typealias C = Any
public typealias FC = Optional<C>
public typealias D = Any
public typealias FD = Optional<D>
public static func liftA<B>(f : A -> B) -> Optional<A> -> Optional<B> {
return { a in Optional<A -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(f : A -> B -> C) -> Optional<A> -> Optional<B> -> Optional<C> {
return { a in { b in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(f : A -> B -> C -> D) -> Optional<A> -> Optional<B> -> Optional<C> -> Optional<D> {
return { a in { b in { c in f <^> a <*> b <*> c } } }
}
}
extension Optional : Monad {
public func bind<B>(f : A -> Optional<B>) -> Optional<B> {
return self >>- f
}
}
extension Optional : MonadOps {
public static func liftM<B>(f : A -> B) -> Optional<A> -> Optional<B> {
return { m1 in m1 >>- { x1 in Optional<B>.pure(f(x1)) } }
}
public static func liftM2<B, C>(f : A -> B -> C) -> Optional<A> -> Optional<B> -> Optional<C> {
return { m1 in { m2 in m1 >>- { x1 in m2 >>- { x2 in Optional<C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3<B, C, D>(f : A -> B -> C -> D) -> Optional<A> -> Optional<B> -> Optional<C> -> Optional<D> {
return { m1 in { m2 in { m3 in m1 >>- { x1 in m2 >>- { x2 in m3 >>- { x3 in Optional<D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <A, B, C>(f : A -> Optional<B>, g : B -> Optional<C>) -> (A -> Optional<C>) {
return { x in f(x) >>- g }
}
public func <<-<< <A, B, C>(g : B -> Optional<C>, f : A -> Optional<B>) -> (A -> Optional<C>) {
return f >>->> g
}
extension Optional : Foldable {
public func foldr<B>(k : A -> B -> B, _ i : B) -> B {
if let v = self {
return k(v)(i)
}
return i
}
public func foldl<B>(k : B -> A -> B, _ i : B) -> B {
if let v = self {
return k(i)(v)
}
return i
}
public func foldMap<M : Monoid>(f : A -> M) -> M {
return self.foldr(curry(<>) • f, M.mempty)
}
}
extension Optional : SequenceType {
public typealias Generator = GeneratorOfOne<Wrapped>
public func generate() -> GeneratorOfOne<Wrapped> {
return GeneratorOfOne(self)
}
}
/// Forbidden by Swift 1.2; see ~( http://stackoverflow.com/a/29750368/945847 ))
/// Given one or more Optional values, returns the first Optional value that is not nil
/// when evaulated from left to right
// public func coalesce<T>(all : @autoclosure () -> T? ...) -> T? {
// for f : () -> T? in all {
// if let x = f() { return x }
// }
// return nil
// }
/// Forbidden by Swift 1.2; see ~( http://stackoverflow.com/a/29750368/945847 ))
/// Given one or more Optional values, returns the first Optional value that is not nil
/// and satisfies the approve function when evaulated from left to right
// public func coalesce<T>(approve : T -> Bool) -> (@autoclosure () -> T? ...) -> T? {
// return { all in
// for f : () -> T? in all {
// if let x = f() {
// if approve(x) { return x }
// }
// }
// return nil
// }
// }
| bsd-3-clause | 9f385276e34c385685c0c1e7b0234b9c | 26.075949 | 121 | 0.59093 | 2.871141 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/ObjectMapper/Sources/MapError.swift | 115 | 2431 | //
// MapError.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2016-09-26.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct MapError: Error {
public var key: String?
public var currentValue: Any?
public var reason: String?
public var file: StaticString?
public var function: StaticString?
public var line: UInt?
public init(key: String?, currentValue: Any?, reason: String?, file: StaticString? = nil, function: StaticString? = nil, line: UInt? = nil) {
self.key = key
self.currentValue = currentValue
self.reason = reason
self.file = file
self.function = function
self.line = line
}
}
extension MapError: CustomStringConvertible {
private var location: String? {
guard let file = file, let function = function, let line = line else { return nil }
let fileName = ((String(describing: file).components(separatedBy: "/").last ?? "").components(separatedBy: ".").first ?? "")
return "\(fileName).\(function):\(line)"
}
public var description: String {
let info: [(String, Any?)] = [
("- reason", reason),
("- location", location),
("- key", key),
("- currentValue", currentValue),
]
let infoString = info.map { "\($0): \($1 ?? "nil")" }.joined(separator: "\n")
return "Got an error while mapping.\n\(infoString)"
}
}
| mit | a2b9c5c40c4de44f90088d72d70aefb4 | 34.75 | 142 | 0.703003 | 3.933657 | false | false | false | false |
siutsin/STLLapTimer-Swift | Playground.playground/section-1.swift | 1 | 568 | // Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
//let ti: Double = Double(2.3477777777)
//let x: Double = fmod(ti, 1) * 100
//let y: Double = round(x)
//let centiseconds: Int = Int(round(fmod(ti, 1) * 100))
let interval = NSTimeInterval(18.777777777777777)
let ti: Double = Double(interval)
let minutes: Int = (Int(ti) / 60) % 60
let seconds: Int = Int(ti) % 60
let centiseconds: Int = Int(round(fmod(ti, 1) * 100))
var timeUnits: [String: Int] = ["minutes": minutes, "seconds": seconds, "centiseconds": centiseconds] | mit | 9c7ef6b2b096eec3c8d5d23c3e14244d | 32.470588 | 101 | 0.683099 | 3.021277 | false | false | false | false |
prosperence/prosperence-ios | Prosperance/Prosperance/AddProfileViewController.swift | 1 | 982 | import UIKit
class AddProfileViewController: UIViewController
{
@IBOutlet weak var profileNameTextField: UITextField!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var rememberPasswordSwitch: UISwitch!
var simpleProfile = SimpleProfile()
@IBAction func handleUIUpdate(sender: AnyObject)
{
simpleProfile.profileName = profileNameTextField.text
simpleProfile.username = usernameTextField.text
simpleProfile.password = passwordTextField.text
simpleProfile.rememberPassword = rememberPasswordSwitch.on == true ? 1 : 0
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if(segue.identifier == "saveProfile")
{
var mvc = segue.destinationViewController as! MasterViewController
mvc.newProfile = simpleProfile;
}
}
} | mit | 15db6ab9c51693ee6ad2a9483fdbe375 | 29.71875 | 83 | 0.682281 | 5.74269 | false | false | false | false |
OlegTretiakov/ByzantineClock | TodayExtension/TodayViewController.swift | 1 | 2482 | //
// TodayViewController.swift
// TodayExtension
//
// Created by Олег Третьяков on 06.02.16.
// Copyright © 2016 Олег Третьяков. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
let placeChangeNotification = "placeChangeNotification"
let byzantineModel = ByzantineModel()
var timer : NSTimer?
@IBOutlet var clockView: ClockView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
self.preferredContentSize = CGSizeMake(320, 296)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateData()
timer = NSTimer(timeInterval: 1, target: self, selector: "tickTime", userInfo: nil, repeats: true)
timer!.tolerance = 0.5
NSRunLoop.mainRunLoop().addTimer(timer!, forMode: NSDefaultRunLoopMode)
}
override func viewWillDisappear(animated: Bool) {
timer?.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func updateData() {
let locationSaver = LocationSaver.sharedInstance
if locationSaver.isDataEmpty() {
clockView.noData = true
}
else {
clockView.noData = false
byzantineModel.setVariables()
reDraw()
}
}
func tickTime() {
byzantineModel.changeTime()
reDraw()
}
func reDraw() {
let byzantineMinutes = Int(byzantineModel.byzantineTime())
if clockView.timeInMinutes != byzantineMinutes {
clockView.timeInMinutes = byzantineMinutes
clockView.setNeedsDisplay()
}
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.NoData)
}
func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsetsZero
}
}
| mit | d9ad68ecb39b4fd8cf7eac9aa5a89889 | 30.474359 | 106 | 0.652546 | 5.290948 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/ViewControllerAbout.swift | 1 | 4234 | //
// ViewControllerAbout.swift
// RsyncOSX
//
// Created by Thomas Evensen on 18/11/2016.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length
import Cocoa
import Foundation
class ViewControllerAbout: NSViewController {
@IBOutlet var version: NSTextField!
@IBOutlet var downloadbutton: NSButton!
@IBOutlet var thereisanewversion: NSTextField!
@IBOutlet var rsyncversionstring: NSTextField!
@IBOutlet var copyright: NSTextField!
@IBOutlet var iconby: NSTextField!
@IBOutlet var chinese: NSTextField!
@IBOutlet var norwegian: NSTextField!
@IBOutlet var german: NSTextField!
@IBOutlet var italian: NSTextField!
@IBOutlet var configpath: NSTextField!
@IBOutlet var dutch: NSTextField!
var copyrigthstring: String = NSLocalizedString("Copyright ©2020 Thomas Evensen", comment: "copyright")
var iconbystring: String = NSLocalizedString("Icon by: Zsolt Sándor", comment: "icon")
var chinesestring: String = NSLocalizedString("Chinese (Simplified) translation by: StringKe (Chen)", comment: "chinese")
var norwegianstring: String = NSLocalizedString("Norwegian translation by: Thomas Evensen", comment: "norwegian")
var germanstring: String = NSLocalizedString("German translation by: Andre Voigtmann", comment: "german")
var italianstring: String = NSLocalizedString("Italian translation by: Stefano Steve Cutelle'", comment: "italian")
var dutchstring: String = NSLocalizedString("Dutch translation by: Marcellino Santoso", comment: "ducth")
var appName: String {
(Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String) ?? "RsyncOSX"
}
var appVersion: String {
(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String) ?? "1.0"
}
var appBuild: String {
(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String) ?? "1.0"
}
var resource: Resources?
@IBAction func changelog(_: NSButton) {
if let resource = resource {
NSWorkspace.shared.open(URL(string: resource.getResource(resource: .changelog))!)
}
view.window?.close()
}
@IBAction func documentation(_: NSButton) {
if let resource = resource {
NSWorkspace.shared.open(URL(string: resource.getResource(resource: .documents))!)
}
view.window?.close()
}
@IBAction func download(_: NSButton) {
guard SharedReference.shared.URLnewVersion != nil else {
view.window?.close()
return
}
NSWorkspace.shared.open(URL(string: SharedReference.shared.URLnewVersion!)!)
view.window?.close()
}
@IBAction func closeview(_: NSButton) {
view.window?.close()
}
override func viewDidLoad() {
super.viewDidLoad()
SharedReference.shared.setvcref(viewcontroller: .vcabout, nsviewcontroller: self)
copyright.stringValue = copyrigthstring
iconby.stringValue = iconbystring
chinese.stringValue = chinesestring
norwegian.stringValue = norwegianstring
german.stringValue = germanstring
italian.stringValue = italianstring
dutch.stringValue = dutchstring
resource = Resources()
}
override func viewDidAppear() {
super.viewDidAppear()
downloadbutton.isEnabled = false
let version = appVersion + " build" + "(" + appBuild + ")"
self.version.stringValue = "RsyncOSX ver: " + version
thereisanewversion.stringValue = NSLocalizedString("You have the latest ...", comment: "About")
rsyncversionstring.stringValue = SharedReference.shared.rsyncversionstring ?? ""
configpath.stringValue = NamesandPaths(.configurations).fullpathmacserial ?? ""
if SharedReference.shared.newversionofrsyncosx {
globalMainQueue.async { () in
self.downloadbutton.isEnabled = true
self.thereisanewversion.stringValue = NSLocalizedString("New version is available:", comment: "About")
}
}
}
override func viewDidDisappear() {
super.viewDidDisappear()
downloadbutton.isEnabled = false
}
}
| mit | 734b3e4b11b0b3c55962a8ede3295a2d | 38.175926 | 125 | 0.679745 | 4.732662 | false | false | false | false |
AsyncNinja/AsyncNinja | Sources/AsyncNinja/Debug.swift | 1 | 3479 | //
// Copyright (c) 2018 Anton Mironov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom
// the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
import Foundation
import Dispatch
private func loggableFileName(_ file: String) -> String {
guard let slashIndex = file.lastIndex(of: "/") else {
return file
}
let index = file.index(after: slashIndex)
return String(file[index...])
}
private func logDebug(identifier: String, content: String) {
print("\(AsyncNinjaConstants.debugDateFormatter.string(from: Date())) - \(identifier): \(content)")
}
private func identifier(file: String, line: UInt, function: String) -> String {
return "\(loggableFileName(file)):\(line) - \(function)"
}
/// debugging assistance
public extension Completing {
/// prints out completion
func debugCompletion(identifier: String) {
onComplete(executor: .immediate) { (completion) in
logDebug(identifier: identifier, content: "Completed \(completion)")
}
}
/// prints out completion
func debugCompletion(file: String = #file, line: UInt = #line, function: String = #function) {
debugCompletion(identifier: identifier(file: file, line: line, function: function))
}
}
/// debugging assistance
public extension Updating {
/// prints out each update
func debugUpdates(identifier: String) {
onUpdate(executor: .immediate) { (update) in
logDebug(identifier: identifier, content: "Update \(update)")
}
}
/// prints out each update
func debugUpdates(file: String = #file, line: UInt = #line, function: String = #function) {
debugUpdates(identifier: identifier(file: file, line: line, function: function))
}
}
/// debugging assistance
public extension Future {
/// prints out completion
func debug(identifier: String) {
debugCompletion(identifier: identifier)
}
/// prints out completion
func debug(file: String = #file, line: UInt = #line, function: String = #function) {
debugCompletion(file: file, line: line, function: function)
}
}
/// debugging assistance
public extension Channel {
/// prints out each update and completion
func debug(identifier: String) {
debugUpdates(identifier: identifier)
debugCompletion(identifier: identifier)
}
/// prints out each update and completion
func debug(file: String = #file, line: UInt = #line, function: String = #function) {
debugUpdates(file: file, line: line, function: function)
debugCompletion(file: file, line: line, function: function)
}
}
| mit | af30a44bc280ecdbbe131f6d9b5c6b97 | 34.141414 | 101 | 0.716873 | 4.26348 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00961-bool.swift | 1 | 764 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol A {
extension String {
}
typealias e: e()
}
func a: S) {
return S.C() -> : C {
typealias g<T, V, Any, x in a {
typealias e = A) {
}
class A? = e: A? {
}
return { c() {
}
}
}
case .Iterator.substringWithRange(b(x) {
b() -> == b(T) {
}
class a {
}
}
func c, a<A> () {
d: T? {
func b> {
}
typealias b : Sequence, AnyObject> {
}
}
class A {
}
let g = .E == c
}
| apache-2.0 | 5063cd9c8c7709c08b3b1e8c808f4101 | 17.634146 | 79 | 0.641361 | 2.893939 | false | false | false | false |
cloudinary/cloudinary_ios | Cloudinary/Classes/Core/Features/Helpers/Layers/CLDLayer.swift | 1 | 6310 | //
// CLDLayer.swift
//
// Copyright (c) 2016 Cloudinary (http://cloudinary.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
The CLDLayer is used to help adding an overlay or underlay layer to a transformation.
*/
@objcMembers open class CLDLayer: NSObject {
internal var publicId: String?
internal var format: String?
internal var resourceType: String?
internal var type: String?
// MARK: - Init
/**
Initialize a CLDLayer instance.
-returns: The new CLDLayer instance.
*/
@discardableResult
public override init() {
super.init()
}
// MARK: - Set Values
/**
The identifier of the image to use as a layer.
- parameter publicId: The identifier of the image to use as a layer.
- returns: The same instance of CLDLayer.
*/
@discardableResult
open func setPublicId(publicId: String) -> CLDLayer {
self.publicId = publicId
return self
}
/**
The format of the image to use as a layer.
- parameter format: The format of the image to use as a layer.
- returns: The same instance of CLDLayer.
*/
@discardableResult
open func setFormat(format: String) -> CLDLayer {
self.format = format
return self
}
/**
Set the layer resource type.
- parameter resourceType: The layer resource type.
- returns: The same instance of CLDLayer.
*/
@objc(setResourceTypeFromLayerResourceType:)
@discardableResult
open func setResourceType(_ resourceType: LayerResourceType) -> CLDLayer {
return setResourceType(String(describing: resourceType))
}
/**
Set the layer resource type.
- parameter resourceType: The layer resource type.
- returns: The same instance of CLDLayer.
*/
@objc(setResourceTypeFromString:)
@discardableResult
open func setResourceType(_ resourceType: String) -> CLDLayer {
self.resourceType = resourceType
return self
}
/**
Set the layer type.
- parameter type: The layer type.
- returns: The same instance of CLDLayer.
*/
@objc(setTypeFromType:)
@discardableResult
open func setType(_ type: CLDType) -> CLDLayer {
return setType(String(describing: type))
}
/**
Set the layer type.
- parameter rawType: The layer type.
- returns: The same instance of CLDLayer.
*/
@objc(setTypeFromString:)
@discardableResult
open func setType(_ rawType: String) -> CLDLayer {
type = rawType
return self
}
// MARK: - Helpers
fileprivate func isResourceTypeTextual(_ resourceType: String?) -> Bool {
guard let resourceType = resourceType else {
return false
}
return resourceType == String(describing: LayerResourceType.text) || resourceType == String(describing: LayerResourceType.subtitles)
}
internal func getFinalPublicId() -> String? {
var finalPublicId: String?
if let pubId = publicId , !pubId.isEmpty, let format = format , !format.isEmpty {
finalPublicId = "\(pubId).\(format)"
}
return finalPublicId ?? publicId
}
internal func getStringComponents() -> [String]? {
var components: [String] = []
if publicId == nil, let resourceType = resourceType , resourceType != String(describing: LayerResourceType.text) {
printLog(.error, text: "Must supply publicId for non-text layer")
return nil
}
if let resourceType = resourceType , resourceType != String(describing: LayerResourceType.image) {
components.append(resourceType)
}
if let type = type , type != String(describing: CLDType.upload) {
components.append(type)
}
if !isResourceTypeTextual(resourceType) {
if let pubId = getFinalPublicId() , !pubId.isEmpty {
components.append(pubId.replacingOccurrences(of: "/", with: ":"))
}
}
return components
}
// MARK: - Actions
internal func asString() -> String? {
guard let components = self.getStringComponents() else {
return nil
}
return components.joined(separator: ":")
}
// MARK: - Params
@objc public enum LayerResourceType: Int, CustomStringConvertible {
case image, raw, auto, text, subtitles, video, fetch
public var description: String {
get {
switch self {
case .image: return "image"
case .raw: return "raw"
case .auto: return "auto"
case .text: return "text"
case .subtitles: return "subtitles"
case .video: return "video"
case .fetch: return "fetch"
}
}
}
}
}
| mit | afca6b1a6c8dadf77feffda9621552ce | 30.237624 | 140 | 0.596989 | 5.039936 | false | false | false | false |
Tsiems/STRiNg | CarFile/CarFile/HTTP_helper.swift | 1 | 898 | //
// HTTP_helper.swift
// CarFile
//
// Created by Travis Siems on 11/13/15.
// Copyright © 2015 STRiNg, int. All rights reserved.
//
import Foundation
import SwiftHTTP
func getGoogle() {
print("hello google")
// let vin = "2G1FC3D33C9165616"
// do {
// let opt = try HTTP.GET("https://api.edmunds.com/api/vehicle/v2/vins/" + vin + "?fmt=json&api_key=5zyd8sa5k3yxgpcg7t49agav")
// opt.start { response in
// if let err = response.error {
// print("error: \(err.localizedDescription)")
// return //also notify app of failure as needed
// }
// print("opt finished: \(response.description)")
// //print("data is: \(response.data)") access the response of the data with response.data
// }
// } catch let error {
// print("got an error creating the request: \(error)")
// }
} | gpl-2.0 | b1469affa3e41869230ea1e1feb47d5f | 28.933333 | 133 | 0.583055 | 3.309963 | false | false | false | false |
hucool/XMImagePicker | Pod/Classes/XMImagePickerController.swift | 1 | 3781 | //
// XMImagePickerController.swift
// XMImagePicker
//
// Created by tiger on 2017/3/3.
// Copyright © 2017年 xinma. All rights reserved.
//
import UIKit
import Photos
import Foundation
open class XMImagePickerController: UINavigationController {
public typealias CallHandler = (_ photos: [Photo]) -> Void
static let IsOriginalKey = "isOriginal"
static let SelectAssetsKey = "selectAssets"
var resultHandler: CallHandler?
public var config: XMImagePickerOptions = XMImagePickerOptions()
private override init(rootViewController: UIViewController) {
super.init(nibName: nil, bundle: nil)
}
private override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(nibName: nil, bundle: nil)
}
public init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// setup navigationBar
navigationBar.tintColor = .white
navigationBar.isTranslucent = true
navigationBar.barStyle = .blackTranslucent
addNotification()
checkAuthorizationStatus()
}
deinit {
removeNotification()
}
// MARK:- Photos
// request photo authorization
fileprivate func checkAuthorizationStatus() {
let status = PHPhotoLibrary.authorizationStatus()
switch status {
case .authorized:
pushListViewController()
case .notDetermined:
requestAuthorization()
case .denied, .restricted:
showAuxiliaryView()
}
}
fileprivate func requestAuthorization() {
PHPhotoLibrary.requestAuthorization { (status) in
switch status {
case .authorized:
self.pushListViewController()
default:
self.showAuxiliaryView()
}
}
}
// MARK:- Notification
fileprivate func addNotification() {
NotificationCenter.default.addObserver(self,
selector: #selector(selectImageDone),
name: .SelectImageDone,
object: nil)
}
fileprivate func removeNotification() {
NotificationCenter.default.removeObserver(self, name: .SelectImageDone, object: nil)
}
@objc private func selectImageDone(not: Notification) {
guard let dic = not.object as? [String : Any] else {
return
}
guard let s = dic[XMImagePickerController.SelectAssetsKey] as? [PHAsset] else {
return
}
let o = (dic[XMImagePickerController.IsOriginalKey] as? Bool) ?? false
PhotoMannager.requestImages(isMarkUrl: config.isMarkImageURL, isCreateThumbImage: !o, assets: s) { (photos) in
if let handle = self.resultHandler {
handle(photos)
self.resultHandler = nil
}
self.dismiss(animated: true, completion: nil)
}
}
fileprivate func pushListViewController() {
DispatchQueue.main.async(execute: {
self.viewControllers = [ListViewController()]
})
}
fileprivate func showAuxiliaryView() {
DispatchQueue.main.async(execute: {
self.viewControllers = [TipVIewController()]
})
}
public func setFinishPickingHandle(handle: @escaping(_ photos: [Photo]) -> Void) {
resultHandler = handle
}
}
| mit | a8dee61a18bb6d84371e6207c908bfdc | 28.515625 | 118 | 0.591053 | 5.351275 | false | false | false | false |
tardieu/swift | stdlib/public/core/Policy.swift | 6 | 26241 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized uninhabited type
//===----------------------------------------------------------------------===//
/// The return type of functions that do not return normally; a type with no
/// values.
///
/// Use `Never` as the return type when declaring a closure, function, or
/// method that unconditionally throws an error, traps, or otherwise does
/// not terminate.
///
/// func crashAndBurn() -> Never {
/// fatalError("Something very, very bad happened")
/// }
@_fixed_layout
public enum Never {}
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The return type of functions that don't explicitly specify a return type;
/// an empty tuple (i.e., `()`).
///
/// When declaring a function or method, you don't need to specify a return
/// type if no value will be returned. However, the type of a function,
/// method, or closure always includes a return type, which is `Void` if
/// otherwise unspecified.
///
/// Use `Void` or an empty tuple as the return type when declaring a
/// closure, function, or method that doesn't return a value.
///
/// // No return type declared:
/// func logMessage(_ s: String) {
/// print("Message: \(s)")
/// }
///
/// let logger: (String) -> Void = logMessage
/// logger("This is a void function")
/// // Prints "Message: This is a void function"
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
///
/// When you create a constant or variable using one of the Boolean literals
/// `true` or `false`, the resulting type is determined by the
/// `BooleanLiteralType` alias. For example:
///
/// let isBool = true
/// print("isBool is a '\(type(of: isBool))'")
/// // Prints "isBool is a 'Bool'"
///
/// The type aliased by `BooleanLiteralType` must conform to the
/// `ExpressibleByBooleanLiteral` protocol.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
// Integer literals are limited to 2048 bits.
// The intent is to have arbitrary-precision literals, but implementing that
// requires more work.
//
// Rationale: 1024 bits are enough to represent the absolute value of min/max
// IEEE Binary64, and we need 1 bit to represent the sign. Instead of using
// 1025, we use the next round number -- 2048.
public typealias _MaxBuiltinIntegerType = Builtin.Int2048
#if (!os(Windows) || CYGWIN) && (arch(i386) || arch(x86_64))
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// You use `AnyObject` when you need the flexibility of an untyped object or
/// when you use bridged Objective-C methods and properties that return an
/// untyped result. `AnyObject` can be used as the concrete type for an
/// instance of any class, class type, or class-only protocol. For example:
///
/// class FloatRef {
/// let value: Float
/// init(_ value: Float) {
/// self.value = value
/// }
/// }
///
/// let x = FloatRef(2.3)
/// let y: AnyObject = x
/// let z: AnyObject = FloatRef.self
///
/// `AnyObject` can also be used as the concrete type for an instance of a type
/// that bridges to an Objective-C class. Many value types in Swift bridge to
/// Objective-C counterparts, like `String` and `Int`.
///
/// let s: AnyObject = "This is a bridged string." as NSString
/// print(s is NSString)
/// // Prints "true"
///
/// let v: AnyObject = 100 as NSNumber
/// print(type(of: v))
/// // Prints "__NSCFNumber"
///
/// The flexible behavior of the `AnyObject` protocol is similar to
/// Objective-C's `id` type. For this reason, imported Objective-C types
/// frequently use `AnyObject` as the type for properties, method parameters,
/// and return values.
///
/// Casting AnyObject Instances to a Known Type
/// ===========================================
///
/// Objects with a concrete type of `AnyObject` maintain a specific dynamic
/// type and can be cast to that type using one of the type-cast operators
/// (`as`, `as?`, or `as!`).
///
/// This example uses the conditional downcast operator (`as?`) to
/// conditionally cast the `s` constant declared above to an instance of
/// Swift's `String` type.
///
/// if let message = s as? String {
/// print("Successful cast to String: \(message)")
/// }
/// // Prints "Successful cast to String: This is a bridged string."
///
/// If you have prior knowledge that an `AnyObject` instance has a particular
/// type, you can use the unconditional downcast operator (`as!`). Performing
/// an invalid cast triggers a runtime error.
///
/// let message = s as! String
/// print("Successful cast to String: \(message)")
/// // Prints "Successful cast to String: This is a bridged string."
///
/// let badCase = v as! String
/// // Runtime error
///
/// Casting is always safe in the context of a `switch` statement.
///
/// let mixedArray: [AnyObject] = [s, v]
/// for object in mixedArray {
/// switch object {
/// case let x as String:
/// print("'\(x)' is a String")
/// default:
/// print("'\(object)' is not a String")
/// }
/// }
/// // Prints "'This is a bridged string.' is a String"
/// // Prints "'100' is not a String"
///
/// Accessing Objective-C Methods and Properties
/// ============================================
///
/// When you use `AnyObject` as a concrete type, you have at your disposal
/// every `@objc` method and property---that is, methods and properties
/// imported from Objective-C or marked with the `@objc` attribute. Because
/// Swift can't guarantee at compile time that these methods and properties
/// are actually available on an `AnyObject` instance's underlying type, these
/// `@objc` symbols are available as implicitly unwrapped optional methods and
/// properties, respectively.
///
/// This example defines an `IntegerRef` type with an `@objc` method named
/// `getIntegerValue()`.
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
///
/// @objc func getIntegerValue() -> Int {
/// return value
/// }
/// }
///
/// func getObject() -> AnyObject {
/// return IntegerRef(100)
/// }
///
/// let obj: AnyObject = getObject()
///
/// In the example, `obj` has a static type of `AnyObject` and a dynamic type
/// of `IntegerRef`. You can use optional chaining to call the `@objc` method
/// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of
/// `obj`, you can call `getIntegerValue()` directly.
///
/// let possibleValue = obj.getIntegerValue?()
/// print(possibleValue)
/// // Prints "Optional(100)"
///
/// let certainValue = obj.getIntegerValue()
/// print(certainValue)
/// // Prints "100"
///
/// If the dynamic type of `obj` doesn't implement a `getIntegerValue()`
/// method, the system returns a runtime error when you initialize
/// `certainValue`.
///
/// Alternatively, if you need to test whether `obj.getIntegerValue()` exists,
/// use optional binding before calling the method.
///
/// if let f = obj.getIntegerValue {
/// print("The value of 'obj' is \(f())")
/// } else {
/// print("'obj' does not have a 'getIntegerValue()' method")
/// }
/// // Prints "The value of 'obj' is 100"
///
/// - SeeAlso: `AnyClass`
@objc
public protocol AnyObject : class {}
#else
/// The protocol to which all classes implicitly conform.
///
/// - SeeAlso: `AnyClass`
public protocol AnyObject : class {}
#endif
// Implementation note: the `AnyObject` protocol *must* not have any method or
// property requirements.
// FIXME: AnyObject should have an alternate version for non-objc without
// the @objc attribute, but AnyObject needs to be not be an address-only
// type to be able to be the target of castToNativeObject and an empty
// non-objc protocol appears not to be. There needs to be another way to make
// this the right kind of object.
/// The protocol to which all class types implicitly conform.
///
/// You can use the `AnyClass` protocol as the concrete type for an instance of
/// any class. When you do, all known `@objc` class methods and properties are
/// available as implicitly unwrapped optional methods and properties,
/// respectively. For example:
///
/// class IntegerRef {
/// @objc class func getDefaultValue() -> Int {
/// return 42
/// }
/// }
///
/// func getDefaultValue(_ c: AnyClass) -> Int? {
/// return c.getDefaultValue?()
/// }
///
/// The `getDefaultValue(_:)` function uses optional chaining to safely call
/// the implicitly unwrapped class method on `c`. Calling the function with
/// different class types shows how the `getDefaultValue()` class method is
/// only conditionally available.
///
/// print(getDefaultValue(IntegerRef.self))
/// // Prints "Optional(42)"
///
/// print(getDefaultValue(NSString.self))
/// // Prints "nil"
///
/// - SeeAlso: `AnyObject`
public typealias AnyClass = AnyObject.Type
/// A type that supports standard bitwise arithmetic operators.
///
/// Types that conform to the `BitwiseOperations` protocol implement operators
/// for bitwise arithmetic. The integer types in the standard library all
/// conform to `BitwiseOperations` by default. When you use bitwise operators
/// with an integer, you perform operations on the raw data bits that store
/// the integer's value.
///
/// In the following examples, the binary representation of any values are
/// shown in a comment to the right, like this:
///
/// let x: UInt8 = 5 // 0b00000101
///
/// Here are the required operators for the `BitwiseOperations` protocol:
///
/// - The bitwise OR operator (`|`) returns a value that has each bit set to
/// `1` where *one or both* of its arguments had that bit set to `1`. This
/// is equivalent to the union of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
///
/// Performing a bitwise OR operation with a value and `allZeros` always
/// returns the same value.
///
/// print(x | .allZeros) // 0b00000101
/// // Prints "5"
///
/// - The bitwise AND operator (`&`) returns a value that has each bit set to
/// `1` where *both* of its arguments had that bit set to `1`. This is
/// equivalent to the intersection of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
///
/// Performing a bitwise AND operation with a value and `allZeros` always
/// returns `allZeros`.
///
/// print(x & .allZeros) // 0b00000000
/// // Prints "0"
///
/// - The bitwise XOR operator (`^`), or exclusive OR operator, returns a value
/// that has each bit set to `1` where *one or the other but not both* of
/// its operators has that bit set to `1`. This is equivalent to the
/// symmetric difference of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
///
/// Performing a bitwise XOR operation with a value and `allZeros` always
/// returns the same value.
///
/// print(x ^ .allZeros) // 0b00000101
/// // Prints "5"
///
/// - The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// where all the bits of its argument are flipped: Bits that are `1` in the
/// argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on `allZeros` returns a value with
/// every bit set to `1`.
///
/// let allOnes = ~UInt8.allZeros // 0b11111111
///
/// The `OptionSet` protocol uses a raw value that conforms to
/// `BitwiseOperations` to provide mathematical set operations like
/// `union(_:)`, `intersection(_:)` and `contains(_:)` with O(1) performance.
///
/// Conforming to the BitwiseOperations Protocol
/// ============================================
///
/// To make your custom type conform to `BitwiseOperations`, add a static
/// `allZeros` property and declare the four required operator functions. Any
/// type that conforms to `BitwiseOperations`, where `x` is an instance of the
/// conforming type, must satisfy the following conditions:
///
/// - `x | Self.allZeros == x`
/// - `x ^ Self.allZeros == x`
/// - `x & Self.allZeros == .allZeros`
/// - `x & ~Self.allZeros == x`
/// - `~x == x ^ ~Self.allZeros`
///
/// - SeeAlso: `OptionSet`
public protocol BitwiseOperations {
/// Returns the intersection of bits set in the two arguments.
///
/// The bitwise AND operator (`&`) returns a value that has each bit set to
/// `1` where *both* of its arguments had that bit set to `1`. This is
/// equivalent to the intersection of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
///
/// Performing a bitwise AND operation with a value and `allZeros` always
/// returns `allZeros`.
///
/// print(x & .allZeros) // 0b00000000
/// // Prints "0"
///
/// - Complexity: O(1).
static func & (lhs: Self, rhs: Self) -> Self
/// Returns the union of bits set in the two arguments.
///
/// The bitwise OR operator (`|`) returns a value that has each bit set to
/// `1` where *one or both* of its arguments had that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
///
/// Performing a bitwise OR operation with a value and `allZeros` always
/// returns the same value.
///
/// print(x | .allZeros) // 0b00000101
/// // Prints "5"
///
/// - Complexity: O(1).
static func | (lhs: Self, rhs: Self) -> Self
/// Returns the bits that are set in exactly one of the two arguments.
///
/// The bitwise XOR operator (`^`), or exclusive OR operator, returns a value
/// that has each bit set to `1` where *one or the other but not both* of
/// its operators has that bit set to `1`. This is equivalent to the
/// symmetric difference of two sets. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
///
/// Performing a bitwise XOR with a value and `allZeros` always returns the
/// same value:
///
/// print(x ^ .allZeros) // 0b00000101
/// // Prints "5"
///
/// - Complexity: O(1).
static func ^ (lhs: Self, rhs: Self) -> Self
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in the
/// argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on `allZeros` returns a value with
/// every bit set to `1`.
///
/// let allOnes = ~UInt8.allZeros // 0b11111111
///
/// - Complexity: O(1).
static prefix func ~ (x: Self) -> Self
/// The empty bitset.
///
/// The `allZeros` static property is the [identity element][] for bitwise OR
/// and XOR operations and the [fixed point][] for bitwise AND operations.
/// For example:
///
/// let x: UInt8 = 5 // 0b00000101
///
/// // Identity
/// x | .allZeros // 0b00000101
/// x ^ .allZeros // 0b00000101
///
/// // Fixed point
/// x & .allZeros // 0b00000000
///
/// [identity element]:http://en.wikipedia.org/wiki/Identity_element
/// [fixed point]:http://en.wikipedia.org/wiki/Fixed_point_(mathematics)
static var allZeros: Self { get }
}
/// Calculates the union of bits sets in the two arguments and stores the result
/// in the first argument.
///
/// - Parameters:
/// - lhs: A value to update with the union of bits set in the two arguments.
/// - rhs: Another value.
public func |= <T : BitwiseOperations>(lhs: inout T, rhs: T) {
lhs = lhs | rhs
}
/// Calculates the intersections of bits sets in the two arguments and stores
/// the result in the first argument.
///
/// - Parameters:
/// - lhs: A value to update with the intersections of bits set in the two
/// arguments.
/// - rhs: Another value.
public func &= <T : BitwiseOperations>(lhs: inout T, rhs: T) {
lhs = lhs & rhs
}
/// Calculates the bits that are set in exactly one of the two arguments and
/// stores the result in the first argument.
///
/// - Parameters:
/// - lhs: A value to update with the bits that are set in exactly one of the
/// two arguments.
/// - rhs: Another value.
public func ^= <T : BitwiseOperations>(lhs: inout T, rhs: T) {
lhs = lhs ^ rhs
}
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
/// Returns a Boolean value indicating whether two arguments match by value
/// equality.
///
/// The pattern-matching operator (`~=`) is used internally in `case`
/// statements for pattern matching. When you match against an `Equatable`
/// value in a `case` statement, this operator is called behind the scenes.
///
/// let weekday = 3
/// let lunch: String
/// switch weekday {
/// case 3:
/// lunch = "Taco Tuesday!"
/// default:
/// lunch = "Pizza again."
/// }
/// // lunch == "Taco Tuesday!"
///
/// In this example, the `case 3` expression uses this pattern-matching
/// operator to test whether `weekday` is equal to the value `3`.
///
/// - Note: In most cases, you should use the equal-to operator (`==`) to test
/// whether two instances are equal. The pattern-matching operator is
/// primarily intended to enable `case` statement pattern matching.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@_transparent
public func ~= <T : Equatable>(a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard precedence groups
//===----------------------------------------------------------------------===//
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
precedencegroup FunctionArrowPrecedence {
associativity: right
higherThan: AssignmentPrecedence
}
precedencegroup TernaryPrecedence {
associativity: right
higherThan: FunctionArrowPrecedence
}
precedencegroup DefaultPrecedence {
higherThan: TernaryPrecedence
}
precedencegroup LogicalDisjunctionPrecedence {
associativity: left
higherThan: TernaryPrecedence
}
precedencegroup LogicalConjunctionPrecedence {
associativity: left
higherThan: LogicalDisjunctionPrecedence
}
precedencegroup ComparisonPrecedence {
higherThan: LogicalConjunctionPrecedence
}
precedencegroup NilCoalescingPrecedence {
associativity: right
higherThan: ComparisonPrecedence
}
precedencegroup CastingPrecedence {
higherThan: NilCoalescingPrecedence
}
precedencegroup RangeFormationPrecedence {
higherThan: CastingPrecedence
}
precedencegroup AdditionPrecedence {
associativity: left
higherThan: RangeFormationPrecedence
}
precedencegroup MultiplicationPrecedence {
associativity: left
higherThan: AdditionPrecedence
}
precedencegroup BitwiseShiftPrecedence {
higherThan: MultiplicationPrecedence
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ++
postfix operator --
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator !
// Standard prefix operators.
prefix operator ++
prefix operator --
prefix operator !
prefix operator ~
prefix operator +
prefix operator -
// Standard infix operators.
// "Exponentiative"
infix operator << : BitwiseShiftPrecedence
infix operator >> : BitwiseShiftPrecedence
// "Multiplicative"
infix operator * : MultiplicationPrecedence
infix operator &* : MultiplicationPrecedence
infix operator / : MultiplicationPrecedence
infix operator % : MultiplicationPrecedence
infix operator & : MultiplicationPrecedence
// "Additive"
infix operator + : AdditionPrecedence
infix operator &+ : AdditionPrecedence
infix operator - : AdditionPrecedence
infix operator &- : AdditionPrecedence
infix operator | : AdditionPrecedence
infix operator ^ : AdditionPrecedence
// FIXME: is this the right precedence level for "..." ?
infix operator ... : RangeFormationPrecedence
infix operator ..< : RangeFormationPrecedence
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as : CastingPrecedence
// "Coalescing"
infix operator ?? : NilCoalescingPrecedence
// "Comparative"
infix operator < : ComparisonPrecedence
infix operator <= : ComparisonPrecedence
infix operator > : ComparisonPrecedence
infix operator >= : ComparisonPrecedence
infix operator == : ComparisonPrecedence
infix operator != : ComparisonPrecedence
infix operator === : ComparisonPrecedence
infix operator !== : ComparisonPrecedence
// FIXME: ~= will be built into the compiler.
infix operator ~= : ComparisonPrecedence
// "Conjunctive"
infix operator && : LogicalConjunctionPrecedence
// "Disjunctive"
infix operator || : LogicalDisjunctionPrecedence
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : : TernaryPrecedence
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator = : AssignmentPrecedence
// Compound
infix operator *= : AssignmentPrecedence
infix operator /= : AssignmentPrecedence
infix operator %= : AssignmentPrecedence
infix operator += : AssignmentPrecedence
infix operator -= : AssignmentPrecedence
infix operator <<= : AssignmentPrecedence
infix operator >>= : AssignmentPrecedence
infix operator &= : AssignmentPrecedence
infix operator ^= : AssignmentPrecedence
infix operator |= : AssignmentPrecedence
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~>
@available(*, unavailable, renamed: "BitwiseOperations")
public typealias BitwiseOperationsType = BitwiseOperations
| apache-2.0 | 15d37af797c1fa60f6dc0150351ddbb0 | 35.445833 | 81 | 0.617126 | 4.517301 | false | false | false | false |
verticon/MecklenburgTrailOfHistory | Trail of History/Common/PointOfInterest.swift | 1 | 10316 | //
// PointOfInterest.swift
// Trail of History
//
// Created by Robert Vaessen on 12/23/16.
// Copyright © 2018 Robert Vaessen. All rights reserved.
//
import UIKit
import Firebase
import CoreLocation
import VerticonsToolbox
enum PoiLoadStatus {
case success
case error(String)
}
final class PointOfInterest : Equatable, Encoding {
// **********************************************************************************************************************
// Public
// **********************************************************************************************************************
static func == (lhs: PointOfInterest, rhs: PointOfInterest) -> Bool { return lhs.name == rhs.name }
typealias ListenerToken = Any
private class Token {
var observer: Firebase.TypeObserver<PointOfInterest>?
init(observer: Firebase.TypeObserver<PointOfInterest>?) { self.observer = observer }
}
private static let poiPath = "PointsOfInterest"
// Points of Interest are obtained via a listener. Listeners will receive the
// currently existing POIs and will be informed of additions, updates, or removals.
// Currently (03/22/18) there are two scenarios:
// 1) The POIs are being obtained from a bundled file. In this case the listener will
// be called for each POI before the addListener method returns and there will be
// no future invocations.
// 2) The POIs are being obtained from a database. In this case the listener will
// called in the future, asynchronously, as the POIs arive from the database.
// If the database is subsequently updated then the listener will be called again
// Each listener receives its own copies of the POIs
static func addListener(_ listener: @escaping Firebase.TypeObserver<PointOfInterest>.TypeListener) -> ListenerToken {
var observer: Firebase.TypeObserver<PointOfInterest>? = nil
if let fileName = tohFileName {
if case .error(let message) = loadFrom(fileName: fileName, listener: listener) {
alertUser(title: "Cannot Load Points of Interest", body: message)
}
}
else {
observer = Firebase.TypeObserver(path: poiPath, with: listener)
}
return Token(observer: observer)
}
static func loadFrom(fileName: String, listener: @escaping Firebase.TypeObserver<PointOfInterest>.TypeListener) -> PoiLoadStatus {
guard let jsonFilePath = Bundle.main.path(forResource: fileName, ofType: "json")
else { return .error("Could not find the bundled file \(fileName).json") }
let jsonFileUrl = URL(fileURLWithPath: jsonFilePath)
do {
let jsonData = try Data(contentsOf: jsonFileUrl)
let jsonObject = try JSONSerialization.jsonObject(with: jsonData)
if let jsonData = jsonObject as? [String : Any],
let pointsOfInterest = jsonData[poiPath] as? [String : Properties] {
for (key, properties) in pointsOfInterest {
if let poi = PointOfInterest(properties) { poi.finish(event: .added, key: key, listener: listener) }
else { print("Invalid POI properties: \(properties)") }
}
}
else {
return .error("The json object does not contain the expected types and/or keys:\n\(jsonObject)")
}
}
catch {
return .error("Cannot read/parse \(fileName): \(error)")
}
return .success
}
static func removeListener(token: ListenerToken) -> Bool {
if let token = token as? Token {
token.observer?.cancel()
token.observer = nil
return true
}
return false
}
var distanceToUser: Int? {
guard let userLocation = UserLocation.instance.currentLocation else { return nil }
return Int(round(self.location.yards(from: userLocation)))
}
var distanceToUserText: String {
guard let distance = distanceToUser else { return "<unknown>" }
return "\(distance) yds"
}
// Return the heading that would take the user to the point of interest.
var poiHeading: Double? {
return UserLocation.instance.currentLocation?.bearing(to: self.location)
}
// Return the positive, clockwise angle (0 -> 359.999) from the user's heading to the poi's heading.
var angleWithUserHeading: Double? {
if let userHeading = UserLocation.instance.currentBearing, let poiHeading = self.poiHeading {
let delta = abs(poiHeading - userHeading)
return userHeading > poiHeading ? 360 - delta : delta
}
return nil
}
// **********************************************************************************************************************
// Internal
// **********************************************************************************************************************
private static let latitudeKey = "latitude"
private static let longitudeKey = "longitude"
private static let descriptionKey = "description"
private static let imageUrlKey = "imageUrl"
private static let movieUrlKey = "movieUrl"
private static let meckncGovUrlKey = "meckncGovUrl"
var name: String
let description: String
let location: CLLocation
let movieUrl: URL?
let meckncGovUrl: URL?
var image: UIImage!
private let imageUrl: URL
public init?(_ properties: Properties?) {
guard
let properties = properties,
let latitude = properties[PointOfInterest.latitudeKey] as? Double,
let longitude = properties[PointOfInterest.longitudeKey] as? Double,
let description = properties[PointOfInterest.descriptionKey] as? String,
let imageUrlString = properties[PointOfInterest.imageUrlKey] as? String,
let imageUrl = URL(string: imageUrlString)
else { return nil }
location = CLLocation(latitude: latitude, longitude: longitude)
self.description = description
self.imageUrl = imageUrl
if let url = properties[PointOfInterest.movieUrlKey] as? String { self.movieUrl = URL(string: url) } else { self.movieUrl = nil }
if let url = properties[PointOfInterest.meckncGovUrlKey] as? String { self.meckncGovUrl = URL(string: url) } else { self.meckncGovUrl = nil }
self.name = "<unknown>" // The name is provided by the record's key, see the finish() method.
}
func finish(event: Firebase.TypeObserver<PointOfInterest>.Event, key: Firebase.TypeObserver<PointOfInterest>.Key, listener: @escaping Firebase.TypeObserver<PointOfInterest>.TypeListener) {
name = key
let imageUrlKey = "url:" + name
let imageDataKey = "image:" + name
enum ImageRetrievalResult {
case success(Data)
case failure(String)
}
func finish(result: ImageRetrievalResult) {
var image: UIImage!
switch result {
case .success(let imageData):
image = UIImage(data: imageData)
if image != nil {
UserDefaults.standard.set(imageUrl, forKey: imageUrlKey)
UserDefaults.standard.set(imageData, forKey: imageDataKey)
}
else {
image = UIImage.createFailureIndication(ofSize: CGSize(width: 1920, height: 1080), withText: "The image data is corrupt")
}
case .failure(let errorText):
image = UIImage.createFailureIndication(ofSize: CGSize(width: 1920, height: 1080), withText: errorText)
}
self.image = image
DispatchQueue.main.async { listener(event, key, self) }
}
DispatchQueue.global().async {
// If the image URL has not changed then use the locally stored image. Else download the image from the remote database
if let prevImageUrl = UserDefaults.standard.url(forKey: imageUrlKey), prevImageUrl == self.imageUrl {
guard let imageData = UserDefaults.standard.data(forKey: imageDataKey) else {
fatalError("User defaults has an image url but no image data???")
}
finish(result: ImageRetrievalResult.success(imageData))
}
else {
let session = URLSession(configuration: .default)
let imageDownloadTask = session.dataTask(with: self.imageUrl) { (data, response, error) in
if let error = error {
finish(result: ImageRetrievalResult.failure("URLSession data task error: \(error)"))
}
else {
if let response = response as? HTTPURLResponse {
if response.statusCode == 200 {
if let imageData = data {
finish(result: ImageRetrievalResult.success(imageData))
}
else {
finish(result: ImageRetrievalResult.failure("Image data is nil"))
}
}
else {
finish(result: ImageRetrievalResult.failure("HTTP response error: \(response.statusCode)"))
}
}
else {
finish(result: ImageRetrievalResult.failure("Response type is \(type(of: response)); expected HTTPURLResponse"))
}
}
}
imageDownloadTask.resume()
}
}
}
public func encode() -> Properties {
fatalError("Encode is not implememnted") // We don't need to encode points of interest; the app does not update the database.
}
}
| mit | 7a69e63e46ddb8eee6843bc67d44bd17 | 42.158996 | 192 | 0.560349 | 5.513095 | false | false | false | false |
C453/Easy-Photo-Compressor | Easy Photo Compressor/MainView.swift | 1 | 3609 | //
// MainView.swift
// Easy Photo Compressor
//
// Created by Case Wright on 9/19/15.
// Copyright © 2015 C453. All rights reserved.
//
import Cocoa
class MainView: NSView {
let fileTypes = ["jpg", "jpeg", "bmp", "png", "gif"]
var fileTypeIsOk = false
var droppedFilePath: String?
var directoryPath: String?
var viewController:ViewController!
var count:Int!
override func drawRect(dirtyRect: NSRect) {
window?.alphaValue = 0.8
window?.backgroundColor = NSColor.blackColor()
viewController = window?.contentViewController as! ViewController
super.drawRect(dirtyRect)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
registerForDraggedTypes([NSFilenamesPboardType, NSURLPboardType, NSPasteboardTypeTIFF])
}
override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation {
if checkExtension(sender) {
self.fileTypeIsOk = true
viewController!.StatusLabel.stringValue = "Drop File(s)"
return .Copy
} else {
self.fileTypeIsOk = false
return .None
}
}
override func draggingExited(sender: NSDraggingInfo?) {
if checkExtension(sender!) {
//Set label text back to default if drag exited
viewController!.StatusLabel.stringValue = "Drag Photos on to Window to Compress"
}
}
override func draggingUpdated(sender: NSDraggingInfo) -> NSDragOperation {
if self.fileTypeIsOk {
return .Copy
} else {
return .None
}
}
override func performDragOperation(sender: NSDraggingInfo) -> Bool {
if let board = sender.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray {
createDirectory()
viewController!.StatusLabel.stringValue = "Compressing..."
count = board.count
for file in board {
self.droppedFilePath = (file as! String)
let compressedImageData = ImageCompressor.compressImage(droppedFilePath!, level: viewController.CompressionLevelSlider.floatValue)
let path = "\(self.directoryPath!)/\(file.lastPathComponent!)"
compressedImageData.writeToFile(path, atomically: true)
}
//Compression Complete
viewController!.StatusLabel.stringValue = "Compressed \(count) Image(s)"
//Show folder
NSWorkspace.sharedWorkspace().activateFileViewerSelectingURLs([NSURL(fileURLWithPath: directoryPath!)])
}
return true
}
func checkExtension(drag: NSDraggingInfo) -> Bool {
if let board = drag.draggingPasteboard().propertyListForType("NSFilenamesPboardType") as? NSArray {
let url = NSURL(fileURLWithPath: (board[0] as! String))
let suffix = url.pathExtension!
for ext in self.fileTypes {
if ext.lowercaseString == suffix {
return true
}
}
}
return false
}
func createDirectory() {
let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .NoStyle)
self.directoryPath = ("~/Desktop/\(timestamp)" as NSString).stringByExpandingTildeInPath
try? NSFileManager.defaultManager().createDirectoryAtPath(directoryPath!, withIntermediateDirectories: true, attributes: nil)
}
} | mit | 9bba0182c8e760e299b93f5aef969982 | 35.454545 | 146 | 0.615022 | 5.51682 | false | false | false | false |
lorentey/swift | benchmark/single-source/BitCount.swift | 18 | 1264 | //===--- BitCount.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift bit count.
// and mask operator.
// rdar://problem/22151678
import TestsUtils
public let BitCount = BenchmarkInfo(
name: "BitCount",
runFunction: run_BitCount,
tags: [.validation, .algorithm])
func countBitSet(_ num: Int) -> Int {
let bits = MemoryLayout<Int>.size * 8
var cnt: Int = 0
var mask: Int = 1
for _ in 0...bits {
if num & mask != 0 {
cnt += 1
}
mask <<= 1
}
return cnt
}
@inline(never)
public func run_BitCount(_ N: Int) {
var sum = 0
for _ in 1...1000*N {
// Check some results.
sum = sum &+ countBitSet(getInt(1))
&+ countBitSet(getInt(2))
&+ countBitSet(getInt(2457))
}
CheckResults(sum == 8 * 1000 * N)
}
| apache-2.0 | c7fcb76e66579a931fc120b0b723ee1e | 26.478261 | 80 | 0.56962 | 4.103896 | false | false | false | false |
hstdt/GodEye | GodEye/Classes/Controller/TabController/ConsoleController/ConsoleController+Eye.swift | 1 | 3656 | //
// ConsoleViewController+Eye.swift
// Pods
//
// Created by zixun on 16/12/28.
//
//
import Foundation
import ASLEye
import CrashEye
import NetworkEye
import ANREye
import Log4G
import LeakEye
extension ConsoleController {
/// open god's eyes
func openEyes() {
EyesManager.shared.delegate = self
let defaultSwitch = GodEyeController.shared.configuration!.defaultSwitch
if defaultSwitch.asl { EyesManager.shared.openASLEye() }
if defaultSwitch.log4g { EyesManager.shared.openLog4GEye() }
if defaultSwitch.crash { EyesManager.shared.openCrashEye() }
if defaultSwitch.network { EyesManager.shared.openNetworkEye() }
if defaultSwitch.anr { EyesManager.shared.openANREye() }
if defaultSwitch.leak { EyesManager.shared.openLeakEye() }
}
func addRecord(model:RecordORMProtocol) {
if let pc = self.printViewController {
pc.addRecord(model: model)
}else {
let type = type(of:model).type
type.addUnread()
self.reloadRow(of: type)
}
}
}
extension ConsoleController: Log4GDelegate {
fileprivate func openLog4GEye() {
Log4G.add(delegate: self)
}
func log4gDidRecord(with model:LogModel) {
let recordModel = LogRecordModel(model: model)
recordModel.insert(complete: { [unowned self] (success:Bool) in
self.addRecord(model: recordModel)
})
}
}
//MARK: - NetworkEye
extension ConsoleController: NetworkEyeDelegate {
/// god's network eye callback
func networkEyeDidCatch(with request:URLRequest?,response:URLResponse?,data:Data?) {
Store.shared.addNetworkByte(response?.expectedContentLength ?? 0)
let model = NetworkRecordModel(request: request, response: response as? HTTPURLResponse, data: data)
model.insert(complete: { [unowned self] (success:Bool) in
self.addRecord(model: model)
})
}
}
//MARK: - CrashEye
extension ConsoleController: CrashEyeDelegate {
/// god's crash eye callback
func crashEyeDidCatchCrash(with model:CrashModel) {
let model = CrashRecordModel(model: model)
model.insertSync(complete: { [unowned self] (success:Bool) in
self.addRecord(model: model)
})
}
}
//MARK: - ASLEye
extension ConsoleController: ASLEyeDelegate {
/// god's asl eye callback
func aslEye(aslEye:ASLEye,catchLogs logs:[String]) {
for log in logs {
let model = LogRecordModel(type: .asl, message: log)
model.insert(complete: { [unowned self] (success:Bool) in
self.addRecord(model: model)
})
}
}
}
extension ConsoleController: LeakEyeDelegate {
func leakEye(leakEye:LeakEye,didCatchLeak object:NSObject) {
let model = LeakRecordModel(obj: object)
model.insert { [unowned self] (success:Bool) in
self.addRecord(model: model)
}
}
}
//MARK: - ANREye
extension ConsoleController: ANREyeDelegate {
/// god's anr eye callback
func anrEye(anrEye:ANREye,
catchWithThreshold threshold:Double,
mainThreadBacktrace:String?,
allThreadBacktrace:String?) {
let model = ANRRecordModel(threshold: threshold,
mainThreadBacktrace: mainThreadBacktrace,
allThreadBacktrace: allThreadBacktrace)
model.insert(complete: { [unowned self] (success:Bool) in
self.addRecord(model: model)
})
}
}
| mit | 0fb04616ca048df2e7b2094df1a7a2a6 | 28.723577 | 108 | 0.627735 | 4.326627 | false | false | false | false |
icecrystal23/ios-charts | ChartsDemo-iOS/Swift/Demos/ColoredLineChartViewController.swift | 2 | 2552 | //
// ColoredLineChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-04.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class ColoredLineChartViewController: DemoBaseViewController {
@IBOutlet var chartViews: [LineChartView]!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Colored Line Chart"
let colors = [UIColor(red: 137/255, green: 230/255, blue: 81/255, alpha: 1),
UIColor(red: 240/255, green: 240/255, blue: 30/255, alpha: 1),
UIColor(red: 89/255, green: 199/255, blue: 250/255, alpha: 1),
UIColor(red: 250/255, green: 104/255, blue: 104/255, alpha: 1)]
for (i, chartView) in chartViews.enumerated() {
let data = dataWithCount(36, range: 100)
data.setValueFont(UIFont(name: "HelveticaNeue", size: 7)!)
setupChart(chartView, data: data, color: colors[i % colors.count])
}
}
func setupChart(_ chart: LineChartView, data: LineChartData, color: UIColor) {
(data.getDataSetByIndex(0) as! LineChartDataSet).circleHoleColor = color
chart.delegate = self
chart.backgroundColor = color
chart.chartDescription?.enabled = false
chart.dragEnabled = true
chart.setScaleEnabled(true)
chart.pinchZoomEnabled = false
chart.setViewPortOffsets(left: 10, top: 0, right: 10, bottom: 0)
chart.legend.enabled = false
chart.leftAxis.enabled = false
chart.leftAxis.spaceTop = 0.4
chart.leftAxis.spaceBottom = 0.4
chart.rightAxis.enabled = false
chart.xAxis.enabled = false
chart.data = data
chart.animate(xAxisDuration: 2.5)
}
func dataWithCount(_ count: Int, range: UInt32) -> LineChartData {
let yVals = (0..<count).map { i -> ChartDataEntry in
let val = Double(arc4random_uniform(range)) + 3
return ChartDataEntry(x: Double(i), y: val)
}
let set1 = LineChartDataSet(values: yVals, label: "DataSet 1")
set1.lineWidth = 1.75
set1.circleRadius = 5.0
set1.circleHoleRadius = 2.5
set1.setColor(.white)
set1.setCircleColor(.white)
set1.highlightColor = .white
set1.drawValuesEnabled = false
return LineChartData(dataSet: set1)
}
}
| apache-2.0 | 4edcfc4b351443eada555b861a8304a4 | 32.12987 | 85 | 0.586829 | 4.375643 | false | false | false | false |
jum/Charts | Source/Charts/Charts/PieChartView.swift | 3 | 16721 | //
// PieChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
/// View that represents a pie chart. Draws cake like slices.
open class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
private var _circleBox = CGRect()
/// flag indicating if entry labels should be drawn or not
private var _drawEntryLabelsEnabled = true
/// array that holds the width of each pie-slice in degrees
private var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
private var _absoluteAngles = [CGFloat]()
/// if true, the hole inside the chart will be drawn
private var _drawHoleEnabled = true
private var _holeColor: NSUIColor? = NSUIColor.white
/// Sets the color the entry labels are drawn with.
private var _entryLabelColor: NSUIColor? = NSUIColor.white
/// Sets the font the entry labels are drawn with.
private var _entryLabelFont: NSUIFont? = NSUIFont(name: "HelveticaNeue", size: 13.0)
/// if true, the hole will see-through to the inner tips of the slices
private var _drawSlicesUnderHoleEnabled = false
/// if true, the values inside the piechart are drawn as percent values
private var _usePercentValuesEnabled = false
/// variable for the text that is drawn in the center of the pie-chart
private var _centerAttributedText: NSAttributedString?
/// the offset on the x- and y-axis the center text has in dp.
private var _centerTextOffset: CGPoint = CGPoint()
/// indicates the size of the hole in the center of the piechart
///
/// **default**: `0.5`
private var _holeRadiusPercent = CGFloat(0.5)
private var _transparentCircleColor: NSUIColor? = NSUIColor(white: 1.0, alpha: 105.0/255.0)
/// the radius of the transparent circle next to the chart-hole in the center
private var _transparentCircleRadiusPercent = CGFloat(0.55)
/// if enabled, centertext is drawn
private var _drawCenterTextEnabled = true
private var _centerTextRadiusPercent: CGFloat = 1.0
/// maximum angle for this pie
private var _maxAngle: CGFloat = 360.0
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
_xAxis = nil
self.highlighter = PieHighlighter(chart: self)
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
if _data === nil
{
return
}
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext, let renderer = renderer else
{
return
}
renderer.drawData(context: context)
if (valuesToHighlight())
{
renderer.drawHighlighted(context: context, indices: _indicesToHighlight)
}
renderer.drawExtras(context: context)
renderer.drawValues(context: context)
legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if _data === nil
{
return
}
let radius = diameter / 2.0
let c = self.centerOffsets
let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = (c.x - radius) + shift
_circleBox.origin.y = (c.y - radius) + shift
_circleBox.size.width = diameter - shift * 2.0
_circleBox.size.height = diameter - shift * 2.0
}
internal override func calcMinMax()
{
calcAngles()
}
open override func getMarkerPosition(highlight: Highlight) -> CGPoint
{
let center = self.centerCircleBox
var r = self.radius
var off = r / 10.0 * 3.6
if self.isDrawHoleEnabled
{
off = (r - (r * self.holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let entryIndex = Int(highlight.x)
// offset needed to center the drawn text in the slice
let offset = drawAngles[entryIndex] / 2.0
// calculate the text position
let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[entryIndex] - offset) * CGFloat(_animator.phaseY)).DEG2RAD) + center.x)
let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[entryIndex] - offset) * CGFloat(_animator.phaseY)).DEG2RAD) + center.y)
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
private func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
guard let data = _data else { return }
let entryCount = data.entryCount
_drawAngles.reserveCapacity(entryCount)
_absoluteAngles.reserveCapacity(entryCount)
let yValueSum = (_data as! PieChartData).yValueSum
var cnt = 0
for set in data.dataSets
{
for j in 0 ..< set.entryCount
{
guard let e = set.entryForIndex(j) else { continue }
_drawAngles.append(calcAngle(value: abs(e.y), yValueSum: yValueSum))
if cnt == 0
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt += 1
}
}
}
/// Checks if the given index is set to be highlighted.
@objc open func needsHighlight(index: Int) -> Bool
{
return _indicesToHighlight.contains { Int($0.x) == index }
}
/// calculates the needed angle for a given value
private func calcAngle(_ value: Double) -> CGFloat
{
return calcAngle(value: value, yValueSum: (_data as! PieChartData).yValueSum)
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double, yValueSum: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(yValueSum) * _maxAngle
}
/// This will throw an exception, PieChart has no XAxis object.
open override var xAxis: XAxis
{
fatalError("PieChart has no XAxis")
}
open override func indexForAngle(_ angle: CGFloat) -> Int
{
// TODO: Return nil instead of -1
// take the current angle of the chart into consideration
let a = (angle - self.rotationAngle).normalizedAngle
return _absoluteAngles.firstIndex { $0 > a } ?? -1
}
/// - Returns: The index of the DataSet this x-index belongs to.
@objc open func dataSetIndexForIndex(_ xValue: Double) -> Int
{
// TODO: Return nil instead of -1
return _data?.dataSets.firstIndex {
$0.entryForXValue(xValue, closestToY: .nan) != nil
} ?? -1
}
/// - Returns: An integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
@objc open var drawAngles: [CGFloat]
{
return _drawAngles
}
/// - Returns: The absolute angles of the different chart slices (where the
/// slices end)
@objc open var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// The color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// - Note: Use holeTransparent with holeColor = nil to make the hole transparent.*
@objc open var holeColor: NSUIColor?
{
get
{
return _holeColor
}
set
{
_holeColor = newValue
setNeedsDisplay()
}
}
/// if true, the hole will see-through to the inner tips of the slices
///
/// **default**: `false`
@objc open var drawSlicesUnderHoleEnabled: Bool
{
get
{
return _drawSlicesUnderHoleEnabled
}
set
{
_drawSlicesUnderHoleEnabled = newValue
setNeedsDisplay()
}
}
/// `true` if the inner tips of the slices are visible behind the hole, `false` if not.
@objc open var isDrawSlicesUnderHoleEnabled: Bool
{
return drawSlicesUnderHoleEnabled
}
/// `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot
@objc open var drawHoleEnabled: Bool
{
get
{
return _drawHoleEnabled
}
set
{
_drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot
@objc open var isDrawHoleEnabled: Bool
{
get
{
return drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart
@objc open var centerText: String?
{
get
{
return self.centerAttributedText?.string
}
set
{
var attrString: NSMutableAttributedString?
if newValue == nil
{
attrString = nil
}
else
{
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
attrString = NSMutableAttributedString(string: newValue!)
attrString?.setAttributes([
.foregroundColor: NSUIColor.black,
.font: NSUIFont.systemFont(ofSize: 12.0),
.paragraphStyle: paragraphStyle
], range: NSMakeRange(0, attrString!.length))
}
self.centerAttributedText = attrString
}
}
/// the text that is displayed in the center of the pie-chart
@objc open var centerAttributedText: NSAttributedString?
{
get
{
return _centerAttributedText
}
set
{
_centerAttributedText = newValue
setNeedsDisplay()
}
}
/// Sets the offset the center text should have from it's original position in dp. Default x = 0, y = 0
@objc open var centerTextOffset: CGPoint
{
get
{
return _centerTextOffset
}
set
{
_centerTextOffset = newValue
setNeedsDisplay()
}
}
/// `true` if drawing the center text is enabled
@objc open var drawCenterTextEnabled: Bool
{
get
{
return _drawCenterTextEnabled
}
set
{
_drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// `true` if drawing the center text is enabled
@objc open var isDrawCenterTextEnabled: Bool
{
get
{
return drawCenterTextEnabled
}
}
internal override var requiredLegendOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
open override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// The circlebox, the boundingbox of the pie-chart slices
@objc open var circleBox: CGRect
{
return _circleBox
}
/// The center of the circlebox
@objc open var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
@objc open var holeRadiusPercent: CGFloat
{
get
{
return _holeRadiusPercent
}
set
{
_holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The color that the transparent-circle should have.
///
/// **default**: `nil`
@objc open var transparentCircleColor: NSUIColor?
{
get
{
return _transparentCircleColor
}
set
{
_transparentCircleColor = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
@objc open var transparentCircleRadiusPercent: CGFloat
{
get
{
return _transparentCircleRadiusPercent
}
set
{
_transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The color the entry labels are drawn with.
@objc open var entryLabelColor: NSUIColor?
{
get { return _entryLabelColor }
set
{
_entryLabelColor = newValue
setNeedsDisplay()
}
}
/// The font the entry labels are drawn with.
@objc open var entryLabelFont: NSUIFont?
{
get { return _entryLabelFont }
set
{
_entryLabelFont = newValue
setNeedsDisplay()
}
}
/// Set this to true to draw the enrty labels into the pie slices
@objc open var drawEntryLabelsEnabled: Bool
{
get
{
return _drawEntryLabelsEnabled
}
set
{
_drawEntryLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// `true` if drawing entry labels is enabled, `false` ifnot
@objc open var isDrawEntryLabelsEnabled: Bool
{
get
{
return drawEntryLabelsEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
@objc open var usePercentValuesEnabled: Bool
{
get
{
return _usePercentValuesEnabled
}
set
{
_usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// `true` if drawing x-values is enabled, `false` ifnot
@objc open var isUsePercentValuesEnabled: Bool
{
get
{
return usePercentValuesEnabled
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
@objc open var centerTextRadiusPercent: CGFloat
{
get
{
return _centerTextRadiusPercent
}
set
{
_centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The max angle that is used for calculating the pie-circle.
/// 360 means it's a full pie-chart, 180 results in a half-pie-chart.
/// **default**: 360.0
@objc open var maxAngle: CGFloat
{
get
{
return _maxAngle
}
set
{
_maxAngle = newValue
if _maxAngle > 360.0
{
_maxAngle = 360.0
}
if _maxAngle < 90.0
{
_maxAngle = 90.0
}
}
}
}
| apache-2.0 | 268e826c45e1063ad98c39e19f7d7b7c | 26.913189 | 189 | 0.563098 | 5.128834 | false | false | false | false |
krin-san/SwiftCalc | SwiftCalc/Model/Constants.swift | 1 | 410 | //
// Constants.swift
// SwiftCalc
//
// Created by Krin-San on 30.10.14.
//
import Foundation
// MARK: - Core constants
let InfiniteOperands = Int.max
let kCoreValuesChangedNotification = "CoreValuesChanged"
let kCoreValueExpression = "equation"
let kCoreValueResult = "result"
let kCoreValueError = "error"
// MARK: - VC constants
let calculateKey = "="
let buttonReuseID = "buttonReuseID"
| gpl-3.0 | 1459c5c11a4c7476004d64f73a72a421 | 17.636364 | 56 | 0.714634 | 3.38843 | false | false | false | false |
LYM-mg/DemoTest | 其他功能/SwiftyDemo/SwiftyDemo/BiometricService.swift | 1 | 5781 | //
// BiometricService.swift
// ITService
//
// Created by jiali on 2019/4/11.
// Copyright © 2019 Dan Fu. All rights reserved.
//
import Foundation
import LocalAuthentication
enum BiometricServiceError{
case notAvailable
case touchIDLockout
case biometryLockout
case passcodeNotSet
case biometryNotEnrolled
case userFallback
case systemCancel
case authenticationFailed
@available(iOS 11.0, *)
case faceID
@available(iOS 11.0, *)
case touchID
}
open class BiometricService {
let context = LAContext()
var authError : NSError? = nil
var localizedReason : String = ""
static func share() -> BiometricService{
let shareInstance = BiometricService.init()
shareInstance.loadAuthentication()
return shareInstance
}
fileprivate func loadAuthentication() {
context.localizedCancelTitle = "取消"
}
fileprivate func canSupportBiometric() -> Bool {
//首先判断版本
if NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_8_0 {
return false
}
return context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &authError)
}
func usesBiometric(success: @escaping(()->Void),failure:@escaping (_ error: BiometricServiceError?)-> Void) {
if canSupportBiometric() {
if #available(iOS 11.0, *) {
if context.biometryType == .faceID{
localizedReason = "请验证面容ID"
}else {
localizedReason = "请按Home键验证指纹"
}
} else {
localizedReason = "请按Home键验证指纹"
}
self.biometricPolicy(successed: success, failure: failure)
}else{
//提示不可用
dealErrorCode(authError, failure: failure)
}
}
fileprivate func biometricPolicy(successed: @escaping(()->Void),failure:@escaping (_ error: BiometricServiceError?)-> Void) {
context.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: localizedReason) {[weak self] (success : Bool?, error : Error?) in
// guard let `self` = self else{ return }
if success == true {
//成功
DispatchQueue.main.async {
// 进行支付
successed()
}
}else{
if let error = error as NSError?{
self?.dealErrorCode(error, failure: failure)
}
}
}
}
fileprivate func dealErrorCode(_ error: NSError?,failure:@escaping (_ error: BiometricServiceError?)-> Void){
guard let error = error else {
// 设备不支持
failure(BiometricServiceError.notAvailable)
return;
}
switch error.code {
case LAError.touchIDNotAvailable.rawValue:
failure(BiometricServiceError.notAvailable)
case LAError.touchIDLockout.rawValue:
unLockOutTouchID()
failure(BiometricServiceError.touchIDLockout)
break
case LAError.authenticationFailed.rawValue:
DispatchQueue.main.async {
//认证失败,请输入支付密码支付
failure(BiometricServiceError.authenticationFailed)
}
break
case LAError.passcodeNotSet.rawValue:
guideUserSettingTouchID()
failure(BiometricServiceError.passcodeNotSet)
break
case LAError.systemCancel.rawValue:
print("取消授权,如其他应用切入,用户自主")
failure(BiometricServiceError.systemCancel)
break
case LAError.userFallback.rawValue:
failure(BiometricServiceError.userFallback)
DispatchQueue.main.async {
//用户选择其他验证方式
}
break
default:
if #available(iOS 11.0, *) {
if context.biometryType == LABiometryType.faceID{
failure(BiometricServiceError.faceID)
//设备不支持面容 ID
}else if context.biometryType == LABiometryType.touchID{
//设备不支持Touch ID
failure(BiometricServiceError.touchID)
}else if error.code == LAError.biometryNotEnrolled.rawValue {
// iPhone没录入指纹
guideUserSettingTouchID()
failure(BiometricServiceError.biometryNotEnrolled)
}else if error.code == LAError.biometryLockout.rawValue {
//验证手机锁屏密码,解锁指纹
failure(BiometricServiceError.biometryLockout)
}else {
//设备不支持Touch ID
}
}
break
}
}
func guideUserSettingTouchID() {
DispatchQueue.main.async {
//引导用户跳转到设置去开启
}
}
func unLockOutTouchID(){
DispatchQueue.main.async {
self.context.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: "验证手机锁屏密码解锁指纹", reply: { [weak self] (success : Bool?, error : Error?) in
if success == true {
self?.loadAuthentication()
}
})
}
}
}
| mit | a30b01be2cda5532317ce817d4ff42f8 | 33.553459 | 166 | 0.547142 | 5.516064 | false | false | false | false |
devxoul/Bagel | Bagel/AppDelegate.swift | 1 | 6483 | //
// Copyright (c) 2015 Suyeol Jeon (http://xoul.kr)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
import Cocoa
public class AppDelegate: NSObject {
public var window: NSWindow!
public var openButton: NSButton!
public var indicator: NSProgressIndicator!
public var label: NSTextField!
public func openDocument(sender: AnyObject?) {
let openPanel = NSOpenPanel()
openPanel.title = "Choose a movie file"
openPanel.showsResizeIndicator = true
openPanel.showsHiddenFiles = true
openPanel.canChooseDirectories = false
openPanel.canCreateDirectories = false
openPanel.allowsMultipleSelection = false
openPanel.allowedFileTypes = ["mov", "avi", "mp4", "flv"]
openPanel.beginSheetModalForWindow(self.window) { result in
guard result == NSModalResponseOK else { return }
if let path = openPanel.URLs.first?.path?.stringByResolvingSymlinksInPath {
self.openButton.hidden = true
self.indicator.startAnimation(nil)
self.displayMessage("Converting...", color: NSColor.grayColor())
convert(path) { gif in
self.openButton.hidden = false
self.indicator.stopAnimation(nil)
if gif != nil {
self.displayMessage("✓", color: NSColor(red: 0, green: 0.6, blue: 0, alpha: 1))
} else {
self.displayMessage("✗", color: NSColor(red: 0.6, green: 0, blue: 0, alpha: 1))
}
}
}
}
}
private func displayMessage(string: String, color: NSColor) {
self.label.stringValue = string
self.label.textColor = color
self.label.sizeToFit()
self.label.frame.origin.x = self.openButton.frame.midX - self.label.frame.width / 2
self.label.frame.origin.y = self.openButton.frame.minY - self.label.frame.height - 5
}
}
// MARK: - NSApplicationDelegate
extension AppDelegate: NSApplicationDelegate {
public func applicationDidFinishLaunching(aNotification: NSNotification) {
let contentRect = NSRect(x: 0, y: 0, width: 300, height: 200)
let styleMask = (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask |
NSTexturedBackgroundWindowMask)
self.window = NSWindow(contentRect: contentRect, styleMask: styleMask, backing: .Buffered, `defer`: false)
self.window.hasShadow = true
self.window.opaque = false
self.window.movableByWindowBackground = true
self.window.backgroundColor = NSColor.whiteColor()
self.window.delegate = self
self.window.center()
self.window.makeKeyAndOrderFront(nil)
self.openButton = NSButton(frame: NSRect.zeroRect)
self.openButton.title = "Open..."
self.openButton.bezelStyle = .RegularSquareBezelStyle
self.openButton.setButtonType(.MomentaryLightButton)
self.openButton.sizeToFit()
self.openButton.frame.origin.x = (self.window.frame.width - self.openButton.frame.width) / 2
self.openButton.frame.origin.y = (self.window.frame.height - self.openButton.frame.height) / 2
self.openButton.target = self
self.openButton.action = "openDocument:"
self.indicator = NSProgressIndicator()
self.indicator.style = .SpinningStyle
self.indicator.controlSize = .SmallControlSize
self.indicator.displayedWhenStopped = false
self.indicator.sizeToFit()
self.indicator.frame.origin.x = (self.window.frame.width - self.indicator.frame.width) / 2
self.indicator.frame.origin.y = (self.window.frame.height - self.indicator.frame.height) / 2
self.label = NSTextField()
self.label.alignment = .Center
self.label.selectable = false
self.label.editable = false
self.label.bezeled = false
self.displayMessage("Select a movie file.", color: NSColor.grayColor())
self.window.contentView.addSubview(self.openButton)
self.window.contentView.addSubview(self.indicator)
self.window.contentView.addSubview(self.label)
let mainMenu = NSMenu()
// Bagel
let bagelMenu = NSMenuItem()
bagelMenu.submenu = NSMenu()
bagelMenu.submenu!.addItemWithTitle("Hide Bagel", action: "hide:", keyEquivalent: "h")
bagelMenu.submenu!.addItemWithTitle("Hide Others", action: "hideOtherApplications:", keyEquivalent: "h")?
.keyEquivalentModifierMask =
Int(NSEventModifierFlags.CommandKeyMask.rawValue | NSEventModifierFlags.AlternateKeyMask.rawValue)
bagelMenu.submenu!.addItem(NSMenuItem.separatorItem())
bagelMenu.submenu!.addItemWithTitle("Quit Bagel", action: "terminate:", keyEquivalent: "q")
mainMenu.addItem(bagelMenu)
// File
let fileMenu = NSMenuItem()
fileMenu.submenu = NSMenu(title: "File")
fileMenu.submenu!.addItemWithTitle("Close Window", action: "terminate:", keyEquivalent: "w")
fileMenu.submenu!.addItem(NSMenuItem.separatorItem())
fileMenu.submenu!.addItemWithTitle("Open", action: "openDocument:", keyEquivalent: "o")
mainMenu.addItem(fileMenu)
// Help
let helpMenu = NSMenuItem()
helpMenu.submenu = NSMenu(title: "Help")
mainMenu.addItem(helpMenu)
NSApp.mainMenu = mainMenu
}
public func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
// MARK: - NSWindowDelegate
extension AppDelegate: NSWindowDelegate {
public func windowWillClose(notification: NSNotification) {
NSApp.terminate(nil)
}
}
| gpl-2.0 | 8e56965e710b60e81de8cec561419a28 | 39.49375 | 114 | 0.663374 | 4.725748 | false | false | false | false |
jay18001/brickkit-ios | Example/Source/Examples/Images/ImagesInCollectionBrickHorizontalViewController.swift | 1 | 1956 | //
// ImagesInCollectionBrickHorizontalViewController.swift
// BrickKit-Example
//
// Created by Ruben Cagnie on 10/19/16.
// Copyright © 2016 Wayfair LLC. All rights reserved.
//
import UIKit
import BrickKit
class ImagesInCollectionBrickHorizontalViewController: BrickViewController {
override class var brickTitle: String {
return "Horizontal Images in CollectionBrick"
}
override class var subTitle: String {
return "Shows how to use images in a CollectionBrick"
}
let numberOfImages = 9
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .brickBackground
registerBrickClass(CollectionBrick.self)
let collectionSection = BrickSection(backgroundColor: .brickGray1, bricks: [
ImageBrick(BrickIdentifiers.repeatLabel, dataSource: self),
], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5))
collectionSection.repeatCountDataSource = self
let section = BrickSection(bricks: [
CollectionBrick(scrollDirection: .horizontal, dataSource: CollectionBrickCellModel(section: collectionSection), brickTypes: [ImageBrick.self])
])
self.setSection(section)
}
}
extension ImagesInCollectionBrickHorizontalViewController: BrickRepeatCountDataSource {
func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int {
if identifier == BrickIdentifiers.repeatLabel {
return numberOfImages
} else {
return 1
}
}
}
extension ImagesInCollectionBrickHorizontalViewController: ImageBrickDataSource {
func imageForImageBrickCell(cell: ImageBrickCell) -> UIImage? {
return UIImage(named: "image\(cell.index)")
}
func contentModeForImageBrickCell(imageBrickCell: ImageBrickCell) -> UIViewContentMode {
return .scaleAspectFill
}
}
| apache-2.0 | 44d459cdc6bdba669db0bcc1bf0dc1ea | 29.546875 | 154 | 0.705371 | 5.255376 | false | false | false | false |
ello/ello-ios | Specs/Controllers/Editorials/EditorialsViewControllerSpec.swift | 1 | 6389 | ////
/// EditorialsViewControllerSpec.swift
//
@testable import Ello
import Quick
import Nimble
class EditorialsViewControllerSpec: QuickSpec {
override func spec() {
describe("EditorialsViewController") {
var subject: EditorialsViewController!
beforeEach {
subject = EditorialsViewController(usage: .loggedIn)
}
let setupEditorialCell: (Editorial) -> EditorialCell = { editorial in
let item = StreamCellItem(jsonable: editorial, type: .editorial(editorial.kind))
subject.streamViewController.appendStreamCellItems([item])
return subject.streamViewController.collectionView.cellForItem(
at: IndexPath(row: 0, section: 0)
) as! EditorialCell
}
describe("opening EditorialCells") {
it("can open internal links") {
let editorial = Editorial.stub([
"kind": "internal",
"url": "https://ello.co",
])
var posted = false
let observer = NotificationObserver(notification: InternalWebNotification) {
_ in
posted = true
}
let cell = setupEditorialCell(editorial)
subject.editorialTapped(cellContent: cell.editorialContentView!)
observer.removeObserver()
expect(posted) == true
}
it("can open external links") {
let editorial = Editorial.stub([
"kind": "external",
"url": "https://test.com",
])
var posted = false
let observer = NotificationObserver(notification: ExternalWebNotification) {
_ in
posted = true
}
let cell = setupEditorialCell(editorial)
subject.editorialTapped(cellContent: cell.editorialContentView!)
observer.removeObserver()
expect(posted) == true
}
it("can open a post") {
let postId = "postId"
let editorial = Editorial.stub([
"kind": "post",
"post": Post.stub(["id": postId]),
])
let nav = FakeNavigationController(rootViewController: subject)
let cell = setupEditorialCell(editorial)
subject.editorialTapped(cellContent: cell.editorialContentView!)
let postController = nav.pushedViewController as? PostDetailViewController
expect(postController).notTo(beNil())
expect(postController?.postParam) == postId
}
it("can open a post within a post stream") {
let postId = "postId"
let editorial = Editorial.stub([
"kind": "post_stream",
"posts": [Post.stub(["id": "0"]), Post.stub(["id": postId])],
])
let nav = FakeNavigationController(rootViewController: subject)
let cell = setupEditorialCell(editorial)
subject.editorialTapped(index: 1, cell: cell)
let postController = nav.pushedViewController as? PostDetailViewController
expect(postController).notTo(beNil())
expect(postController?.postParam) == postId
}
it("sets invite info after submitting invitations") {
let editorial = Editorial.stub([
"kind": "invite",
])
editorial.invite = (emails: "emails", sent: nil)
let cell = setupEditorialCell(editorial)
subject.submitInvite(cell: cell, emails: "[email protected]")
expect(editorial.invite?.emails) == ""
expect(editorial.invite?.sent).notTo(beNil())
}
it("shows the join controller on invalid inputs") {
let editorial = Editorial.stub([
"kind": "join",
])
let cell = setupEditorialCell(editorial)
let nav = FakeNavigationController(rootViewController: subject)
subject.submitJoin(cell: cell, email: "email", username: "", password: "")
let joinController = nav.pushedViewController as? JoinViewController
expect(joinController).notTo(beNil())
expect(joinController?.screen.email) == "email"
}
describe("lots of ways to show a post") {
var content: EditorialPostCell!
var post: Post!
beforeEach {
let postId = "postId"
post = Post.stub(["id": postId])
let editorial = Editorial.stub([
"kind": "post",
"post": post,
])
let cell = setupEditorialCell(editorial)
content = cell.editorialContentView as? EditorialPostCell
}
it("tapping comments") {
let nav = FakeNavigationController(rootViewController: subject)
subject.commentTapped(post: post, cell: content)
let postController = nav.pushedViewController as? PostDetailViewController
expect(postController).notTo(beNil())
}
it("tapping repost") {
let nav = FakeNavigationController(rootViewController: subject)
subject.repostTapped(post: post, cell: content)
let postController = nav.pushedViewController as? PostDetailViewController
expect(postController).notTo(beNil())
}
}
}
}
}
}
| mit | dc71a3656e4f04ef12604401c718b9b8 | 46.325926 | 98 | 0.486305 | 6.492886 | false | false | false | false |
SwiftyMagic/Magic | Magic/Magic/UIKit/UIImageViewExtension.swift | 1 | 1365 | //
// UIImageViewExtension.swift
// Magic
//
// Created by Broccoli on 2016/10/11.
// Copyright © 2016年 broccoliii. All rights reserved.
//
import Foundation
// MARK: - Initializers
extension UIImageView {
convenience init(imageName: String) {
self.init(image: UIImage(named: imageName))
}
}
// MARK: - Methods
public extension UIImageView {
func reflect() {
var frame = self.frame
frame.origin.y += (frame.size.height + 1)
let reflectionImageView = UIImageView(frame: frame)
clipsToBounds = true
reflectionImageView.contentMode = contentMode
reflectionImageView.image = image
reflectionImageView.transform = CGAffineTransform(scaleX: 1.0, y: -1.0)
let reflectionLayer = reflectionImageView.layer
let gradientLayer = CAGradientLayer()
gradientLayer.bounds = reflectionLayer.bounds
gradientLayer.position = CGPoint(x: reflectionLayer.bounds.size.width / 2, y: reflectionLayer.bounds.size.height * 0.5)
gradientLayer.colors = [UIColor.clear.cgColor, UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3).cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0)
reflectionLayer.mask = gradientLayer
superview!.addSubview(reflectionImageView)
}
}
| mit | c757f4dc164296670b5c15e5622a80b2 | 33.923077 | 127 | 0.673275 | 4.10241 | false | false | false | false |
postmanlabs/httpsnippet | test/fixtures/output/swift/nsurlsession/https.swift | 2 | 575 | import Foundation
var request = NSMutableURLRequest(URL: NSURL(string: "https://mockbin.com/har")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
println(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
println(httpResponse)
}
})
dataTask.resume()
| mit | 2997f6d2b8fbb693679611230a54f12d | 30.944444 | 107 | 0.64 | 4.831933 | false | false | false | false |
alokc83/rayW-SwiftSeries | RW-SwiftSeries_Tuple-Challenge9.playground/Contents.swift | 1 | 2187 | //: Playground - noun: a place where people can play
import UIKit
//Implicit
let name = ("Alok", "Choudhary")
var houseAddress = (732, "S Millvale Ave", "Apt B2", "Pittsburgh", 15213)
houseAddress.0
let (houseNUmber, streetName, apt, city, zipcode) = houseAddress
houseNUmber
zipcode
//Explicit
let somePage:(pageNumber:Int, PageText:String) = (10, "Call me baby")
somePage.pageNumber
somePage.PageText
let anotherPage:(pageNumber:Int, pageText:String) = (10, "Call me. Baby")
func currentPage() -> (pageNumber:Int, pageText:String){
return (1, "Its was something new, that I never saw before")
}
currentPage().pageNumber
currentPage().pageText
let books = [("A Wrinkle in time", 10, 199, "Young adult"),
("On the road", 18, 250, "litrature"),
("Hop on pop", 3, 30, "Child")]
for book in books{
println("\(book) - ")
switch book {
case (_,18,let pageCount, let genre):
print("This book is for older readers - \(pageCount) pages - \(genre)")
case(_, 1...4, _,_):
print("kid friendly")
default :
print("An uncataloged book")
break;
}
println()
}
var name1 = "Ray"
var name2 = "Wenderlich"
(name1, name2) = (name2, name1)
// Chellenge
func randomIndex(count: Int) -> Int {
return Int(arc4random_uniform(UInt32(count)))
}
// Your code here! Write knockKnockJoke() function
// Make an array of 3 knock knock jokes
// Return a random joke!
func knockKnockJoke() ->((who:String, punchline:String)){
let jokes = [("robin","Robin the piggy bank"),
("Lettuce","Lettuce in it’s cold out here."),("King Tut","King Tut-key fried chicken!")]
return jokes[randomIndex(jokes.count)]
}
let joke2 = knockKnockJoke()
println("Knock, knock.")
println("Who's there?")
println("\(joke2.who)")
println("\(joke2.who) who?")
println("\(joke2.punchline)")
let joke = knockKnockJoke()
println("Knock, knock.")
println("Who's there?")
println("\(joke.who)")
println("\(joke.who) who?")
println("\(joke.punchline)")
let joke3 = knockKnockJoke()
println("Knock, knock.")
println("Who's there?")
println("\(joke3.who)")
println("\(joke3.who) who?")
println("\(joke3.punchline)")
| mit | 150632e78846cd13cde50b787a3708d8 | 21.760417 | 96 | 0.649886 | 3.300604 | false | false | false | false |
jackdao1992/JDProgressImageView | ProgressCustom/ProgressCustom/JDProgressView.swift | 1 | 6848 | //
// JDProgressView.swift
// ProgressCustom
//
// Created by Jack Dao on 3/14/16.
// Copyright © 2016 Rubify. All rights reserved.
//
import UIKit
class JDProgressView: UIView {
var emptyProgressImagePath = "bottle_empty.png"
var fullProgressImagePath: String? = nil
var fullColorProgress: UIColor? = nil
var maskImageView = UIImageView()
let shapeMaskValue = CAShapeLayer()
var isVerticalProgress = false // doc
private var progress:CGFloat = 0
// percent ignore value on image
/*
||||
|||| |||| -> % ignore top
|| 100% ||
|| : ||
|| : ||
|| : ||
|| 2% ||
|| 1% ||
|||||||||| -> % ignore bottom
||||||||||
*/
var ignoreTopPercent:CGFloat = 0
var ignoreBottomPercent:CGFloat = 0
var layerEmpty = CALayer()
var layerFull: CALayer?
var layerFullTemp: CAShapeLayer?
// class func createJDProgressView() -> JDProgressView {
// let progressView = JDProgressView()
// return progressView
// }
override init(frame: CGRect) {
super.init(frame: frame)
self.configView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.configView()
}
func configView() {
self.backgroundColor = UIColor.whiteColor()
}
func getProgress() -> CGFloat {
return self.progress
}
func setProgress(value: CGFloat) {
if value > 1{
self.progress = 1
} else if value < 0 {
self.progress = 0
} else {
self.progress = value
}
self.setNeedsDisplay()
}
override func drawRect(rect: CGRect) {
layerEmpty.contents = UIImage(named: emptyProgressImagePath)?.CGImage
layerEmpty.frame = self.bounds
let path = UIBezierPath()
if !isVerticalProgress {
let ignoreYTop = ignoreTopPercent * self.bounds.height
let ignoreYBottom = ignoreBottomPercent * self.bounds.height
let heightOfValue = progress * (self.bounds.height - ignoreYTop - ignoreYBottom)
let yLimit = self.bounds.height - ignoreYBottom - heightOfValue
path.moveToPoint(CGPointMake(0, yLimit))
path.addLineToPoint(CGPointMake(self.bounds.width, yLimit))
path.addLineToPoint(CGPointMake(self.bounds.width, yLimit + heightOfValue))
path.addLineToPoint(CGPointMake(0, yLimit + heightOfValue))
path.closePath()
} else {
let ignoreYTop = ignoreTopPercent * self.bounds.width
let ignoreYBottom = ignoreBottomPercent * self.bounds.width
let widthOfValue = progress * (self.bounds.width - ignoreYTop - ignoreYBottom)
let xLimit = widthOfValue
path.moveToPoint(CGPointMake(ignoreYBottom, 0))
path.addLineToPoint(CGPointMake(xLimit + ignoreYBottom, 0))
path.addLineToPoint(CGPointMake(xLimit + ignoreYBottom, self.bounds.height))
path.addLineToPoint(CGPointMake(ignoreYBottom, self.bounds.height))
path.closePath()
}
let oldPath = shapeMaskValue.path
if fullProgressImagePath != nil && fullColorProgress == nil {
if fullProgressImagePath != nil {
if layerFull == nil {
layerFull = CALayer()
}
layerFull?.contents = UIImage(named: fullProgressImagePath!)?.CGImage
layerFull?.frame = self.bounds
}
shapeMaskValue.frame = self.bounds
shapeMaskValue.path = path.CGPath
let animationLine = CABasicAnimation(keyPath: "path")
animationLine.fromValue = oldPath
animationLine.toValue = path.CGPath
animationLine.duration = 0.33
animationLine.additive = true
shapeMaskValue.addAnimation(animationLine, forKey: "animationPath")
layerFull?.mask = shapeMaskValue
self.layer.addSublayer(layerEmpty)
self.layer.addSublayer(layerFull!)
} else if self.fullColorProgress != nil && self.fullProgressImagePath == nil {
shapeMaskValue.frame = self.bounds
shapeMaskValue.path = path.CGPath
shapeMaskValue.fillColor = fullColorProgress?.CGColor
if layerFull == nil {
layerFull = CALayer()
layerFull?.frame = self.bounds
layerFull?.backgroundColor = fullColorProgress?.CGColor
maskImageView = UIImageView(image: self.imageWithImage(UIImage(named: emptyProgressImagePath)!, scaledToSize: self.bounds.size))
}
let animationLine = CABasicAnimation(keyPath: "path")
animationLine.fromValue = oldPath
animationLine.toValue = path.CGPath
animationLine.duration = 0.33
animationLine.additive = true
shapeMaskValue.addAnimation(animationLine, forKey: "animationPath")
self.layer.addSublayer(layerEmpty)
self.layer.addSublayer(shapeMaskValue)
self.maskView = maskImageView
} else {
shapeMaskValue.frame = self.bounds
shapeMaskValue.path = path.CGPath
shapeMaskValue.fillColor = fullColorProgress?.CGColor
if layerFull == nil {
layerFull = CALayer()
layerFull?.frame = self.bounds
layerFull?.backgroundColor = fullColorProgress?.CGColor
maskImageView = UIImageView(image: self.imageWithImage(UIImage(named: fullProgressImagePath!)!, scaledToSize: self.bounds.size))
}
let animationLine = CABasicAnimation(keyPath: "path")
animationLine.fromValue = oldPath
animationLine.toValue = path.CGPath
animationLine.duration = 0.33
animationLine.additive = true
shapeMaskValue.addAnimation(animationLine, forKey: "animationPath")
shapeMaskValue.mask = maskImageView.layer
self.layer.addSublayer(layerEmpty)
self.layer.addSublayer(shapeMaskValue)
// self.maskView = maskImageView
}
}
func imageWithImage(image: UIImage, scaledToSize newSize:CGSize) -> UIImage {
UIGraphicsBeginImageContext( newSize );
image .drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return newImage;
}
}
| mit | b2a920f6cdea9ae6956830b4e11bf95a | 35.614973 | 144 | 0.588433 | 5.455777 | false | false | false | false |
peaks-cc/iOS11_samplecode | chapter_10/BookReader/BookReader/OutlineViewController.swift | 1 | 2377 | //
// OutlineViewController.swift
// BookReader
//
// Created by Kishikawa Katsumi on 2017/07/03.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import UIKit
import PDFKit
class OutlineViewController: UITableViewController {
var pdfDocument: PDFDocument?
var toc = [PDFOutline]()
weak var delegate: OutlineViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = UITableViewAutomaticDimension
if let root = pdfDocument?.outlineRoot {
var stack = [root]
while !stack.isEmpty {
let current = stack.removeLast()
if let label = current.label, !label.isEmpty {
toc.append(current)
}
for i in (0..<current.numberOfChildren).reversed() {
stack.append(current.child(at: i))
}
}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return toc.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! OutlineCell
let outline = toc[indexPath.row]
cell.label = outline.label
cell.pageLabel = outline.destination?.page?.label
var indentationLevel = -1
var parent = outline.parent
while let _ = parent {
indentationLevel += 1
parent = parent?.parent
}
cell.indentationLevel = indentationLevel
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let outline = toc[indexPath.row]
if let destination = outline.destination {
delegate?.outlineViewController(self, didSelectOutlineAt: destination)
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
protocol OutlineViewControllerDelegate: class {
func outlineViewController(_ outlineViewController: OutlineViewController, didSelectOutlineAt destination: PDFDestination)
}
| mit | b813415fdd68c6f2c97212ddf8989bcc | 31.108108 | 126 | 0.647306 | 5.315436 | false | false | false | false |
asymptotik/asymptotik-rnd-scenekit-kaleidoscope | Atk_Rnd_VisualToys/CVReturnExtensions.swift | 2 | 1995 | //
// CVReturn+Extensions.swift
// Atk_Rnd_VisualToys
//
// Created by Rick Boykin on 9/27/14.
// Copyright (c) 2014 Asymptotik Limited. All rights reserved.
//
import Foundation
import CoreVideo
extension CVReturn {
static func stringValue(value:CVReturn) -> String {
var ret = ""
switch value {
case kCVReturnSuccess:
ret = "kCVReturnSuccess"
case kCVReturnFirst:
ret = "kCVReturnFirst"
case kCVReturnLast:
ret = "kCVReturnLast"
case kCVReturnInvalidArgument:
ret = "kCVReturnInvalidArgument"
case kCVReturnAllocationFailed:
ret = "kCVReturnAllocationFailed"
case kCVReturnInvalidDisplay:
ret = "kCVReturnInvalidDisplay"
case kCVReturnDisplayLinkAlreadyRunning:
ret = "kCVReturnDisplayLinkAlreadyRunning"
case kCVReturnDisplayLinkNotRunning:
ret = "kCVReturnDisplayLinkNotRunning"
case kCVReturnDisplayLinkCallbacksNotSet:
ret = "kCVReturnDisplayLinkCallbacksNotSet"
case kCVReturnInvalidPixelFormat:
ret = "kCVReturnInvalidPixelFormat"
case kCVReturnInvalidSize:
ret = "kCVReturnInvalidSize"
case kCVReturnInvalidPixelBufferAttributes:
ret = "kCVReturnInvalidPixelBufferAttributes"
case kCVReturnPixelBufferNotOpenGLCompatible:
ret = "kCVReturnPixelBufferNotOpenGLCompatible"
case kCVReturnPixelBufferNotMetalCompatible:
ret = "kCVReturnPixelBufferNotMetalCompatible"
case kCVReturnWouldExceedAllocationThreshold:
ret = "kCVReturnWouldExceedAllocationThreshold"
case kCVReturnPoolAllocationFailed:
ret = "kCVReturnPoolAllocationFailed"
case kCVReturnInvalidPoolAttributes:
ret = "kCVReturnInvalidPoolAttributes"
default:
ret = "Unknown"
}
return ret;
}
} | mit | 06d972fcf50a3dac2c4b5fae7faad65c | 32.830508 | 63 | 0.65614 | 5.465753 | false | false | false | false |
austinzheng/swift | test/SILOptimizer/definite_init_objc_factory_init.swift | 6 | 3365 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/../IDE/Inputs/custom-modules %s -emit-sil -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import ImportAsMember.Class
// CHECK-LABEL: sil shared [serializable] [thunk] @$sSo4HiveC5queenABSgSo3BeeCSg_tcfCTO : $@convention(method) (@owned Optional<Bee>, @thick Hive.Type) -> @owned Optional<Hive>
func testInstanceTypeFactoryMethod(queen: Bee) {
// CHECK: bb0([[QUEEN:%[0-9]+]] : $Optional<Bee>, [[HIVE_META:%[0-9]+]] : $@thick Hive.Type):
// CHECK-NEXT: [[HIVE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[HIVE_META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK-NEXT: [[FACTORY:%[0-9]+]] = objc_method [[HIVE_META_OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: [[HIVE:%[0-9]+]] = apply [[FACTORY]]([[QUEEN]], [[HIVE_META_OBJC]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK-NEXT: release_value [[QUEEN]]
// CHECK-NEXT: return [[HIVE]] : $Optional<Hive>
var hive1 = Hive(queen: queen)
}
extension Hive {
// CHECK-LABEL: sil hidden @$sSo4HiveC027definite_init_objc_factory_C0E10otherQueenABSo3BeeC_tcfC
convenience init(otherQueen other: Bee) {
// CHECK: bb0({{.*}}, [[META:%.*]] : $@thick Hive.Type)
// CHECK: [[SELF_ADDR:%[0-9]+]] = alloc_stack $Hive
// CHECK: [[OBJC_META:%[0-9]+]] = thick_to_objc_metatype [[META]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[FACTORY:%[0-9]+]] = objc_method [[OBJC_META]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?, $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: apply [[FACTORY]]([[QUEEN:%[0-9]+]], [[OBJC_META]]) : $@convention(objc_method) (Optional<Bee>, @objc_metatype Hive.Type) -> @autoreleased Optional<Hive>
// CHECK: store [[NEW_SELF:%[0-9]+]] to [[SELF_ADDR]]
// CHECK: dealloc_stack [[SELF_ADDR]]
// CHECK: return [[NEW_SELF]]
self.init(queen: other)
}
convenience init(otherFlakyQueen other: Bee) throws {
try self.init(flakyQueen: other)
}
}
extension SomeClass {
// SIL-LABEL: sil hidden @_TFE16import_as_memberCSo9SomeClasscfT6doubleSd_S0_
// SIL: bb0([[DOUBLE:%[0-9]+]] : $Double
// SIL-NOT: value_metatype
// SIL: [[FNREF:%[0-9]+]] = function_ref @MakeIAMSomeClass
// SIL: apply [[FNREF]]([[DOUBLE]])
convenience init(double: Double) {
self.init(value: double)
}
}
class SubHive : Hive {
// CHECK-LABEL: sil hidden @$s027definite_init_objc_factory_B07SubHiveC20delegatesToInheritedACyt_tcfC
convenience init(delegatesToInherited: ()) {
// CHECK: bb0([[METATYPE:%.*]] : $@thick SubHive.Type)
// CHECK: [[UPMETA:%.*]] = upcast [[METATYPE]]
// CHECK: [[OBJC:%.*]] = thick_to_objc_metatype [[UPMETA]] : $@thick Hive.Type to $@objc_metatype Hive.Type
// CHECK: [[METHOD:%.*]] = objc_method [[OBJC]] : $@objc_metatype Hive.Type, #Hive.init!allocator.1.foreign : (Hive.Type) -> (Bee?) -> Hive?
// CHECK: apply [[METHOD]]({{.*}}, [[OBJC]])
// CHECK: return {{%.*}} : $SubHive
self.init(queen: Bee())
}
}
| apache-2.0 | 2d4c26ce53de1d3663a0d3044b252636 | 54.163934 | 265 | 0.641605 | 3.295788 | false | false | false | false |
brentdax/swift | test/Parse/self_rebinding.swift | 30 | 1410 | // RUN: %target-typecheck-verify-swift
class Writer {
private var articleWritten = 47
func stop() {
let rest: () -> Void = { [weak self] in
let articleWritten = self?.articleWritten ?? 0
guard let `self` = self else {
return
}
self.articleWritten = articleWritten
}
fatalError("I'm running out of time")
rest()
}
func nonStop() {
let write: () -> Void = { [weak self] in
self?.articleWritten += 1
if let self = self {
self.articleWritten += 1
}
if let `self` = self {
self.articleWritten += 1
}
guard let self = self else {
return
}
self.articleWritten += 1
}
write()
}
}
struct T {
var mutable: Int = 0
func f() {
// expected-error @+2 {{keyword 'self' cannot be used as an identifier here}}
// expected-note @+1 {{if this name is unavoidable, use backticks to escape it}}
let self = self
}
}
class MyCls {
func something() {}
func test() {
// expected-warning @+1 {{initialization of immutable value 'self' was never used}}
let `self` = Writer() // Even if `self` is shadowed,
something() // this should still refer `MyCls.something`.
}
}
| apache-2.0 | 77a77acd9a8b755a6a73540a9fcb1f3d | 22.5 | 91 | 0.500709 | 4.533762 | false | false | false | false |
zeroleaf/LeetCode | LeetCode/LeetCodeTests/4_MedianOfTwoSortedArraysSpec.swift | 1 | 3868 | //
// MedianOfTwoSortedArraysSpec.swift
// LeetCode
//
// Created by zeroleaf on 16/1/21.
// Copyright © 2016年 zeroleaf. All rights reserved.
//
import XCTest
import Quick
import Nimble
class MedianOfTwoSortedArrays {
// Put into one sorted array then we can easily find the median of the array.
// func findMedianSortedArrays(nums1: [Int], _ nums2: [Int]) -> Double {
//
// var nums = [Int](count: nums1.count + nums2.count, repeatedValue: 0)
// var i = 0, i1 = 0, i2 = 0;
//
// while i1 < nums1.count && i2 < nums2.count {
// if nums1[i1] < nums2[i2] {
// nums[i++] = nums1[i1++]
// } else {
// nums[i++] = nums2[i2++]
// }
// }
// while i1 < nums1.count {
// nums[i++] = nums1[i1++]
// }
// while i2 < nums2.count {
// nums[i++] = nums2[i2++]
// }
//
// if nums.count % 2 == 0 {
// return Double((nums[nums.count / 2] + nums[nums.count / 2 - 1])) / 2.0
// }
// return Double(nums[nums.count / 2])
// }
// Inspired by https://leetcode.com/discuss/15790/share-my-o-log-min-m-n-solution-with-explanation.
func findMedianSortedArrays(nums1: [Int], _ nums2: [Int]) -> Double {
// Make sure nums in A is <= B
let (A, B) = nums1.count > nums2.count ? (nums2, nums1) : (nums1, nums2)
let (m, n) = (A.count, B.count)
var (imin, imax) = (0, m)
let half_len = (m + n + 1) / 2
while imin <= imax {
let i = (imin + imax) / 2
let j = half_len - i
// j > 0 && i < m is the edge value for B[j - 1] > A[i], otherwise index will out of the array bound
if j > 0 && i < m && B[j - 1] > A[i] {
imin = i + 1
}
else if i > 0 && j < n && A[i - 1] > B[j] {
imax = i - 1
}
else {
var num1 = 0, num2 = 0
if i == 0 {
num1 = B[j - 1]
}
else if j == 0 {
num1 = A[i - 1]
}
else {
num1 = max(A[i - 1], B[j - 1])
}
if (m + n) % 2 == 1 {
return Double(num1)
}
if i == m {
num2 = B[j]
}
else if (j == n) {
num2 = A[i]
}
else {
num2 = min(A[i], B[j])
}
return Double(num1 + num2) / 2.0
}
}
return 0.0
}
}
class MedianOfTwoSortedArraysSpec: QuickSpec {
override func spec() {
describe("Find Median Sorted Arrays") {
var solution: MedianOfTwoSortedArrays!
beforeEach {
solution = MedianOfTwoSortedArrays()
}
// This should not be the case.
// it("Not nums.") {
// expect(solution.findMedianSortedArrays([], [])).to(equal(0.0))
// }
it("Only 1 num in nums1") {
expect(solution.findMedianSortedArrays([1], [])).to(equal(1.0))
}
it("Only 1 num in nums2") {
expect(solution.findMedianSortedArrays([], [2])).to(equal(2.0))
}
it("Two nums in num1") {
expect(solution.findMedianSortedArrays([1, 2], [])).to(equal(1.5))
}
it("Two nums in num1 and num2") {
expect(solution.findMedianSortedArrays([1], [2])).to(equal(1.5))
}
it("Nums1 all less than nums2") {
expect(solution.findMedianSortedArrays([1, 2, 3], [4])).to(equal(2.5))
}
}
}
}
| mit | c916ca63afb9524d49d70be21ed294c8 | 27.62963 | 112 | 0.422768 | 3.649669 | false | false | false | false |
nicemohawk/nmf-ios | nmf/ScheduleItem.swift | 1 | 2989 | //
// Schedule.swift
// nmf
//
// Created by Daniel Pagan on 4/6/16.
// Copyright © 2017 Nelsonville Music Festival. All rights reserved.
//
import Foundation
@objcMembers class ScheduleItem: NSObject, NSCoding {
var objectId: String?
var artistName: String?
var startTime: Date?
var stage: String?
var day: String?
// local-only
var _starred: Bool = false
var _updated: Bool = false
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
objectId = aDecoder.decodeObject(forKey: "oid") as? String
artistName = aDecoder.decodeObject(forKey: "artist") as? String
startTime = aDecoder.decodeObject(forKey: "start") as? Date
day = aDecoder.decodeObject(forKey: "day") as? String
stage = aDecoder.decodeObject(forKey: "stage") as? String
_starred = aDecoder.decodeBool(forKey: "starred")
_updated = aDecoder.decodeBool(forKey: "updated")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(objectId, forKey: "oid")
aCoder.encode(artistName, forKey: "artist")
aCoder.encode(startTime, forKey: "start")
aCoder.encode(day, forKey: "day")
aCoder.encode(stage, forKey: "stage")
aCoder.encode(_starred, forKey: "starred")
aCoder.encode(_updated, forKey: "updated")
}
// MARK: - Custom methods
func update(_ otherItem: ScheduleItem) {
guard objectId == otherItem.objectId else {
return
}
artistName = otherItem.artistName
startTime = otherItem.startTime
day = otherItem.day
stage = otherItem.stage
// we don't merge starred
_updated = true
}
//MARK: - date formatting
static let hourFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "h:mma"
return formatter
}()
static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE h:mma"
return formatter
}()
func timeString() -> String {
if let startDate = startTime {
let components = Calendar.current.dateComponents([.hour,.minute], from: startDate)
if let hour = components.hour, let minute = components.minute {
switch (hour, minute) {
case (23, 59):
return "12:00AM"
default:
return ScheduleItem.hourFormatter.string(from: startDate)
}
}
return ScheduleItem.hourFormatter.string(from: startDate)
}
return ""
}
func dateString() -> String {
if let startDate = startTime {
return ScheduleItem.dateFormatter.string(from: startDate)
}
return ""
}
}
| apache-2.0 | c5bd2a6b6956770420d8220482c55bdf | 25.918919 | 94 | 0.569612 | 4.819355 | false | false | false | false |
dasdom/StackViewExperiments | StackViewExperiments/UIStackViewPlayground.playground/Pages/Profile.xcplaygroundpage/Contents.swift | 1 | 5513 | //: [Previous](@previous)
//: # Profile
import UIKit
import XCPlayground
//: Constants
let socialButtonHeight: CGFloat = 30
let socialButtonSpacing: CGFloat = 10
let avatarImageHeight: CGFloat = 100
// Helper function to create the small social buttons on the header image.
func socialButtonWithWhite(white: CGFloat) -> UIButton {
let button = UIButton(type: .Custom)
button.backgroundColor = UIColor(white: white, alpha: 1.0)
button.layer.cornerRadius = ceil(socialButtonHeight/2)
return button
}
//: First we need a `hostView` to put the different elements on.
let hostView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))
hostView.backgroundColor = UIColor.lightGrayColor()
XCPShowView("hostView", view: hostView)
/*:
Those elements are:
- a header image
*/
let headerImageView = UIImageView(frame: CGRect.zeroRect)
headerImageView.backgroundColor = UIColor.yellowColor()
headerImageView.contentMode = .ScaleAspectFill
//: - different social button (App.net, Twitter, StackOverflow, Github)
let adnButton = socialButtonWithWhite(0.2)
let twitterButton = socialButtonWithWhite(0.3)
let stackOverflowButton = socialButtonWithWhite(0.4)
let githubButton = socialButtonWithWhite(0.5)
//: - avatar image
let avatarImageView = UIImageView(frame: CGRect.zeroRect)
avatarImageView.backgroundColor = UIColor(white: 0.6, alpha: 1.0)
avatarImageView.layer.cornerRadius = ceil(avatarImageHeight/2)
avatarImageView.layer.borderColor = UIColor.grayColor().CGColor
avatarImageView.layer.borderWidth = 2
avatarImageView.clipsToBounds = true
avatarImageView.contentMode = .ScaleAspectFit
//: - the name
let nameLabel = UILabel(frame: CGRect.zeroRect)
nameLabel.text = "Dominik Hauser"
nameLabel.font = UIFont(name: "Avenir-Medium", size: 25)
nameLabel.textColor = UIColor.whiteColor()
//: - the handle
let handleLabel = UILabel(frame: CGRect.zeroRect)
handleLabel.text = "dasdom"
handleLabel.font = UIFont(name: "Avenir-Book", size: 18)
handleLabel.textColor = UIColor.lightGrayColor()
//: - a short bio of the user
let bioLabel = UILabel(frame: CGRect.zeroRect)
bioLabel.text = "iOS dev durung the day. iOS dev at night. Father and husband all time. Auto Layout master. Swift lover"
bioLabel.numberOfLines = 0
bioLabel.font = UIFont(name: "Avenir-Oblique", size: 13)
bioLabel.textAlignment = .Center
bioLabel.textColor = UIColor.lightGrayColor()
// dark background color
hostView.backgroundColor = UIColor(red: 0.12, green: 0.12, blue: 0.14, alpha: 1.0)
//: This if statement is needed, otherwise the Playground isn't executed.
if #available(iOS 9, *) {
/*:
## Building the user interface
The user interface is build using four `UIStackView`s.
- a vertical stack view for the round social buttons on top of the header image
*/
let socialButtonStackView = UIStackView(arrangedSubviews: [adnButton, twitterButton, stackOverflowButton, githubButton])
socialButtonStackView.axis = .Vertical
socialButtonStackView.spacing = socialButtonSpacing
socialButtonStackView.distribution = .FillEqually
socialButtonStackView.alignment = .Center
//: - a horizontal stack view for the header view and the social button stack view (note: the spacing is negative)
let headerStackView = UIStackView(arrangedSubviews: [headerImageView, socialButtonStackView])
headerStackView.spacing = -(socialButtonHeight+socialButtonSpacing*2)
headerStackView.alignment = .Center
let personInfoStackView = UIStackView(arrangedSubviews: [avatarImageView, nameLabel, handleLabel, bioLabel])
personInfoStackView.axis = .Vertical
personInfoStackView.alignment = .Center
personInfoStackView.spacing = 10
let mainStackView = UIStackView(arrangedSubviews: [headerStackView, personInfoStackView])
mainStackView.translatesAutoresizingMaskIntoConstraints = false
mainStackView.axis = .Vertical
mainStackView.alignment = .Center
mainStackView.spacing = -ceil(avatarImageHeight/2)
hostView.addSubview(mainStackView)
// MARK: - Layout
headerImageView.heightAnchor.constraintEqualToConstant(220).active = true
socialButtonStackView.widthAnchor.constraintEqualToConstant(socialButtonHeight+socialButtonSpacing*2).active = true
let numberOfSocialButtons = CGFloat(socialButtonStackView.arrangedSubviews.count)
let socialButtonStackViewHeight = numberOfSocialButtons * socialButtonHeight + (numberOfSocialButtons - 1) * socialButtonSpacing
socialButtonStackView.heightAnchor.constraintEqualToConstant(socialButtonStackViewHeight).active = true
avatarImageView.widthAnchor.constraintEqualToConstant(avatarImageHeight).active = true
avatarImageView.heightAnchor.constraintEqualToConstant(avatarImageHeight).active = true
let views = ["stackView": mainStackView, "headerStackView": headerStackView, "bio": bioLabel]
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[headerStackView]|", options: [], metrics: nil, views: views))
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-10-[bio]", options: [], metrics: nil, views: views))
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[stackView]|", options: [], metrics: nil, views: views))
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: [], metrics: nil, views: views))
}
headerImageView.image = UIImage(named: "DSC_1165.jpg")
avatarImageView.image = UIImage(named: "IMG_0345.jpg")
hostView
//: [Next](@next)
| mit | 31d2493dbf2861468c748d528408851d | 41.736434 | 152 | 0.786867 | 4.736254 | false | false | false | false |
calkinssean/TIY-Assignments | Day 21/SpotifyAPI/Song.swift | 1 | 747 | //
// Song.swift
// SpotifyAPI
//
// Created by Sean Calkins on 2/29/16.
// Copyright © 2016 Dape App Productions LLC. All rights reserved.
//
import Foundation
let kSongName = "song"
class Song: NSObject, NSCoding {
var name: String = ""
override init() {
}
init(dict: JSONDictionary) {
if let name = dict["name"] as? String {
self.name = name
} else {
print("there was an issue with the name")
}
}
required init?(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObjectForKey(kSongName) as! String
super.init()
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: kSongName)
}
} | cc0-1.0 | 7843598e027896ff21a8a0a458d2e79c | 20.342857 | 69 | 0.581769 | 3.94709 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Domains/Domain registration/RegisterDomainDetails/ViewModel/RegisterDomainDetailsViewModel+CellIndex.swift | 2 | 2832 | import Foundation
extension RegisterDomainDetailsViewModel {
enum CellIndex {
enum PrivacyProtection: Int {
case privately
case publicly
var jsonKey: String {
return "privacyProtection"
}
}
enum ContactInformation: Int {
case firstName
case lastName
case organization
case email
case country
var indexPath: IndexPath {
return IndexPath(row: rawValue,
section: SectionIndex.contactInformation.rawValue)
}
var keyboardType: UIKeyboardType {
switch self {
case .email:
return .emailAddress
default:
return UIKeyboardType.default
}
}
}
enum PhoneNumber: Int {
case countryCode
case number
var indexPath: IndexPath {
return IndexPath(row: rawValue,
section: SectionIndex.phone.rawValue)
}
}
enum AddressField {
case addressLine1
case addressLine2
case addNewAddressLine
case city
case state
case postalCode
}
struct AddressSectionIndexHelper {
var addressLine1: Int {
return 0
}
private(set) var extraAddressLineCount = 0
var isAddNewAddressVisible = false
mutating func addNewAddressField() {
extraAddressLineCount += 1
}
private var totalExtra: Int {
return isAddNewAddressVisible ? extraAddressLineCount + 1 : extraAddressLineCount
}
var addNewAddressIndex: Int {
return totalExtra
}
var cityIndex: Int {
return 1 + totalExtra
}
var stateIndex: Int {
return 2 + totalExtra
}
var postalCodeIndex: Int {
return 3 + totalExtra
}
func addressField(for index: Int) -> AddressField {
if isAddNewAddressVisible && index == totalExtra {
return .addNewAddressLine
}
if cityIndex == index {
return .city
} else if stateIndex == index {
return .state
} else if postalCodeIndex == index {
return .postalCode
} else if addressLine1 == index {
return .addressLine1
}
return .addressLine2
}
}
}
}
| gpl-2.0 | facb7589f2a4a13a0216384042ad71fa | 27.039604 | 97 | 0.46822 | 6.726841 | false | false | false | false |
ya7lelkom/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Style/WPStyleGuide+Notifications.swift | 1 | 16786 | import Foundation
extension WPStyleGuide
{
public struct Notifications
{
// MARK: - Styles Used by NotificationsViewController
//
// NoteTableViewHeader
public static let sectionHeaderBackgroundColor = UIColor(red: 0xFF/255.0, green: 0xFF/255.0, blue: 0xFF/255.0, alpha: 0xEA/255.0)
public static let sectionHeaderRegularStyle = [ NSParagraphStyleAttributeName: sectionHeaderParagraph,
NSFontAttributeName: sectionHeaderFont,
NSForegroundColorAttributeName: sectionHeaderTextColor ]
// NoteTableViewCell
public static let noticonFont = UIFont(name: "Noticons", size: 16)
public static let noticonTextColor = UIColor.whiteColor()
public static let noticonReadColor = UIColor(red: 0xA4/255.0, green: 0xB9/255.0, blue: 0xC9/255.0, alpha: 0xFF/255.0)
public static let noticonUnreadColor = UIColor(red: 0x25/255.0, green: 0x9C/255.0, blue: 0xCF/255.0, alpha: 0xFF/255.0)
public static let noticonUnmoderatedColor = UIColor(red: 0xFF/255.0, green: 0xBA/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0)
public static let noteBackgroundReadColor = UIColor.whiteColor()
public static let noteBackgroundUnreadColor = UIColor(red: 0xF1/255.0, green: 0xF6/255.0, blue: 0xF9/255.0, alpha: 0xFF/255.0)
public static let noteSeparatorColor = blockSeparatorColor
public static let gravatarPlaceholderImage = UIImage(named: "gravatar")
public static let blavatarPlaceholderImage = UIImage(named: "blavatar-default")
// NoteUndoOverlayView
public static let noteUndoBackgroundColor = WPStyleGuide.errorRed()
public static let noteUndoTextColor = UIColor.whiteColor()
public static let noteUndoTextFont = subjectRegularFont
// Subject Text
public static let subjectRegularStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectRegularFont,
NSForegroundColorAttributeName: subjectTextColor ]
public static let subjectBoldStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectBoldFont ]
public static let subjectItalicsStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectItalicsFont ]
public static let subjectNoticonStyle = [ NSParagraphStyleAttributeName: subjectParagraph,
NSFontAttributeName: subjectNoticonFont!,
NSForegroundColorAttributeName: subjectNoticonColor ]
public static let subjectQuotedStyle = blockQuotedStyle
// Subject Snippet
public static let snippetRegularStyle = [ NSParagraphStyleAttributeName: snippetParagraph,
NSFontAttributeName: subjectRegularFont,
NSForegroundColorAttributeName: snippetColor ]
// MARK: - Styles used by NotificationDetailsViewController
//
// Header
public static let headerTitleColor = blockTextColor
public static let headerTitleBoldFont = blockBoldFont
public static let headerDetailsColor = blockSubtitleColor
public static let headerDetailsRegularFont = blockRegularFont
public static let headerTitleRegularStyle = [ NSParagraphStyleAttributeName: headerTitleParagraph,
NSFontAttributeName: headerTitleRegularFont,
NSForegroundColorAttributeName: headerTitleColor]
public static let headerTitleBoldStyle = [ NSParagraphStyleAttributeName: headerTitleParagraph,
NSFontAttributeName: headerTitleBoldFont,
NSForegroundColorAttributeName: headerTitleColor]
public static let headerTitleContextStyle = [ NSParagraphStyleAttributeName: headerTitleParagraph,
NSFontAttributeName: headerTitleItalicsFont,
NSForegroundColorAttributeName: headerTitleContextColor]
// Footer
public static let footerRegularStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockRegularFont,
NSForegroundColorAttributeName: footerTextColor]
// Badges
public static let badgeBackgroundColor = UIColor.clearColor()
public static let badgeLinkColor = blockLinkColor
public static let badgeRegularStyle = [ NSParagraphStyleAttributeName: badgeParagraph,
NSFontAttributeName: blockRegularFont,
NSForegroundColorAttributeName: blockTextColor]
public static let badgeBoldStyle = blockBoldStyle
public static let badgeItalicsStyle = blockItalicsStyle
public static let badgeQuotedStyle = blockQuotedStyle
// Blocks
public static let contentBlockRegularFont = WPFontManager.merriweatherRegularFontOfSize(blockFontSize)
public static let contentBlockBoldFont = WPFontManager.merriweatherBoldFontOfSize(blockFontSize)
public static let contentBlockItalicFont = WPFontManager.merriweatherItalicFontOfSize(blockFontSize)
public static let blockRegularFont = WPFontManager.openSansRegularFontOfSize(blockFontSize)
public static let blockBoldFont = WPFontManager.openSansSemiBoldFontOfSize(blockFontSize)
public static let blockTextColor = WPStyleGuide.littleEddieGrey()
public static let blockQuotedColor = UIColor(red: 0x7E/255.0, green: 0x9E/255.0, blue: 0xB5/255.0, alpha: 0xFF/255.0)
public static let blockBackgroundColor = UIColor.whiteColor()
public static let blockLinkColor = WPStyleGuide.baseLighterBlue()
public static let blockSubtitleColor = UIColor(red: 0x00/255.0, green: 0xAA/255.0, blue: 0xDC/255.0, alpha: 0xFF/255.0)
public static let blockSeparatorColor = WPStyleGuide.readGrey()
public static let blockApprovedBgColor = UIColor.clearColor()
public static let blockUnapprovedSideColor = UIColor(red: 0xFF/255.0, green: 0xBA/255.0, blue: 0x00/255.0, alpha: 0xFF/255.0)
public static let blockUnapprovedBgColor = UIColor(red: 0xFF/255.0, green: 0xBA/255.0, blue: 0x00/255.0, alpha: 0x19/255.0)
public static let blockUnapprovedTextColor = UIColor(red: 0xF0/255.0, green: 0x82/255.0, blue: 0x1E/255.0, alpha: 0xFF/255.0)
public static let blockUnapprovedLinkColor = WPStyleGuide.mediumBlue()
public static let contentBlockRegularStyle = [ NSParagraphStyleAttributeName: contentBlockParagraph,
NSFontAttributeName: contentBlockRegularFont,
NSForegroundColorAttributeName: blockTextColor ]
public static let contentBlockBoldStyle = [ NSParagraphStyleAttributeName: contentBlockParagraph,
NSFontAttributeName: contentBlockBoldFont,
NSForegroundColorAttributeName: blockTextColor ]
public static let contentBlockItalicStyle = [ NSParagraphStyleAttributeName: contentBlockParagraph,
NSFontAttributeName: contentBlockItalicFont,
NSForegroundColorAttributeName: blockTextColor ]
public static let contentBlockQuotedStyle = [ NSParagraphStyleAttributeName: contentBlockParagraph,
NSFontAttributeName: contentBlockItalicFont,
NSForegroundColorAttributeName: blockQuotedColor ]
public static let contentBlockMatchStyle = [ NSParagraphStyleAttributeName: contentBlockParagraph,
NSFontAttributeName: contentBlockRegularFont,
NSForegroundColorAttributeName: blockLinkColor ]
public static let blockRegularStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockRegularFont,
NSForegroundColorAttributeName: blockTextColor ]
public static let blockBoldStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockBoldFont,
NSForegroundColorAttributeName: blockTextColor ]
public static let blockItalicsStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockItalicsFont,
NSForegroundColorAttributeName: blockTextColor ]
public static let blockQuotedStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockItalicsFont,
NSForegroundColorAttributeName: blockQuotedColor ]
public static let blockMatchStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockRegularFont,
NSForegroundColorAttributeName: blockLinkColor ]
public static let blockNoticonStyle = [ NSParagraphStyleAttributeName: blockParagraph,
NSFontAttributeName: blockNoticonFont!,
NSForegroundColorAttributeName: blockNoticonColor ]
// Action Buttons
public static let blockActionDisabledColor = UIColor(red: 0x7F/255.0, green: 0x9E/255.0, blue: 0xB4/255.0, alpha: 0xFF/255.0)
public static let blockActionEnabledColor = UIColor(red: 0xEA/255.0, green: 0x6D/255.0, blue: 0x1B/255.0, alpha: 0xFF/255.0)
// RichText Helpers
public static func blockBackgroundColorForRichText(isBadge: Bool) -> UIColor {
return isBadge ? badgeBackgroundColor : blockBackgroundColor
}
// Comment Helpers
public static func blockSeparatorColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockSeparatorColor : blockUnapprovedSideColor
}
public static func blockBackgroundColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockApprovedBgColor : blockUnapprovedBgColor
}
public static func blockTitleColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockTextColor : blockUnapprovedTextColor
}
public static func blockDetailsColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockQuotedColor : blockUnapprovedTextColor
}
public static func blockLinkColorForComment(isApproved approved: Bool) -> UIColor {
return approved ? blockLinkColor : blockUnapprovedLinkColor
}
// MARK: - Constants
//
public static let headerFontSize = CGFloat(12)
public static let headerLineSize = CGFloat(16)
public static let subjectFontSize = UIDevice.isPad() ? CGFloat(16) : CGFloat(14)
public static let subjectNoticonSize = UIDevice.isPad() ? CGFloat(15) : CGFloat(14)
public static let subjectLineSize = UIDevice.isPad() ? CGFloat(24) : CGFloat(18)
public static let snippetLineSize = subjectLineSize
public static let blockFontSize = UIDevice.isPad() ? CGFloat(16) : CGFloat(14)
public static let blockLineSize = UIDevice.isPad() ? CGFloat(24) : CGFloat(20)
public static let contentBlockLineSize = UIDevice.isPad() ? CGFloat(24) : CGFloat(21)
public static let maximumCellWidth = CGFloat(600)
// MARK: - Private Propreties
//
// ParagraphStyle's
private static let sectionHeaderParagraph = NSMutableParagraphStyle(
minLineHeight: headerLineSize, maxLineHeight: headerLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let subjectParagraph = NSMutableParagraphStyle(
minLineHeight: subjectLineSize, maxLineHeight: subjectLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let snippetParagraph = NSMutableParagraphStyle(
minLineHeight: snippetLineSize, maxLineHeight: snippetLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let headerTitleParagraph = NSMutableParagraphStyle(
minLineHeight: blockLineSize, lineBreakMode: .ByTruncatingTail, alignment: .Left
)
private static let blockParagraph = NSMutableParagraphStyle(
minLineHeight: blockLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let contentBlockParagraph = NSMutableParagraphStyle(
minLineHeight: contentBlockLineSize, lineBreakMode: .ByWordWrapping, alignment: .Left
)
private static let badgeParagraph = NSMutableParagraphStyle(
minLineHeight: blockLineSize, maxLineHeight: blockLineSize, lineBreakMode: .ByWordWrapping, alignment: .Center
)
// Colors
private static let sectionHeaderTextColor = UIColor(red: 0xA7/255.0, green: 0xBB/255.0, blue: 0xCA/255.0, alpha: 0xFF/255.0)
private static let subjectTextColor = WPStyleGuide.littleEddieGrey()
private static let subjectNoticonColor = noticonReadColor
private static let footerTextColor = WPStyleGuide.allTAllShadeGrey()
private static let blockNoticonColor = WPStyleGuide.allTAllShadeGrey()
private static let snippetColor = WPStyleGuide.allTAllShadeGrey()
private static let headerTitleContextColor = WPStyleGuide.allTAllShadeGrey()
// Fonts
private static let sectionHeaderFont = WPFontManager.openSansSemiBoldFontOfSize(headerFontSize)
private static let subjectRegularFont = WPFontManager.openSansRegularFontOfSize(subjectFontSize)
private static let subjectBoldFont = WPFontManager.openSansSemiBoldFontOfSize(subjectFontSize)
private static let subjectItalicsFont = WPFontManager.openSansItalicFontOfSize(subjectFontSize)
private static let subjectNoticonFont = UIFont(name: "Noticons", size: subjectNoticonSize)
private static let headerTitleRegularFont = blockRegularFont
private static let headerTitleItalicsFont = blockItalicsFont
private static let blockItalicsFont = WPFontManager.openSansItalicFontOfSize(blockFontSize)
private static let blockNoticonFont = subjectNoticonFont
}
}
| gpl-2.0 | 32e0c72539fb02509103953c2b648bfd | 64.570313 | 138 | 0.60056 | 6.687649 | false | false | false | false |
jwzhuang/KanManHua | KanManHua/IKanMan.swift | 1 | 4005 | //
// IKanMan.swift
// KanManHua
//
// Created by JingWen on 2016/12/7.
// Copyright © 2016年 JingWen. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import MagicalRecord
class IKanMan: BaseWebProtocol {
var RegexContentsURL:String = "(http:\\/\\/\\D+\\d+.)"
var RegexTitle: String = "book-title.+<h1>(.+)<\\/h1>"
var RegexImage: String = "<img src=\"(.+?)\".+\\/>"
var RegexChapter:String = "<h2>\\D*([0-9]+)\\D+<\\/h2>"
var RegexUpdate:String = "<span class=\"text\">\\D+([0-9]+)\\D+<\\/span>"
static let sharedInstance = IKanMan()
private init(){}
func prevPage(_ webview: UIWebView) {
let script = "document.getElementById('prev').click()"
webview.stringByEvaluatingJavaScript(from: script)
}
func prevChapter(_ webview: UIWebView) {
let script = "document.getElementsByClassName('prevC')[0].click()"
webview.stringByEvaluatingJavaScript(from: script)
}
func nextPage(_ webview:UIWebView){
let script = "document.getElementById('next').click()"
webview.stringByEvaluatingJavaScript(from: script)
}
func nextChapter(_ webview:UIWebView){
let script = "document.getElementsByClassName('nextC')[0].click()"
webview.stringByEvaluatingJavaScript(from: script)
}
func addNewManHua(_ url: String, completionHandler: @escaping (Bool) -> Void) {
Alamofire.request(url).responseString { response in
if response.result.isFailure{
completionHandler(false)
return
}
if let result = response.result.value{
let title = RegexHtml.regex(htmlSrc: result, pattern: self.RegexTitle)
let image = RegexHtml.regex(htmlSrc: result, pattern: self.RegexImage)
MagicalRecord.save({ (localContext) in
let manhua = ManHua.mr_findFirstOrCreate(byAttribute: "url", withValue: url, in: localContext)
manhua.title = title
manhua.url = url
manhua.image = image
manhua.prepare = true
}, completion: { (success, error) in
self.tagNew()
completionHandler(true)
})
}
}
}
func analyzeURL(_ url:String?) -> String?{
if let url = url {
var fixed = RegexHtml.regex(htmlSrc: url, pattern: self.RegexContentsURL)
if fixed.hasPrefix("http://m.ikanman.com") {
fixed = fixed.replace(target: "http://m.ikanman.com", withString: "http://tw.ikanman.com")
}
if fixed.hasPrefix("http://www.ikanman.com") {
fixed = fixed.replace(target: "http://www.ikanman.com", withString: "http://tw.ikanman.com")
}
return fixed
}
return nil
}
func tagNew(){
if let defaults = UserDefaults.init(suiteName: "group.kanmanhua.app"){
defaults.set(true, forKey: "newData")
defaults.synchronize()
}
}
func checkManHuaUpdate(_ url:String, completionHandler: @escaping (_ updateChapter:Int) -> Void){
Alamofire.request(url).responseString { response in
if response.result.isFailure{
completionHandler(-1)
return
}
if let result = response.result.value{
let update = RegexHtml.regex(htmlSrc: result, pattern: self.RegexUpdate)
MagicalRecord.save({ (localContext) in
let manhua = ManHua.mr_findFirstOrCreate(byAttribute: "url", withValue: url, in: localContext)
manhua.update = Int16(update)! > manhua.chapter
}, completion: { (success, error) in
completionHandler(1)
})
}
}
}
}
| mit | 4d4955b00c8d81e2b0de6302fa4fbbde | 35.381818 | 114 | 0.556972 | 4.578947 | false | false | false | false |
myoungsc/SCPageControl | SCPageControl/Classes/SCP_SCJAFlatBar.swift | 1 | 3021 | //
// SCP_SCFlatBar.swift
// Pods
//
// Created by Myoung on 2017. 5. 2..
//
//
import UIKit
class SCP_SCJAFlatBar: UIView {
var numberOfPage: Int = 0, currentOfPage: Int = 0
var f_start_point: CGFloat = 0.0, f_last_x: CGFloat = 0.0
let img_move = UIImageView()
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)!
}
override init(frame:CGRect) {
super.init(frame:frame)
}
override func layoutSubviews() {
super.layoutSubviews()
}
// ## view init method ##
func set_view(_ page: Int, current: Int, current_color: UIColor) {
numberOfPage = page
currentOfPage = current
let f_all_width: CGFloat = CGFloat(numberOfPage*20)
guard f_all_width < self.frame.size.width else {
print("frame.Width over Number Of Page")
return
}
let f_width: CGFloat = 15.0, f_height: CGFloat = 3.0
var f_x: CGFloat = ((self.frame.size.width-f_all_width)/2.0) - (f_width/2.0)
var f_y: CGFloat = (self.frame.size.height-f_height)/2.0, f_move_x: CGFloat = 0.0
f_start_point = f_x
for i in 0 ..< numberOfPage {
let img_page = UIImageView(frame: CGRect(x: f_x, y: f_y, width: f_width, height: f_height))
img_page.backgroundColor = current_color
img_page.alpha = 0.2
img_page.layer.cornerRadius = img_page.frame.size.height/2.0
img_page.tag = i+10
self.addSubview(img_page)
if i == current {
f_move_x = img_page.frame.origin.x + 11
}
f_x += f_width + 5
}
f_last_x = f_move_x
img_move.frame = CGRect(x: f_move_x, y: f_y, width: f_width, height: f_height)
img_move.backgroundColor = current_color
img_move.layer.cornerRadius = img_move.frame.size.height/2.0
img_move.tag = 5
self.addSubview(img_move)
}
// ## Call the move page in scrollView ##
func scroll_did(_ scrollView: UIScrollView) {
let f_move_x: CGFloat = (20*(scrollView.contentOffset.x/scrollView.frame.size.width))
img_move.frame.origin.x = f_start_point + f_move_x
f_last_x = img_move.frame.origin.x
}
// ## Call the moment in rotate Device ##
func set_rotateDevice(_ frame: CGRect) {
self.frame = frame
let f_width: CGFloat = CGFloat(numberOfPage*20) - 7.5
var f_x: CGFloat = (self.frame.size.width-f_width)/2.0
f_start_point = f_x
for subview in self.subviews {
if subview.isKind(of: UIImageView.classForCoder()) {
if subview.tag != 5 {
subview.frame.origin.x = f_x
f_x += subview.frame.size.width + 5
}
}
}
img_move.frame.origin.x = f_start_point
}
}
| mit | b9ccd3aae20939ee8d83d1fc0e8831d6 | 29.21 | 103 | 0.534922 | 3.596429 | false | false | false | false |
wangyuanou/Coastline | Coastline/UI/View+Transition.swift | 1 | 17898 | //
// View+Transition.swift
// Coastline
//
// Created by 王渊鸥 on 2017/5/13.
// Copyright © 2017年 王渊鸥. All rights reserved.
//
import UIKit
class TransContainer : NSObject {
enum AnimationType {
case presentLeft
case dismissLeft
case presentRight
case dismissRight
case presentTop
case dismissTop
case presentBottom
case dismissBottom
case presentScale
case dismissScale
case presentBottomScale
case dismissBottomScale
case presentPop
case dismissPop
}
var timeout:TimeInterval = 0.2
var type:AnimationType = .presentLeft
var scale:(view:UIView, frame:CGRect)?
var scaleBottom:(scale:CGFloat, height:CGFloat)?
var scaleMiddle:(constraint:NSLayoutConstraint, height:CGFloat)?
var popScale:(scale:CGFloat, color:UIColor)?
init(_ t:AnimationType, duration:TimeInterval) {
type = t
timeout = duration
}
init(_ t:AnimationType, duration:TimeInterval, scale s:(view:UIView, frame:CGRect)) {
type = t
timeout = duration
scale = s
}
init(_ t:AnimationType, duration:TimeInterval, scaleBottom s:(scale:CGFloat, height:CGFloat)) {
type = t
timeout = duration
scaleBottom = s
}
init(_ t:AnimationType, duration:TimeInterval, popScale s:(scale:CGFloat, color:UIColor)) {
type = t
timeout = duration
popScale = s
}
private func itemsFromContext(context:UIViewControllerContextTransitioning) -> (from:UIViewController, to:UIViewController, container:UIView)? {
guard let from = context.viewController(forKey: UITransitionContextViewControllerKey.from), let to = context.viewController(forKey: UITransitionContextViewControllerKey.to) else { return nil }
let container = context.containerView
container.addSubview(to.view)
return (from, to, container)
}
func animationPresentLeft(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.to.view.frame = items.container.bounds.outside(.minXEdge, width: items.container.bounds.width)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.to.view.frame = items.container.bounds
}) { (finish) in
items.from.view.isUserInteractionEnabled = true
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationDismissLeft(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.container.bringSubview(toFront: items.from.view)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.from.view.frame = items.container.bounds.outside(.minXEdge, width: items.container.bounds.width)
}) { (finish) in
items.from.view.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationPresentRight(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.to.view.frame = items.container.bounds.outside(.maxXEdge, width: items.container.bounds.width)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.to.view.frame = items.container.bounds
}) { (finish) in
items.from.view.isUserInteractionEnabled = true
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationDismissRight(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.container.bringSubview(toFront: items.from.view)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.from.view.frame = items.container.bounds.outside(.maxXEdge, width: items.container.bounds.width)
}) { (finish) in
items.from.view.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationPresentTop(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.to.view.frame = items.container.bounds.outside(.minYEdge, width: items.container.bounds.height)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.to.view.frame = items.container.bounds
}) { (finish) in
items.from.view.isUserInteractionEnabled = true
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationDismissTop(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.container.bringSubview(toFront: items.from.view)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.from.view.frame = items.container.bounds.outside(.minYEdge, width: items.container.bounds.height)
}) { (finish) in
items.from.view.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationPresentBottom(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.to.view.frame = items.container.bounds.outside(.maxYEdge, width: items.container.bounds.height)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.to.view.frame = items.container.bounds
}) { (finish) in
items.from.view.isUserInteractionEnabled = true
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationDismissBottom(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.container.bringSubview(toFront: items.from.view)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.from.view.frame = items.container.bounds.outside(.maxYEdge, width: items.container.bounds.height)
}) { (finish) in
items.from.view.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationPresentScale(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context), let scale = scale else { return }
items.from.view.isUserInteractionEnabled = false
items.to.view.isHidden = true
let originFrame = scale.view.frame
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
scale.view.frame = scale.frame
}) { (finish) in
items.from.view.isUserInteractionEnabled = true
items.to.view.isHidden = false
scale.view.frame = originFrame
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationDismissScale(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context), let scale = scale else { return }
let originFrame = scale.view.frame
scale.view.frame = scale.frame
items.from.view.isHidden = true
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
scale.view.frame = originFrame
}) { (finish) in
items.from.view.removeFromSuperview()
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationPresentBottomScale(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context), let scaleBottom = scaleBottom else { return }
items.from.view.isUserInteractionEnabled = false
items.to.view.frame = items.container.bounds.outside(.maxYEdge, width: items.container.bounds.height)
UIView.animate(withDuration: transitionDuration(using: context),
delay: 0,
usingSpringWithDamping: 0.55,
initialSpringVelocity: 1 / 0.88,
options: [],
animations: {
items.from.view.transform = CGAffineTransform(scaleX: scaleBottom.scale, y: scaleBottom.scale)
items.to.view.frame = items.container.bounds.inside(.maxYEdge, width: scaleBottom.height)
}) { (finish) in
context.completeTransition(!context.transitionWasCancelled)
items.container.insertSubview(items.from.view, belowSubview: items.to.view)
}
}
func animationDismissBottomScale(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.container.bringSubview(toFront: items.from.view)
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.to.view.transform = CGAffineTransform.identity
items.from.view.frame = items.container.bounds.outside(.maxYEdge, width: items.container.bounds.height)
}) { (finish) in
items.from.view.removeFromSuperview()
items.to.view.isUserInteractionEnabled = true
context.completeTransition(!context.transitionWasCancelled)
}
}
func animationPresentPop(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context), let popScale = popScale else { return }
let b = UIView(frame: items.container.bounds)
b.backgroundColor = popScale.color
b.tag = 50223
items.container.insertSubview(b, belowSubview: items.to.view)
items.from.view.isUserInteractionEnabled = false
// items.to.view.frame = CGRect(center:items.container.center, size:CGSize(width:items.container.bounds.width * popScale.scale * 0.8, height:items.container.bounds.height * popScale.scale * 0.8))
items.to.view.transform = CGAffineTransform(scaleX: popScale.scale * 0.8, y: popScale.scale * 0.8)
UIView.animate(withDuration: transitionDuration(using: context),
delay: 0,
usingSpringWithDamping: 0.55,
initialSpringVelocity: 1 / 0.88,
options: [],
animations: {
items.to.view.transform = CGAffineTransform(scaleX: popScale.scale, y: popScale.scale)
}) { (finish) in
context.completeTransition(!context.transitionWasCancelled)
items.container.insertSubview(items.from.view, belowSubview: b)
items.to.view.transform = CGAffineTransform.identity
items.to.view.frame = CGRect(center:items.container.center, size:CGSize(width:items.container.bounds.width * popScale.scale, height:items.container.bounds.height * popScale.scale))
}
}
func animationDismissPop(context:UIViewControllerContextTransitioning) {
guard let items = itemsFromContext(context: context) else { return }
items.from.view.isUserInteractionEnabled = false
items.container.bringSubview(toFront: items.from.view)
let originFrame = items.to.view.frame
UIView.animate(withDuration: transitionDuration(using: context),
animations: {
items.from.view.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
}) { (finish) in
items.from.view.removeFromSuperview()
items.to.view.isUserInteractionEnabled = true
if let v = items.container.viewWithTag(50223) {
v.removeFromSuperview()
}
context.completeTransition(!context.transitionWasCancelled)
items.to.view.frame = originFrame
}
}
}
extension TransContainer : UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return timeout
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
switch type {
case .presentLeft:
animationPresentLeft(context: transitionContext)
case .dismissLeft:
animationDismissLeft(context: transitionContext)
case .presentRight:
animationPresentRight(context: transitionContext)
case .dismissRight:
animationDismissRight(context: transitionContext)
case .presentTop:
animationPresentTop(context: transitionContext)
case .dismissTop:
animationDismissTop(context: transitionContext)
case .presentBottom:
animationPresentBottom(context: transitionContext)
case .dismissBottom:
animationDismissBottom(context: transitionContext)
case .presentScale:
animationPresentScale(context: transitionContext)
case .dismissScale:
animationDismissScale(context: transitionContext)
case .presentBottomScale:
animationPresentBottomScale(context: transitionContext)
case .dismissBottomScale:
animationDismissBottomScale(context: transitionContext)
case .presentPop:
animationPresentPop(context: transitionContext)
case .dismissPop:
animationDismissPop(context: transitionContext)
}
}
}
public class CLTransLeftDelegate : NSObject {
var duration:TimeInterval
public init(duration d:TimeInterval) {
duration = d
}
}
extension CLTransLeftDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentLeft, duration: duration)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissLeft, duration: duration)
}
}
public class CLTransRightDelegate : NSObject {
var duration:TimeInterval
public init(duration d:TimeInterval) {
duration = d
}
}
extension CLTransRightDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentRight, duration: duration)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissRight, duration: duration)
}
}
public class CLTransTopDelegate : NSObject {
var duration:TimeInterval
public init(duration d:TimeInterval) {
duration = d
}
}
extension CLTransTopDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentTop, duration: duration)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissTop, duration: duration)
}
}
public class CLTransBottomDelegate : NSObject {
var duration:TimeInterval
public init(duration d:TimeInterval) {
duration = d
}
}
extension CLTransBottomDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentBottom, duration: duration)
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissBottom, duration: duration)
}
}
public class CLTransScaleDelegate : NSObject {
var duration:TimeInterval
public var view:UIView
var frame:CGRect
public init(duration d:TimeInterval, view v:UIView, frame f:CGRect) {
duration = d
view = v
frame = f
}
}
extension CLTransScaleDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentScale, duration: duration, scale: (view, frame))
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissScale, duration: duration, scale: (view, frame))
}
}
public class CLTransBottomScaleDelegate : NSObject {
var duration:TimeInterval
var scale:CGFloat
var height:CGFloat
public init(duration d:TimeInterval, scale s:CGFloat, height h:CGFloat) {
duration = d
scale = s
height = h
}
}
extension CLTransBottomScaleDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentBottomScale, duration: duration, scaleBottom: (scale, height))
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissBottomScale, duration: duration, scaleBottom: (scale, height))
}
}
public class CLTransPopDelegate : NSObject {
var duration:TimeInterval
var scale:CGFloat
var color:UIColor
public init(duration d:TimeInterval, scale s:CGFloat, color c:UIColor) {
duration = d
scale = s
color = c
}
}
extension CLTransPopDelegate : UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.presentPop, duration: duration, popScale: (scale, color))
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransContainer(.dismissPop, duration: duration, popScale: (scale, color))
}
}
| mit | 8dd7cee1a31dbf0c3f4af4cbc9e89380 | 35.720739 | 198 | 0.762959 | 4.51705 | false | false | false | false |
eytanbiala/On-The-Map | On The Map/UdacityClient.swift | 1 | 6124 | //
// UdacityClient.swift
// On The Map
//
// Created by Eytan Biala on 4/27/16.
// Copyright © 2016 Udacity. All rights reserved.
//
import Foundation
import UIKit
typealias UdacityClientResult = (error: NSError?, result: Dictionary<String, AnyObject>?) -> (Void)
class UdacityClient : NSObject {
class func jsonFromResponseData(data: NSData) -> Dictionary<String, AnyObject>? {
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
return jsonObject as? Dictionary<String, AnyObject>
} catch let jsonError as NSError {
print(jsonError.localizedDescription)
}
return nil
}
class func udacityDataTaskWithCompletion(request: NSURLRequest, completion: UdacityClientResult?) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
guard error == nil else {
dispatch_async(dispatch_get_main_queue(), {
completion?(error: error, result: nil)
})
return
}
/* subset response data! */
let json = jsonFromResponseData(data!.subdataWithRange(NSMakeRange(5, data!.length - 5)))
print(json)
dispatch_async(dispatch_get_main_queue(), {
completion?(error: error, result: json)
})
}
task.resume()
}
class func parseDataTask(request: NSURLRequest, completion: UdacityClientResult?) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
guard error == nil else {
dispatch_async(dispatch_get_main_queue(), {
completion?(error: error, result: nil)
})
return
}
let json = jsonFromResponseData(data!)
print(json)
dispatch_async(dispatch_get_main_queue(), {
completion?(error: error, result: json)
})
}
task.resume()
}
class func login(username: String, password: String, completion: UdacityClientResult?) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/session")!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let bodyDict = ["udacity": ["username": "\(username)", "password": "\(password)"]]
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: NSJSONWritingOptions.init(rawValue: 0))
} catch let jsonError as NSError {
dispatch_async(dispatch_get_main_queue(), {
completion?(error: jsonError, result: nil)
})
return
}
udacityDataTaskWithCompletion(request, completion: completion)
}
class func logout(completion: UdacityClientResult?) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/session")!)
request.HTTPMethod = "DELETE"
var xsrfCookie: NSHTTPCookie? = nil
let sharedCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in sharedCookieStorage.cookies! {
if cookie.name == "XSRF-TOKEN" { xsrfCookie = cookie }
}
if let xsrfCookie = xsrfCookie {
request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN")
}
udacityDataTaskWithCompletion(request, completion: completion)
}
class func getUserData(userId: String, completion: UdacityClientResult?) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://www.udacity.com/api/users/\(userId)")!)
udacityDataTaskWithCompletion(request, completion: completion)
}
class func getStudentLocations(completion: UdacityClientResult?) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.parse.com/1/classes/StudentLocation?limit=100&order=-updatedAt")!)
request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
parseDataTask(request, completion: completion)
}
class func addStudentLocation(userId: String, firstName: String, lastName: String, mapString: String, url: String, latitude: Double, longitude: Double, completion: UdacityClientResult?) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.parse.com/1/classes/StudentLocation")!)
request.HTTPMethod = "POST"
request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id")
request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let bodyDict = ["uniqueKey": "\(userId)",
"firstName": "\(firstName)",
"lastName": "\(lastName)",
"mapString": "\(mapString)",
"mediaURL": "\(url)",
"latitude": latitude,
"longitude": longitude
]
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(bodyDict, options: NSJSONWritingOptions.init(rawValue: 0))
} catch let jsonError as NSError {
dispatch_async(dispatch_get_main_queue(), {
completion?(error: jsonError, result: nil)
})
return
}
parseDataTask(request, completion: completion)
}
} | mit | da05f2bedae9bcbffc94996e92088d46 | 40.659864 | 191 | 0.633186 | 4.798589 | false | false | false | false |
guowilling/iOSExamples | Swift/Socket/protobuf-swift-master/Source/ExtendableMessage.swift | 12 | 18282 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
typealias ExtensionsValueType = Hashable & Equatable
open class ExtendableMessage : GeneratedMessage
{
fileprivate var extensionMap:[Int32:Any] = [Int32:Any]()
public var extensionRegistry:[Int32:ConcreateExtensionField] = [Int32:ConcreateExtensionField]()
required public init()
{
super.init()
}
//Override
override open class func className() -> String
{
return "ExtendableMessage"
}
override open func className() -> String
{
return "ExtendableMessage"
}
//
public func isInitialized(object:Any) -> Bool
{
switch object
{
case let array as Array<Any>:
for child in array
{
if (!isInitialized(object: child))
{
return false
}
}
case let array as Array<GeneratedMessage>:
for child in array
{
if (!isInitialized(object: child))
{
return false
}
}
case let message as GeneratedMessage:
return message.isInitialized()
default:
return true
}
return true
}
open func extensionsAreInitialized() -> Bool {
let arr = Array(extensionMap.values)
return isInitialized(object:arr)
}
internal func ensureExtensionIsRegistered(extensions:ConcreateExtensionField)
{
extensionRegistry[extensions.fieldNumber] = extensions
}
public func getExtension(extensions:ConcreateExtensionField) -> Any? {
ensureExtensionIsRegistered(extensions: extensions)
if let value = extensionMap[extensions.fieldNumber] {
return value
}
return extensions.defaultValue
}
public func hasExtension(extensions:ConcreateExtensionField) -> Bool
{
guard (extensionMap[extensions.fieldNumber] != nil) else
{
return false
}
return true
}
public func writeExtensionsTo(codedOutputStream:CodedOutputStream, startInclusive:Int32, endExclusive:Int32) throws
{
var keys = Array(extensionMap.keys)
keys.sort(by: { $0 < $1 })
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let extensions = extensionRegistry[fieldNumber]!
let value = extensionMap[fieldNumber]!
try extensions.writeValueIncludingTagToCodedOutputStream(value: value, output: codedOutputStream)
}
}
}
public func getExtensionDescription(startInclusive:Int32 ,endExclusive:Int32, indent:String) throws -> String {
var output = ""
var keys = Array(extensionMap.keys)
keys.sort(by: { $0 < $1 })
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let extensions = extensionRegistry[fieldNumber]!
let value = extensionMap[fieldNumber]!
output += try extensions.getDescription(value: value, indent: indent)
}
}
return output
}
public func isEqualExtensionsInOther(otherMessage:ExtendableMessage, startInclusive:Int32, endExclusive:Int32) -> Bool {
var keys = Array(extensionMap.keys)
keys.sort(by: { $0 < $1 })
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let value = extensionMap[fieldNumber]!
let otherValue = otherMessage.extensionMap[fieldNumber]!
return compare(lhs: value, rhs: otherValue)
}
}
return true
}
private func compare(lhs:Any, rhs:Any) -> Bool
{
switch (lhs,rhs)
{
case (let value as Int32, let value2 as Int32):
return value == value2
case (let value as Int64, let value2 as Int64):
return value == value2
case (let value as Double, let value2 as Double):
return value == value2
case (let value as Float, let value2 as Float):
return value == value2
case (let value as Bool, let value2 as Bool):
return value == value2
case (let value as String, let value2 as String):
return value == value2
case (let value as Data, let value2 as Data):
return value == value2
case (let value as UInt32, let value2 as UInt32):
return value == value2
case (let value as UInt64, let value2 as UInt64):
return value == value2
case (let value as GeneratedMessage, let value2 as GeneratedMessage):
return value == value2
case (let value as [Int32], let value2 as [Int32]):
return value == value2
case (let value as [Int64], let value2 as [Int64]):
return value == value2
case (let value as [Double], let value2 as [Double]):
return value == value2
case (let value as [Float], let value2 as [Float]):
return value == value2
case (let value as [Bool], let value2 as [Bool]):
return value == value2
case (let value as [String], let value2 as [String]):
return value == value2
case (let value as Array<Data>, let value2 as Array<Data>):
return value == value2
case (let value as [UInt32], let value2 as [UInt32]):
return value == value2
case (let value as [UInt64], let value2 as [UInt64]):
return value == value2
case (let value as [GeneratedMessage], let value2 as [GeneratedMessage]):
return value == value2
default:
return false
}
}
private func getHash<T>(lhs:T) -> Int!
{
switch lhs
{
case let value as Int32:
return getHashValue(lhs: value)
case let value as Int64:
return getHashValue(lhs: value)
case let value as UInt32:
return getHashValue(lhs: value)
case let value as UInt64:
return getHashValue(lhs: value)
case let value as Float:
return getHashValue(lhs: value)
case let value as Double:
return getHashValue(lhs: value)
case let value as Bool:
return getHashValue(lhs: value)
case let value as String:
return getHashValue(lhs: value)
case let value as GeneratedMessage:
return getHashValue(lhs: value)
case let value as Data:
return value.hashValue
case let value as [Int32]:
return getHashValueRepeated(lhs: value)
case let value as [Int64]:
return getHashValueRepeated(lhs: value)
case let value as [UInt32]:
return getHashValueRepeated(lhs: value)
case let value as [UInt64]:
return getHashValueRepeated(lhs: value)
case let value as [Float]:
return getHashValueRepeated(lhs: value)
case let value as [Double]:
return getHashValueRepeated(lhs: value)
case let value as [Bool]:
return getHashValueRepeated(lhs: value)
case let value as [String]:
return getHashValueRepeated(lhs: value)
case let value as Array<Data>:
return getHashValueRepeated(lhs: value)
case let value as [GeneratedMessage]:
return getHashValueRepeated(lhs: value)
default:
return nil
}
}
private func getHashValueRepeated<T>(lhs:T) -> Int! where T:Collection, T.Iterator.Element:Hashable & Equatable
{
var hashCode:Int = 0
for vv in lhs
{
hashCode = (hashCode &* 31) &+ vv.hashValue
}
return hashCode
}
private func getHashValue<T>(lhs:T) -> Int! where T:Hashable & Equatable
{
return lhs.hashValue
}
public func hashExtensionsFrom(startInclusive:Int32, endExclusive:Int32) -> Int {
var hashCode:Int = 0
var keys = Array(extensionMap.keys)
keys.sort(by: { $0 < $1 })
for fieldNumber in keys {
if (fieldNumber >= startInclusive && fieldNumber < endExclusive) {
let value = extensionMap[fieldNumber]!
hashCode = (hashCode &* 31) &+ getHash(lhs: value)!
}
}
return hashCode
}
public func extensionsSerializedSize() ->Int32 {
var size:Int32 = 0
for fieldNumber in extensionMap.keys {
let extensions = extensionRegistry[fieldNumber]!
let value = extensionMap[fieldNumber]!
size += extensions.computeSerializedSizeIncludingTag(value: value)
}
return size
}
}
open class ExtendableMessageBuilder:GeneratedMessageBuilder
{
override open var internalGetResult:ExtendableMessage {
get
{
return ExtendableMessage()
}
}
override open func checkInitialized() throws
{
let result = internalGetResult
if (!result.isInitialized())
{
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
}
override open func checkInitializedParsed() throws
{
let result = internalGetResult
if (!result.isInitialized())
{
throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message")
}
}
override open func isInitialized() -> Bool
{
return internalGetResult.isInitialized()
}
@discardableResult
override open func merge(unknownField: UnknownFieldSet) throws -> Self
{
let result:GeneratedMessage = internalGetResult
result.unknownFields = try UnknownFieldSet.builderWithUnknownFields(copyFrom: result.unknownFields).merge(unknownFields: unknownField).build()
return self
}
override public func parse(codedInputStream:CodedInputStream ,unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, tag:Int32) throws -> Bool {
let message = internalGetResult
let wireType = WireFormat.getTagWireType(tag: tag)
let fieldNumber:Int32 = WireFormat.getTagFieldNumber(tag: tag)
let extensions = extensionRegistry.getExtension(clName: type(of: message), fieldNumber: fieldNumber)
if extensions != nil {
if extensions!.wireType.rawValue == wireType {
try extensions!.mergeFrom(codedInputStream: codedInputStream, unknownFields:unknownFields, extensionRegistry:extensionRegistry, builder:self, tag:tag)
return true
}
}
return try super.parse(codedInputStream: codedInputStream, unknownFields: unknownFields, extensionRegistry: extensionRegistry, tag: tag)
}
public func getExtension(extensions:ConcreateExtensionField) -> Any? {
return internalGetResult.getExtension(extensions: extensions)
}
public func hasExtension(extensions:ConcreateExtensionField) -> Bool {
return internalGetResult.hasExtension(extensions: extensions)
}
@discardableResult
public func setExtension(extensions:ConcreateExtensionField, value:Any) throws -> Self {
let message = internalGetResult
message.ensureExtensionIsRegistered(extensions: extensions)
guard !extensions.isRepeated else {
throw ProtocolBuffersError.illegalArgument("Must call addExtension() for repeated types.")
}
message.extensionMap[extensions.fieldNumber] = value
return self
}
@discardableResult
public func addExtension<T>(extensions:ConcreateExtensionField, value:T) throws -> ExtendableMessageBuilder {
let message = internalGetResult
message.ensureExtensionIsRegistered(extensions: extensions)
guard extensions.isRepeated else
{
throw ProtocolBuffersError.illegalArgument("Must call addExtension() for repeated types.")
}
let fieldNumber = extensions.fieldNumber
if let val = value as? GeneratedMessage
{
var list:[GeneratedMessage]! = message.extensionMap[fieldNumber] as? [GeneratedMessage] ?? []
list.append(val)
message.extensionMap[fieldNumber] = list
}
else
{
var list:[T]! = message.extensionMap[fieldNumber] as? [T] ?? []
list.append(value)
message.extensionMap[fieldNumber] = list
}
return self
}
@discardableResult
public func setExtension<T>(extensions:ConcreateExtensionField, index:Int32, value:T) throws -> Self {
let message = internalGetResult
message.ensureExtensionIsRegistered(extensions: extensions)
guard extensions.isRepeated else {
throw ProtocolBuffersError.illegalArgument("Must call setExtension() for singular types.")
}
let fieldNumber = extensions.fieldNumber
if let val = value as? GeneratedMessage
{
var list:[GeneratedMessage]! = message.extensionMap[fieldNumber] as? [GeneratedMessage] ?? []
list[Int(index)] = val
message.extensionMap[fieldNumber] = list
}
else
{
var list:[T]! = message.extensionMap[fieldNumber] as? [T] ?? []
list[Int(index)] = value
message.extensionMap[fieldNumber] = list
}
return self
}
@discardableResult
public func clearExtension(extensions:ConcreateExtensionField) -> Self {
let message = internalGetResult
message.ensureExtensionIsRegistered(extensions: extensions)
message.extensionMap.removeValue(forKey: extensions.fieldNumber)
return self
}
private func mergeRepeatedExtensionFields<T>(otherList:T, extensionMap:[Int32:Any], fieldNumber:Int32) -> [T.Iterator.Element] where T:Collection
{
var list:[T.Iterator.Element]! = extensionMap[fieldNumber] as? [T.Iterator.Element] ?? []
list! += otherList
return list!
}
public func mergeExtensionFields(other:ExtendableMessage) throws {
let thisMessage = internalGetResult
guard thisMessage.className() == other.className() else {
throw ProtocolBuffersError.illegalArgument("Cannot merge extensions from a different type")
}
if other.extensionMap.count > 0 {
var registry = other.extensionRegistry
for fieldNumber in other.extensionMap.keys {
let thisField = registry[fieldNumber]!
let value = other.extensionMap[fieldNumber]!
if thisField.isRepeated {
switch value
{
case let values as [Int32]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Int64]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [UInt64]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [UInt32]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Bool]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Float]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [Double]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [String]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as Array<Data>:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
case let values as [GeneratedMessage]:
thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber)
default:
break
}
}
else
{
thisMessage.extensionMap[fieldNumber] = value
}
}
}
}
}
| mit | 321eb44b5ee6bf39b36ccc45129aeecd | 37.897872 | 177 | 0.616508 | 5.518261 | false | false | false | false |
loudnate/xDripG5 | CGMBLEKit/Messages/TransmitterTimeRxMessage.swift | 1 | 833 | //
// TransmitterTimeRxMessage.swift
// xDrip5
//
// Created by Nathan Racklyeft on 11/23/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import Foundation
struct TransmitterTimeRxMessage: TransmitterRxMessage {
let status: UInt8
let currentTime: UInt32
let sessionStartTime: UInt32
init?(data: Data) {
guard data.count == 16 && data.isCRCValid else {
return nil
}
guard data.starts(with: .transmitterTimeRx) else {
return nil
}
status = data[1]
currentTime = data[2..<6].toInt()
sessionStartTime = data[6..<10].toInt()
}
}
extension TransmitterTimeRxMessage: Equatable { }
func ==(lhs: TransmitterTimeRxMessage, rhs: TransmitterTimeRxMessage) -> Bool {
return lhs.currentTime == rhs.currentTime
}
| mit | d22e87a3bab5495a6225edc36c5165c2 | 22.111111 | 79 | 0.649038 | 4.20202 | false | false | false | false |
sammyd/Concurrency-VideoSeries | prototyping/GCD.playground/Pages/Groups.xcplaygroundpage/Contents.swift | 1 | 3136 | //: [Previous](@previous)
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let workerQueue = dispatch_queue_create("com.raywenderlich.worker", DISPATCH_QUEUE_CONCURRENT)
func asyncSum(input: (Int, Int), queue: dispatch_queue_t, completion: (Int) -> ()) {
dispatch_async(workerQueue) {
let result = slowSum(input.0, rhs: input.1)
dispatch_async(queue) {
completion(result)
}
}
}
let numberArray = [(0,1), (2,3), (4,5), (6,7), (8,9)]
let firstGroup = dispatch_group_create()
for inValue in numberArray {
dispatch_group_async(firstGroup, workerQueue) {
let result = slowSum(inValue.0, rhs: inValue.1)
//dispatch_group_async(firstGroup, dispatch_get_main_queue()) {
print("Result = \(result)")
//}
}
}
dispatch_group_notify(firstGroup, dispatch_get_main_queue()) {
print("Completed all operations in group")
}
// DANGER of synchronous dispatch
dispatch_group_wait(firstGroup, DISPATCH_TIME_FOREVER)
print("===Starting next group")
let secondGroup = dispatch_group_create()
//: Wrapping an existing API
func asyncSum(input: (Int, Int), queue: dispatch_queue_t, group: dispatch_group_t, completion: (Int) -> ()) {
dispatch_group_enter(group)
asyncSum(input, queue: queue) {
completion($0)
dispatch_group_leave(group)
}
}
for pair in numberArray {
asyncSum(pair, queue: workerQueue, group: secondGroup) {
print("Result = \($0)")
}
}
dispatch_group_notify(secondGroup, dispatch_get_main_queue()) {
print("Completed all operations in group")
}
//: Challenge: Wrap another async function
extension UIView {
static func animateWithDuration(duration: NSTimeInterval, animations: () -> Void, completionQueue: dispatch_queue_t, group: dispatch_group_t, completion: ((Bool) -> Void)?) {
dispatch_group_enter(group)
animateWithDuration(duration, animations: animations, completion: {
success in
dispatch_async(completionQueue) {
completion?(success)
dispatch_group_leave(group)
}
})
}
}
let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
view.backgroundColor = UIColor.redColor()
let box = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
box.backgroundColor = UIColor.yellowColor()
view.addSubview(box)
XCPlaygroundPage.currentPage.liveView = view
let animationGroup = dispatch_group_create()
UIView.animateWithDuration(1, animations: {
box.center = CGPoint(x: 180, y: 180)
}, completionQueue: dispatch_get_main_queue(), group: animationGroup) {
_ in
UIView.animateWithDuration(2, animations: {
box.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4))
}, completionQueue: dispatch_get_main_queue(), group: animationGroup, completion: nil)
}
UIView.animateWithDuration(4, animations: { () -> Void in
view.backgroundColor = UIColor.blueColor()
}, completionQueue: dispatch_get_main_queue(), group: animationGroup, completion: nil)
dispatch_group_notify(animationGroup, dispatch_get_main_queue()) {
print("Animations completed!")
XCPlaygroundPage.currentPage.finishExecution()
}
//: [Next](@next)
| mit | 93d14a41810ccc9387be799cb7db24e3 | 27.770642 | 176 | 0.705676 | 3.733333 | false | false | false | false |
getaccent/accent-ios | Accent/ArticleTextView.swift | 1 | 1668 | //
// ArticleTextView.swift
// Accent
//
// Created by Jack Cook on 4/9/16.
// Copyright © 2016 Tiny Pixels. All rights reserved.
//
import UIKit
class ArticleTextView: UITextView, UIGestureRecognizerDelegate {
private var articleDelegate: ArticleTextViewDelegate?
private var longPressRecognizer: UILongPressGestureRecognizer!
init(delegate: ArticleTextViewDelegate?) {
super.init(frame: CGRect.zero, textContainer: nil)
articleDelegate = delegate
longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
longPressRecognizer.delegate = self
addGestureRecognizer(longPressRecognizer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func longPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
guard let superview = superview?.superview else {
return
}
let point = gestureRecognizer.location(in: superview)
articleDelegate?.longTouchReceived(point, state: gestureRecognizer.state, text: (text as NSString).substring(with: selectedRange))
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return false
}
}
protocol ArticleTextViewDelegate {
func longTouchReceived(_ point: CGPoint, state: UIGestureRecognizerState, text: String)
}
| mit | 29182df5f24d6698dc601a544c180bcf | 32.34 | 157 | 0.70126 | 5.650847 | false | false | false | false |
sarvex/SwiftRecepies | Security/Storing Files Securely in the App Sandbox/Storing Files Securely in the App Sandbox/AppDelegate.swift | 1 | 2659 | //
// AppDelegate.swift
// Storing Files Securely in the App Sandbox
//
// Created by Vandad Nahavandipoor on 7/7/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var filePath: String?{
let fileManager = NSFileManager()
var error:NSError?
let documentFolderUrl = fileManager.URLForDirectory(.DocumentDirectory,
inDomain: .UserDomainMask,
appropriateForURL: nil,
create: true,
error: &error)
if error == nil && documentFolderUrl != nil{
let fileName = "MyFile.txt"
let filePath =
documentFolderUrl!.path!.stringByAppendingPathComponent(fileName)
return filePath
}
return nil
}
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
/*
Prerequisites:
1) Sign with a valid provision profile
2) Your profile has to have complete-file-protection enabled.
3) Add Code Signing Entitlements to your project
*/
let fileManager = NSFileManager()
if let path = filePath{
let dataToWrite = "Hello, World".dataUsingEncoding(
NSUTF8StringEncoding,
allowLossyConversion: false)
let fileAttributes = [
NSFileProtectionKey : NSFileProtectionComplete
]
let wrote = fileManager.createFileAtPath(path,
contents: dataToWrite,
attributes: fileAttributes)
if wrote{
println("Successfully and securely stored the file")
} else {
println("Failed to write the file")
}
}
return true
}
}
| isc | 989d432e7cfc3ab007b72ec4265b0f57 | 26.989474 | 83 | 0.645731 | 4.914972 | false | false | false | false |
0416354917/FeedMeIOS | FeedMeIOS/RetrievePasswordViewController.swift | 2 | 2410 | //
// RetrievePasswordViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 7/04/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class RetrievePasswordViewController: UIViewController {
@IBOutlet weak var phoneButton: UIButton!
@IBOutlet weak var emailButton: UIButton!
@IBOutlet weak var confirmButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayMessage(validationResult: (statusCode: Int, description: String)) {
let alert = UIAlertController(title: "Message", message: validationResult.description, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(okAction)
self.presentViewController(alert, animated: true, completion: nil)
}
@IBAction func phoneButtonClicked(sender: UIButton) {
}
@IBAction func emailButtonClicked(sender: UIButton) {
}
@IBAction func confirmButtonClicked(sender: UIButton) {
}
@IBAction func sendAgainButtonClicked(sender: UIButton) {
}
func sendVerificationCode(phone: String) {
// clear current input if any:
// MARK: TODO: HTTP POST.
// From the http response: get verification code and store in self.validVerificationCode.
// uncomment the statement below and put it into callback handler:
// self.confirmButton.userInteractionEnabled = true
}
func validateVerificationCode(verificationCode: String?) -> (statusCode: Int, description: String) {
var statusCode = 1
var description = ""
return (statusCode, description)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| bsd-3-clause | bfa771b08751aeed5b16d507f17293e2 | 28.740741 | 140 | 0.662516 | 5.317881 | false | false | false | false |
baottran/nSURE | nSURE/Activity.swift | 1 | 2437 | //
// Activity.swift
// nSURE
//
// Created by Bao Tran on 10/1/15.
// Copyright © 2015 Sprout Designs. All rights reserved.
//
import Foundation
class Activity: PFObject, PFSubclassing {
@NSManaged var completed: Bool
@NSManaged var estimatedTime: Int
@NSManaged var type: String
@NSManaged var lastActionTime: NSDate?
@NSManaged var timerIsOn: Bool
@NSManaged var elapsedTime: NSNumber?
// added items
@NSManaged var started: Bool
@NSManaged var repair: Repair?
var elapsedTimeInt: Int? {
if let elapsedTime = elapsedTime {
return Int(elapsedTime)
} else {
return nil
}
}
var elapsedTimeSecs: Int? {
get {
if let elapsedTime = elapsedTime {
return Int(elapsedTime)
} else {
return nil
}
}
}
var currentStatus: ActivityStatus {
get {
return .Idle
}
}
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
static func parseClassName() -> String {
return "Activity"
}
func getActivityStatus() -> String {
guard let lastActionTime = lastActionTime else {
return "Idle"
}
var currentElapsedTime = 0
if let elapsedTimeInt = elapsedTimeInt {
currentElapsedTime = elapsedTimeInt
}
if type == "DropOff" {
return "ON-TIME"
}
if timerIsOn == false {
if elapsedTimeInt > estimatedTime {
print("type for \(self.objectId) is \(type)")
return "OVERTIME"
} else {
return "ON-TIME"
}
} else {
let currentTime = NSDate()
let currentTimeDifference = -(lastActionTime.secondsFrom(currentTime))
currentElapsedTime = currentElapsedTime + currentTimeDifference
if currentElapsedTime > estimatedTime {
print("type for \(self.objectId) is \(type)")
return "OVERTIME"
} else {
return "ON-TIME"
}
}
}
} | mit | f670aa9ec14d90388b47ac2f313cfc5c | 23.128713 | 82 | 0.513547 | 5.25 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Telemetry/SearchTelemetry.swift | 2 | 4028 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import WebKit
import Glean
// Search Partner Codes
// https://docs.google.com/spreadsheets/d/1HMm9UXjfJv-uHhGU1pJlbP4ILkdpSD9w_Fd-3yOd8oY/
struct SearchPartner {
// Google partner code for US and ROW (rest of the world)
private static let google = ["US": "firefox-b-1-m",
"ROW": "firefox-b-m"]
static func getCode(searchEngine: SearchEngine, region: String) -> String {
switch searchEngine {
case .google:
return google[region] ?? "none"
case .none:
return "none"
}
}
}
// Our default search engines
enum SearchEngine: String, CaseIterable {
case google
case none
}
class SearchTelemetry {
var code: String = ""
var provider: SearchEngine = .none
var shouldSetGoogleTopSiteSearch = false
var shouldSetUrlTypeSearch = false
// MARK: Searchbar SAP
// sap: directly from search access point
func trackSAP() {
GleanMetrics.Search.inContent["\(provider).in-content.sap.\(code)"].add()
}
// sap-follow-on: user continues to search from an existing sap search
func trackSAPFollowOn() {
GleanMetrics.Search.inContent["\(provider).in-content.sap-follow-on.\(code)"].add()
}
// organic: search that didn't come from a SAP
func trackOrganic() {
GleanMetrics.Search.inContent["\(provider).organic.none"].add()
}
// MARK: Google Top Site SAP
// Note: This tracks google top site tile tap which opens a google search page
func trackGoogleTopSiteTap() {
GleanMetrics.Search.googleTopsitePressed["\(SearchEngine.google).\(code)"].add()
}
// Note: This tracks SAP follow-on search. Also, the first search that the user performs is considered
// a follow-on where OQ query item in google url is present but has no data in it
// Flow: User taps google top site tile -> google page opens -> user types item to search in the page
func trackGoogleTopSiteFollowOn() {
GleanMetrics.Search.inContent["\(SearchEngine.google).in-content.google-topsite-follow-on.\(code)"].add()
}
// MARK: Track Regular and Follow-on SAP from Tab and TopSite
func trackTabAndTopSiteSAP(_ tab: Tab, webView: WKWebView) {
let provider = tab.getProviderForUrl()
let code = SearchPartner.getCode(searchEngine: provider, region: Locale.current.regionCode == "US" ? "US" : "ROW")
self.code = code
self.provider = provider
if shouldSetGoogleTopSiteSearch {
tab.urlType = .googleTopSite
shouldSetGoogleTopSiteSearch = false
self.trackGoogleTopSiteTap()
} else if shouldSetUrlTypeSearch {
tab.urlType = .search
shouldSetUrlTypeSearch = false
self.trackSAP()
} else if let webUrl = webView.url {
let components = URLComponents(url: webUrl, resolvingAgainstBaseURL: false)!
let clientValue = components.valueForQuery("client")
let sClientValue = components.valueForQuery("sclient")
// Special case google followOn search
if (tab.urlType == .googleTopSite || tab.urlType == .googleTopSiteFollowOn) && clientValue == code {
tab.urlType = .googleTopSiteFollowOn
self.trackGoogleTopSiteFollowOn()
// Check if previous tab type is search
} else if (tab.urlType == .search || tab.urlType == .followOnSearch) && clientValue == code {
tab.urlType = .followOnSearch
self.trackSAPFollowOn()
} else if provider == .google && sClientValue != nil {
tab.urlType = .organicSearch
self.trackOrganic()
} else {
tab.urlType = .regular
}
}
}
}
| mpl-2.0 | 7461703e0cc097ba926749468281a0ff | 37.361905 | 122 | 0.635055 | 4.402186 | false | false | false | false |
malaonline/iOS | mala-ios/Model/StudyReport/SingleTimeIntervalData.swift | 1 | 1098 | //
// SingleTimeIntervalData.swift
// mala-ios
//
// Created by 王新宇 on 16/5/31.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class SingleTimeIntervalData: NSObject {
// MARK: - Property
/// 答题数量
var total_item: Int = 0
/// 错题数量
var error_item: Int = 0
/// 年份
var year: Int = 0
/// 月份
var month: Int = 0
/// 日期(为1/16,对应标记此数据是上旬/下旬)
var day: Int = 0
// 上下旬文字(上/下)
var periodString: String {
get {
return day == 1 ? "上" : "下"
}
}
// MARK: - Constructed
override init() {
super.init()
}
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
convenience init(totalItem: Int, errorItem: Int, year: Int, month: Int, day: Int) {
self.init()
self.total_item = totalItem
self.error_item = errorItem
self.year = year
self.month = month
self.day = day
}
}
| mit | 12c156d20ac40102e0d11e6fa57ae368 | 19.06 | 87 | 0.524427 | 3.377104 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/SearchResultLabelTests.swift | 1 | 3716 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
import SnapshotTesting
@testable import Wire
final class SearchResultLabelTests: ZMSnapshotTestCase {
var sut: SearchResultLabel!
override func setUp() {
super.setUp()
accentColor = .violet
}
override func tearDown() {
sut = nil
resetColorScheme()
super.tearDown()
}
fileprivate func performTest(file: StaticString = #file, line: UInt = #line) {
let textCombinations = Set<String>(arrayLiteral: "Very short text", "Very very long text Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
let queryCombinations = Set<String>(arrayLiteral: "", "Short", "Very", "very long", "veniam")
let firstMutation = { (proto: SearchResultLabel, value: String) -> SearchResultLabel in
let new = proto.copyInstance()
new.resultText = value
return new
}
let firstMutator = Mutator<SearchResultLabel, String>(applicator: firstMutation, combinations: textCombinations)
let secondMutation = { (proto: SearchResultLabel, value: String) -> SearchResultLabel in
let new = proto.copyInstance()
new.queries = value.components(separatedBy: .whitespaces)
return new
}
let secondMutator = Mutator<SearchResultLabel, String>(applicator: secondMutation, combinations: queryCombinations)
let combinator = CombinationTest(mutable: self.sut, mutators: [firstMutator, secondMutator])
XCTAssertEqual(combinator.testAll {
let identifier = "\($0.combinationChain)"
print("Testing combination " + identifier)
$0.result.configure(with: $0.result.resultText!, queries: $0.result.queries)
$0.result.numberOfLines = 1
$0.result.translatesAutoresizingMaskIntoConstraints = false
$0.result.setContentCompressionResistancePriority(.required, for: .vertical)
$0.result.setContentHuggingPriority(.required, for: .vertical)
$0.result.widthAnchor.constraint(lessThanOrEqualToConstant: 320).isActive = true
$0.result.layoutForTest()
let mockBackgroundView = UIView(frame: $0.result.frame)
mockBackgroundView.backgroundColor = .from(scheme: .background)
mockBackgroundView.addSubview($0.result)
self.verify(view: mockBackgroundView, identifier: identifier, file: #file, line: #line)
return .none
}.count, 0, line: #line)
}
func prepareForTest(variant: ColorSchemeVariant) {
ColorScheme.default.variant = variant
sut = SearchResultLabel()
sut.font = UIFont.systemFont(ofSize: 17)
}
func testThatItShowsStringWithoutHighlightInDarkTheme() {
prepareForTest(variant: .dark)
performTest()
}
func testThatItShowsStringWithoutHighlight() {
prepareForTest(variant: .light)
performTest()
}
}
| gpl-3.0 | 4de1f518967ea26480155905a3369774 | 36.16 | 220 | 0.676803 | 4.825974 | false | true | false | false |
yufdjsdfkhsdfsdw/- | 计算器/计算器/ViewController.swift | 1 | 1343 | //
// ViewController.swift
// 计算器
//
// Created by 上海海洋大学 on 17/3/23.
// Copyright © 2017年 上海海洋大学. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTyping = false
@IBAction func touchDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTyping {
let textCurrentlyInDisplay = display.text!
display.text = textCurrentlyInDisplay + digit
}else {
display.text = digit
userIsInTheMiddleOfTyping = true
}
}
var displayValue : Double{
get {
return Double(display.text!)!
}
set {
display.text = String(newValue)
}
}
private var brain: CalculatorBrain = CalculatorBrain()
@IBAction func performOperation(_ sender: UIButton) {
if userIsInTheMiddleOfTyping{
brain.setOperand(displayValue)
userIsInTheMiddleOfTyping = false
}
if let mathematicalSymbol = sender.currentTitle{
brain.performOperation(mathematicalSymbol)
}
if let result = brain.result{
displayValue = result
}
}
}
| mit | 8f3ad0658dd8baac534145c06098a1c3 | 21.586207 | 58 | 0.585496 | 5.24 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.