repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
elationfoundation/Reporta-iOS
|
refs/heads/master
|
IWMF/ViewControllers/HomeLoginViewController/SelectLanguageViewController.swift
|
gpl-3.0
|
1
|
//
// SelectLanguageViewController.swift
// IWMF
//
// This class is used for display and select Job Title.
//
//
import UIKit
protocol SelctedLanguageProtocol{
func jobTitleSelcted(selectedText : String)
func countryOfOrigin(selectedText : String, selectedCode : String)
func countryWhereWorking(selectedText : String, selectedCode : String)
}
enum TypeOfCell: Int{
case JobTitle = 1
case CountryOfOring = 2
case CountryWhereWorking = 3
}
class SelectLanguageViewController: UIViewController,UITableViewDataSource, UITableViewDelegate,PersonalDetailTextProtocol,ARPersonalDetailsTableView{
@IBOutlet weak var textSearchBG: UIImageView!
@IBOutlet weak var textSearch: UITextField!
@IBOutlet weak var btnBack: UIButton!
@IBOutlet weak var verticalSpaceTable: NSLayoutConstraint!
@IBOutlet weak var viewSearch: UIView!
@IBOutlet weak var btnDone: UIButton!
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var tableView: UITableView!
var selectLang : NSMutableArray!
var delegate : SelctedLanguageProtocol?
var selectedText : String!
var selectedCode : String!
var selectType : Int = 0
var activeTextField : UITextField!
var isSearchActive : Bool!
var arrSearchResult :NSMutableArray!
var isFromProfile : Int!
override func viewDidLoad() {
super.viewDidLoad()
if isFromProfile == 0{
labelTitle.text=NSLocalizedString(Utility.getKey("create_account_header"),comment:"")
}else{
labelTitle.text=NSLocalizedString(Utility.getKey("profile"),comment:"")
}
labelTitle.font = Utility.setNavigationFont()
textSearch.placeholder = NSLocalizedString(Utility.getKey("search_contacts"),comment:"")
self.tableView.registerNib(UINib(nibName: "FrequencyTitleTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.TitleTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "FrequencyDetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.DetailTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "PersonalDetailsTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.PersonalDetailCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ARDetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARDetailTableViewCellIdentifier)
self.tableView.registerNib(UINib(nibName: "ARPersonalDetailsTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARPersonalDetailsTableViewCellIndetifier)
self.tableView.rowHeight = UITableViewAutomaticDimension
isSearchActive = false
arrSearchResult = [] as NSMutableArray
switch selectType{
case TypeOfCell.JobTitle.rawValue :
viewSearch.hidden = true
verticalSpaceTable.constant = 0
if let path = NSBundle.mainBundle().pathForResource("JobTitle", ofType: "plist")
{
selectLang = NSMutableArray(contentsOfFile: path)
let arrTemp : NSMutableArray = NSMutableArray(array: selectLang)
for (index, element) in arrTemp.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject> {
let strTitle = innerDict["Title"] as! String!
if strTitle.characters.count != 0
{
let strPlaceholder = innerDict["Placeholder"] as! NSString!
if strPlaceholder != nil
{
innerDict["Placeholder"] = NSLocalizedString(Utility.getKey("Please describe"),comment:"")
}
innerDict["Title"] = NSLocalizedString(Utility.getKey(strTitle),comment:"")
selectLang.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
}
case TypeOfCell.CountryOfOring.rawValue :
selectLang = Structures.Constant.appDelegate.arrCountryList.mutableCopy() as! NSMutableArray
case TypeOfCell.CountryWhereWorking.rawValue :
selectLang = Structures.Constant.appDelegate.arrCountryList.mutableCopy() as! NSMutableArray
default :
print("")
}
arrSearchResult = Utility.setSelected(selectLang, selectedText: selectedText)
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool)
{
if Structures.Constant.appDelegate.isArabic == true
{
btnBack.setTitle(NSLocalizedString(Utility.getKey("done"),comment:""), forState: .Normal)
btnDone.setTitle(NSLocalizedString(Utility.getKey("back"),comment:""), forState: .Normal)
textSearch.textAlignment = NSTextAlignment.Right
textSearchBG.image = UIImage(named: "ARsearch-bg.png")
}
else
{
btnBack.setTitle(NSLocalizedString(Utility.getKey("back"),comment:""), forState: .Normal)
btnDone.setTitle(NSLocalizedString(Utility.getKey("done"),comment:""), forState: .Normal)
textSearch.textAlignment = NSTextAlignment.Left
textSearchBG.image = UIImage(named: "search-bg.png")
}
}
override func viewWillDisappear(animated: Bool) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func btnBackPressed(sender: AnyObject)
{
self.view.endEditing(true)
if Structures.Constant.appDelegate.isArabic == true
{
btnDoneEvent()
}
else
{
self.navigationController?.popViewControllerAnimated(true)
}
}
@IBAction func doneBtnPressed(sender: AnyObject)
{
self.view.endEditing(true)
if Structures.Constant.appDelegate.isArabic == true
{
self.navigationController?.popViewControllerAnimated(true)
}
else
{
btnDoneEvent()
}
}
func btnDoneEvent()
{
if (selectType == 1){
if self.activeTextField != nil{
self.activeTextField.resignFirstResponder()
}
self.delegate?.jobTitleSelcted(self.selectedText)
}
if (selectType == 2){
self.delegate?.countryOfOrigin(selectedText, selectedCode: selectedCode)
}
if (selectType == 3){
self.delegate?.countryWhereWorking(selectedText, selectedCode: selectedCode)
}
self.navigationController?.popViewControllerAnimated(true)
}
//MARK:- PersonalDetailsTableview
func textFieldStartEditing(textField: UITextField, tableViewCell: PersonalDetailsTableViewCell, identity: NSString, level: NSString) {
self.activeTextField = textField
let point : CGPoint = textField.convertPoint(textField.frame.origin, toView:self.tableView)
let newContentOffset : CGPoint = CGPointMake(0, (point.y-40))
self.tableView.setContentOffset(newContentOffset, animated: true)
}
func textFieldEndEditing(textField: UITextField, tableViewCell: PersonalDetailsTableViewCell, identity: NSString, level: NSString) {
if identity == "OtherSelected" {
self.selectedText = textField.text
if selectedText.characters.count == 0 {
Utility.showAlertWithTitle(NSLocalizedString(Utility.getKey("please_select_job_title"),comment:""), strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self)
}
}
}
func textFieldShouldReturn(textField: UITextField, tableViewCell: PersonalDetailsTableViewCell, identity: NSString, level: NSString) {
if (identity as String == "OtherSelected")
{
let newContentOffset : CGPoint = CGPointMake(0, self.tableView.contentSize.height-self.tableView.frame.height)
self.tableView.setContentOffset(newContentOffset, animated: true)
}
textField.resignFirstResponder()
}
func textFieldShouldChangeCharactersInRange(textField: UITextField, tableViewCell: PersonalDetailsTableViewCell, identity: NSString, level: NSString, range: NSRange, replacementString string: String) {
}
//MARK:- ARPersonalDetailsTableview
func textFieldShouldChangeCharactersInRange1(textField: UITextField, tableViewCell: ARPersonalDetailsTableViewCell, identity: NSString, level: NSString, range: NSRange, replacementString string: String) {
}
func textFieldStartEditing1(textField: UITextField, tableViewCell: ARPersonalDetailsTableViewCell, identity: NSString, level: NSString)
{
self.activeTextField = textField
let point : CGPoint = textField.convertPoint(textField.frame.origin, toView:self.tableView)
let newContentOffset : CGPoint = CGPointMake(0, (point.y-40))
self.tableView.setContentOffset(newContentOffset, animated: true)
}
func textFieldEndEditing1(textField: UITextField, tableViewCell: ARPersonalDetailsTableViewCell, identity: NSString, level: NSString) {
if identity == "OtherSelected" {
self.selectedText = textField.text
if selectedText.characters.count == 0 {
Utility.showAlertWithTitle(NSLocalizedString(Utility.getKey("please_select_job_title"),comment:""), strMessage: "", strButtonTitle: NSLocalizedString(Utility.getKey("Ok"),comment:""), view: self)
}
}
}
func textFieldShouldReturn1(textField: UITextField, tableViewCell: ARPersonalDetailsTableViewCell, identity: NSString, level: NSString) {
if (identity as String == "OtherSelected")
{
let newContentOffset : CGPoint = CGPointMake(0, self.tableView.contentSize.height-self.tableView.frame.height)
self.tableView.setContentOffset(newContentOffset, animated: true)
}
textField.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool
{
self.view.endEditing(true)
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
{
if textField == textSearch
{
if string != "\n"
{
arrSearchResult = NSMutableArray()
var strSearch : String!;
if textField.text!.characters.count == range.location
{
strSearch = textField.text! + string
}
else
{
let str : String = textField.text!
let index: String.Index = str.startIndex.advancedBy(range.location)
strSearch = str.substringToIndex(index) // "Stack"
}
if (strSearch.characters.count==0)
{
self.isSearchActive = false
arrSearchResult = selectLang
}
else
{
self.isSearchActive = true
for (var i : Int = 0; i < selectLang.count ; i++)
{
let strRangeText : NSString = (selectLang.objectAtIndex(i).valueForKey("Title") as! NSString).lowercaseString + (selectLang.objectAtIndex(i).valueForKey("Identity") as! NSString).lowercaseString
let range : NSRange = strRangeText.rangeOfString(strSearch.lowercaseString) as NSRange
if range.location != NSNotFound
{
arrSearchResult.addObject(selectLang.objectAtIndex(i))
}
}
}
self.tableView.reloadData()
}
}
return true
}
//MARK: - TableView Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrSearchResult.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let kRowHeight = self.arrSearchResult[indexPath.row]["RowHeight"] as! CGFloat
return kRowHeight;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let kCellIdentifier = self.arrSearchResult[indexPath.row]["CellIdentifier"] as! String
if let cell: TitleTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TitleTableViewCell {
cell.lblDetail.text = ""
cell.levelString = self.arrSearchResult[indexPath.row]["Level"] as! NSString!
cell.lblTitle.text = self.arrSearchResult[indexPath.row]["Title"] as! String!
cell.type = self.arrSearchResult[indexPath.row]["Type"] as! Int!
cell.intialize()
return cell
}
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == Structures.TableViewCellIdentifiers.DetailTableViewCellIdentifier
{
if let cell: ARDetailTableViewCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.ARDetailTableViewCellIdentifier) as? ARDetailTableViewCell
{
cell.lblSubDetail.text = ""
cell.levelString = self.arrSearchResult[indexPath.row]["Level"] as! NSString!
cell.lblDetail.text = self.arrSearchResult[indexPath.row]["Title"] as! String!
cell.isSelectedValue = self.arrSearchResult[indexPath.row]["IsSelected"] as! Bool!
cell.type = self.arrSearchResult[indexPath.row]["Type"] as! Int!
cell.intialize()
return cell
}
}
else
{
if let cell: DetailTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? DetailTableViewCell {
cell.lblSubDetail.text = ""
cell.levelString = self.arrSearchResult[indexPath.row]["Level"] as! NSString!
cell.lblDetail.text = self.arrSearchResult[indexPath.row]["Title"] as! String!
cell.isSelectedValue = self.arrSearchResult[indexPath.row]["IsSelected"] as! Bool!
cell.type = self.arrSearchResult[indexPath.row]["Type"] as! Int!
cell.intialize()
return cell
}
}
if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == "PersonalDetailCellIdentifier"
{
if let cell: ARPersonalDetailsTableViewCell = tableView.dequeueReusableCellWithIdentifier("ARPersonalDetailsTableViewCellIndetifier") as? ARPersonalDetailsTableViewCell
{
cell.detailstextField.placeholder = self.arrSearchResult[indexPath.row]["Placeholder"] as! String!
cell.detailstextField.accessibilityIdentifier = self.arrSearchResult[indexPath.row]["Identity"] as! String!
cell.identity = self.arrSearchResult[indexPath.row]["Identity"] as! NSString!
cell.levelString = self.arrSearchResult[indexPath.row]["Level"] as! NSString!
cell.delegate = self
cell.indexPath = indexPath
cell.initialize()
return cell
}
}
else
{
if let cell: PersonalDetailsTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? PersonalDetailsTableViewCell
{
cell.detailstextField.placeholder = self.arrSearchResult[indexPath.row]["Placeholder"] as! String!
cell.detailstextField.accessibilityIdentifier = self.arrSearchResult[indexPath.row]["Identity"] as! String!
cell.identity = self.arrSearchResult[indexPath.row]["Identity"] as! NSString!
cell.levelString = self.arrSearchResult[indexPath.row]["Level"] as! NSString!
cell.delegate = self
cell.indexPath = indexPath
cell.initialize()
return cell
}
}
//assert(false, "The dequeued table view cell was of an unknown type!");
let blankCell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)!
return blankCell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
let connectedID = self.arrSearchResult[indexPath.row]["ConnectedID"] as! Int!
let identity = arrSearchResult[indexPath.row]["Identity"] as! NSString!
for (index, element) in self.arrSearchResult.enumerate() {
if var innerDict = element as? Dictionary<String, AnyObject> {
let iden = innerDict["Identity"] as! NSString!
let cnID = innerDict["ConnectedID"] as! Int!
if cnID == connectedID{
if iden == identity{
innerDict["IsSelected"] = true
self.selectedText = innerDict["Title"] as! String
self.selectedCode = innerDict["Identity"] as! String
}else{
innerDict["IsSelected"] = false
}
self.arrSearchResult.replaceObjectAtIndex(index, withObject: innerDict)
}
}
}
self.tableView.reloadData()
}
}
|
296f43b3baebaceb68c918468c87d4e4
| 46.882507 | 219 | 0.633023 | false | false | false | false |
mercadopago/px-ios
|
refs/heads/develop
|
MercadoPagoSDK/MercadoPagoSDK/UI/PaymentMethod/PXPaymentMethodIconRenderer.swift
|
mit
|
1
|
import UIKit
class PXPaymentMethodIconRenderer: NSObject {
let RADIUS_DELTA_FROM_ICON_TO_BACKGROUND: CGFloat = 58
func render(component: PXPaymentMethodIconComponent) -> PXPaymentMethodIconView {
let pmIconView = PXPaymentMethodIconView()
pmIconView.translatesAutoresizingMaskIntoConstraints = false
let background = UIView()
background.translatesAutoresizingMaskIntoConstraints = false
background.backgroundColor = ThemeManager.shared.iconBackgroundColor()
pmIconView.paymentMethodIconBackground = background
pmIconView.addSubview(pmIconView.paymentMethodIconBackground!)
PXLayout.matchWidth(ofView: pmIconView.paymentMethodIconBackground!).isActive = true
PXLayout.matchHeight(ofView: pmIconView.paymentMethodIconBackground!).isActive = true
PXLayout.centerVertically(view: pmIconView.paymentMethodIconBackground!).isActive = true
PXLayout.centerHorizontally(view: pmIconView.paymentMethodIconBackground!).isActive = true
let pmIcon = UIImageView()
pmIcon.translatesAutoresizingMaskIntoConstraints = false
pmIcon.image = component.props.paymentMethodIcon
pmIconView.paymentMethodIcon = pmIcon
pmIconView.addSubview(pmIconView.paymentMethodIcon!)
PXLayout.matchWidth(ofView: pmIconView.paymentMethodIcon!, toView: pmIconView.paymentMethodIconBackground, withPercentage: self.RADIUS_DELTA_FROM_ICON_TO_BACKGROUND).isActive = true
PXLayout.matchHeight(ofView: pmIconView.paymentMethodIcon!, toView: pmIconView.paymentMethodIconBackground, withPercentage: self.RADIUS_DELTA_FROM_ICON_TO_BACKGROUND).isActive = true
PXLayout.centerVertically(view: pmIconView.paymentMethodIcon!, to: pmIconView.paymentMethodIconBackground).isActive = true
PXLayout.centerHorizontally(view: pmIconView.paymentMethodIcon!, to: pmIconView.paymentMethodIconBackground).isActive = true
pmIconView.layer.masksToBounds = true
return pmIconView
}
}
class PXPaymentMethodIconView: PXBodyView {
var paymentMethodIcon: UIImageView?
var paymentMethodIconBackground: UIView?
}
|
917beb48933732a75932d42e153e53c7
| 55.473684 | 190 | 0.779124 | false | false | false | false |
gyro-n/PaymentsIos
|
refs/heads/master
|
GyronPayments/Classes/Resources/LedgerResource.swift
|
mit
|
1
|
//
// LedgerResource.swift
// GyronPayments
//
// Created by Ye David on 11/18/16.
// Copyright © 2016 gyron. All rights reserved.
//
import Foundation
import PromiseKit
/**
LedgerListRequestData is a class that defines the request pararmeters that is used to get a list of ledger objects.
*/
open class LedgerListRequestData: ExtendedAnyObject, RequestDataDelegate, SortRequestDelegate, PaginationRequestDelegate {
/**
The sort order for the list (ASC or DESC)
*/
public var sortOrder: String?
/**
The property name to sort by
*/
public var sortBy: String?
/**
The desired page no
*/
public var page: Int?
/**
The desired page size of the returning data set
*/
public var pageSize: Int?
/**
Get all of the ledgers
*/
public var all: Bool?
public var from: String?
public var to: String?
public var min: Int?
public var max: Int?
/**
The currency of the ledger
*/
public var currency: String?
public init(all: Bool? = nil,
from: String? = nil,
to: String? = nil,
min: Int? = nil,
max: Int? = nil,
currency: String? = nil,
sortOrder: String? = nil,
sortBy: String? = "created_on",
page: Int? = nil,
pageSize: Int? = nil) {
self.all = all
self.from = from
self.to = to
self.min = min
self.max = max
self.currency = currency
self.sortOrder = sortOrder
self.sortBy = sortBy
self.page = page
self.pageSize = pageSize
}
public func convertToMap() -> RequestData {
return convertToRequestData()
}
}
/**
The LedgerResource class is used to perform operations related to the management of transfer ledgers.
*/
open class LedgerResource: BaseResource {
/**
The base root path for the request url
*/
let basePath: String = "/transfers/:transferId/ledgers"
///---------------------------
/// @name Routes
///---------------------------
/**
Lists the ledgers available based on the transfer id.
@param transferId the transfer id
@param data the parameters to be passed to the request
@param callback the callback function to be called when the request is completed
@return A promise object with the Ledgers list
*/
public func list(transferId: String, data: LedgerListRequestData?, callback: ResponseCallback<Ledgers>?) -> Promise<Ledgers> {
let routePath: String = self.getRoutePath(id: nil, basePath: basePath, pathParams: [(":transferId", transferId)])
return self.runRoute(requiredParams: [], method: HttpProtocol.HTTPMethod.GET, path: routePath, pathParams: nil, data: data, callback: callback)
}
}
|
4ad5651d33368e25acd315bf25cd5605
| 27.897959 | 151 | 0.610523 | false | false | false | false |
darkerk/v2ex
|
refs/heads/master
|
V2EX/Cells/LoadMoreCommentCell.swift
|
mit
|
1
|
//
// LoadMoreCommentCell.swift
// V2EX
//
// Created by darker on 2017/3/13.
// Copyright © 2017年 darker. All rights reserved.
//
import UIKit
class LoadMoreCommentCell: UITableViewCell {
@IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let selectedView = UIView()
selectedView.backgroundColor = AppStyle.shared.theme.cellSelectedBackgroundColor
self.selectedBackgroundView = selectedView
backgroundColor = AppStyle.shared.theme.cellBackgroundColor
contentView.backgroundColor = backgroundColor
if AppStyle.shared.theme == .night {
activityIndicatorView.style = .white
titleLabel.textColor = #colorLiteral(red: 0.1137254902, green: 0.631372549, blue: 0.9490196078, alpha: 1)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
c2ac654042cd2f71c7e2d04eb9916c9b
| 28.589744 | 117 | 0.671577 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
refs/heads/main
|
Swift/pancake-sorting.swift
|
mit
|
2
|
/**
* https://leetcode.com/problems/pancake-sorting/
*
*
*/
// Date: Sat Aug 29 16:22:37 PDT 2020
class Solution {
/// From the largest number to smallest one,
/// Try to find the number and flip it to the front.
/// Then, make another flip to make it to the right position.
///
/// - Complexity:
/// - Time: O(n^2), n is the number of elements in A.
/// - Space: O(n)
func pancakeSort(_ A: [Int]) -> [Int] {
var A = A
var result: [Int] = []
for num in stride(from: A.count, through: 1, by: -1) {
for index in 0 ..< A.count {
if num == A[index] {
print("\(index)")
if num != index + 1 {
self.flip(&A, by: index)
result.append(index + 1)
self.flip(&A, by: num - 1)
result.append(num)
}
break
}
}
}
return result
}
private func flip(_ A: inout [Int], by k: Int) {
var left = 0
var right = k
while left < right {
let tmp = A[left]
A[left] = A[right]
A[right] = tmp
left += 1
right -= 1
}
}
}
|
2efd82f1fd57befa12a588977b187c5e
| 27.630435 | 65 | 0.415653 | false | false | false | false |
Ivacker/swift
|
refs/heads/master
|
validation-test/compiler_crashers/27369-swift-type-transform.swift
|
apache-2.0
|
9
|
// RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {{} k. "
if true{
class d<T {let:a{}
g {class B<T B:C{let f=e()
typealias e
enum S<T> : A?
func a== f=Dictionary<T.E
}
class c{struct B<T{
class b<T{struct Q<T B : T{
class c<a
typealias ()
struct B<a:a{
}
class A{let a{} k. "
}
class A<T{}
class B<T {
struct B
class A{var f
"
class B<T{
class A{{
func f
}struct c<T B:C{let f=e()
}
func g:a{
import a:a{
}
enum S<T a{
class A{
func p{
class B<H : T.E
struct c<T B :a{
class B< E {}
class A{let ad{}
let T h.h =b()
1
typealias ()
let T B :b: AsB
class A? f{
typeal
|
4adcdb56add37a6e44ecb5bb858e5c59
| 14.5625 | 87 | 0.64257 | false | false | false | false |
SoCM/iOS-FastTrack-2014-2015
|
refs/heads/master
|
04-App Architecture/Swift 2/Breadcrumbs/Solution/BackgroundTest/BCOptionsTableViewController.swift
|
mit
|
1
|
//
// BCOptionsTableViewController.swift
// Breadcrumbs
//
// Created by Nicholas Outram on 02/12/2015.
// Copyright © 2015 Plymouth University. All rights reserved.
//
import UIKit
protocol BCOptionsSheetDelegate : class {
//Required methods
func dismissWithUpdatedOptions(updatedOptions : BCOptions?)
}
class BCOptionsTableViewController: UITableViewController {
@IBOutlet weak var backgroundUpdateSwitch: UISwitch!
@IBOutlet weak var headingUPSwitch: UISwitch!
@IBOutlet weak var headingUPLabel: UILabel!
@IBOutlet weak var showTrafficSwitch: UISwitch!
@IBOutlet weak var distanceSlider: UISlider!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var gpsPrecisionLabel: UILabel!
@IBOutlet weak var gpsPrecisionSlider: UISlider!
//Delegate property
weak var delegate : BCOptionsSheetDelegate?
//Local copy of all options with defaults
var options : BCOptions = BCOptions() {
didSet {
print("OPTIONS COPY UPDATED in \(__FUNCTION__)")
//updateUIWithState() //this would cause a crash when this property is set by the presenting controller
}
}
//Functions to synchronise UI and state
//Error prone, with no clever binding strategies here - just keeping things simple
func updateUIWithState() {
self.backgroundUpdateSwitch.on = self.options.backgroundUpdates
//Only devices with heading support can switch on the heading UP support
if self.options.headingAvailable {
self.headingUPSwitch.on = self.options.headingUP
self.headingUPSwitch.enabled = true
self.headingUPLabel.alpha = 1.0
} else {
self.headingUPSwitch.on = false
self.headingUPSwitch.enabled = false
self.headingUPLabel.alpha = 0.2
}
self.showTrafficSwitch.on = self.options.showTraffic
self.distanceSlider.value = Float(self.options.distanceBetweenMeasurements)
self.distanceLabel.text = String(format: "%d", Int(self.options.distanceBetweenMeasurements))
self.gpsPrecisionSlider.value = Float(self.options.gpsPrecision)
self.gpsPrecisionLabel.text = String(format: "%d", Int(self.options.gpsPrecision))
}
func updateStateFromUI() {
self.options.backgroundUpdates = self.backgroundUpdateSwitch.on
self.options.headingUP = self.headingUPSwitch.on
self.options.showTraffic = self.showTrafficSwitch.on
self.options.distanceBetweenMeasurements = Double(self.distanceSlider.value)
self.options.gpsPrecision = Double(self.gpsPrecisionSlider.value)
}
override func awakeFromNib() {
print("\(__FILE__), \(__FUNCTION__)")
}
override func viewDidLoad() {
print("\(__FILE__), \(__FUNCTION__)")
super.viewDidLoad()
guard let _ = self.delegate else {
print("WARNING - DELEGATE NOTE SET FOR \(self)")
return
}
//Initialise the UI
updateUIWithState()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Triggered by a rotation event
override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
//Forward the message
super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
print("\(__FILE__), \(__FUNCTION__) : new traits \(newCollection)")
}
// MARK: Actions
@IBAction func doBackgroundUpdateSwitch(sender: AnyObject) {
updateStateFromUI()
}
@IBAction func doHeadingUpSwitch(sender: AnyObject) {
updateStateFromUI()
}
@IBAction func doShowTrafficSwitch(sender: AnyObject) {
updateStateFromUI()
}
@IBAction func doDistanceSliderChanged(sender: AnyObject) {
updateStateFromUI()
self.distanceLabel.text = String(format: "%d", Int(self.distanceSlider.value))
}
@IBAction func doGPSPrecisionSliderChanged(sender: AnyObject) {
updateStateFromUI()
self.gpsPrecisionLabel.text = String(format: "%d", Int(self.gpsPrecisionSlider.value))
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 4 {
if indexPath.row == 0 {
print("Save tapped")
self.delegate?.dismissWithUpdatedOptions(self.options)
} else {
print("Cancel tapped")
self.delegate?.dismissWithUpdatedOptions(nil)
}
}
}
// MARK: Rotation
// New Autorotation support.
override func shouldAutorotate() -> Bool {
return false
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return .Portrait
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return [.Portrait]
}
}
|
a1221a7b4f2677b7bb53f9cda1935f98
| 33.794521 | 163 | 0.688189 | false | false | false | false |
felipecarreramo/R3LRackspace
|
refs/heads/dev
|
Pod/Classes/CloudFiles.swift
|
mit
|
1
|
//
// Cloud.swift
// R3LRackspace
//
// Created by Juan Carrera on 12/18/15.
// Copyright © 2015 Rokk3rlabs. All rights reserved.
//
import Foundation
public class CloudFiles {
public enum CloudFilesRegion: String {
case Chicago = "ORD"
case Dallas = "DFW"
case HongKong = "HKG"
case London = "LON"
case NorthernVirginia = "IAD"
case Sydney = "SYD"
}
private var region: CloudFilesRegion?
private var services: [ServiceCatalog]?
public var username: String?
public var apiKey: String?
public var debug = false
private var token: String?
private var tenant: [String: String] = [:]
private var endpoint:String?
private var authenticated: Bool = false
private let network: Network
public init(username: String, apiKey: String, region:CloudFilesRegion) {
self.username = username
self.apiKey = apiKey
self.region = region
services = [CloudFilesCDN(), CloudFilesPrivate()]
network = Network(authURL: CFConstants.AuthURL)
network.debug = self.debug
}
public func authenticate(completion: (authenticated: Bool)->()) {
if let username = username, let apiKey = apiKey {
let credentials = [ "username": username , "apiKey": apiKey]
let key = ["RAX-KSKEY:apiKeyCredentials": credentials]
let auth = ["auth": key]
network.sendRequest(Network.RSHTTPMethod.POST, params: auth )
.responseJSONWithCompletionHandler { (data, response, error) in
if let data = data as? [String: AnyObject] , let access = data["access"] as? [String: AnyObject] {
self.authenticated = true
if let tokenDict = access["token"] as? [String: AnyObject] {
if let tokenID = tokenDict["id"] as? String {
self.token = tokenID
self.network.token = self.token
}
if let tenant = tokenDict["tenant"] as? [String: String] {
self.tenant["id"] = tenant["id"]
self.tenant["name"] = tenant["name"]
}
}
if let APIServices = access["serviceCatalog"] as? [[String: AnyObject]] {
if let installedServices = self.services {
for service in installedServices {
if let region = self.region, let name = service.name {
let serviceFix = self.filterAPIService(APIServices, name: name, region: region.rawValue)
if let serviceFix = serviceFix, let regionEndpoint = serviceFix["endpoints"] as? [String: AnyObject] {
if let foundedEndpoint = regionEndpoint["publicURL"] as? String {
service.endpoint = foundedEndpoint
}
}
}
}
}
}
} else {
self.authenticated = false
}
completion(authenticated: self.authenticated)
}
}
}
public func putObject(data: NSData, name: String, container: String, completion:(success: Bool)->()) {
let put:()->() = {
if let cdn: CloudFilesPrivate = self.services?[1] as? CloudFilesPrivate, let endpoint = cdn.endpoint {
if let url = NSURL(string: "\(endpoint)/\(container)/\(name)") {
self.network.uploadFile(data,
url: url,
method: Network.RSHTTPMethod.PUT,
completion: { success in
if success {
completion(success: true)
}else {
completion(success: false)
}
}
)
}
}
}
if authenticated {
put()
}else {
authenticate(){
success in
if success {
self.authenticated = true
put()
}else {
completion(success: false)
}
}
}
}
public func getPublicURL(container: String, name: String, completion:(urlObject: String?) -> ()) {
self.getPublicContainerURL(container) { urlString in
if let urlString = urlString {
completion(urlObject: "\(urlString)/\(name)")
}else {
completion(urlObject: nil)
}
}
}
public func getContainer(container: String) {
let get:()->() = {
if let cdn: CloudFilesPrivate = self.services?[1] as? CloudFilesPrivate, let endpoint = cdn.endpoint {
self.network.sendRequest(Network.RSHTTPMethod.GET,
endpoint: "\(endpoint)/\(container)",
headers: [
"Accept": "application/json"
]).responseJSONWithCompletionHandler({ (data, response, error) -> () in
guard let _ = error else {
print(response)
print(data)
return
}
})
}
}
if authenticated {
get()
}else {
authenticate(){
success in
if success {
self.authenticated = true
get()
}
}
}
}
public func getContainers() {
let get:()->() = {
if let cdn: CloudFilesPrivate = self.services?[1] as? CloudFilesPrivate, let endpoint = cdn.endpoint {
self.network.sendRequest(Network.RSHTTPMethod.GET,
endpoint: "\(endpoint)",
headers: [
"Accept": "application/json"
]).responseJSONWithCompletionHandler({ (data, response, error) -> () in
guard let _ = error else {
print(response)
print(data)
return
}
})
}
}
if authenticated {
get()
}else {
authenticate(){
success in
if success {
self.authenticated = true
get()
}
}
}
}
public func enableContainerForCDN(container: String, completion:(success: Bool)->()) {
let put:()->() = {
if let cdn: CloudFilesPrivate = self.services?[1] as? CloudFilesPrivate, let endpoint = cdn.endpoint {
self.network.sendRequest(Network.RSHTTPMethod.PUT,
endpoint: "\(endpoint)/\(container)",
headers: [
"X-CDN-Enabled": "True"
]).responseJSONWithCompletionHandler({ (data, response, error) -> () in
print(NSString(data: data as! NSData, encoding: NSUTF8StringEncoding))
print(response)
guard let _ = error else {
completion(success: true)
return
}
completion(success: false)
})
}
}
if authenticated {
put()
}else {
authenticate(){
success in
if success {
self.authenticated = true
put()
}
}
}
}
public func getPublicContainers() {
let get:()->() = {
if let cdn: CloudFilesCDN = self.services?.first as? CloudFilesCDN, let endpoint = cdn.endpoint {
self.network.sendRequest(Network.RSHTTPMethod.GET,
endpoint: "\(endpoint)",
headers: [
"Accept": "application/json"
]).responseJSONWithCompletionHandler( { (data, response, error) -> () in
guard let _ = error else {
print(response)
print(data)
return
}
})
}
}
if authenticated {
get()
}else {
authenticate(){
success in
if success {
self.authenticated = true
get()
}
}
}
}
private func publicContainerInfo(containerName:String, completionInfo:(urlString: String?)->()){
if let cdn: CloudFilesCDN = self.services?.first as? CloudFilesCDN, let endpoint = cdn.endpoint {
self.network.sendRequest(Network.RSHTTPMethod.HEAD,
endpoint: "\(endpoint)/\(containerName)").responseDataWithCompletionHandler({ (data, response, error) -> () in
if let _ = error {
completionInfo(urlString: nil)
}else {
if let response = response, let headers = response.allHeaderFields as? [String: AnyObject] {
let urlString = headers["X-Cdn-Ssl-Uri"] as? String
completionInfo(urlString: urlString)
}
}
})
}
}
public func getPublicContainerURL(containerName: String, completion: (urlString: String?)->()){
if authenticated {
publicContainerInfo(containerName) { urlString in
completion(urlString: urlString)
}
}else {
authenticate(){
success in
if success {
self.authenticated = true
self.publicContainerInfo(containerName) { urlString in
completion(urlString: urlString)
}
}
}
}
}
public func createContainer(name: String) {
let put:()->() = {
if let cdn: CloudFilesPrivate = self.services?[1] as? CloudFilesPrivate, let endpoint = cdn.endpoint, let account = self.tenant["id"]{
self.network.sendRequest(Network.RSHTTPMethod.PUT,
endpoint: "\(endpoint)/\(account)/\(name)").responseJSONWithCompletionHandler({ (data, response, error) -> () in
guard let _ = error else {
print(response)
print(data)
return
}
})
}
}
if authenticated {
put()
}else {
authenticate(){
success in
if success {
self.authenticated = true
put()
}
}
}
}
private func filterAPIService(APIServices: [[String: AnyObject]], name: String, region: String? = nil) -> [String: AnyObject]? {
let filteredByName = APIServices.filter({ service in
if let serviceName = service["name"] as? String where name == serviceName {
return true
}else {
return false
}
})
if let region = region {
if var serviceByName = filteredByName.first, let endpoints = serviceByName["endpoints"] as? [AnyObject]{
let regionEndpointsAPI = endpoints.filter({ ep in
if let APIRegion = ep["region"] as? String where APIRegion == region {
return true
}else {
return false
}
})
if let regionEndpoint = regionEndpointsAPI.first {
serviceByName.updateValue(regionEndpoint, forKey: "endpoints")
}
return serviceByName
}else {
return nil
}
}else {
return filteredByName.first
}
}
}
|
d8af2900362d675e3cbe72d27e3a11c5
| 32.885 | 146 | 0.422932 | false | false | false | false |
HongxiangShe/STV
|
refs/heads/master
|
DDLive/Pods/ProtocolBuffers-Swift/Source/CodedInputStream.swift
|
apache-2.0
|
4
|
// 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
let DEFAULT_RECURSION_LIMIT:Int = 64
let DEFAULT_SIZE_LIMIT:Int = 64 << 20 // 64MB
let BUFFER_SIZE:Int = 4096
public class CodedInputStream {
public var buffer:[UInt8]
fileprivate var input:InputStream?
fileprivate var bufferSize:Int = 0
fileprivate var bufferSizeAfterLimit:Int = 0
fileprivate var bufferPos:Int = 0
fileprivate var lastTag:Int32 = 0
fileprivate var totalBytesRetired:Int = 0
fileprivate var currentLimit:Int = 0
fileprivate var recursionDepth:Int = 0
fileprivate var recursionLimit:Int = 0
fileprivate var sizeLimit:Int = 0
public init (data:Data) {
buffer = [UInt8](data)
bufferSize = buffer.count
currentLimit = Int.max
recursionLimit = DEFAULT_RECURSION_LIMIT
sizeLimit = DEFAULT_SIZE_LIMIT
}
public init (stream:InputStream) {
buffer = [UInt8](repeating: 0, count: BUFFER_SIZE)
bufferSize = 0
input = stream
input?.open()
//
currentLimit = Int.max
recursionLimit = DEFAULT_RECURSION_LIMIT
sizeLimit = DEFAULT_SIZE_LIMIT
}
private func isAtEnd() throws -> Bool {
if bufferPos == bufferSize {
if !(try refillBuffer(mustSucceed: false)) {
return true
}
}
return false
}
private func refillBuffer(mustSucceed:Bool) throws -> Bool {
guard bufferPos >= bufferSize else {
throw ProtocolBuffersError.illegalState("RefillBuffer called when buffer wasn't empty.")
}
if (totalBytesRetired + bufferSize == currentLimit) {
guard !mustSucceed else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
return false
}
totalBytesRetired += bufferSize
bufferPos = 0
bufferSize = 0
if let input = self.input {
// let pointer = UnsafeMutablePointerUInt8From(data: buffer)
bufferSize = input.read(&buffer, maxLength:buffer.count)
}
if bufferSize <= 0 {
bufferSize = 0
guard !mustSucceed else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
return false
} else {
recomputeBufferSizeAfterLimit()
let totalBytesRead = totalBytesRetired + bufferSize + bufferSizeAfterLimit
guard totalBytesRead <= sizeLimit || totalBytesRead >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Size Limit Exceeded")
}
return true
}
}
public func readRawData(size:Int) throws -> Data {
// let pointer = UnsafeMutablePointerUInt8From(data: buffer)
guard size >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
}
if totalBytesRetired + bufferPos + size > currentLimit {
try skipRawData(size: currentLimit - totalBytesRetired - bufferPos)
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
if (size <= bufferSize - bufferPos) {
let data = Data(bytes: &buffer + bufferPos, count: size)
bufferPos += size
return data
} else if (size < BUFFER_SIZE) {
var bytes = [UInt8](repeating: 0, count: size)
var pos = bufferSize - bufferPos
// let byPointer = UnsafeMutablePointerUInt8From(data: bytes)
memcpy(&bytes, &buffer + bufferPos, pos)
bufferPos = bufferSize
_ = try refillBuffer(mustSucceed: true)
while size - pos > bufferSize {
memcpy(&bytes + pos, &buffer, bufferSize)
pos += bufferSize
bufferPos = bufferSize
_ = try refillBuffer(mustSucceed: true)
}
memcpy(&bytes + pos, &buffer, size - pos)
bufferPos = size - pos
return Data(bytes:bytes, count:bytes.count)
} else {
let originalBufferPos = bufferPos
let originalBufferSize = bufferSize
totalBytesRetired += bufferSize
bufferPos = 0
bufferSize = 0
var sizeLeft = size - (originalBufferSize - originalBufferPos)
var chunks:Array<[UInt8]> = Array<[UInt8]>()
while sizeLeft > 0 {
var chunk = [UInt8](repeating: 0, count: min(sizeLeft, BUFFER_SIZE))
var pos:Int = 0
while pos < chunk.count {
var n:Int = 0
if input != nil {
// let pointer = UnsafeMutablePointerUInt8From(data: chunk)
n = input!.read(&chunk + pos, maxLength:chunk.count - pos)
}
guard n > 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
totalBytesRetired += n
pos += n
}
sizeLeft -= chunk.count
chunks.append(chunk)
}
var bytes = [UInt8](repeating: 0, count: size)
// let byPointer = UnsafeMutablePointerUInt8From(data: bytes)
var pos = originalBufferSize - originalBufferPos
memcpy(&bytes, &buffer + originalBufferPos, pos)
for chunk in chunks {
// let chPointer = UnsafeMutablePointerUInt8From(data: chunk)
memcpy(&bytes + pos, chunk, chunk.count)
pos += chunk.count
}
return Data(bytes)
}
}
public func skipRawData(size:Int) throws{
guard size >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
}
if (totalBytesRetired + bufferPos + size > currentLimit) {
try skipRawData(size: currentLimit - totalBytesRetired - bufferPos)
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
if (size <= (bufferSize - bufferPos)) {
bufferPos += size
}
else
{
var pos:Int = bufferSize - bufferPos
totalBytesRetired += pos
bufferPos = 0
bufferSize = 0
while (pos < size) {
var data = [UInt8](repeating: 0, count: size - pos)
var n:Int = 0
guard let input = self.input else {
n = -1
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
// let pointer = UnsafeMutablePointerUInt8From(data: data)
n = input.read(&data, maxLength:Int(size - pos))
pos += n
totalBytesRetired += n
}
}
}
public func readRawLittleEndian32() throws -> Int32 {
let b1 = try readRawByte()
let b2 = try readRawByte()
let b3 = try readRawByte()
let b4 = try readRawByte()
var result:Int32 = (Int32(b1) & 0xff)
result |= ((Int32(b2) & 0xff) << 8)
result |= ((Int32(b3) & 0xff) << 16)
result |= ((Int32(b4) & 0xff) << 24)
return result
}
public func readRawLittleEndian64() throws -> Int64 {
let b1 = try readRawByte()
let b2 = try readRawByte()
let b3 = try readRawByte()
let b4 = try readRawByte()
let b5 = try readRawByte()
let b6 = try readRawByte()
let b7 = try readRawByte()
let b8 = try readRawByte()
var result:Int64 = (Int64(b1) & 0xff)
result |= ((Int64(b2) & 0xff) << 8)
result |= ((Int64(b3) & 0xff) << 16)
result |= ((Int64(b4) & 0xff) << 24)
result |= ((Int64(b5) & 0xff) << 32)
result |= ((Int64(b6) & 0xff) << 40)
result |= ((Int64(b7) & 0xff) << 48)
result |= ((Int64(b8) & 0xff) << 56)
return result
}
public func readTag() throws -> Int32 {
if (try isAtEnd())
{
lastTag = 0
return 0
}
let tag = lastTag
lastTag = try readRawVarint32()
guard lastTag != 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Tag: after tag \(tag)")
}
return lastTag
}
public func checkLastTagWas(value:Int32) throws {
guard lastTag == value else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Tag: after tag \(lastTag)")
}
}
@discardableResult
public func skipField(tag:Int32) throws -> Bool {
let wireFormat = WireFormat.getTagWireType(tag: tag)
guard let format = WireFormat(rawValue: wireFormat) else {
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type")
}
switch format {
case .varint:
_ = try readInt32()
return true
case .fixed64:
_ = try readRawLittleEndian64()
return true
case .lengthDelimited:
try skipRawData(size: Int(try readRawVarint32()))
return true
case .startGroup:
try skipMessage()
try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: WireFormat.getTagFieldNumber(tag: tag)))
return true
case .endGroup:
return false
case .fixed32:
_ = try readRawLittleEndian32()
return true
default:
throw ProtocolBuffersError.invalidProtocolBuffer("Invalid Wire Type")
}
}
private func skipMessage() throws {
while (true) {
let tag:Int32 = try readTag()
let fieldSkip = try skipField(tag: tag)
if tag == 0 || !fieldSkip
{
break
}
}
}
public func readDouble() throws -> Double {
let convert:Int64 = try readRawLittleEndian64()
var result:Double = 0.0
result = WireFormat.convertTypes(convertValue: convert, defaultValue: result)
return result
}
public func readFloat() throws -> Float {
let convert:Int32 = try readRawLittleEndian32()
var result:Float = 0.0
result = WireFormat.convertTypes(convertValue: convert, defaultValue: result)
return result
}
public func readUInt64() throws -> UInt64 {
var retvalue:UInt64 = 0
retvalue = WireFormat.convertTypes(convertValue: try readRawVarint64(), defaultValue:retvalue)
return retvalue
}
public func readInt64() throws -> Int64 {
return try readRawVarint64()
}
public func readInt32() throws -> Int32 {
return try readRawVarint32()
}
public func readFixed64() throws -> UInt64 {
var retvalue:UInt64 = 0
retvalue = WireFormat.convertTypes(convertValue: try readRawLittleEndian64(), defaultValue:retvalue)
return retvalue
}
public func readFixed32() throws -> UInt32 {
var retvalue:UInt32 = 0
retvalue = WireFormat.convertTypes(convertValue: try readRawLittleEndian32(), defaultValue:retvalue)
return retvalue
}
public func readBool() throws ->Bool {
return try readRawVarint32() != 0
}
public func readRawByte() throws -> Int8 {
if (bufferPos == bufferSize) {
_ = try refillBuffer(mustSucceed: true)
}
let res = buffer[Int(bufferPos)]
bufferPos+=1
var convert:Int8 = 0
convert = WireFormat.convertTypes(convertValue: res, defaultValue: convert)
return convert
}
public class func readRawVarint32(firstByte:UInt8, inputStream:InputStream) throws -> Int32
{
if ((Int32(firstByte) & 0x80) == 0) {
return Int32(firstByte)
}
var result:Int32 = Int32(firstByte) & 0x7f
var offset:Int32 = 7
while offset < 32 {
var b:UInt8 = UInt8()
guard inputStream.read(&b, maxLength: 1) > 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
result |= (Int32(b) & 0x7f) << offset
if ((b & 0x80) == 0) {
return result
}
offset += 7
}
while offset < 64 {
var b:UInt8 = UInt8()
guard inputStream.read(&b, maxLength: 1) > 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
if ((b & 0x80) == 0) {
return result
}
offset += 7
}
throw ProtocolBuffersError.invalidProtocolBuffer("Truncated Message")
}
public func readRawVarint32() throws -> Int32 {
var tmp = try readRawByte();
if (tmp >= 0) {
return Int32(tmp);
}
var result : Int32 = Int32(tmp) & 0x7f;
tmp = try readRawByte()
if (tmp >= 0) {
result |= Int32(tmp) << 7;
} else {
result |= (Int32(tmp) & 0x7f) << 7;
tmp = try readRawByte()
if (tmp >= 0) {
result |= Int32(tmp) << 14;
} else {
result |= (Int32(tmp) & 0x7f) << 14;
tmp = try readRawByte()
if (tmp >= 0) {
result |= Int32(tmp) << 21;
} else {
result |= (Int32(tmp) & 0x7f) << 21;
tmp = try readRawByte()
result |= (Int32(tmp) << 28);
if (tmp < 0) {
// Discard upper 32 bits.
for _ in 0..<5 {
let byte = try readRawByte()
if (byte >= 0) {
return result;
}
}
throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint")
}
}
}
}
return result;
}
public func readRawVarint64() throws -> Int64 {
var shift:Int64 = 0
var result:Int64 = 0
while (shift < 64) {
let b = try readRawByte()
result |= (Int64(b & 0x7F) << shift)
if ((Int32(b) & 0x80) == 0) {
return result
}
shift += 7
}
throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint")
}
public func readString() throws -> String {
let size = Int(try readRawVarint32())
if size <= (bufferSize - bufferPos) && size > 0 {
let result = String(bytesNoCopy: &buffer + bufferPos, length: size, encoding: String.Encoding.utf8, freeWhenDone: false)
guard result != nil else {
throw ProtocolBuffersError.invalidProtocolBuffer("InvalidUTF8StringData")
}
bufferPos += size
return result!
} else {
let data = try readRawData(size: size)
return String(data: data, encoding: String.Encoding.utf8)!
}
}
public func readData() throws -> Data {
let size = Int(try readRawVarint32())
if size < bufferSize - bufferPos && size > 0 {
// let pointer = UnsafeMutablePointerInt8From(data: buffer)
let unsafeRaw = UnsafeRawPointer(&buffer+bufferPos)
let data = Data(bytes: unsafeRaw, count: size)
bufferPos += size
return data
} else {
return try readRawData(size: size)
}
}
public func readUInt32() throws -> UInt32 {
let value:Int32 = try readRawVarint32()
var retvalue:UInt32 = 0
retvalue = WireFormat.convertTypes(convertValue: value, defaultValue:retvalue)
return retvalue
}
public func readEnum() throws -> Int32 {
return try readRawVarint32()
}
public func readSFixed32() throws -> Int32 {
return try readRawLittleEndian32()
}
public func readSFixed64() throws -> Int64 {
return try readRawLittleEndian64()
}
public func readSInt32() throws -> Int32 {
return WireFormat.decodeZigZag32(n: try readRawVarint32())
}
public func readSInt64() throws -> Int64 {
return WireFormat.decodeZigZag64(n: try readRawVarint64())
}
public func setRecursionLimit(limit:Int) throws -> Int {
guard limit >= 0 else {
throw ProtocolBuffersError.illegalArgument("Recursion limit cannot be negative")
}
let oldLimit:Int = recursionLimit
recursionLimit = limit
return oldLimit
}
public func setSizeLimit(limit:Int) throws -> Int {
guard limit >= 0 else {
throw ProtocolBuffersError.illegalArgument("Recursion limit cannot be negative")
}
let oldLimit:Int = sizeLimit
sizeLimit = limit
return oldLimit
}
private func resetSizeCounter() {
totalBytesRetired = 0
}
private func recomputeBufferSizeAfterLimit() {
bufferSize += bufferSizeAfterLimit
let bufferEnd:Int = totalBytesRetired + bufferSize
if (bufferEnd > currentLimit) {
bufferSizeAfterLimit = bufferEnd - currentLimit
bufferSize -= bufferSizeAfterLimit
} else {
bufferSizeAfterLimit = 0
}
}
public func pushLimit(byteLimit:Int) throws -> Int {
guard byteLimit >= 0 else {
throw ProtocolBuffersError.invalidProtocolBuffer("Negative Size")
}
let newByteLimit = byteLimit + totalBytesRetired + bufferPos
let oldLimit = currentLimit
guard newByteLimit <= oldLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("MalformedVarint")
}
currentLimit = newByteLimit
recomputeBufferSizeAfterLimit()
return oldLimit
}
public func popLimit(oldLimit:Int) {
currentLimit = oldLimit
recomputeBufferSizeAfterLimit()
}
public func bytesUntilLimit() ->Int {
if currentLimit == Int.max {
return -1
}
let currentAbsolutePosition:Int = totalBytesRetired + bufferPos
return currentLimit - currentAbsolutePosition
}
public func readGroup(fieldNumber:Int, builder:ProtocolBuffersMessageBuilder, extensionRegistry:ExtensionRegistry) throws {
guard recursionDepth < recursionLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded")
}
recursionDepth+=1
_ = try builder.mergeFrom(codedInputStream: self, extensionRegistry:extensionRegistry)
try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: Int32(fieldNumber)))
recursionDepth-=1
}
public func readUnknownGroup(fieldNumber:Int32, builder:UnknownFieldSet.Builder) throws {
guard recursionDepth < recursionLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded")
}
recursionDepth+=1
_ = try builder.mergeFrom(codedInputStream: self)
try checkLastTagWas(value: WireFormat.endGroup.makeTag(fieldNumber: fieldNumber))
recursionDepth-=1
}
public func readMessage(builder:ProtocolBuffersMessageBuilder, extensionRegistry:ExtensionRegistry) throws {
let length = try readRawVarint32()
guard recursionDepth < recursionLimit else {
throw ProtocolBuffersError.invalidProtocolBuffer("Recursion Limit Exceeded")
}
let oldLimit = try pushLimit(byteLimit: Int(length))
recursionDepth+=1
_ = try builder.mergeFrom(codedInputStream: self, extensionRegistry:extensionRegistry)
try checkLastTagWas(value: 0)
recursionDepth-=1
popLimit(oldLimit: oldLimit)
}
}
|
d1a29e9d7bb8fa38c4f584f5065b5d42
| 33.683007 | 132 | 0.558466 | false | false | false | false |
JaSpa/swift
|
refs/heads/master
|
benchmark/single-source/ObjectAllocation.swift
|
apache-2.0
|
10
|
//===--- ObjectAllocation.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 the performance of allocations.
import TestsUtils
final class XX {
var xx: Int
init(_ x: Int) {
xx = x
}
}
final class TreeNode {
let left: XX
let right: XX
init(_ l: XX, _ r: XX) {
left = l
right = r
}
}
final class LinkedNode {
var next: LinkedNode?
var xx: Int
init(_ x: Int, _ n: LinkedNode?) {
xx = x
next = n
}
}
@inline(never)
func getInt(_ x: XX) -> Int {
return x.xx
}
@inline(never)
func testSingleObject() -> Int {
var s = 0
for i in 0..<1000 {
let x = XX(i)
s += getInt(x)
}
return s
}
@inline(never)
func addInts(_ t: TreeNode) -> Int {
return t.left.xx + t.right.xx
}
@inline(never)
func testTree() -> Int {
var s = 0
for i in 0..<300 {
let t = TreeNode(XX(i), XX(i + 1))
s += addInts(t)
}
return s
}
@inline(never)
func addAllInts(_ n: LinkedNode) -> Int {
var s = 0
var iter: LinkedNode? = n
while let iter2 = iter {
s += iter2.xx
iter = iter2.next
}
return s
}
@inline(never)
func testList() -> Int {
var s = 0
for i in 0..<250 {
let l = LinkedNode(i, LinkedNode(27, LinkedNode(42, nil)))
s += addAllInts(l)
}
return s
}
@inline(never)
func identity(_ x: Int) -> Int {
return x
}
@inline(never)
func testArray() -> Int {
var s = 0
for _ in 0..<1000 {
for i in [0, 1, 2] {
s += identity(i)
}
}
return s
}
@inline(never)
public func run_ObjectAllocation(_ N: Int) {
var SingleObjectResult = 0
var TreeResult = 0
var ListResult = 0
var ArrayResult = 0
for _ in 0..<N {
SingleObjectResult = testSingleObject()
TreeResult = testTree()
ListResult = testList()
ArrayResult = testArray()
}
CheckResults(SingleObjectResult == 499500,
"Incorrect results in testSingleObject")
CheckResults(TreeResult == 90000,
"Incorrect results in testTree")
CheckResults(ListResult == 48375,
"Incorrect results in testList")
CheckResults(ArrayResult == 3000,
"Incorrect results in testArray")
}
|
283186a09a81f077c44c001c75fcf40f
| 18.111111 | 80 | 0.57907 | false | true | false | false |
dnseitz/YAPI
|
refs/heads/master
|
YAPI/YAPI/V2/V2_YelpPhoneSearchResponse.swift
|
mit
|
1
|
//
// YelpPhoneSearchResponse.swift
// YAPI
//
// Created by Daniel Seitz on 9/12/16.
// Copyright © 2016 Daniel Seitz. All rights reserved.
//
import Foundation
public final class YelpV2PhoneSearchResponse : YelpV2Response {
public let region: YelpRegion?
public let total: Int?
public let businesses: [YelpBusiness]?
public let error: YelpResponseError?
public init(withJSON data: [String: AnyObject]) {
if let error = data["error"] as? [String: AnyObject] {
self.error = YelpV2PhoneSearchResponse.parseError(errorDict: error)
}
else {
self.error = nil
}
if self.error == nil {
if let regionDict = data["region"] as? [String: AnyObject] {
self.region = YelpRegion(withDict: regionDict)
}
else {
self.region = nil
}
if let total = data["total"] as? Int {
self.total = total
}
else {
self.total = nil
}
var businesses = [YelpBusiness]()
for business in data["businesses"] as! [[String: AnyObject]] {
let yelpBusiness = YelpBusiness(withDict: business)
businesses.append(yelpBusiness)
}
self.businesses = businesses
}
else {
self.region = nil
self.total = nil
self.businesses = nil
}
}
}
|
c46e012b6cba18003e43fd2a01934e5b
| 23.698113 | 73 | 0.608862 | false | false | false | false |
GitHubZebra/JKit-Swift
|
refs/heads/master
|
JKit_Swift/String+Ext.swift
|
mit
|
1
|
//
// String+Ext.swift
// JKit-SwiftDemo
//
// Created by Zebra on 2017/7/25.
// Copyright © 2017年 Zebra. All rights reserved.
//
import UIKit
/// 正则验证
///
/// - email: 邮箱
/// - phoneNum: 手机号
/// - username: 用户名
/// - password: 密码
/// - nickname: 昵称
/// - URL: url
/// - IP: IP
///
/// **用法**
///
///Validate.URL("https://www.baidu.com").isRight
///
public enum Validate {
case email( _: String )
case phoneNum( _: String )
case username( _: String )
case password( _: String )
case nickname( _: String )
case URL( _: String )
case IP( _: String )
case chinese( _: String)
case number( _: String)
case money( _: String)
case identityCard( _: String )
public var isRight: Bool {
var predicateStr: String!
var currObject: String!
switch self {
case let .email(str):
predicateStr = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
currObject = str
case let .phoneNum(str):
predicateStr = "^((13[0,0-9])|(15[0,0-9])|(16[0,0-9])|(17[0,0-9])|(18[0,0-9]))\\d{8}$"
currObject = str
case let .username(str):
predicateStr = "^[A-Za-z0-9]{6,18}+$"
currObject = str
case let .password(str):
predicateStr = "^[a-zA-Z0-9]{6,18}+$"
currObject = str
case let .nickname(str):
predicateStr = "^[\\u4e00-\\u9fa5]{4,8}$"
currObject = str
case let .URL(str):
predicateStr = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
currObject = str
case let .IP(str):
predicateStr = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
currObject = str
case let .chinese(str):
predicateStr = "^[\\u4e00-\\u9fa5]+$"
currObject = str
case let .number(str):
predicateStr = "^[0-9]*$"
currObject = str
case let .money(str):
predicateStr = "^(0|[1-9][0-9]*)(\\.[0-9]{0,2})?$"
currObject = str
case let .identityCard(str):
predicateStr = "^(\\d{14}|\\d{17})(\\d|[xX])$"
currObject = str
}
guard let regex = try? NSRegularExpression(pattern: predicateStr, options: NSRegularExpression.Options(rawValue:0)), currObject != nil else {
return false
}
let res = regex.matches(in: currObject, options: NSRegularExpression.MatchingOptions(rawValue:0), range: NSMakeRange(0, currObject.count))
return res.count > 0 ? true : false
}
}
extension String {
//MARK: -转16进制
public func j_toHex() -> String? {
guard var tmpid = Int(self) else {
return nil
}
var nLetterValue = "" , str = ""
var ttmpig: Int = 0
for _ in 0 ..< 9 {
ttmpig = tmpid % 16
tmpid = tmpid / 16
switch ttmpig {
case 10:
nLetterValue = "A"
case 11:
nLetterValue = "B"
case 12:
nLetterValue = "C"
case 13:
nLetterValue = "D"
case 14:
nLetterValue = "E"
case 15:
nLetterValue = "F"
default:
nLetterValue = "\(ttmpig)"
}
str = nLetterValue + str
}
return str
}
//MARK: -判断
/// 邮箱判断
///
/// - Returns: true/false
public func j_isEmail() -> Bool { return Validate.email(self).isRight }
/// 手机号判断
///
/// - Returns: true/false
public func j_isMobile() -> Bool { return Validate.phoneNum(self).isRight }
/// 钱规则判断
///
/// - Returns: true/false
public func j_isMoney() -> Bool { return Validate.money(self).isRight }
/// 数字判断
///
/// - Returns: true/false
public func j_isNumber() -> Bool { return Validate.number(self).isRight }
/// 身份证号判断
///
/// - Returns: true/false
public func j_isIdentityCard() -> Bool { return Validate.identityCard(self).isRight }
/// 用户名判断 无特殊字符 6-18 位
///
/// - Returns: true/false
public func j_isUserName() -> Bool { return Validate.username(self).isRight }
/// 密码判断 无特殊字符 6-18 位
///
/// - Returns: true/false
public func j_isPassword() -> Bool { return Validate.password(self).isRight }
/// 昵称判断 中文 4-8 位
///
/// - Returns: true/false
public func j_isNickname() -> Bool { return Validate.nickname(self).isRight }
/// URL 判断
///
/// - Returns: true/false
public func j_isURL() -> Bool { return Validate.URL(self).isRight }
/// IP 判断
///
/// - Returns: true/false
public func j_isIP() -> Bool { return Validate.IP(self).isRight }
/// 中文判断
///
/// - Returns: true/false
public func j_isChinese() -> Bool { return Validate.chinese(self).isRight }
//MARK: -计算文字的 size
/// 获取文字宽高
///
/// - Parameters:
/// - font: 文字大小
/// - constrainedSize: 最大范围
/// - Returns: text.size
public func j_size( font: UIFont, constrainedSize: CGSize) -> CGSize {
var resultSize = CGSize()
guard !self.isEmpty else {
return resultSize
}
let dic = NSDictionary(object: font, forKey: NSAttributedStringKey.font as NSCopying)
resultSize = self.boundingRect(with: constrainedSize, options: .usesLineFragmentOrigin, attributes: dic as? [NSAttributedStringKey : AnyObject], context:nil).size
return resultSize
}
/// 获取文字宽
///
/// - Parameters:
/// - font: 文字大小
/// - constrainedSize: 最大范围
/// - Returns: text.size.width
public func j_width( font: UIFont, constrainedSize: CGSize) -> CGFloat {
return j_size(font: font, constrainedSize: constrainedSize).width
}
/// 获取文字高
///
/// - Parameters:
/// - font: 文字大小
/// - constrainedSize: 最大范围
/// - Returns: text.size.height
public func j_height( font: UIFont, constrainedSize: CGSize) -> CGFloat {
return j_size(font: font, constrainedSize: constrainedSize).height
}
/// json -> 数组
///
/// - Returns: Array<Any>?
func j_toArray() -> [Any]? {
let jsonObject = try? JSONSerialization.jsonObject(with: self.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments)
return jsonObject as? [Any]
}
/// json -> 字典
///
/// - Returns: [String: Any]?
func j_toDictionary() -> [String: Any]? {
let jsonObject = try? JSONSerialization.jsonObject(with: self.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments)
return jsonObject as? [String: Any]
}
/// 返回沙盒文件路径
///
/// - Returns: 路径
public func j_documentsFile() -> String {
return NSSearchPathForDirectoriesInDomains(.documentationDirectory, .userDomainMask, true)[0].appending(self)
}
/// 删除沙盒中的文件
///
/// - Returns: 成功/失败
@discardableResult public func j_removeDocumentsFile() -> Bool {
do {
try FileManager.default.removeItem(atPath: NSSearchPathForDirectoriesInDomains(.documentationDirectory, .userDomainMask, true)[0].appending(self))
return true
} catch {
return false
}
}
/// 写入系统偏好
///
/// - Parameter key: key
/// - Returns: 成功/失败
@discardableResult public func j_saveUserDefaults( toKey key: String ) -> Bool {
UserDefaults.standard.set(self, forKey: key)
return UserDefaults.standard.synchronize()
}
/// 获取系统偏好
///
/// - Returns: value
public func j_getUserDefaults() -> Any? {
return UserDefaults.standard.value(forKey: self)
}
}
|
5d34eeb00f66fb14cf26be88d88f2eaa
| 25.551402 | 170 | 0.499472 | false | false | false | false |
xcodeswift/xcproj
|
refs/heads/master
|
Sources/XcodeProj/Extensions/Dictionary+Enumerate.swift
|
mit
|
1
|
import Foundation
extension Dictionary {
func enumerateKeysAndObjects(
options opts: NSEnumerationOptions = [],
using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) throws -> Void
) throws {
var blockError: Error?
// For performance it is very important to create a separate dictionary instance.
// (self as NSDictionary).enumerateKeys... - works much slower
let dictionary = NSDictionary(dictionary: self)
dictionary.enumerateKeysAndObjects(options: opts) { key, obj, stops in
do {
try block(key, obj, stops)
} catch {
blockError = error
stops.pointee = true
}
}
if let error = blockError {
throw error
}
}
}
|
90f7437ae5ef54afe4f734924c2006de
| 32.416667 | 89 | 0.581047 | false | false | false | false |
DigiFarm/BeaconSDK
|
refs/heads/master
|
Example/BeaconSDK/StreamViewController.swift
|
apache-2.0
|
1
|
//
// StreamViewController.swift
// BeaconSDKTestClient
//
// Created by Paul Himes on 3/9/16.
// Copyright © 2016 Glacial Ridge Technologies. All rights reserved.
//
import UIKit
class StreamViewController: UIViewController {
private var beaconStringObserver: NotificationObserver?
private let maxTextViewCharacterCount = 3000
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
beaconStringObserver = NotificationObserver(notification: beaconStringNotification, queue: OperationQueue.main) {
[weak self] (string) in
self?.displayString(string)
}
}
private func displayString(_ string: String) {
let text = textView.text ?? ""
textView.text = "\(text)\(string)"
if textView.text.count > maxTextViewCharacterCount {
textView.text = String(textView.text.suffix(maxTextViewCharacterCount))
}
textView.scrollRangeToVisible(NSMakeRange(textView.text.count - 1, 1))
}
}
|
0fea320d3ae7849f210c85e4cdae3731
| 28.555556 | 121 | 0.670113 | false | false | false | false |
RevenueCat/purchases-ios
|
refs/heads/main
|
Sources/LocalReceiptParsing/ReceiptParser.swift
|
mit
|
1
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ReceiptParser.swift
//
// Created by Andrés Boedo on 7/22/20.
//
import Foundation
class ReceiptParser {
static let `default`: ReceiptParser = .init()
private let containerBuilder: ASN1ContainerBuilder
private let receiptBuilder: AppleReceiptBuilder
init(containerBuilder: ASN1ContainerBuilder = ASN1ContainerBuilder(),
receiptBuilder: AppleReceiptBuilder = AppleReceiptBuilder()) {
self.containerBuilder = containerBuilder
self.receiptBuilder = receiptBuilder
}
func receiptHasTransactions(receiptData: Data) -> Bool {
Logger.info(Strings.receipt.parsing_receipt)
if let receipt = try? parse(from: receiptData) {
return receipt.inAppPurchases.count > 0
}
Logger.warn(Strings.receipt.parsing_receipt_failed(fileName: #fileID, functionName: #function))
return true
}
func parse(from receiptData: Data) throws -> AppleReceipt {
let intData = [UInt8](receiptData)
let asn1Container = try containerBuilder.build(fromPayload: ArraySlice(intData))
guard let receiptASN1Container = try findASN1Container(withObjectId: ASN1ObjectIdentifier.data,
inContainer: asn1Container) else {
Logger.error(Strings.receipt.data_object_identifer_not_found_receipt)
throw ReceiptReadingError.dataObjectIdentifierMissing
}
let receipt = try receiptBuilder.build(fromContainer: receiptASN1Container)
Logger.info(Strings.receipt.parsing_receipt_success)
return receipt
}
}
// @unchecked because:
// - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe.
extension ReceiptParser: @unchecked Sendable {}
// MARK: -
private extension ReceiptParser {
func findASN1Container(withObjectId objectId: ASN1ObjectIdentifier,
inContainer container: ASN1Container) throws -> ASN1Container? {
if container.encodingType == .constructed {
for (index, internalContainer) in container.internalContainers.enumerated() {
if internalContainer.containerIdentifier == .objectIdentifier {
let objectIdentifier = try ASN1ObjectIdentifierBuilder.build(
fromPayload: internalContainer.internalPayload)
if objectIdentifier == objectId && index < container.internalContainers.count - 1 {
// the container that holds the data comes right after the one with the object identifier
return container.internalContainers[index + 1]
}
} else {
let receipt = try findASN1Container(withObjectId: objectId, inContainer: internalContainer)
if receipt != nil {
return receipt
}
}
}
}
return nil
}
}
|
618688c8872f0d9df1e9311c715ccd05
| 37.658824 | 117 | 0.644857 | false | false | false | false |
lyft/SwiftLint
|
refs/heads/master
|
Source/SwiftLintFramework/Models/AccessControlLevel.swift
|
mit
|
1
|
import Foundation
public enum AccessControlLevel: String, CustomStringConvertible {
case `private` = "source.lang.swift.accessibility.private"
case `fileprivate` = "source.lang.swift.accessibility.fileprivate"
case `internal` = "source.lang.swift.accessibility.internal"
case `public` = "source.lang.swift.accessibility.public"
case `open` = "source.lang.swift.accessibility.open"
internal init?(description value: String) {
switch value {
case "private": self = .private
case "fileprivate": self = .fileprivate
case "internal": self = .internal
case "public": self = .public
case "open": self = .open
default: return nil
}
}
init?(identifier value: String) {
self.init(rawValue: value)
}
public var description: String {
switch self {
case .private: return "private"
case .fileprivate: return "fileprivate"
case .internal: return "internal"
case .public: return "public"
case .open: return "open"
}
}
// Returns true if is `private` or `fileprivate`
var isPrivate: Bool {
return self == .private || self == .fileprivate
}
}
extension AccessControlLevel: Comparable {
private var priority: Int {
switch self {
case .private: return 1
case .fileprivate: return 2
case .internal: return 3
case .public: return 4
case .open: return 5
}
}
public static func < (lhs: AccessControlLevel, rhs: AccessControlLevel) -> Bool {
return lhs.priority < rhs.priority
}
}
|
ea01936a21452604e8c631ec7a6989e1
| 28.214286 | 85 | 0.619804 | false | false | false | false |
DaveWoodCom/XCGLogger
|
refs/heads/master
|
Examples/Pippin/Pods/XCGLogger/Sources/XCGLogger/LogFormatters/ANSIColorLogFormatter.swift
|
mit
|
5
|
//
// ANSIColorLogFormatter.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2016-08-30.
// Copyright © 2016 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
// MARK: - ANSIColorLogFormatter
/// A log formatter that will add ANSI colour codes to the message
open class ANSIColorLogFormatter: LogFormatterProtocol, CustomDebugStringConvertible {
/// ANSI Escape code
public static let escape: String = "\u{001b}["
/// ANSI Reset colours code
public static let reset: String = "\(escape)m"
/// Enum to specify ANSI colours
public enum ANSIColor: CustomStringConvertible {
case black
case red
case green
case yellow
case blue
case magenta
case cyan
case lightGrey, lightGray
case darkGrey, darkGray
case lightRed
case lightGreen
case lightYellow
case lightBlue
case lightMagenta
case lightCyan
case white
case `default`
case rgb(red: Int, green: Int, blue: Int)
case colorIndex(number: Int)
public var foregroundCode: String {
switch self {
case .black:
return "30"
case .red:
return "31"
case .green:
return "32"
case .yellow:
return "33"
case .blue:
return "34"
case .magenta:
return "35"
case .cyan:
return "36"
case .lightGrey, .lightGray:
return "37"
case .darkGrey, .darkGray:
return "90"
case .lightRed:
return "91"
case .lightGreen:
return "92"
case .lightYellow:
return "93"
case .lightBlue:
return "94"
case .lightMagenta:
return "95"
case .lightCyan:
return "96"
case .white:
return "97"
case .default: // Note: Different from the default: at the end of a switch, this is the `default` colour
return "39"
case .rgb(let red, let green, let blue):
return "38;2;\(min(max(0, red), 255));\(min(max(0, green), 255));\(min(max(0, blue), 255))"
case .colorIndex(let number):
return "38;5;\(min(max(0, number), 255))"
}
}
public var backgroundCode: String {
switch self {
case .black:
return "40"
case .red:
return "41"
case .green:
return "42"
case .yellow:
return "43"
case .blue:
return "44"
case .magenta:
return "45"
case .cyan:
return "46"
case .lightGrey, .lightGray:
return "47"
case .darkGrey, .darkGray:
return "100"
case .lightRed:
return "101"
case .lightGreen:
return "102"
case .lightYellow:
return "103"
case .lightBlue:
return "104"
case .lightMagenta:
return "105"
case .lightCyan:
return "106"
case .white:
return "107"
case .default: // Note: Different from the default: at the end of a switch, this is the `default` colour
return "49"
case .rgb(let red, let green, let blue):
return "48;2;\(min(max(0, red), 255));\(min(max(0, green), 255));\(min(max(0, blue), 255))"
case .colorIndex(let number):
return "48;5;\(min(max(0, number), 255))"
}
}
/// Human readable description of this colour (CustomStringConvertible)
public var description: String {
switch self {
case .black:
return "Black"
case .red:
return "Red"
case .green:
return "Green"
case .yellow:
return "Yellow"
case .blue:
return "Blue"
case .magenta:
return "Magenta"
case .cyan:
return "Cyan"
case .lightGrey, .lightGray:
return "Light Grey"
case .darkGrey, .darkGray:
return "Dark Grey"
case .lightRed:
return "Light Red"
case .lightGreen:
return "Light Green"
case .lightYellow:
return "Light Yellow"
case .lightBlue:
return "Light Blue"
case .lightMagenta:
return "Light Magenta"
case .lightCyan:
return "Light Cyan"
case .white:
return "White"
case .default: // Note: Different from the default: at the end of a switch, this is the `default` colour
return "Default"
case .rgb(let red, let green, let blue):
return String(format: "(r: %d, g: %d, b: %d) #%02X%02X%02X", red, green, blue, red, green, blue)
case .colorIndex(let number):
return "ANSI color index: \(number)"
}
}
}
/// Enum to specific ANSI options
public enum ANSIOption: CustomStringConvertible {
case bold
case faint
case italic
case underline
case blink
case blinkFast
case strikethrough
public var code: String {
switch self {
case .bold:
return "1"
case .faint:
return "2"
case .italic:
return "3"
case .underline:
return "4"
case .blink:
return "5"
case .blinkFast:
return "6"
case .strikethrough:
return "9"
}
}
public var description: String {
switch self {
case .bold:
return "Bold"
case .faint:
return "Faint"
case .italic:
return "Italic"
case .underline:
return "Underline"
case .blink:
return "Blink"
case .blinkFast:
return "Blink Fast"
case .strikethrough:
return "Strikethrough"
}
}
}
/// Internal cache of the ANSI codes for each log level
internal var formatStrings: [XCGLogger.Level: String] = [:]
/// Internal cache of the description for each log level
internal var descriptionStrings: [XCGLogger.Level: String] = [:]
public init() {
resetFormatting()
}
/// Set the colours and/or options for a specific log level.
///
/// - Parameters:
/// - level: The log level.
/// - foregroundColor: The text colour of the message. **Default:** Restore default text colour
/// - backgroundColor: The background colour of the message. **Default:** Restore default background colour
/// - options: Array of ANSIOptions to apply to the message. **Default:** No options
///
/// - Returns: Nothing
///
open func colorize(level: XCGLogger.Level, with foregroundColor: ANSIColor = .default, on backgroundColor: ANSIColor = .default, options: [ANSIOption] = []) {
var codes: [String] = [foregroundColor.foregroundCode, backgroundColor.backgroundCode]
var description: String = "\(foregroundColor) on \(backgroundColor)"
for option in options {
codes.append(option.code)
description += "/\(option)"
}
formatStrings[level] = ANSIColorLogFormatter.escape + codes.joined(separator: ";") + "m"
descriptionStrings[level] = description
}
/// Set the colours and/or options for a specific log level.
///
/// - Parameters:
/// - level: The log level.
/// - custom: A specific ANSI code to use.
///
/// - Returns: Nothing
///
open func colorize(level: XCGLogger.Level, custom: String) {
if custom.hasPrefix(ANSIColorLogFormatter.escape) {
formatStrings[level] = "\(custom)"
descriptionStrings[level] = "Custom: \(custom[custom.index(custom.startIndex, offsetBy: ANSIColorLogFormatter.escape.lengthOfBytes(using: .utf8)) ..< custom.endIndex])"
}
else {
formatStrings[level] = ANSIColorLogFormatter.escape + "\(custom)"
descriptionStrings[level] = "Custom: \(custom)"
}
}
/// Get the cached ANSI codes for the specified log level.
///
/// - Parameters:
/// - level: The log level.
///
/// - Returns: The ANSI codes for the specified log level.
///
internal func formatString(for level: XCGLogger.Level) -> String {
return formatStrings[level] ?? ANSIColorLogFormatter.reset
}
/// Apply a default set of colours.
///
/// - Parameters: None
///
/// - Returns: Nothing
///
open func resetFormatting() {
colorize(level: .verbose, with: .white, options: [.bold])
colorize(level: .debug, with: .black)
colorize(level: .info, with: .blue)
colorize(level: .warning, with: .yellow)
colorize(level: .error, with: .red, options: [.bold])
colorize(level: .severe, with: .white, on: .red)
colorize(level: .none)
}
/// Clear all previously set colours. (Sets each log level back to default)
///
/// - Parameters: None
///
/// - Returns: Nothing
///
open func clearFormatting() {
colorize(level: .verbose)
colorize(level: .debug)
colorize(level: .info)
colorize(level: .warning)
colorize(level: .error)
colorize(level: .severe)
colorize(level: .none)
}
// MARK: - LogFormatterProtocol
/// Apply some additional formatting to the message if appropriate.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: message with the additional formatting
///
@discardableResult open func format(logDetails: inout LogDetails, message: inout String) -> String {
message = "\(formatString(for: logDetails.level))\(message)\(ANSIColorLogFormatter.reset)"
return message
}
// MARK: - CustomDebugStringConvertible
open var debugDescription: String {
get {
var description: String = "\(extractTypeName(self)): "
for level in XCGLogger.Level.allCases {
description += "\n\t- \(level) > \(descriptionStrings[level] ?? "None")"
}
return description
}
}
}
|
90be21e40e3fe2d6a1e528eabc5254f1
| 31.94152 | 180 | 0.516954 | false | false | false | false |
dvor/Antidote
|
refs/heads/master
|
Antidote/FriendListCell.swift
|
mit
|
1
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import SnapKit
class FriendListCell: BaseCell {
struct Constants {
static let AvatarSize = 30.0
static let AvatarLeftOffset = 10.0
static let AvatarRightOffset = 16.0
static let TopLabelHeight = 22.0
static let MinimumBottomLabelHeight = 15.0
static let VerticalOffset = 3.0
}
fileprivate var avatarView: ImageViewWithStatus!
fileprivate var topLabel: UILabel!
fileprivate var bottomLabel: UILabel!
fileprivate var arrowImageView: UIImageView!
override func setupWithTheme(_ theme: Theme, model: BaseCellModel) {
super.setupWithTheme(theme, model: model)
guard let friendModel = model as? FriendListCellModel else {
assert(false, "Wrong model \(model) passed to cell \(self)")
return
}
separatorInset.left = CGFloat(Constants.AvatarLeftOffset + Constants.AvatarSize + Constants.AvatarRightOffset)
avatarView.imageView.image = friendModel.avatar
avatarView.userStatusView.theme = theme
avatarView.userStatusView.userStatus = friendModel.status
avatarView.userStatusView.isHidden = friendModel.hideStatus
topLabel.text = friendModel.topText
topLabel.textColor = theme.colorForType(.NormalText)
bottomLabel.text = friendModel.bottomText
bottomLabel.textColor = theme.colorForType(.FriendCellStatus)
bottomLabel.numberOfLines = friendModel.multilineBottomtext ? 0 : 1
accessibilityLabel = friendModel.accessibilityLabel
accessibilityValue = friendModel.accessibilityValue
}
override func createViews() {
super.createViews()
avatarView = ImageViewWithStatus()
contentView.addSubview(avatarView)
topLabel = UILabel()
topLabel.font = UIFont.systemFont(ofSize: 18.0)
contentView.addSubview(topLabel)
bottomLabel = UILabel()
bottomLabel.font = UIFont.antidoteFontWithSize(12.0, weight: .light)
contentView.addSubview(bottomLabel)
let image = UIImage(named: "right-arrow")!.flippedToCorrectLayout()
arrowImageView = UIImageView(image: image)
arrowImageView.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal)
contentView.addSubview(arrowImageView)
}
override func installConstraints() {
super.installConstraints()
avatarView.snp.makeConstraints {
$0.leading.equalTo(contentView).offset(Constants.AvatarLeftOffset)
$0.centerY.equalTo(contentView)
$0.size.equalTo(Constants.AvatarSize)
}
topLabel.snp.makeConstraints {
$0.leading.equalTo(avatarView.snp.trailing).offset(Constants.AvatarRightOffset)
$0.top.equalTo(contentView).offset(Constants.VerticalOffset)
$0.height.equalTo(Constants.TopLabelHeight)
}
bottomLabel.snp.makeConstraints {
$0.leading.trailing.equalTo(topLabel)
$0.top.equalTo(topLabel.snp.bottom)
$0.bottom.equalTo(contentView).offset(-Constants.VerticalOffset)
$0.height.greaterThanOrEqualTo(Constants.MinimumBottomLabelHeight)
}
arrowImageView.snp.makeConstraints {
$0.centerY.equalTo(contentView)
$0.leading.greaterThanOrEqualTo(topLabel.snp.trailing)
$0.trailing.equalTo(contentView)
}
}
}
// Accessibility
extension FriendListCell {
override var isAccessibilityElement: Bool {
get {
return true
}
set {}
}
// Label and value are set in setupWithTheme:model: method
// var accessibilityLabel: String?
// var accessibilityValue: String?
override var accessibilityTraits: UIAccessibilityTraits {
get {
return UIAccessibilityTraitButton
}
set {}
}
}
|
b2e14a72dc32e3e896bea956b19d0c07
| 33.166667 | 118 | 0.677561 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
refs/heads/develop
|
Carthage/Checkouts/SwiftEntryKit/Source/Model/EntryAttributes/EKAttributes+Precedence.swift
|
apache-2.0
|
3
|
//
// EKAttributes+Precedence.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/29/18.
//
import Foundation
fileprivate extension Int {
var isValidDisplayPriority: Bool {
return self >= EKAttributes.Precedence.Priority.minRawValue && self <= EKAttributes.Precedence.Priority.maxRawValue
}
}
public extension EKAttributes {
/**
Describes the manner on which the entry is pushed and displayed.
See the various values of more explanation.
*/
enum Precedence {
/**
The display priority of the entry - Determines whether is can be overriden by other entries.
Must be in range [0...1000]
*/
public struct Priority: Hashable, Equatable, RawRepresentable, Comparable {
public var rawValue: Int
public var hashValue: Int {
return rawValue
}
public init(_ rawValue: Int) {
assert(rawValue.isValidDisplayPriority, "Display Priority must be in range [\(Priority.minRawValue)...\(Priority.maxRawValue)]")
self.rawValue = rawValue
}
public init(rawValue: Int) {
assert(rawValue.isValidDisplayPriority, "Display Priority must be in range [\(Priority.minRawValue)...\(Priority.maxRawValue)]")
self.rawValue = rawValue
}
public static func == (lhs: Priority, rhs: Priority) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func < (lhs: Priority, rhs: Priority) -> Bool {
return lhs.rawValue < rhs.rawValue
}
}
/**
Describes the queueing heoristic of entries.
*/
public enum QueueingHeuristic {
/** Determines the heuristic which the entry-queue is based on */
public static var value = QueueingHeuristic.priority
/** Chronological - FIFO */
case chronological
/** Ordered by priority */
case priority
/** Returns the caching heuristics mechanism that determines the priority in queue */
var heuristic: EntryCachingHeuristic {
switch self {
case .chronological:
return EKEntryChronologicalQueue()
case .priority:
return EKEntryPriorityQueue()
}
}
}
/**
Describes an *overriding* behavior for a new entry.
- In case no previous entry is currently presented, display the new entry.
- In case there is an entry that is currently presented - override it using the new entry. Also optionally drop all previously enqueued entries.
*/
case override(priority: Priority, dropEnqueuedEntries: Bool)
/**
Describes a FIFO behavior for an entry presentation.
- In case no previous entry is currently presented, display the new entry.
- In case there is an entry that is currently presented - enqueue the new entry, an present it just after the previous one is dismissed.
*/
case enqueue(priority: Priority)
var isEnqueue: Bool {
switch self {
case .enqueue:
return true
default:
return false
}
}
/** Setter / Getter for the display priority */
public var priority: Priority {
set {
switch self {
case .enqueue(priority: _):
self = .enqueue(priority: newValue)
case .override(priority: _, dropEnqueuedEntries: let dropEnqueuedEntries):
self = .override(priority: newValue, dropEnqueuedEntries: dropEnqueuedEntries)
}
}
get {
switch self {
case .enqueue(priority: let priority):
return priority
case .override(priority: let priority, dropEnqueuedEntries: _):
return priority
}
}
}
}
}
/** High priority entries can be overriden by other equal or higher priority entries only.
Entries are ignored as a higher priority entry is being displayed.
High priority entry overrides any other entry including another equal priority one.
You can you on of the values (.max, high, normal, low, min) and also set your own values. */
public extension EKAttributes.Precedence.Priority {
static let maxRawValue = 1000
static let highRawValue = 750
static let normalRawValue = 500
static let lowRawValue = 250
static let minRawValue = 0
/** Max - the highest possible priority of an entry. Can override only entries with *max* priority */
static let max = EKAttributes.Precedence.Priority(rawValue: maxRawValue)
static let high = EKAttributes.Precedence.Priority(rawValue: highRawValue)
static let normal = EKAttributes.Precedence.Priority(rawValue: normalRawValue)
static let low = EKAttributes.Precedence.Priority(rawValue: lowRawValue)
static let min = EKAttributes.Precedence.Priority(rawValue: minRawValue)
}
|
4ea5f0455fd199c90883069823c44eb3
| 36.943662 | 153 | 0.587045 | false | false | false | false |
Chakery/AyLoading
|
refs/heads/master
|
Classes/UIButton+Loading.swift
|
mit
|
1
|
//
// UIButton+Loading.swift
// Pods
//
// Created by Chakery on 2017/9/7.
//
//
import UIKit
extension AyLoading where Base: UIButton {
@discardableResult
public func startLoading(message: String? = nil) -> Bool {
guard !base.ay.isLoading else { return false }
prepareStartLoading()
base.ay.startAnimation(message)
base.isUserInteractionEnabled = false
return true
}
@discardableResult
public func stopLoading() -> Bool {
guard base.ay.isLoading else { return false }
prepareStopLoading()
base.ay.stopAnimation { [weak base] in
base?.isUserInteractionEnabled = true
}
return true
}
private func prepareStartLoading() {
base.titleLabel?.ay.removeFromSuperview(animated: true)
base.imageView?.ay.removeFromSuperview(animated: true)
}
private func prepareStopLoading() {
if let titleLabel = base.titleLabel {
base.ay.addSubview(titleLabel, animated: true)
}
if let imageView = base.imageView {
base.ay.addSubview(imageView, animated: true)
}
}
}
|
67e2f36f74d9d822f0500d569ff92885
| 25.066667 | 63 | 0.618926 | false | false | false | false |
leftdal/youslow
|
refs/heads/master
|
iOS/YouTubeView/YTPlayerEnumerations.swift
|
gpl-3.0
|
1
|
//
// YTPlayerEnumerations.swift
// Demo
//
// Created by to0 on 2/1/15.
// Copyright (c) 2015 to0. All rights reserved.
//
import Foundation
enum YTPlayerState: String {
case Unstarted = "-1"
case Ended = "0"
case Playing = "1"
case Paused = "2"
case Buffering = "3"
case Cued = "5"
case Unknown = "unknown"
}
enum YTPlayerQuality: String {
case Small = "small"
case Medium = "medium"
case Large = "large"
case HD720 = "hd720"
case HD1080 = "hd1080"
case HighRes = "highres"
case Auto = "auto"
case Default = "default"
case Unknown = "unknown"
}
enum YTPlayerError: String {
case InvalidParam = "2"
case HTML5 = "5"
case VideoNotFound = "100"
case NotEmbeddable = "101"
case CannotFindVideo = "105"
}
enum YTPlayerCallback: String {
case OnReady = "onReady"
case OnStateChange = "onStateChange"
case OnPlaybackQualityChange = "onPlaybackQualityChange"
case OnError = "onError"
case OnYouTubeIframeAPIReady = "onYouTubeIframeAPIReady"
}
|
9ab5ff76093f2acf6141e017f1f406d6
| 20.895833 | 60 | 0.644762 | false | false | false | false |
dclelland/AudioKit
|
refs/heads/master
|
AudioKit/Common/Nodes/Generators/Oscillators/FM Oscillator/AKFMOscillator.swift
|
mit
|
1
|
//
// AKFMOscillator.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// Classic FM Synthesis audio generation.
///
/// - parameter baseFrequency: In cycles per second, or Hz, this is the common denominator for the carrier and modulating frequencies.
/// - parameter carrierMultiplier: This multiplied by the baseFrequency gives the carrier frequency.
/// - parameter modulatingMultiplier: This multiplied by the baseFrequency gives the modulating frequency.
/// - parameter modulationIndex: This multiplied by the modulating frequency gives the modulation amplitude.
/// - parameter amplitude: Output Amplitude.
///
public class AKFMOscillator: AKVoice {
// MARK: - Properties
internal var internalAU: AKFMOscillatorAudioUnit?
internal var token: AUParameterObserverToken?
private var waveform: AKTable?
private var baseFrequencyParameter: AUParameter?
private var carrierMultiplierParameter: AUParameter?
private var modulatingMultiplierParameter: AUParameter?
private var modulationIndexParameter: AUParameter?
private var amplitudeParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// In cycles per second, or Hz, this is the common denominator for the carrier and modulating frequencies.
public var baseFrequency: Double = 440 {
willSet {
if baseFrequency != newValue {
if internalAU!.isSetUp() {
baseFrequencyParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.baseFrequency = Float(newValue)
}
}
}
}
/// This multiplied by the baseFrequency gives the carrier frequency.
public var carrierMultiplier: Double = 1.0 {
willSet {
if carrierMultiplier != newValue {
if internalAU!.isSetUp() {
carrierMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.carrierMultiplier = Float(newValue)
}
}
}
}
/// This multiplied by the baseFrequency gives the modulating frequency.
public var modulatingMultiplier: Double = 1 {
willSet {
if modulatingMultiplier != newValue {
if internalAU!.isSetUp() {
modulatingMultiplierParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.modulatingMultiplier = Float(newValue)
}
}
}
}
/// This multiplied by the modulating frequency gives the modulation amplitude.
public var modulationIndex: Double = 1 {
willSet {
if modulationIndex != newValue {
if internalAU!.isSetUp() {
modulationIndexParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.modulationIndex = Float(newValue)
}
}
}
}
/// Output Amplitude.
public var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
if internalAU!.isSetUp() {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.amplitude = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
override public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize the oscillator with defaults
public convenience override init() {
self.init(waveform: AKTable(.Sine))
}
/// Initialize this oscillator node
///
/// - parameter baseFrequency: In cycles per second, or Hz, this is the common denominator for the carrier and modulating frequencies.
/// - parameter carrierMultiplier: This multiplied by the baseFrequency gives the carrier frequency.
/// - parameter modulatingMultiplier: This multiplied by the baseFrequency gives the modulating frequency.
/// - parameter modulationIndex: This multiplied by the modulating frequency gives the modulation amplitude.
/// - parameter amplitude: Output Amplitude.
///
public init(
waveform: AKTable,
baseFrequency: Double = 440,
carrierMultiplier: Double = 1.0,
modulatingMultiplier: Double = 1,
modulationIndex: Double = 1,
amplitude: Double = 1) {
self.waveform = waveform
self.baseFrequency = baseFrequency
self.carrierMultiplier = carrierMultiplier
self.modulatingMultiplier = modulatingMultiplier
self.modulationIndex = modulationIndex
self.amplitude = amplitude
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x666f7363 /*'fosc'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKFMOscillatorAudioUnit.self,
asComponentDescription: description,
name: "Local AKFMOscillator",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKFMOscillatorAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
self.internalAU?.setupWaveform(Int32(waveform.size))
for i in 0 ..< waveform.size {
self.internalAU?.setWaveformValue(waveform.values[i], atIndex: UInt32(i))
}
}
guard let tree = internalAU?.parameterTree else { return }
baseFrequencyParameter = tree.valueForKey("baseFrequency") as? AUParameter
carrierMultiplierParameter = tree.valueForKey("carrierMultiplier") as? AUParameter
modulatingMultiplierParameter = tree.valueForKey("modulatingMultiplier") as? AUParameter
modulationIndexParameter = tree.valueForKey("modulationIndex") as? AUParameter
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.baseFrequencyParameter!.address {
self.baseFrequency = Double(value)
} else if address == self.carrierMultiplierParameter!.address {
self.carrierMultiplier = Double(value)
} else if address == self.modulatingMultiplierParameter!.address {
self.modulatingMultiplier = Double(value)
} else if address == self.modulationIndexParameter!.address {
self.modulationIndex = Double(value)
} else if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
}
}
}
internalAU?.baseFrequency = Float(baseFrequency)
internalAU?.carrierMultiplier = Float(carrierMultiplier)
internalAU?.modulatingMultiplier = Float(modulatingMultiplier)
internalAU?.modulationIndex = Float(modulationIndex)
internalAU?.amplitude = Float(amplitude)
}
/// Function create an identical new node for use in creating polyphonic instruments
override public func duplicate() -> AKVoice {
let copy = AKFMOscillator(waveform: self.waveform!, baseFrequency: self.baseFrequency, carrierMultiplier: self.carrierMultiplier, modulatingMultiplier: self.modulatingMultiplier, modulationIndex: self.modulationIndex, amplitude: self.amplitude)
return copy
}
/// Function to start, play, or activate the node, all do the same thing
override public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
override public func stop() {
self.internalAU!.stop()
}
}
|
2ac0665053cc0f758423928146166f1a
| 39.144796 | 252 | 0.635257 | false | false | false | false |
noppoMan/Slimane
|
refs/heads/0.9.x
|
Sources/Slimane/HTTP/Slimane+Server.swift
|
mit
|
1
|
//
// Serve.swift
// Slimane
//
// Created by Yuki Takei on 4/16/16.
//
//
extension Slimane {
public func listen(host: String = "0.0.0.0", port: Int = 3000) throws {
let server = Skelton { [unowned self] result in
switch result {
case .onRequest(let request, let stream):
self.dispatch(request, stream)
case .onError(let error):
print(error)
default:
break //ignore eof
}
}
// proxy settings
server.setNoDelay = self.setNodelay
server.keepAliveTimeout = self.keepAliveTimeout
server.backlog = self.backlog
// bind & listen
if Cluster.isMaster {
try server.bind(host: host, port: port)
}
try server.listen()
}
private func dispatch(_ request: Request, _ stream: DuplexStream){
middlewares.chain(request: request, response: Response()) { [unowned self] chainer in
switch chainer {
case .respond(let response):
self.respond(request, response, stream)
case .next(let request, let response):
if let (route, request) = self.router.matchedRoute(for: request) {
route.middlewares.chain(request: request, response: response) { [unowned self] chainer in
switch chainer {
// middleware respond
case .respond(let response):
self.respond(request, response, stream)
case .next(let request, let response):
route.respond(request, response) { chainer in
switch chainer {
// route respond
case .respond(let response):
self.respond(request, response, stream)
case .next(let request, let response):
self.respondError(MiddlewareError.noNextMiddleware, request, response, stream)
case .error(let error):
self.respondError(error, request, response, stream)
}
}
case .error(let error):
self.respondError(error, request, response, stream)
}
}
} else {
let error = RoutingError.routeNotFound(path: request.path ?? "/")
self.respondError(error, request, response, stream)
}
case .error(let error):
self.respondError(error, request, Response(), stream)
}
}
}
private func respondError(_ error: Error, _ request: Request, _ response: HTTPCore.Response, _ stream: DuplexStream){
self.catchHandler(MiddlewareError.noNextMiddleware, request, response) { [unowned self] chainer in
var response = response
switch chainer {
case .respond(let response):
self.respond(request, response, stream)
case .next(_):
response.status(.internalServerError)
response.text("\(MiddlewareError.noNextMiddleware)")
self.processStream(request, response, stream)
case .error(_):
response.status(.internalServerError)
response.text("Something went wrong.")
self.processStream(request, response, stream)
}
}
}
private func respond(_ request: HTTPCore.Request, _ response: HTTPCore.Response, _ stream: DuplexStream){
if let responder = response.customResponder {
responder.respond(request, response) { [unowned self] chainer in
switch chainer {
case .respond(let response):
self.processStream(request, response, stream)
case .next(_):
var response = response
response.status(.internalServerError)
response.text("\(MiddlewareError.noNextMiddleware)")
self.processStream(request, response, stream)
case .error(let error):
var response = response
response.status(.internalServerError)
response.text("\(error)")
self.processStream(request, response, stream)
}
}
} else {
self.processStream(request, response, stream)
}
}
private func processStream(_ request: HTTPCore.Request, _ response: HTTPCore.Response, _ stream: DuplexStream){
var response = response
response.headers["Server"] = "Slimane"
if response.contentType == nil {
response.contentType = mediaType(forFileExtension: "html")!
}
ResponseSerializer(stream: stream).serialize(response) { [unowned self] result in
if case .failure(_) = result {
return stream.close()
}
self.finallyHandler(request, response)
if let upgradeConnection = response.upgradeConnection {
upgradeConnection(request, stream)
}
if !request.isKeepAlive && response.upgradeConnection == nil {
stream.close()
}
}
}
}
|
1bee61f6448b5833db56d1e468c090df
| 38.503356 | 121 | 0.490146 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Mac/Preferences/Accounts/AddAccountsView.swift
|
mit
|
1
|
//
// AddAccountsView.swift
// NetNewsWire
//
// Created by Stuart Breckenridge on 28/10/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import SwiftUI
import Account
import RSCore
enum AddAccountSections: Int, CaseIterable {
case local = 0
case icloud
case web
case selfhosted
case allOrdered
var sectionHeader: String {
switch self {
case .local:
return NSLocalizedString("Local", comment: "Local Account")
case .icloud:
return NSLocalizedString("iCloud", comment: "iCloud Account")
case .web:
return NSLocalizedString("Web", comment: "Web Account")
case .selfhosted:
return NSLocalizedString("Self-hosted", comment: "Self hosted Account")
case .allOrdered:
return ""
}
}
var sectionFooter: String {
switch self {
case .local:
return NSLocalizedString("Local accounts do not sync feeds across devices", comment: "Local Account")
case .icloud:
return NSLocalizedString("Your iCloud account syncs your feeds across your Mac and iOS devices", comment: "iCloud Account")
case .web:
return NSLocalizedString("Web accounts sync your feeds across all your devices", comment: "Web Account")
case .selfhosted:
return NSLocalizedString("Self-hosted accounts sync your feeds across all your devices", comment: "Self hosted Account")
case .allOrdered:
return ""
}
}
var sectionContent: [AccountType] {
switch self {
case .local:
return [.onMyMac]
case .icloud:
return [.cloudKit]
case .web:
if AppDefaults.shared.isDeveloperBuild {
return [.bazQux, .feedbin, .feedly, .inoreader, .newsBlur, .theOldReader].filter({ $0.isDeveloperRestricted == false })
} else {
return [.bazQux, .feedbin, .feedly, .inoreader, .newsBlur, .theOldReader]
}
case .selfhosted:
return [.freshRSS]
case .allOrdered:
return AddAccountSections.local.sectionContent +
AddAccountSections.icloud.sectionContent +
AddAccountSections.web.sectionContent +
AddAccountSections.selfhosted.sectionContent
}
}
}
struct AddAccountsView: View {
weak var parent: NSHostingController<AddAccountsView>? // required because presentationMode.dismiss() doesn't work
var addAccountDelegate: AccountsPreferencesAddAccountDelegate?
private let chunkLimit = 4 // use this to control number of accounts in each web account column
@State private var selectedAccount: AccountType = .onMyMac
init(delegate: AccountsPreferencesAddAccountDelegate?) {
self.addAccountDelegate = delegate
}
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("Choose an account type to add...")
.font(.headline)
.padding()
localAccount
if !AppDefaults.shared.isDeveloperBuild {
icloudAccount
}
webAccounts
selfhostedAccounts
HStack(spacing: 12) {
Spacer()
if #available(OSX 11.0, *) {
Button(action: {
parent?.dismiss(nil)
}, label: {
Text("Cancel")
.frame(width: 76)
})
.help("Cancel")
.keyboardShortcut(.cancelAction)
} else {
Button(action: {
parent?.dismiss(nil)
}, label: {
Text("Cancel")
.frame(width: 76)
})
.accessibility(label: Text("Add Account"))
}
if #available(OSX 11.0, *) {
Button(action: {
addAccountDelegate?.presentSheetForAccount(selectedAccount)
parent?.dismiss(nil)
}, label: {
Text("Continue")
.frame(width: 76)
})
.help("Add Account")
.keyboardShortcut(.defaultAction)
} else {
Button(action: {
addAccountDelegate?.presentSheetForAccount(selectedAccount)
parent?.dismiss(nil)
}, label: {
Text("Continue")
.frame(width: 76)
})
}
}
.padding(.top, 12)
.padding(.bottom, 4)
}
.pickerStyle(RadioGroupPickerStyle())
.fixedSize(horizontal: false, vertical: true)
.frame(width: 420)
.padding()
}
var localAccount: some View {
VStack(alignment: .leading) {
Text("Local")
.font(.headline)
.padding(.horizontal)
Picker(selection: $selectedAccount, label: Text(""), content: {
ForEach(AddAccountSections.local.sectionContent, id: \.self, content: { account in
HStack(alignment: .center) {
account.image()
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20, alignment: .center)
.padding(.leading, 4)
Text(account.localizedAccountName())
}
.tag(account)
})
})
.pickerStyle(RadioGroupPickerStyle())
.offset(x: 7.5, y: 0)
Text(AddAccountSections.local.sectionFooter).foregroundColor(.gray)
.padding(.horizontal)
.lineLimit(3)
.fixedSize(horizontal: false, vertical: true)
}
}
var icloudAccount: some View {
VStack(alignment: .leading) {
Text("iCloud")
.font(.headline)
.padding(.horizontal)
.padding(.top, 8)
Picker(selection: $selectedAccount, label: Text(""), content: {
ForEach(AddAccountSections.icloud.sectionContent, id: \.self, content: { account in
HStack(alignment: .center) {
account.image()
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20, alignment: .center)
.padding(.leading, 4)
Text(account.localizedAccountName())
}
.tag(account)
})
})
.offset(x: 7.5, y: 0)
.disabled(isCloudInUse())
Text(AddAccountSections.icloud.sectionFooter).foregroundColor(.gray)
.padding(.horizontal)
.lineLimit(3)
.fixedSize(horizontal: false, vertical: true)
}
}
@ViewBuilder
var webAccounts: some View {
VStack(alignment: .leading) {
Text("Web")
.font(.headline)
.padding(.horizontal)
.padding(.top, 8)
HStack {
ForEach(0..<chunkedWebAccounts().count, content: { chunk in
VStack {
Picker(selection: $selectedAccount, label: Text(""), content: {
ForEach(chunkedWebAccounts()[chunk], id: \.self, content: { account in
HStack(alignment: .center) {
account.image()
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20, alignment: .center)
.padding(.leading, 4)
Text(account.localizedAccountName())
}
.tag(account)
})
})
Spacer()
}
})
}
.offset(x: 7.5, y: 0)
Text(AddAccountSections.web.sectionFooter).foregroundColor(.gray)
.padding(.horizontal)
.lineLimit(3)
.fixedSize(horizontal: false, vertical: true)
}
}
var selfhostedAccounts: some View {
VStack(alignment: .leading) {
Text("Self-hosted")
.font(.headline)
.padding(.horizontal)
.padding(.top, 8)
Picker(selection: $selectedAccount, label: Text(""), content: {
ForEach(AddAccountSections.selfhosted.sectionContent, id: \.self, content: { account in
HStack(alignment: .center) {
account.image()
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 20, height: 20, alignment: .center)
.padding(.leading, 4)
Text(account.localizedAccountName())
}.tag(account)
})
})
.offset(x: 7.5, y: 0)
Text(AddAccountSections.selfhosted.sectionFooter).foregroundColor(.gray)
.padding(.horizontal)
.lineLimit(3)
.fixedSize(horizontal: false, vertical: true)
}
}
private func isCloudInUse() -> Bool {
AccountManager.shared.accounts.contains(where: { $0.type == .cloudKit })
}
private func chunkedWebAccounts() -> [[AccountType]] {
AddAccountSections.web.sectionContent.chunked(into: chunkLimit)
}
}
struct AddAccountsView_Previews: PreviewProvider {
static var previews: some View {
AddAccountsView(delegate: nil)
}
}
|
b2c553809406a04ef2ba094c4fdd9eac
| 24.723333 | 126 | 0.650901 | false | false | false | false |
Rush42/SwiftCron
|
refs/heads/master
|
Sources/MonthField.swift
|
mit
|
2
|
import Foundation
class MonthField: Field, FieldCheckerInterface {
func isSatisfiedBy(_ date: Date, value: String) -> Bool {
let month = Calendar.current.component(.month, from: date)
return isSatisfied(String(month), value: value)
}
func increment(_ date: Date, toMatchValue: String) -> Date {
if let nextDate = date.nextDate(matchingUnit: .month, value: toMatchValue) {
return nextDate
}
let calendar = Calendar.current
let midnightComponents = calendar.dateComponents([.day, .month, .year], from: date)
var components = DateComponents()
components.month = 1
return calendar.date(byAdding: components, to: calendar.date(from: midnightComponents)!)!
}
func validate(_ value: String) -> Bool {
return StringValidator.isUpperCaseOrNumber(value)
}
}
|
0c5373ef08d584239bbdc0d21cdeeb86
| 28.481481 | 97 | 0.718593 | false | false | false | false |
ryuichis/swift-lint
|
refs/heads/master
|
Sources/Lint/Rule/RedundantVariableDeclarationKeywordRule.swift
|
apache-2.0
|
2
|
/*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import AST
class RedundantVariableDeclarationKeywordRule: RuleBase, ASTVisitorRule {
let name = "Redundant Variable Declaration Keyword"
var description: String? {
return """
When the result of a function call or computed property is discarded by
a wildcard variable `_`, its `let` or `var` keyword can be safely removed.
"""
}
var examples: [String]? {
return [
"let _ = foo() // _ = foo()",
"var _ = bar // _ = bar",
]
}
let category = Issue.Category.badPractice
private func containsOnlyOneWildcard(_ inits: [PatternInitializer]) -> Bool {
guard inits.count == 1 else {
return false
}
let pattrnInit = inits[0]
if let wildcardPttrn = pattrnInit.pattern as? WildcardPattern,
wildcardPttrn.typeAnnotation == nil,
pattrnInit.initializerExpression != nil
{
return true
}
return false
}
func visit(_ varDecl: VariableDeclaration) throws -> Bool {
if case .initializerList(let inits) = varDecl.body, containsOnlyOneWildcard(inits) {
emitIssue(
varDecl.sourceRange,
description: "`var` keyword is redundant and can be safely removed"
)
}
return true
}
func visit(_ constDecl: ConstantDeclaration) throws -> Bool {
if containsOnlyOneWildcard(constDecl.initializerList) {
emitIssue(
constDecl.sourceRange,
description: "`let` keyword is redundant and can be safely removed"
)
}
return true
}
}
|
fe99a09a944882ecf6203ef4c40fd104
| 28.342466 | 88 | 0.684874 | false | false | false | false |
stulevine/firefox-ios
|
refs/heads/master
|
Storage/SQL/BookmarksSqlite.swift
|
mpl-2.0
|
1
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
class BookmarkTable<T> : GenericTable<BookmarkNode> {
private let favicons = FaviconsTable<Favicon>()
private let joinedFavicons = JoinedFaviconsHistoryTable<(Site, Favicon)>()
override var name: String { return "bookmarks" }
override var version: Int { return 2 }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"guid TEXT NOT NULL UNIQUE, " +
"url TEXT, " +
"parent INTEGER, " +
"faviconId INTEGER, " +
"title TEXT" }
override func create(db: SQLiteDBConnection, version: Int) -> Bool {
return super.create(db, version: version) && favicons.create(db, version: version) && joinedFavicons.create(db, version: version)
}
override func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool {
return super.updateTable(db, from: from, to: to) && favicons.updateTable(db, from: from, to: to) && updateTable(db, from: from, to: to)
}
private func setupFavicon(db: SQLiteDBConnection, item: Type?) {
// If this has an icon attached, try to use it
if let favicon = item?.favicon {
if favicon.id == nil {
favicons.insertOrUpdate(db, obj: favicon)
}
} else {
// Otherwise, lets go look one up for this URL
if let bookmark = item as? BookmarkItem {
let options = QueryOptions(filter: bookmark.url, filterType: FilterType.ExactUrl)
let favicons = joinedFavicons.query(db, options: options)
if favicons.count > 0 {
if let (site, favicon) = favicons[0] as? (Site, Favicon) {
bookmark.favicon = favicon
}
}
}
}
}
override func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
setupFavicon(db, item: item)
return super.insert(db, item: item, err: &err)
}
override func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int {
setupFavicon(db, item: item)
return super.update(db, item: item, err: &err)
}
override func getInsertAndArgs(inout item: BookmarkNode) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.guid)
if let bookmark = item as? BookmarkItem {
args.append(bookmark.url)
} else {
args.append(nil)
}
args.append(item.title)
args.append(item.favicon?.id)
return ("INSERT INTO \(name) (guid, url, title, faviconId) VALUES (?,?,?,?)", args)
}
override func getUpdateAndArgs(inout item: BookmarkNode) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let bookmark = item as? BookmarkItem {
args.append(bookmark.url)
} else {
args.append(nil)
}
args.append(item.title)
args.append(item.favicon?.id)
args.append(item.guid)
return ("UPDATE \(name) SET url = ?, title = ?, faviconId = ? WHERE guid = ?", args)
}
override func getDeleteAndArgs(inout item: BookmarkNode?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let bookmark = item as? BookmarkItem {
if bookmark.guid != "" {
// If there's a guid, we'll delete entries with it
args.append(bookmark.guid)
return ("DELETE FROM \(name) WHERE guid = ?", args)
} else if bookmark.url != "" {
// If there's a url, we'll delete ALL entries with it
args.append(bookmark.url)
return ("DELETE FROM \(name) WHERE url = ?", args)
} else {
// If you passed us something with no url or guid, we'll just have to bail...
return nil
}
}
return ("DELETE FROM \(name)", args)
}
override var factory: ((row: SDRow) -> BookmarkNode)? {
return { row -> BookmarkNode in
let url = row["bookmarkUrl"] as! String
let guid = row["guid"] as! String
let bookmark = BookmarkItem(guid: guid,
title: row["title"] as? String ?? url,
url: url)
bookmark.id = row["bookmarkId"] as? Int
if let faviconUrl = row["faviconUrl"] as? String,
let date = row["faviconDate"] as? Double,
let faviconType = row["faviconType"] as? Int {
bookmark.favicon = Favicon(url: faviconUrl,
date: NSDate(timeIntervalSince1970: date),
type: IconType(rawValue: faviconType)!)
}
return bookmark
}
}
override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
// XXX - This should support querying for a particular bookmark, querying by name/url, and querying
// for everything in a folder. Right now it doesn't do any of that :(
var sql = "SELECT \(name).id as bookmarkId, guid, \(name).url as bookmarkUrl, title, \(favicons.name).url as faviconUrl, date as faviconDate, type as faviconType FROM \(name)" +
" LEFT OUTER JOIN \(favicons.name) ON \(favicons.name).id = \(name).faviconId"
if let filter: AnyObject = options?.filter {
if let type = options?.filterType {
switch(type) {
case .ExactUrl:
args.append(filter)
return ("\(sql) WHERE bookmarkUrl = ?", args)
default:
break
}
}
// Default to search by guid (i.e. for a folder)
args.append(filter)
return ("\(sql) WHERE guid = ?", args)
}
return (sql, args)
}
}
class SqliteBookmarkFolder: BookmarkFolder {
private let cursor: Cursor
override var count: Int {
return cursor.count
}
override subscript(index: Int) -> BookmarkNode {
let bookmark = cursor[index]
if let item = bookmark as? BookmarkItem {
return item
}
// TODO: this is fragile.
return bookmark as! SqliteBookmarkFolder
}
init(guid: String, title: String, children: Cursor) {
self.cursor = children
super.init(guid: guid, title: title)
}
}
public class BookmarksSqliteFactory : BookmarksModelFactory, ShareToDestination {
let db: BrowserDB
let table = BookmarkTable<BookmarkNode>()
public init(files: FileAccessor) {
db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
private func getChildren(guid: String) -> Cursor {
var err: NSError? = nil
return db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: QueryOptions(filter: guid))
})
}
public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
let children = getChildren(folder.guid)
if children.status == .Failure {
failure(children.statusMessage)
return
}
let f = SqliteBookmarkFolder(guid: folder.guid, title: folder.title, children: children)
success(BookmarksModel(modelFactory: self, root: f))
}
public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let children = db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: QueryOptions(filter: guid))
})
let folder = SqliteBookmarkFolder(guid: guid, title: "", children: children)
success(BookmarksModel(modelFactory: self, root: folder))
}
public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let children = db.query(&err, callback: { (connection, err) -> Cursor in
return self.table.query(connection, options: QueryOptions(filter: nil))
})
let folder = SqliteBookmarkFolder(guid: BookmarkRoots.PLACES_FOLDER_GUID, title: "Root", children: children)
success(BookmarksModel(modelFactory: self, root: folder))
}
public var nullModel: BookmarksModel {
let children = Cursor(status: .Failure, msg: "Null model")
let folder = SqliteBookmarkFolder(guid: "Null", title: "Null", children: children)
return BookmarksModel(modelFactory: self, root: folder)
}
public func shareItem(item: ShareItem) {
var err: NSError? = nil
let inserted = db.insert(&err, callback: { (connection, err) -> Int in
var bookmark = BookmarkItem(guid: Bytes.generateGUID(), title: item.title ?? "", url: item.url)
bookmark.favicon = item.favicon
return self.table.insert(connection, item: bookmark, err: &err)
})
}
public func findForUrl(url: String, success: (Cursor) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let children = db.query(&err, callback: { (connection, err) -> Cursor in
let opts = QueryOptions(filter: url, filterType: FilterType.ExactUrl, sort: QuerySort.None)
return self.table.query(connection, options: opts)
})
if children.status == .Failure {
failure(children.statusMessage)
return
}
return success(children)
}
public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) {
findForUrl(url, success: { children in
success(children.count > 0)
}, failure: failure)
}
// Why does this function look so strangely worded? Segfault in the compiler.
public func remove(bookmark: BookmarkNode, success: (Bool) -> (), failure: (Any) -> ()) {
var err: NSError? = nil
let numDeleted = self.db.delete(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: bookmark, err: &err)
}
if err == nil {
success(numDeleted > 0)
return
}
failure(err!)
}
}
|
940163825357aad2fa2bff5827b3fb0b
| 38.3 | 185 | 0.574404 | false | false | false | false |
seandavidmcgee/HumanKontactBeta
|
refs/heads/master
|
src/keyboardTest/SingletonManager.swift
|
mit
|
1
|
//
// SingletonManager.swift
// keyboardTest
//
// Created by Sean McGee on 9/7/15.
// Copyright (c) 2015 Kannuu. All rights reserved.
//
import Foundation
import UIKit
import RealmSwift
class GlobalVariables {
// These are the properties you can store in your singleton
var keyboardFirst : Bool = true
var keyboardOrientChanged : Bool = false
let avatarColors : Array<UInt32> = [0x2A93EB, 0x07E36D, 0xFF9403, 0x9E80FF, 0xACF728, 0xFF5968, 0x17BAF0, 0xF7F00E, 0xFA8EC7, 0xE41931, 0x04E5E0, 0xBD10E0]
let nameColors : Array<String> = ["0x2A93EB", "0x07E36D", "0xFF9403", "0x9E80FF", "0xACF728", "0xFF5968", "0x17BAF0", "0xF7F00E", "0xFA8EC7", "0xE41931", "0x04E5E0", "0xBD10E0"]
var searchControllerArray : [UIViewController] = []
let controller = KeyboardViewController()
let master = MasterSearchController()
var lastModified = NSDate()
var recordsModified = Int()
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var myResults = [AnyObject]()
var objectKeys = [AnyObject]()
var sortOrdering = "alpha"
var realm = RealmManager.setupRealmInApp()
// Here is how you would get to it without there being a global collision of variables.
// It is a globally accessable parameter that is specific to the class.
class var sharedManager: GlobalVariables {
struct Static {
static let instance = GlobalVariables()
}
return Static.instance
}
}
|
988b7693ffaab22b0a37bc25256ed38a
| 35.682927 | 181 | 0.69016 | false | false | false | false |
Melon-IT/base-view-controller-swift
|
refs/heads/master
|
MelonBaseViewController/MelonBaseViewController/MBFDownSideAnimator.swift
|
mit
|
1
|
//
// MBFDownSideAnimator.swift
// MelonBaseViewController
//
// Created by Tomasz Popis on 07/07/2019.
// Copyright © 2019 Melon-IT. All rights reserved.
//
import UIKit
open class MBFDownSideAnimator: MBFBaseTransitionAnimator {
public override init(duration: Double, interaction: Bool) {
super.init(duration: duration, interaction: interaction)
}
open override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
if let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) {
let containerView = transitionContext.containerView
if self.presented == false {
let height = fromViewController.view.frame.height
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
fromViewController.view.frame = toViewController.view.frame.offsetBy(dx: 0, dy: height)
}, completion: { (finished: Bool) in transitionContext .completeTransition(finished) })
} else {
containerView.addSubview(toViewController.view)
let height = toViewController.view.frame.height
toViewController.view.frame.origin.y = height
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), animations: {
toViewController.view.frame = toViewController.view.frame.offsetBy(dx: 0, dy: -height)
}, completion: { (finished: Bool) in
transitionContext.completeTransition(finished)
containerView.insertSubview(fromViewController.view, belowSubview: toViewController.view)
})
}
}
}
}
|
3ef0d01872b1fc5ffbfbd89eff35d50d
| 36.26 | 116 | 0.698873 | false | false | false | false |
zmarvin/EnjoyMusic
|
refs/heads/master
|
Pods/Macaw/Source/views/NodesMap.swift
|
mit
|
1
|
import UIKit
let nodesMap = NodesMap()
var parentsMap = [Node: Set<Node>]()
class NodesMap {
var map = [Node: MacawView]()
// MARK: - Macaw View
func add(_ node: Node, view: MacawView) {
map[node] = view
if let group = node as? Group {
group.contents.forEach { child in
self.add(child, view: view)
self.add(child, parent: node)
}
}
}
func getView(_ node: Node) -> MacawView? {
return map[node]
}
func remove(_ node: Node) {
map.removeValue(forKey: node)
parentsMap.removeValue(forKey: node)
}
// MARK: - Parents
func add(_ node: Node, parent: Node) {
if var nodesSet = parentsMap[node] {
nodesSet.insert(parent)
} else {
parentsMap[node] = Set([parent])
}
}
func parents(_ node: Node) -> [Node] {
guard let nodesSet = parentsMap[node] else {
return []
}
return Array(nodesSet)
}
}
|
b3e459f3438ca92cc38850d446284220
| 17.106383 | 46 | 0.627497 | false | false | false | false |
seongkyu-sim/BaseVCKit
|
refs/heads/master
|
BaseVCKit/Classes/views/ProfileImageView.swift
|
mit
|
1
|
//
// ProfileImageView.swift
// BaseVCKit
//
// Created by frank on 2016. 5. 10..
// Copyright © 2016년 colavo. All rights reserved.
//
import UIKit
import Kingfisher
public class ProfileImageView: UIView {
public var bgColor: UIColor {
didSet {
setNeedsDisplay()
}
}
public var placeHolderIcon: UIImage {
didSet {
setNeedsDisplay()
}
}
public init(bgColor: UIColor, placeHolderIcon: UIImage) {
self.bgColor = bgColor
self.placeHolderIcon = placeHolderIcon
super.init(frame: CGRect.zero)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public var url: URL? {
didSet {
if let url = url {
imgView.kf.setImage(with: url, placeholder: placeHolderIcon)
}else {
let url_: URL! = URL(string: "")
imgView.kf.setImage(with: url_, placeholder: placeHolderIcon)
}
}
}
public var path: String? {
didSet {
var newUrl = URL(string: "")
if let path = self.path { newUrl = URL(string: path) }
url = newUrl
}
}
public var newImage: UIImage? { // for update profile image
didSet {
if let newImage = newImage {
imgView.image = newImage
}else {
path = ""
}
}
}
public var customCornerRadius: CGFloat? {
didSet {
setNeedsDisplay()
}
}
private var externalBorderWidth: CGFloat = 0
private var externalBorderColor: UIColor = UIColor.white
private lazy var imgView: UIImageView = { [unowned self] in
let v = UIImageView.init()
v.contentMode = UIView.ContentMode.scaleAspectFill
self.addSubview(v)
return v
}()
private lazy var imgMaskLayer: CAShapeLayer = { [unowned self] in
let l = CAShapeLayer()
return l
}()
private lazy var externalBorder: CALayer = { [unowned self] in
let l = CALayer()
self.layer.insertSublayer(l, at: 0)
return l
}()
public override func draw(_ rect: CGRect) {
super.draw(rect)
if externalBorderWidth > 0 {
let width = frame.size.width + 2 * externalBorderWidth
let height = frame.size.height + 2 * externalBorderWidth
externalBorder.frame = CGRect(x: -externalBorderWidth, y: -externalBorderWidth, width: width, height: height)
externalBorder.borderColor = externalBorderColor.cgColor
externalBorder.borderWidth = externalBorderWidth
externalBorder.cornerRadius = (rect.height + 2 * externalBorderWidth) / 2
layer.masksToBounds = false
}
if let customCornerRadius = customCornerRadius {
let roundRectPath = UIBezierPath(roundedRect: rect, cornerRadius: customCornerRadius)
imgMaskLayer.path = roundRectPath.cgPath
}else {
let circlePath = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: rect.maxX, height: rect.maxY))
imgMaskLayer.path = circlePath.cgPath
}
imgMaskLayer.fillColor = UIColor.black.cgColor
imgView.layer.mask = imgMaskLayer
imgView.backgroundColor = bgColor
}
// MARK: - Init
private func commonInit() {
backgroundColor = UIColor.clear
url = nil
configureConstraints()
}
// MARK: - Layout
private func configureConstraints() {
imgView.snp.makeConstraints {
$0.edges.equalToSuperview()
}
}
// MARK: - Public methods
public func setExternalBorderWithColor(borderColor: UIColor, borderWidth: CGFloat) {
externalBorderColor = borderColor
externalBorderWidth = borderWidth
setNeedsDisplay()
}
}
|
6946f1c4cd15a343d5098497b25de41b
| 27.12766 | 121 | 0.588502 | false | false | false | false |
OscarSwanros/swift
|
refs/heads/master
|
tools/SwiftSyntax/SyntaxData.swift
|
apache-2.0
|
6
|
//===-------------------- SyntaxData.swift - Syntax Data ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// A unique identifier for a node in the tree.
/// Currently, this is an index path from the current node to the root of the
/// tree. It's an implementation detail and shouldn't be
/// exposed to clients.
typealias NodeIdentifier = [Int]
/// SyntaxData is the underlying storage for each Syntax node.
/// It's modelled as an array that stores and caches a SyntaxData for each raw
/// syntax node in its layout. It is up to the specific Syntax nodes to maintain
/// the correct layout of their SyntaxData backing stores.
///
/// SyntaxData is an implementation detail, and should not be exposed to clients
/// of libSyntax.
///
/// The following relationships are preserved:
/// parent.cachedChild(at: indexInParent) === self
/// raw.layout.count == childCaches.count
/// pathToRoot.first === indexInParent
final class SyntaxData: Equatable {
let raw: RawSyntax
let indexInParent: Int
weak var parent: SyntaxData?
let childCaches: [AtomicCache<SyntaxData>]
/// Creates a SyntaxData with the provided raw syntax, pointing to the
/// provided index, in the provided parent.
/// - Parameters:
/// - raw: The raw syntax underlying this node.
/// - indexInParent: The index in the parent's layout where this node will
/// reside.
/// - parent: The parent of this node, or `nil` if this node is the root.
required init(raw: RawSyntax, indexInParent: Int = 0,
parent: SyntaxData? = nil) {
self.raw = raw
self.indexInParent = indexInParent
self.parent = parent
self.childCaches = raw.layout.map { _ in AtomicCache<SyntaxData>() }
}
/// The index path from this node to the root. This can be used to uniquely
/// identify this node in the tree.
lazy private(set) var pathToRoot: NodeIdentifier = {
var path = [Int]()
var node = self
while let parent = node.parent {
path.append(node.indexInParent)
node = parent
}
return path
}()
/// Returns the child data at the provided index in this data's layout.
/// This child is cached and will be used in subsequent accesses.
/// - Note: This function traps if the index is out of the bounds of the
/// data's layout.
///
/// - Parameter index: The index to create and cache.
/// - Returns: The child's data at the provided index.
func cachedChild(at index: Int) -> SyntaxData {
return childCaches[index].value { realizeChild(index) }
}
/// Returns the child data at the provided cursor in this data's layout.
/// This child is cached and will be used in subsequent accesses.
/// - Note: This function traps if the cursor is out of the bounds of the
/// data's layout.
///
/// - Parameter cursor: The cursor to create and cache.
/// - Returns: The child's data at the provided cursor.
func cachedChild<CursorType: RawRepresentable>(
at cursor: CursorType) -> SyntaxData
where CursorType.RawValue == Int {
return cachedChild(at: cursor.rawValue)
}
/// Walks up the provided node's parent tree looking for the receiver.
/// - parameter data: The potential child data.
/// - returns: `true` if the receiver exists in the parent chain of the
/// provided data.
/// - seealso: isDescendent(of:)
func isAncestor(of data: SyntaxData) -> Bool {
return data.isDescendent(of: self)
}
/// Walks up the receiver's parent tree looking for the provided node.
/// - parameter data: The potential ancestor data.
/// - returns: `true` if the data exists in the parent chain of the receiver.
/// - seealso: isAncestor(of:)
func isDescendent(of data: SyntaxData) -> Bool {
if data == self { return true }
var node = self
while let parent = node.parent {
if parent == data { return true }
node = parent
}
return false
}
/// Creates a copy of `self` and recursively creates `SyntaxData` nodes up to
/// the root.
/// - parameter newRaw: The new RawSyntax that will back the new `Data`
/// - returns: A tuple of both the new root node and the new data with the raw
/// layout replaced.
func replacingSelf(
_ newRaw: RawSyntax) -> (root: SyntaxData, newValue: SyntaxData) {
// If we have a parent already, then ask our current parent to copy itself
// recursively up to the root.
if let parent = parent {
let (root, newParent) = parent.replacingChild(newRaw, at: indexInParent)
let newMe = newParent.cachedChild(at: indexInParent)
return (root: root, newValue: newMe)
} else {
// Otherwise, we're already the root, so return the new data as both the
// new root and the new data.
let newMe = SyntaxData(raw: newRaw, indexInParent: indexInParent,
parent: nil)
return (root: newMe, newValue: newMe)
}
}
/// Creates a copy of `self` with the child at the provided index replaced
/// with a new SyntaxData containing the raw syntax provided.
///
/// - Parameters:
/// - child: The raw syntax for the new child to replace.
/// - index: The index pointing to where in the raw layout to place this
/// child.
/// - Returns: The new root node created by this operation, and the new child
/// syntax data.
/// - SeeAlso: replacingSelf(_:)
func replacingChild(_ child: RawSyntax,
at index: Int) -> (root: SyntaxData, newValue: SyntaxData) {
let newRaw = raw.replacingChild(index, with: child)
return replacingSelf(newRaw)
}
/// Creates a copy of `self` with the child at the provided cursor replaced
/// with a new SyntaxData containing the raw syntax provided.
///
/// - Parameters:
/// - child: The raw syntax for the new child to replace.
/// - cursor: A cursor that points to the index of the child you wish to
/// replace
/// - Returns: The new root node created by this operation, and the new child
/// syntax data.
/// - SeeAlso: replacingSelf(_:)
func replacingChild<CursorType: RawRepresentable>(_ child: RawSyntax,
at cursor: CursorType) -> (root: SyntaxData, newValue: SyntaxData)
where CursorType.RawValue == Int {
return replacingChild(child, at: cursor.rawValue)
}
/// Creates the child's syntax data for the provided cursor.
///
/// - Parameter cursor: The cursor pointing into the raw syntax's layout for
/// the child you're creating.
/// - Returns: A new SyntaxData for the specific child you're
/// creating, whose parent is pointing to self.
func realizeChild<CursorType: RawRepresentable>(
_ cursor: CursorType) -> SyntaxData
where CursorType.RawValue == Int {
return realizeChild(cursor.rawValue)
}
/// Creates the child's syntax data for the provided index.
///
/// - Parameter cursor: The cursor pointing into the raw syntax's layout for
/// the child you're creating.
/// - Returns: A new SyntaxData for the specific child you're
/// creating, whose parent is pointing to self.
func realizeChild(_ index: Int) -> SyntaxData {
return SyntaxData(raw: raw.layout[index],
indexInParent: index,
parent: self)
}
/// Tells whether two SyntaxData nodes have the same identity.
/// This is not structural equality.
/// - Returns: True if both datas are exactly the same.
static func ==(lhs: SyntaxData, rhs: SyntaxData) -> Bool {
return lhs === rhs
}
}
|
4398cce0d1e4341c58b69375bfcca8de
| 39.261307 | 80 | 0.652896 | false | false | false | false |
NoManTeam/Hole
|
refs/heads/master
|
CryptoFramework/Crypto/Algorithm/LowLevelEncryption.swift
|
unlicense
|
1
|
//
// RandomText.swift
// 密语输入法
//
// Created by macsjh on 15/9/28.
// Copyright © 2015年 Marcin Krzyzanowski. All rights reserved.
//
import Foundation
///低级加密算法
public class LowLevelEncryption {
///符号集
public static let symbols = ".,!?/\\+=-_;:\"'#$%^&*~∙<>(){}[]|®©™℠×÷。,!?、\\;:♬—“”‘’#¥%^&*~•《》(){}【】…→←↑↓✓✕ "
///英文小写字母集
public static let englishCharacter:String = "abcdefghijklmnopqrstuvwxyz"
///英文大写字母集
public static let bigEnglishCharacter:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
///将明文按一定分隔符分隔成多个单元,并按照随机顺序重组的算法
///- 明文需要一定长度,打乱才有意义
///- 无解密算法(需要正常成年人水平的语义分析才有可能解密)
///
///- Parameter plainText: 待加密的明文
///- Parameter splitChars: 分隔字符集,决定明文以何种方式分隔,留空则以1个NSString单位长度分割
///- Returns: 加密后的密文(均为可打印字符)
public static func randomText(plainText:NSString, splitChars:String?) -> String
{
var charSet:[String] = []
for (var i = 0; i < plainText.length; ++i)
{
if(splitChars == nil)
{
let temp = plainText.substringFromIndex(i)
charSet.append(NSString(string: temp).substringToIndex(1))
}
else
{
var j:Int
var word:String = ""
for(j = i; j < plainText.length; ++j)
{
let temp = plainText.substringFromIndex(j)
let char = NSString(string: temp).substringToIndex(1)
var isEqualToUnit = false
for unit in splitChars!.characters
{
if (char == String(unit))
{
isEqualToUnit = true
break
}
}
if isEqualToUnit == true
{
break
}
}
if(j > plainText.length)
{
word = plainText.substringFromIndex(i)
break
}
else
{
var temp = plainText.substringFromIndex(i)
word = NSString(string: temp).substringToIndex(j-i)
temp = plainText.substringFromIndex(j)
if(temp != "")
{
charSet.append(NSString(string: temp).substringToIndex(1))
}
i = j
}
charSet.append(word)
}
}
var RandomString:String = ""
while(charSet.count != 0)
{
let randNum = Int(arc4random_uniform(UInt32(charSet.count)))
RandomString += charSet[randNum]
charSet.removeAtIndex(randNum)
}
return RandomString
}
///将英文按照字母表的顺序、中文按照密语输入法汉字字库中的顺序,偏移指定的量
///
///- Parameter plainText: 待加密的明文
///- Parameter Shift: 偏移量,不应为零,加解密时的偏移量应互为相反数
///- Returns: 加密后的密文(均为可打印字符)
public static func caesarCode(plainText: String, shift:Int) -> String
{
var cipherText = ""
for(var i = 0; i < plainText.characters.count; ++i)
{
var isEChar = false
for(var j = 0; j < englishCharacter.characters.count; ++j)
{
if englishCharacter[englishCharacter.startIndex.advancedBy(j)] == plainText[plainText.startIndex.advancedBy(i)]
{
var shiftIndex = (shift + j) % 26
if(shiftIndex < 0)
{
shiftIndex += 26
}
cipherText.append(englishCharacter[englishCharacter.startIndex.advancedBy(shiftIndex)]) //.appendFormat("%c", eChar[shiftIndex])
isEChar = true
break
}
else if bigEnglishCharacter[bigEnglishCharacter.startIndex.advancedBy(j)] == plainText[plainText.startIndex.advancedBy(i)]
{
var shiftIndex = (shift + j) % 26
if(shiftIndex < 0)
{
shiftIndex += 26
}
cipherText.append(bigEnglishCharacter[bigEnglishCharacter.startIndex.advancedBy(shiftIndex)]) //Format("%c", bEChar[shiftIndex])
isEChar = true
break
}
}
if(isEChar == false)
{
cipherText.append(plainText[plainText.startIndex.advancedBy(i)])
}
}
return cipherText
// TODO: 增加中文凯撒加密算法
}
///将明文转换为base64编码的字符串
///
///- Parameter plainText: 待编码的明文
///- Returns: base64编码的字符串(均为可打印字符)
public static func base64Encode(plainText:NSString) -> String?
{
let sourceData = plainText.dataUsingEncoding(NSUTF8StringEncoding)
if(sourceData != nil){
return sourceData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}
else {
return nil
}
}
///对base64编码的字符串进行解码
///
///- Parameter plainText: 待编码的明文
///- Returns: 解码后的字符串(均为可打印字符)
public static func base64Decode(cipherText:NSString) -> String?
{
let sourceData = NSData(base64EncodedString: cipherText as String, options: NSDataBase64DecodingOptions(rawValue: 0))
if(sourceData != nil)
{
return String(data: sourceData!, encoding: NSUTF8StringEncoding)
}
return nil
}
}
|
41b2e94a2eb0a26e9fe577f06eaf280f
| 24.866667 | 133 | 0.655261 | false | false | false | false |
KrishMunot/swift
|
refs/heads/master
|
test/DebugInfo/inout.swift
|
apache-2.0
|
3
|
// RUN: %target-swift-frontend %s -emit-ir -g -module-name inout -o %t.ll
// RUN: cat %t.ll | FileCheck %s
// RUN: cat %t.ll | FileCheck %s --check-prefix=PROMO-CHECK
// RUN: cat %t.ll | FileCheck %s --check-prefix=FOO-CHECK
// LValues are direct values, too. They are reference types, though.
func Close(_ fn: () -> Int64) { fn() }
typealias MyFloat = Float
// CHECK: define hidden void @_TF5inout13modifyFooHeap
// CHECK: %[[ALLOCA:.*]] = alloca %Vs5Int64*
// CHECK: %[[ALLOCB:.*]] = alloca %Sf
// CHECK: call void @llvm.dbg.declare(metadata
// CHECK-SAME: %[[ALLOCA]], metadata ![[A:[0-9]+]]
// CHECK: call void @llvm.dbg.declare(metadata
// CHECK-SAME: %[[ALLOCB]], metadata ![[B:[0-9]+]], metadata !{{[0-9]+}})
// Closure with promoted capture.
// PROMO-CHECK: define {{.*}}@_TTSf2i___TFF5inout13modifyFooHeapFTRVs5Int64Sf_T_U_FT_S0_
// PROMO-CHECK: call void @llvm.dbg.declare(metadata {{(i32|i64)}}* %
// PROMO-CHECK-SAME: metadata ![[A1:[0-9]+]], metadata ![[EMPTY_EXPR:[0-9]+]])
// PROMO-CHECK: ![[EMPTY_EXPR]] = !DIExpression()
// PROMO-CHECK: ![[A1]] = !DILocalVariable(name: "a", arg: 1
// PROMO-CHECK-SAME: type: !"_TtVs5Int64"
func modifyFooHeap(_ a: inout Int64,
// CHECK-DAG: ![[A]] = !DILocalVariable(name: "a", arg: 1{{.*}} line: [[@LINE-1]],{{.*}} type: !"_TtRVs5Int64"
_ b: MyFloat)
{
var b = b
if (b > 2.71) {
a = a + 12// Set breakpoint here
}
// Close over the variable to disable promotion of the inout shadow.
Close({ a })
}
// Inout reference type.
// FOO-CHECK: define {{.*}}@_TF5inout9modifyFooFTRVs5Int64Sf_T_
// FOO-CHECK: call void @llvm.dbg.declare(metadata %Vs5Int64** %
// FOO-CHECK-SAME: metadata ![[U:[0-9]+]], metadata ![[EMPTY_EXPR:.*]])
// FOO-CHECK: ![[EMPTY_EXPR]] = !DIExpression()
func modifyFoo(_ u: inout Int64,
// FOO-CHECK-DAG: !DILocalVariable(name: "v", arg: 2{{.*}} line: [[@LINE+2]],{{.*}} type: ![[MYFLOAT:[0-9]+]]
// FOO-CHECK-DAG: [[U]] = !DILocalVariable(name: "u", arg: 1{{.*}} line: [[@LINE-2]],{{.*}} type: !"_TtRVs5Int64"
_ v: MyFloat)
// FOO-CHECK-DAG: ![[MYFLOAT]] = !DIDerivedType(tag: DW_TAG_typedef, name: "_Tta5inout7MyFloat",{{.*}} baseType: !"_TtSf"
{
if (v > 2.71) {
u = u - 41
}
}
func main() -> Int64 {
var c = 11 as Int64
modifyFoo(&c, 3.14)
var d = 64 as Int64
modifyFooHeap(&d, 1.41)
return 0
}
main()
|
53cf463ee13e89333a2fbd7c96a5d794
| 36 | 121 | 0.579853 | false | false | false | false |
superman-coder/pakr
|
refs/heads/master
|
pakr/pakr/WebService/Address/AddressServiceParseImpl.swift
|
apache-2.0
|
1
|
//
// Created by Huynh Quang Thao on 4/7/16.
// Copyright (c) 2016 Pakr. All rights reserved.
//
import Foundation
import Parse
let DemoMode = true
public class AddressServiceParseImpl: NSObject, AddressService {
func getNearByParkingLotByLocation(latitude: Double!, longitude: Double, radius: Double, success: ([Topic] -> Void), fail: (NSError -> Void)) {
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
let innerQuery = PFQuery(className: Constants.Table.Parking)
innerQuery.whereKey(Parking.PKCoordinate, nearGeoPoint: PFGeoPoint(latitude: latitude, longitude: longitude), withinKilometers: radius / 1000)
query.whereKey(Topic.PKParking, matchesQuery: innerQuery)
query.findObjectsInBackgroundWithBlock { (objects, error) in
print("Near by count: \(objects?.count)")
print("Error: \(error)")
if let error = error {
fail(error)
} else if let objs = objects {
var topics = [Topic]()
for pfobj in objs {
let topic = Topic(pfObject: pfobj)
topics.append(topic)
}
success(topics)
}
}
}
func getNearByParkingByAddressName(address: String, radius: Double, success: ([Topic] -> Void), fail: (NSError -> Void)) {
if (DemoMode) {
let lowerAddress = address.lowercaseString
if (lowerAddress.containsString("ho con rua")
|| lowerAddress.containsString("con rua")
|| lowerAddress.containsString("ho rua")
|| lowerAddress.containsString("con rùa")
|| lowerAddress.containsString("hồ con rùa")
|| lowerAddress.containsString("hồ rùa")) {
let coord = Coordinate(latitude: 10.782661, longitude: 106.695915)
self.getNearByParkingLotByLocation(coord.latitude,
longitude: coord.longitude,
radius: radius,
success: { topic in
success(topic)
}, fail: { error in
fail(error)
})
return
}
}
GMServices.requestAddressSearchWithAddress(address) { (successGMS, locationGMS) in
var coord:Coordinate? = nil
if (successGMS) {
if locationGMS?.count > 0 {
let firstPlace = locationGMS![0]
print("Search nearby: \(firstPlace.geometry.latitude),\(firstPlace.geometry.longitude)")
coord = Coordinate(latitude: firstPlace.geometry.latitude, longitude: firstPlace.geometry.longitude)
}
}
if let coord = coord {
self.getNearByParkingLotByLocation(coord.latitude,
longitude: coord.longitude,
radius: radius,
success: { topic in
success(topic)
}, fail: { error in
fail(error)
})
} else {
fail(NSError(domain: "", code: 0, userInfo: nil))
}
}
}
func postTopic(topic:Topic, complete:(Topic?,NSError?) -> Void) {
topic.toPFObject().saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (objects, error) in
if error != nil {
complete(nil, error)
}else{
let topic = Topic(pfObject: objects![0])
complete(topic, nil)
}
})
} else {
complete(nil, error)
}
}
}
func getAllParkingByUser(userId: String, success:([Topic] -> Void), failure:(NSError -> Void)) {
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
let user = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
query.whereKey(Topic.PKPostUser, equalTo: user)
query.findObjectsInBackgroundWithBlock { (objects, error) in
print("User count: \(objects?.count)")
print("Error: \(error)")
if let error = error {
failure(error)
} else if let objs = objects {
var topics = [Topic]()
for pfobj in objs {
let topic = Topic(pfObject: pfobj)
topics.append(topic)
}
success(topics)
}
}
}
// MARK: API comment
func postComment(comment: Comment, complete:(comment: Comment?, error: NSError?) -> Void){
comment.toPFObject().saveInBackgroundWithBlock { (success: Bool, error: NSError?) in
if success {
let query = PFQuery(className: Constants.Table.Comment)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (comments, error) in
if let error = error {
complete(comment: nil, error: error)
} else if let comments = comments {
let comment = Comment(pfObject: comments.first!)
complete(comment: comment, error: nil)
}
})
}else{
complete(comment: nil, error: error)
}
}
}
func getAllCommentsByTopic(topicId: String, success:([Comment] -> Void), failure:(NSError -> Void)){
let query = PFQuery(className: Constants.Table.Comment)
query.includeKey(".")
query.orderByDescending("createdAt")
let topic = PFObject(withoutDataWithClassName: Constants.Table.Topic, objectId: topicId)
query.whereKey(Comment.PKTopic, equalTo: topic)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let error = error {
failure(error)
} else if let objs = objects {
var comments = [Comment]()
for pfobj in objs {
let comment = Comment(pfObject: pfobj)
comments.append(comment)
}
success(comments)
}
}
}
func getUserById(userId: String, complete:(success: User?, error: NSError?) -> Void){
let query = PFQuery(className: Constants.Table.User)
query.whereKey("objectId", equalTo: userId)
query.findObjectsInBackgroundWithBlock { (users, error) in
if let error = error {
complete(success:nil, error: error)
}else{
if let users = users {
complete(success: users[0] as? User, error: error)
return
}else{
complete(success:nil, error: NSError(domain: "", code: -1, userInfo: nil))
}
}
}
}
func postBookMark(bookMark: Bookmark, complete:(bookMark: Bookmark?, error: NSError?) -> Void){
bookMark.toPFObject().saveInBackgroundWithBlock { (success, error) in
if success{
let query = PFQuery(className: Constants.Table.Bookmark)
query.orderByDescending("createdAt")
query.limit = 1
query.findObjectsInBackgroundWithBlock({ (bookMarks, error) in
if let error = error {
complete(bookMark: nil, error: error)
} else if let bookMarks = bookMarks {
let bookMark = Bookmark(pfObject: bookMarks.first!)
self.getTopicById(bookMark, complete: { (bookMark) in
complete(bookMark: bookMark, error: error)
})
}
})
}else{
complete(bookMark: nil, error: error)
}
}
}
func getAllBookMarksByUser(userId: String, complete:(bookMarks: [Bookmark]?, error: NSError?) -> Void){
let query = PFQuery(className: Constants.Table.Bookmark)
query.orderByDescending("createdAt")
let user = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
query.whereKey(Bookmark.PKPostUser, equalTo: user)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let error = error {
complete(bookMarks: nil, error: error)
} else if let objects = objects {
var bookmarks = [Bookmark]()
if objects.count == 0 {
complete(bookMarks: nil, error: error)
}else{
for object in objects {
let bookMark = Bookmark(pfObject: object)
self.getTopicById(bookMark, complete: { (bookMark) in
if let bookMark = bookMark {
bookmarks.append(bookMark)
if objects.count == bookmarks.count {
complete(bookMarks: bookmarks, error: nil)
}
}else{
complete(bookMarks: nil, error: error)
}
})
}
}
}else{
complete(bookMarks: nil, error: error)
}
}
}
func getTopicById(bookMark: Bookmark, complete:(bookMark: Bookmark!) -> Void){
let query = PFQuery(className: Constants.Table.Topic)
query.includeKey(Topic.PKParking)
query.whereKey("objectId", equalTo: bookMark.topicId)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if let objects = objects {
if objects.count > 0 {
let topic = Topic(pfObject: objects[0])
bookMark.topic = topic
complete(bookMark: bookMark)
}else{
complete(bookMark: nil)
}
}else{
complete(bookMark: nil)
}
}
}
func checkIsBookMarkTopicByUser(userId: String, topicId: String, complete:(isBookMark: Bool) -> Void){
let query = PFQuery(className: Constants.Table.Bookmark)
let user = PFObject(withoutDataWithClassName: Constants.Table.User, objectId: userId)
query.whereKey(Bookmark.PKPostUser, equalTo: user)
query.findObjectsInBackgroundWithBlock { (objects, error) in
if error != nil {
complete(isBookMark: false)
}else{
if let objects = objects {
for obj in objects {
let bookMark = Bookmark(pfObject: obj)
if bookMark.topicId == topicId {
complete(isBookMark: true)
return
}
}
complete(isBookMark: false)
}else{
complete(isBookMark: false)
}
}
}
}
}
|
4ec7b58be54dedc2ff408c63872f71a2
| 41.207018 | 150 | 0.500208 | false | false | false | false |
angelvasa/AVLighterStickyHeaderView
|
refs/heads/master
|
AVLighterStickyHeaderView/AVLighterStickyHeaderView.swift
|
mit
|
1
|
//
// AVLighterStickyHeaderView.swift
// AVLighterStickyHeaderView
//
// Created by Angel Vasa on 13/04/16.
// Copyright © 2016 Angel Vasa. All rights reserved.
//
import UIKit
@IBDesignable
open class AVLighterStickyHeaderView: UIView {
@IBInspectable
var minimumHeight: CGFloat = 64
typealias progressValueHandler = (CGFloat) -> ()
@IBOutlet weak var scrollView: UIScrollView?
var gProgressValue: progressValueHandler?
override open func willMove(toSuperview newSuperview: UIView?) {
self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
self.scrollView?.contentInset = UIEdgeInsetsMake((self.scrollView?.contentInset.top)!, 0, 0, 0)
self.scrollView?.scrollIndicatorInsets = (self.scrollView?.contentInset)!;
}
override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
updateView(((change![.newKey] as AnyObject).cgPointValue)!)
}
var currentOffset: CGPoint?
func updateView(_ offset: CGPoint) {
currentOffset = offset
if (currentOffset!.y > -minimumHeight){
currentOffset = CGPoint(x: currentOffset!.x, y: -minimumHeight)
}
self.frame.origin.y = -currentOffset!.y-(self.scrollView?.contentInset.top)!
let distance: CGFloat = (self.scrollView?.contentInset.top)! - minimumHeight
let progressInverse: CGFloat = (currentOffset!.y + (self.scrollView?.contentInset.top)!) / distance
let progress: CGFloat = 1 - progressInverse
gProgressValue!(progress)
}
func getProgressValue(_ progressValue: @escaping progressValueHandler) {
gProgressValue = progressValue
}
}
|
1e3686d8e5989d45cb4d6813dbce55eb
| 32.035088 | 156 | 0.673394 | false | false | false | false |
TG908/iOS
|
refs/heads/master
|
TUM Campus App/Extensions.swift
|
gpl-3.0
|
1
|
//
// Extensions.swift
// TUM Campus App
//
// Created by Mathias Quintero on 7/21/16.
// Copyright © 2016 LS1 TUM. All rights reserved.
//
import Foundation
extension Date {
func numberOfDaysUntilDateTime(_ toDateTime: Date, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let difference = calendar.dateComponents(Set([.day]), from: self, to: toDateTime)
return difference.day ?? 0
}
}
|
618bd10f54ebd2e8cd8f439cce78cd7f
| 25.333333 | 101 | 0.632911 | false | false | false | false |
ruslanskorb/CoreStore
|
refs/heads/master
|
Sources/BaseDataTransaction+Importing.swift
|
mit
|
1
|
//
// BaseDataTransaction+Importing.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 Foundation
import CoreData
// MARK: - BaseDataTransaction
extension BaseDataTransaction {
/**
Creates an `ImportableObject` by importing from the specified import source.
- parameter into: an `Into` clause specifying the entity type
- parameter source: the object to import values from
- throws: an `Error` thrown from any of the `ImportableObject` methods
- returns: the created `ImportableObject` instance, or `nil` if the import was ignored
*/
public func importObject<O: ImportableObject>(
_ into: Into<O>,
source: O.ImportSource) throws -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
let entityType = into.entityClass
guard entityType.shouldInsert(from: source, in: self) else {
return nil
}
let object = self.create(into)
try object.didInsert(from: source, in: self)
return object
}
}
/**
Updates an existing `ImportableObject` by importing values from the specified import source.
- parameter object: the `ImportableObject` to update
- parameter source: the object to import values from
- throws: an `Error` thrown from any of the `ImportableObject` methods
*/
public func importObject<O: ImportableObject>(
_ object: O,
source: O.ImportSource) throws {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to import an object of type \(Internals.typeName(object)) outside the transaction's designated queue."
)
try autoreleasepool {
let entityType = object.runtimeType()
guard entityType.shouldInsert(from: source, in: self) else {
return
}
try object.didInsert(from: source, in: self)
}
}
/**
Creates multiple `ImportableObject`s by importing from the specified array of import sources.
- parameter into: an `Into` clause specifying the entity type
- parameter sourceArray: the array of objects to import values from
- throws: an `Error` thrown from any of the `ImportableObject` methods
- returns: the array of created `ImportableObject` instances
*/
public func importObjects<O: ImportableObject, S: Sequence>(
_ into: Into<O>,
sourceArray: S) throws -> [O] where S.Iterator.Element == O.ImportSource {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
return try sourceArray.compactMap { (source) -> O? in
let entityType = into.entityClass
guard entityType.shouldInsert(from: source, in: self) else {
return nil
}
return try autoreleasepool {
let object = self.create(into)
try object.didInsert(from: source, in: self)
return object
}
}
}
}
/**
Updates an existing `ImportableUniqueObject` or creates a new instance by importing from the specified import source.
- parameter into: an `Into` clause specifying the entity type
- parameter source: the object to import values from
- throws: an `Error` thrown from any of the `ImportableUniqueObject` methods
- returns: the created/updated `ImportableUniqueObject` instance, or `nil` if the import was ignored
*/
public func importUniqueObject<O: ImportableUniqueObject>(
_ into: Into<O>,
source: O.ImportSource) throws -> O? {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
let entityType = into.entityClass
let uniqueIDKeyPath = entityType.uniqueIDKeyPath
guard let uniqueIDValue = try entityType.uniqueID(from: source, in: self) else {
return nil
}
if let object = try self.fetchOne(From(entityType), Where<O>(uniqueIDKeyPath, isEqualTo: uniqueIDValue)) {
guard entityType.shouldUpdate(from: source, in: self) else {
return nil
}
try object.update(from: source, in: self)
return object
}
else {
guard entityType.shouldInsert(from: source, in: self) else {
return nil
}
let object = self.create(into)
object.uniqueIDValue = uniqueIDValue
try object.didInsert(from: source, in: self)
return object
}
}
}
/**
Updates existing `ImportableUniqueObject`s or creates them by importing from the specified array of import sources.
`ImportableUniqueObject` methods are called on the objects in the same order as they are in the `sourceArray`, and are returned in an array with that same order.
- Warning: If `sourceArray` contains multiple import sources with same ID, only the last `ImportSource` of the duplicates will be imported.
- parameter into: an `Into` clause specifying the entity type
- parameter sourceArray: the array of objects to import values from
- parameter preProcess: a closure that lets the caller tweak the internal `UniqueIDType`-to-`ImportSource` mapping to be used for importing. Callers can remove from/add to/update `mapping` and return the updated array from the closure.
- throws: an `Error` thrown from any of the `ImportableUniqueObject` methods
- returns: the array of created/updated `ImportableUniqueObject` instances
*/
public func importUniqueObjects<O: ImportableUniqueObject, S: Sequence>(
_ into: Into<O>,
sourceArray: S,
preProcess: @escaping (_ mapping: [O.UniqueIDType: O.ImportSource]) throws -> [O.UniqueIDType: O.ImportSource] = { $0 }) throws -> [O] where S.Iterator.Element == O.ImportSource {
Internals.assert(
self.isRunningInAllowedQueue(),
"Attempted to import an object of type \(Internals.typeName(into.entityClass)) outside the transaction's designated queue."
)
return try autoreleasepool {
let entityType = into.entityClass
var importSourceByID = Dictionary<O.UniqueIDType, O.ImportSource>()
let sortedIDs = try autoreleasepool {
return try sourceArray.compactMap { (source) -> O.UniqueIDType? in
guard let uniqueIDValue = try entityType.uniqueID(from: source, in: self) else {
return nil
}
importSourceByID[uniqueIDValue] = source // effectively replaces duplicate with the latest
return uniqueIDValue
}
}
importSourceByID = try autoreleasepool { try preProcess(importSourceByID) }
var existingObjectsByID = Dictionary<O.UniqueIDType, O>()
try self
.fetchAll(From(entityType), Where<O>(entityType.uniqueIDKeyPath, isMemberOf: sortedIDs))
.forEach { existingObjectsByID[$0.uniqueIDValue] = $0 }
var processedObjectIDs = Set<O.UniqueIDType>()
var result = [O]()
for objectID in sortedIDs where !processedObjectIDs.contains(objectID) {
guard let source = importSourceByID[objectID] else {
continue
}
try autoreleasepool {
if let object = existingObjectsByID[objectID] {
guard entityType.shouldUpdate(from: source, in: self) else {
return
}
try object.update(from: source, in: self)
result.append(object)
}
else if entityType.shouldInsert(from: source, in: self) {
let object = self.create(into)
object.uniqueIDValue = objectID
try object.didInsert(from: source, in: self)
result.append(object)
}
processedObjectIDs.insert(objectID)
}
}
return result
}
}
}
|
990b2a53ef25d833390b7c0896590782
| 43.086275 | 240 | 0.554795 | false | false | false | false |
EZ-NET/ESSwim
|
refs/heads/swift-2.2
|
ESSwimTests/OperatorTest.swift
|
mit
|
1
|
//
// OperatorTest.swift
// ESSwim
//
// Created by 熊谷 友宏 on H26/12/14.
//
//
import Foundation
import XCTest
import Swim
import ESTestKit
struct MyClass {
var value:Int
init(_ value:Int) {
self.value = value
}
}
class OperatorTest: XCTestCase {
override func setUp() {
super.setUp()
let seed = time(nil)
srand(UInt32(seed))
}
override func tearDown() {
super.tearDown()
}
func testCompareArayOfOptionals() {
let values1:[Int?] = [10, 20, nil, 40]
let values2:[Int?] = [10, 20, nil, 40]
let values3:[Int?] = [10, 20, nil]
expected().success(values1 == values2)
expected().success(values1 != values3)
}
func testAlternativeValue() {
let value1 = Swim.AlternativeValue(trueValue: "Y", falseValue: "N")
XCTAssertTrue(value1[true] == "Y")
XCTAssertTrue(value1[false] == "N")
XCTAssertFalse(value1[true] == "N")
XCTAssertFalse(value1[false] == "Y")
let lhs = "TEST"
let value2 = Swim.alternative(trueValue: "OK", falseValue: "NG") { Swim.equal(lhs)(rhs: $0) }
XCTAssertTrue(value2("TEST") == "OK")
XCTAssertTrue(value2("TESTTEST") == "NG")
XCTAssertFalse(value2("TEST") == "NG")
XCTAssertFalse(value2("TESTTEST") == "OK")
let value3t = Swim.alternative(trueValue: "YES", falseValue: "NO")(true)
let value3f = Swim.alternative(trueValue: "YES", falseValue: "NO")(false)
XCTAssertTrue(value3t == "YES")
XCTAssertTrue(value3f == "NO")
XCTAssertFalse(value3t == "NO")
XCTAssertFalse(value3f == "YES")
}
func testCurriedFunction() {
func func1(x:Double, _ y:Int) -> String {
return String(x) + String(y)
}
func func2(x:Int, _ y:(Int)->Double) -> String {
return String(x) + String(y(x))
}
func func3(x:Int) -> Double {
return Double(x)
}
let cfunc1 = Swim.curry(func1)
let cfunc2 = Swim.curry(func2)
let ccfunc1 = cfunc1(10.5)
let result1 = ccfunc1(10)
XCTAssertEqual(result1, func1(10.5, 10))
let ccfunc2 = cfunc2(5)
let result2 = ccfunc2(func3)
XCTAssertEqual(result2, func2(5, func3))
}
func testEquatableEnhanced() {
let generatorA = EnhancedValueGenerator<EquatableEnhanced<MyClass>> {
$0.value == $1.value
}
let generatorB = EnhancedValueGenerator<EquatableEnhanced<MyClass>> {
$0.value == $1.value
}
let valueA1 = generatorA.generate(MyClass(10))
let valueA2 = generatorA.generate(MyClass(15))
let valueA3 = generatorA.generate(MyClass(5))
let valueA4 = generatorA.generate(MyClass(10))
let valueB1 = generatorB.generate(MyClass(10))
let valueB2 = generatorB.generate(MyClass(15))
let valueB3 = generatorB.generate(MyClass(5))
let valueB4 = generatorB.generate(MyClass(10))
// MyClass 自体は比較できない。
// XCTAssertTrue(valueA1.value == 10)
// XCTAssertTrue(valueA1.value == valueA4.value)
// MyClass.value は Int なので比較可能。
XCTAssertTrue(valueA1*.value == 10)
XCTAssertTrue(valueA2*.value == 15)
XCTAssertTrue(valueA3*.value == 5)
XCTAssertTrue(valueA4*.value == 10)
// MyClass.value は Int なので比較可能。
XCTAssertTrue(valueB1*.value == 10)
XCTAssertTrue(valueB2*.value == 15)
XCTAssertTrue(valueB3*.value == 5)
XCTAssertTrue(valueB4*.value == 10)
// EnhancedValue そのものでなら比較可能
XCTAssertEqual(valueA1, valueA1)
XCTAssertNotEqual(valueA1, valueA2)
XCTAssertNotEqual(valueA1, valueA3)
XCTAssertEqual(valueA1, valueA4)
XCTAssertTrue(valueA1 != valueA2)
// EnhancedValue と値とで比較可能
XCTAssertTrue(valueA1 == MyClass(10))
XCTAssertTrue(valueA2 != MyClass(120))
XCTAssertTrue(valueA1 == valueA1*)
XCTAssertFalse(valueA1 == valueA2*)
XCTAssertFalse(valueA1 == valueA3*)
XCTAssertTrue(valueA1 == valueA4*)
XCTAssertFalse(valueA1 != valueA1*)
XCTAssertTrue(valueA1 != valueA2*)
XCTAssertTrue(valueA1 != valueA3*)
XCTAssertFalse(valueA1 != valueA4*)
// 値と EnhancedValue とで比較可能
XCTAssertTrue(MyClass(10) == valueA1)
XCTAssertTrue(MyClass(120) != valueA2)
XCTAssertTrue(valueA1* == valueA1)
XCTAssertFalse(valueA1* == valueA2)
XCTAssertFalse(valueA1* == valueA3)
XCTAssertTrue(valueA1* == valueA4)
XCTAssertFalse(valueA1* != valueA1)
XCTAssertTrue(valueA1* != valueA2)
XCTAssertTrue(valueA1* != valueA3)
XCTAssertFalse(valueA1* != valueA4)
// ジェネレーターが一致しないと、判定は失敗。
// XCTAssertTrue(valueA1 == valueB1)
XCTAssertTrue(Swim.isSameSource(valueA1, valueA2))
XCTAssertFalse(Swim.isSameSource(valueA1, valueB2))
// ジェネレーターが異なる場合は、片方を値で取り出せば比較可能。
XCTAssertTrue(valueA1 == valueB1*)
}
func testComparableEnhanced() {
let generatorA = EnhancedValueGenerator<ComparableEnhanced<MyClass>> {
Swim.compare($0.value, $1.value)
}
let generatorB = EnhancedValueGenerator<ComparableEnhanced<MyClass>> {
Swim.compare($0.value, $1.value)
}
let valueA1 = generatorA.generate(MyClass(10))
let valueA2 = generatorA.generate(MyClass(15))
let valueA3 = generatorA.generate(MyClass(5))
let valueA4 = generatorA.generate(MyClass(10))
let valueB1 = generatorB.generate(MyClass(10))
let valueB2 = generatorB.generate(MyClass(15))
// let valueB3 = generatorB.generate(MyClass(5))
// let valueB4 = generatorB.generate(MyClass(10))
// MyClass 自体は比較できない。
// XCTAssertTrue(valueA1.value == 10)
// XCTAssertTrue(valueA1.value == valueA4.value)
// MyClass.value は Int なので比較可能。
XCTAssertTrue(valueA1*.value == 10)
XCTAssertTrue(valueA2*.value == 15)
XCTAssertTrue(valueA3*.value == 5)
XCTAssertTrue(valueA4*.value == 10)
// EnhancedValue そのものでなら比較可能
XCTAssertEqual(valueA1, valueA1)
XCTAssertNotEqual(valueA1, valueA2)
XCTAssertNotEqual(valueA1, valueA3)
XCTAssertEqual(valueA1, valueA4)
XCTAssertTrue(valueA1 == valueA1)
XCTAssertTrue(valueA1 == valueA1)
XCTAssertTrue(valueA1 >= valueA1)
XCTAssertTrue(valueA1 <= valueA1)
XCTAssertNotEqual(valueA1, valueA2)
XCTAssertNotEqual(valueA1, valueA3)
XCTAssertEqual(valueA1, valueA4)
XCTAssertTrue(valueA1 != valueA2)
XCTAssertTrue(valueA1 != valueA3)
XCTAssertTrue(valueA1 == valueA4)
XCTAssertTrue(valueA1 >= valueA4)
XCTAssertTrue(valueA1 <= valueA4)
XCTAssertTrue(valueA1 != valueA2)
// EnhancedValue と値とで比較可能
XCTAssertTrue(valueA1 == MyClass(10))
XCTAssertTrue(valueA2 != MyClass(120))
XCTAssertTrue(valueA1 >= MyClass(10))
XCTAssertTrue(valueA1 <= MyClass(10))
XCTAssertTrue(valueA2 < MyClass(120))
XCTAssertTrue(valueA2 <= MyClass(120))
XCTAssertFalse(valueA2 > MyClass(120))
XCTAssertFalse(valueA2 >= MyClass(120))
XCTAssertTrue(valueA1 == valueA1*)
XCTAssertFalse(valueA1 == valueA2*)
XCTAssertFalse(valueA1 == valueA3*)
XCTAssertTrue(valueA1 == valueA4*)
XCTAssertTrue(valueA1 >= valueA1*)
XCTAssertTrue(valueA1 >= valueA4*)
XCTAssertTrue(valueA1 <= valueA2*)
XCTAssertTrue(valueA1 >= valueA3*)
XCTAssertTrue(valueA1 < valueA2*)
XCTAssertTrue(valueA1 > valueA3*)
XCTAssertFalse(valueA1 != valueA1*)
XCTAssertFalse(valueA1 > valueA2*)
XCTAssertFalse(valueA1 < valueA3*)
XCTAssertFalse(valueA1 != valueA4*)
XCTAssertFalse(valueA1 != valueA1*)
XCTAssertTrue(valueA1 != valueA2*)
XCTAssertTrue(valueA1 != valueA3*)
XCTAssertFalse(valueA1 != valueA4*)
// 値と EnhancedValue とで比較可能
XCTAssertTrue(MyClass(10) == valueA1)
XCTAssertTrue(MyClass(120) != valueA2)
XCTAssertTrue(MyClass(10) <= valueA1)
XCTAssertTrue(MyClass(10) >= valueA1)
XCTAssertFalse(MyClass(10) != valueA1)
XCTAssertFalse(MyClass(10) > valueA1)
XCTAssertFalse(MyClass(10) < valueA1)
XCTAssertFalse(MyClass(120) == valueA2)
XCTAssertFalse(MyClass(10) != valueA1)
XCTAssertFalse(MyClass(120) == valueA2)
XCTAssertTrue(valueA1* == valueA1)
XCTAssertFalse(valueA1* == valueA2)
XCTAssertFalse(valueA1* == valueA3)
XCTAssertTrue(valueA1* == valueA4)
XCTAssertTrue(valueA1* >= valueA1)
XCTAssertTrue(valueA1* >= valueA4)
XCTAssertTrue(valueA1* <= valueA1)
XCTAssertTrue(valueA1* <= valueA4)
XCTAssertTrue(valueA1* < valueA2)
XCTAssertTrue(valueA1* > valueA3)
XCTAssertTrue(valueA1* <= valueA2)
XCTAssertTrue(valueA1* >= valueA3)
XCTAssertFalse(valueA1* > valueA2)
XCTAssertFalse(valueA1* < valueA3)
XCTAssertFalse(valueA1* >= valueA2)
XCTAssertFalse(valueA1* <= valueA3)
XCTAssertFalse(valueA1* != valueA1)
XCTAssertTrue(valueA1* != valueA2)
XCTAssertTrue(valueA1* != valueA3)
XCTAssertFalse(valueA1* != valueA4)
XCTAssertTrue(valueA1* == valueA1)
XCTAssertFalse(valueA1* == valueA2)
XCTAssertFalse(valueA1* == valueA3)
XCTAssertTrue(valueA1* == valueA4)
// ジェネレーターが一致しないと、判定は失敗。
// XCTAssertTrue(valueA1 == valueB1)
XCTAssertTrue(Swim.isSameSource(valueA1, valueA2))
XCTAssertFalse(Swim.isSameSource(valueA1, valueB2))
// ジェネレーターが異なる場合は、片方を値で取り出せば比較可能。
XCTAssertTrue(valueA1 == valueB1*)
}
}
|
5ac9e8bb9a44d55b6a83c0197c267ef2
| 25.373134 | 95 | 0.700057 | false | true | false | false |
TheTekton/Malibu
|
refs/heads/master
|
Sources/Response/MIMEType.swift
|
mit
|
1
|
import Foundation
struct MIMEType {
static func components(_ string: String) -> (type: String?, subtype: String?) {
let trimmed = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let splitted = trimmed.substring(to: trimmed.range(of: ";")?.lowerBound ?? trimmed.endIndex)
let array = splitted.components(separatedBy: "/")
return (type: array.first, subtype: array.last)
}
let type: String
let subtype: String
// MARK: - Initialization
init?(contentType: String) {
let components = MIMEType.components(contentType)
guard let type = components.type, let subtype = components.subtype else {
return nil
}
self.type = type
self.subtype = subtype
}
// MARK: - Matches
func matches(_ MIME: MIMEType) -> Bool {
var result: Bool
switch (type, subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
result = true
default:
result = false
}
return result
}
}
|
1d6c9aae828d265876223e4af3448e0d
| 22.581395 | 96 | 0.642998 | false | false | false | false |
alperdemirci/To-Do
|
refs/heads/master
|
To Do/AddNewItemViewController.swift
|
mit
|
1
|
//
// AddNewItemViewController.swift
// To Do
//
// Created by alper on 5/11/17.
// Copyright © 2017 alper. All rights reserved.
//
import UIKit
enum dataMode {
case dataEdit
case dataNew
}
class AddNewItemViewController: UIViewController, ScreenshotProtocol {
var database = FirebaseDataAdapter()
var addMapView = MapViewController()
// MARK: Outlets
var modeCheck: dataMode?
var timeAndDate: String = ""
var screenshot: UIImage?
var currentCellDataToBeEdited: Users?
@IBOutlet weak var imagePreview: UIImageView!
@IBOutlet weak var shareEmailTextField: UITextField!
@IBOutlet weak var sharedContinueSwitch: UISwitch!
@IBOutlet weak var sharedEmailTextFieldHeightContsraint: NSLayoutConstraint!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var errorMessage: UILabel!
@IBOutlet weak var todoTextField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var datePickerHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var datePickerSwitch: UISwitch!
@IBOutlet weak var addLocationSwitch: UISwitch!
@IBOutlet weak var locationSnapshotImageHeightConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
self.sharedContinueSwitch.isOn = false
self.datePickerSwitch.isOn = false
self.addLocationSwitch.isOn = false
self.errorMessage.isHidden = true
self.navigationController?.navigationBar.isHidden = false
// calls the keyboard show and keyboard height methods
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
//height adjustment for animation show/hide
self.sharedEmailTextFieldHeightContsraint.constant = 0
self.datePickerHeightConstraint.constant = 0
self.locationSnapshotImageHeightConstraint.constant = 0
self.modeChecker()
}
// MARK: - UI Actions
@IBAction func sharedContinueSwitchChanged(_ sender: Any) {
// self.shareEmailTextField.isHidden = self.sharedContinueSwitch.isOn == false ? true : false
self.sharedEmailTextFieldHeightContsraint.constant = self.sharedContinueSwitch.isOn == false ? 0 : 60
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
@IBAction func addDateChanged(_ sender: Any) {
self.datePickerHeightConstraint.constant = self.datePickerSwitch.isOn == false ? 0 : 169
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
}
@IBAction func addLocationChanged(_ sender: Any) {
if self.addLocationSwitch.isOn == true {
self.locationSnapshotImageHeightConstraint.constant = 335
let vc = UIStoryboard(name:"MapView", bundle:nil).instantiateViewController(withIdentifier: "mapView") as? MapViewController
vc!.delegate = self
self.navigationController?.pushViewController(vc!, animated:true)
} else {
self.locationSnapshotImageHeightConstraint.constant = 0
self.screenshot = nil
}
}
@IBAction func DateValueChanged(_ sender: Any) {
//TODO: push the date to db
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let timeString = datePicker.date.iso8601
self.timeAndDate = timeString
}
func screenshotImage(image: UIImage) {
self.screenshot = image
self.imagePreview.image = image
}
@IBAction func newTodoAdded(_ sender: Any) {
if self.todoTextField.text != "" {
self.errorMessage.text = "please write something first"
self.errorMessage.isHidden = false
self.navigationController?.popViewController(animated: true)
}
// let currentDateTime = Date()
if self.sharedContinueSwitch.isOn==true && self.shareEmailTextField.text=="" {
self.sharedContinueSwitch.isOn = false
self.sharedContinueSwitchChanged((Any).self)
//TODO: ask user if the are sure not to share this todo with a user
}
self.database.writeTodoIntoDB(image: self.screenshot, value: self.todoTextField.text!, date: self.timeAndDate, sharedEmail: self.shareEmailTextField.text ?? "" ) { (check) in
if check {
// TODO: all good
} else {
// TODO: need to save the todo to phone
}
}
}
// MARK: - Keyboard methods
func keyboardWillShow(notification:NSNotification){
//give room at the bottom of the scroll view, so it doesn't cover up anything the user needs to tap
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
self.scrollView.contentInset = contentInset
}
func keyboardWillHide(notification:NSNotification){
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
self.scrollView.contentInset = contentInset
}
func modeChecker() {
if self.modeCheck == .dataEdit {
//map Switch
self.currentCellDataToBeEdited?.locationAdded == "true" ? addLocationSwitch.setOn(true, animated: true) : addLocationSwitch.setOn(false, animated: true)
//Shared Switch
self.currentCellDataToBeEdited?.sharedEmail != "" ? (self.sharedContinueSwitch.isOn = true) : (self.sharedContinueSwitch.isOn = false)
self.currentCellDataToBeEdited?.sharedEmail != "" ? (self.sharedEmailTextFieldHeightContsraint.constant = 60) : (self.sharedEmailTextFieldHeightContsraint.constant = 0)
//Date Swich
if self.currentCellDataToBeEdited?.timestampcurrent != nil {
let date = Date.dateFromISOString((self.currentCellDataToBeEdited?.timestampcurrent)!)
datePicker.date = date
}
self.datePickerHeightConstraint.constant = self.currentCellDataToBeEdited?.timestampcurrent == nil ? 0 : 169
self.currentCellDataToBeEdited?.timestampcurrent != nil ? self.datePickerSwitch.setOn(true, animated: true) : self.datePickerSwitch.setOn(false, animated: true)
//Shared Email Switch
self.shareEmailTextField.text = self.currentCellDataToBeEdited?.sharedEmail
self.sharedEmailTextFieldHeightContsraint.constant = self.sharedContinueSwitch.isOn == false ? 0 : 60
self.currentCellDataToBeEdited?.value != nil ? (self.todoTextField.text = self.currentCellDataToBeEdited?.value) : (self.todoTextField.text = nil)
UIView.animate(withDuration: 0.5) {
self.view.layoutIfNeeded()
}
if self.currentCellDataToBeEdited != nil {
print(self.currentCellDataToBeEdited ?? "Nothing ")
}
} else if self.modeCheck == .dataNew {
}
}
}
|
eb7124208ad1ca1d77c86e92abf7fb08
| 40.28022 | 182 | 0.665646 | false | false | false | false |
ambientlight/Perfect
|
refs/heads/master
|
Sources/PerfectLib/Dir.swift
|
apache-2.0
|
1
|
//
// Dir.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/7/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
import Foundation
#if os(Linux)
import LinuxBridge
#else
import Darwin
#endif
/// This class represents a directory on the file system.
/// It can be used for creating & inspecting directories and enumerating directory contents.
public struct Dir {
public typealias PermissionMode = File.PermissionMode
var internalPath = ""
/// Create a new Dir object with the given path
public init(_ path: String) {
let pth = path.ends(with: "/") ? path : path + "/"
self.internalPath = File.resolveTilde(inPath: pth)
}
/// Returns true if the directory exists
public var exists: Bool {
return exists(realPath)
}
public func setAsWorkingDir() throws {
let res = chdir(self.internalPath)
guard res == 0 else {
try ThrowFileError()
}
}
public static var workingDir: Dir {
let buffer = Array(repeating: 0 as UInt8, count: 2049)
let _ = getcwd(UnsafeMutableRawPointer(mutating: buffer).assumingMemoryBound(to: Int8.self), 2048)
let path = String(validatingUTF8: UnsafeMutableRawPointer(mutating: buffer).assumingMemoryBound(to: Int8.self)) ?? "."
return Dir(path)
}
func exists(_ path: String) -> Bool {
return access(path, F_OK) != -1
}
/// Creates the directory using the provided permissions. All directories along the path will be created if need be.
/// - parameter perms: The permissions for use for the new directory and preceeding directories which need to be created. Defaults to RWX-GUO
/// - throws: `PerfectError.FileError`
public func create(perms: PermissionMode = [.rwxUser, .rxGroup, .rxOther]) throws {
let pth = realPath
var currPath = pth.begins(with: "/") ? "/" : ""
for component in pth.filePathComponents where component != "/" {
currPath += component
defer {
currPath += "/"
}
guard !exists(currPath) else {
continue
}
let res = mkdir(currPath, perms.rawValue)
guard res != -1 else {
try ThrowFileError()
}
}
}
/// Deletes the directory. The directory must be empty in order to be successfuly deleted.
/// - throws: `PerfectError.FileError`
public func delete() throws {
let res = rmdir(realPath)
guard res != -1 else {
try ThrowFileError()
}
}
/// Returns the name of the directory.
public var name: String {
return internalPath.lastFilePathComponent
}
/// Returns a Dir object representing the current Dir's parent. Returns nil if there is no parent.
public var parentDir: Dir? {
guard internalPath != "/" else {
return nil // can not go up
}
return Dir(internalPath.deletingLastFilePathComponent)
}
/// Returns the path to the current directory.
public var path: String {
return internalPath
}
/// Returns the UNIX style permissions for the directory.
public var perms: PermissionMode {
get {
return File(internalPath).perms
}
set {
File(internalPath).perms = newValue
}
}
var realPath: String {
return internalPath.resolvingSymlinksInFilePath
}
#if os(Linux)
func readDir(_ d: OpaquePointer, _ dirEnt: inout dirent, _ endPtr: UnsafeMutablePointer<UnsafeMutablePointer<dirent>?>!) -> Int32 {
return readdir_r(d, &dirEnt, endPtr)
}
#else
func readDir(_ d: UnsafeMutablePointer<DIR>, _ dirEnt: inout dirent, _ endPtr: UnsafeMutablePointer<UnsafeMutablePointer<dirent>?>!) -> Int32 {
return readdir_r(d, &dirEnt, endPtr)
}
#endif
/// Enumerates the contents of the directory passing the name of each contained element to the provided callback.
/// - parameter closure: The callback which will receive each entry's name
/// - throws: `PerfectError.FileError`
public func forEachEntry(closure: (String) throws -> ()) throws {
guard let dir = opendir(realPath) else {
try ThrowFileError()
}
defer { closedir(dir) }
var ent = dirent()
let entPtr = UnsafeMutablePointer<UnsafeMutablePointer<dirent>?>.allocate(capacity: 1)
defer { entPtr.deallocate(capacity: 1) }
while readDir(dir, &ent, entPtr) == 0 && entPtr.pointee != nil {
let name = ent.d_name
#if os(Linux)
let nameLen = 1024
#else
let nameLen = ent.d_namlen
#endif
let type = ent.d_type
var nameBuf = [CChar]()
let mirror = Mirror(reflecting: name)
let childGen = mirror.children.makeIterator()
for _ in 0..<nameLen {
guard let (_, elem) = childGen.next() else {
break
}
guard let elemI = elem as? Int8, elemI != 0 else {
break
}
nameBuf.append(elemI)
}
nameBuf.append(0)
if let name = String(validatingUTF8: nameBuf), !(name == "." || name == "..") {
if Int32(type) == Int32(DT_DIR) {
try closure(name + "/")
} else {
try closure(name)
}
}
}
}
}
|
b82802549025b2268db20c75f146b357
| 28.626374 | 147 | 0.632975 | false | false | false | false |
megavolt605/CNLFoundationTools
|
refs/heads/master
|
CNLFoundationTools/CNLFT+Timer.swift
|
mit
|
1
|
//
// CNLFT+Timer.swift
// CNLFoundationTools
//
// Created by Igor Smirnov on 11/11/2016.
// Copyright © 2016 Complex Numbers. All rights reserved.
//
import Foundation
public extension Timer {
/// Creates disposable timer and schedule it to invoke handler after delay
///
/// - Parameters:
/// - delay: Delay (seconds)
/// - handler: Closure to be invoked
/// - Returns: Timer instance
public class func schedule(delay: TimeInterval, handler: @escaping (Timer?) -> Void) -> Timer? {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer
}
/// Creates timer and schedule it to invoke handler after delay, repeating with specified interval
///
/// - Parameters:
/// - interval: Repeating interval
/// - handler: Closure to be invoked
/// - Returns: Timer instance
public class func schedule(delay: TimeInterval = 0.0, repeatInterval interval: TimeInterval, handler: @escaping (Timer?) -> Void) -> Timer? {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
return timer
}
}
|
2cb877a09b450f3fdf9faaca33adefd5
| 37.868421 | 145 | 0.677048 | false | false | false | false |
niklassaers/Bolt-swift
|
refs/heads/master
|
Sources/EncryptedSocket.swift
|
bsd-3-clause
|
1
|
import Foundation
import PackStream
import Socket
import SSLService
public class EncryptedSocket {
let hostname: String
let port: Int
let socket: Socket
let configuration: SSLService.Configuration
fileprivate static let readBufferSize = 65536
public init(hostname: String, port: Int, configuration: SSLService.Configuration) throws {
self.hostname = hostname
self.port = port
self.configuration = configuration
self.socket = try Socket.create(family: .inet, type: .stream, proto: .tcp)
self.socket.readBufferSize = EncryptedSocket.readBufferSize
}
public static func defaultConfiguration(sslConfig: SSLConfiguration, allowHostToBeSelfSigned: Bool) -> SSLService.Configuration {
let configuration = SSLService.Configuration(withCipherSuite: nil)
return configuration
}
}
extension EncryptedSocket: SocketProtocol {
public func connect(timeout: Int) throws {
if let sslService = try SSLService(usingConfiguration: self.configuration) {
sslService.skipVerification = true
socket.delegate = sslService
sslService.verifyCallback = { _ in
return (true, nil)
}
}
if socket.isConnected == false {
usleep(10000) // This sleep is anoying, but else SSL may not complete correctly!
let timeout = UInt(max(0, timeout))
try socket.connect(to: hostname, port: Int32(port), timeout: timeout)
} else {
print("Socket was already connected")
}
}
public func disconnect() {
socket.close()
}
private func checkAndPossiblyReconnectSocket () throws {
let (readables, writables) = try Socket.checkStatus(for: [socket])
if socket.isConnected == false || readables.count + writables.count < 1 {
print("Reconnecting")
// reconnect
disconnect()
try connect(timeout: 5)
}
}
public func send(bytes: [Byte]) throws {
try checkAndPossiblyReconnectSocket()
let data = Data(bytes: bytes)
try socket.write(from: data)
}
public func receive(expectedNumberOfBytes: Int32) throws -> [Byte] {
try checkAndPossiblyReconnectSocket()
var data = Data(capacity: EncryptedSocket.readBufferSize)
var numberOfBytes = try socket.read(into: &data)
var bytes = [Byte] (data)
while numberOfBytes != 0 && numberOfBytes % 8192 == 0 {
usleep(10000)
data = Data(capacity: EncryptedSocket.readBufferSize)
numberOfBytes = try socket.read(into: &data)
bytes.append(contentsOf: data)
}
return bytes
}
}
|
719339df0c318f9bdf430e3465363961
| 28.531915 | 133 | 0.631124 | false | true | false | false |
CaiMiao/CGSSGuide
|
refs/heads/master
|
DereGuide/Model/CGSSSkill.swift
|
mit
|
1
|
//
// CGSSSkill.swift
// CGSSFoundation
//
// Created by zzk on 16/6/14.
// Copyright © 2016年 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
fileprivate let skillDescriptions = [
1: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成", comment: "技能描述"),
2: NSLocalizedString("使所有PERFECT/GREAT音符获得 %d%% 的分数加成", comment: "技能描述"),
3: NSLocalizedString("使所有PERFECT/GREAT/NICE音符获得 %d%% 的分数加成", comment: "技能描述"),
4: NSLocalizedString("获得额外的 %d%% 的COMBO加成", comment: "技能描述"),
5: NSLocalizedString("使所有GREAT音符改判为PERFECT", comment: "技能描述"),
6: NSLocalizedString("使所有GREAT/NICE音符改判为PERFECT", comment: "技能描述"),
7: NSLocalizedString("使所有GREAT/NICE/BAD音符改判为PERFECT", comment: "技能描述"),
8: NSLocalizedString("所有音符改判为PERFECT", comment: "技能描述"),
9: NSLocalizedString("使NICE音符不会中断COMBO", comment: "技能描述"),
10: NSLocalizedString("使BAD/NICE音符不会中断COMBO", comment: "技能描述"),
11: NSLocalizedString("使你的COMBO不会中断", comment: "技能描述"),
12: NSLocalizedString("使你的生命不会减少", comment: "技能描述"),
13: NSLocalizedString("使所有音符恢复你 %d 点生命", comment: "技能描述"),
14: NSLocalizedString("消耗 %2$d 生命,PERFECT音符获得 %1$d%% 的分数加成,并且NICE/BAD音符不会中断COMBO", comment: "技能描述"),
15: NSLocalizedString("使所有PERFECT音符获得 %d%% 的分数加成,且使PERFECT判定区间的时间范围缩小", comment: ""),
16: NSLocalizedString("重复发动上一个其他偶像发动过的技能", comment: ""),
17: NSLocalizedString("使所有PERFECT音符恢复你 %d 点生命", comment: "技能描述"),
18: NSLocalizedString("使所有PERFECT/GREAT音符恢复你 %d 点生命", comment: "技能描述"),
19: NSLocalizedString("使所有PERFECT/GREAT/NICE音符恢复你 %d 点生命", comment: "技能描述"),
20: NSLocalizedString("使当前发动的分数加成和COMBO加成额外提高 %d%%,生命恢复和护盾额外恢复 1 点生命,改判范围增加一档", comment: ""),
21: NSLocalizedString("当仅有Cute偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
22: NSLocalizedString("当仅有Cool偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
23: NSLocalizedString("当仅有Passion偶像存在于队伍时,使所有PERFECT音符获得 %d%% 的分数加成,并获得额外的 %d%% 的COMBO加成", comment: ""),
24: NSLocalizedString("获得额外的 %d%% 的COMBO加成,并使所有PERFECT音符恢复你 %d 点生命", comment: ""),
25: NSLocalizedString("获得额外的COMBO加成,当前生命值越高加成越高", comment: ""),
26: NSLocalizedString("当Cute、Cool和Passion偶像存在于队伍时,使所有PERFECT音符获得 %1$d%% 的分数加成/恢复你 %3$d 点生命,并获得额外的 %2$d%% 的COMBO加成", comment: "")
]
fileprivate let intervalClause = NSLocalizedString("每 %d 秒,", comment: "")
fileprivate let probabilityClause = NSLocalizedString("有 %@%% 的几率", comment: "")
fileprivate let lengthClause = NSLocalizedString(",持续 %@ 秒。", comment: "")
extension CGSSSkill {
private var effectValue: Int {
var effectValue = value!
if [1, 2, 3, 4, 14, 15, 21, 22, 23, 24, 26].contains(skillTypeId) {
effectValue -= 100
} else if [20].contains(skillTypeId) {
// there is only one possibility: 20% up for combo bonus and perfect bonus, using fixed value here instead of reading it from database table skill_boost_type. if more possiblities are added to the game, fix here.
effectValue = 20
}
return effectValue
}
private var effectValue2: Int {
var effectValue2 = value2!
if [21, 22, 23, 26].contains(skillTypeId) {
effectValue2 -= 100
}
return effectValue2
}
private var effectValue3: Int {
return value3
}
private var effectExpalin: String {
if skillTypeId == 14 {
return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, skillTriggerValue)
} else {
return String.init(format: skillDescriptions[skillTypeId] ?? NSLocalizedString("未知", comment: ""), effectValue, effectValue2, effectValue3)
}
}
private var intervalExplain: String {
return String.init(format: intervalClause, condition)
}
@nonobjc func getLocalizedExplainByRange(_ range: CountableClosedRange<Int>) -> String {
let probabilityRangeString = String(format: "%.2f ~ %.2f", self.procChanceOfLevel(range.lowerBound) / 100, self.procChanceOfLevel(range.upperBound) / 100)
let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString)
let lengthRangeString = String(format: "%.2f ~ %.2f", self.effectLengthOfLevel(range.lowerBound) / 100, self.effectLengthOfLevel(range.upperBound) / 100)
let lengthExplain = String.init(format: lengthClause, lengthRangeString)
return intervalExplain + probabilityExplain + effectExpalin + lengthExplain
}
@nonobjc func getLocalizedExplainByLevel(_ level: Int) -> String {
let probabilityRangeString = String(format: "%.2f", self.procChanceOfLevel(level) / 100)
let probabilityExplain = String.init(format: probabilityClause, probabilityRangeString)
let lengthRangeString = String(format: "%.2f", self.effectLengthOfLevel(level) / 100)
let lengthExplain = String.init(format: lengthClause, lengthRangeString)
return intervalExplain + probabilityExplain + effectExpalin + lengthExplain
}
var skillFilterType: CGSSSkillTypes {
return CGSSSkillTypes(typeID: skillTypeId)
}
var descriptionShort: String {
return "\(condition!)s/\(procTypeShort)/\(skillFilterType.description)"
}
// 在计算触发几率和持续时间时 要在取每等级增量部分进行一次向下取整
func procChanceOfLevel(_ lv: Int) -> Double {
if let p = procChance {
let p1 = Double(p[1])
let p0 = Double(p[0])
return (floor((p1 - p0) / 9) * (Double(lv) - 1) + p0)
} else {
return 0
}
}
func effectLengthOfLevel(_ lv: Int) -> Double {
if let e = effectLength {
let e1 = Double(e[1])
let e0 = Double(e[0])
return (floor((e1 - e0) / 9) * (Double(lv) - 1) + e0)
} else {
return 0
}
}
var procTypeShort: String {
switch maxChance {
case 6000:
return NSLocalizedString("高", comment: "技能触发几率的简写")
case 5250:
return NSLocalizedString("中", comment: "技能触发几率的简写")
case 4500:
return NSLocalizedString("低", comment: "技能触发几率的简写")
default:
return NSLocalizedString("其他", comment: "通用, 通常不会出现, 为未知字符预留")
}
}
var procType: CGSSProcTypes {
switch maxChance {
case 6000:
return .high
case 5250:
return .middle
case 4500:
return .low
default:
return .none
}
}
var conditionType: CGSSConditionTypes {
switch condition {
case 4:
return .c4
case 6:
return .c6
case 7:
return .c7
case 9:
return .c9
case 11:
return .c11
case 13:
return .c13
default:
return .other
}
}
}
class CGSSSkill: CGSSBaseModel {
var condition: Int!
var cutinType: Int!
var effectLength: [Int]!
var explain: String!
var explainEn: String!
var id: Int!
var judgeType: Int!
var maxChance: Int!
var maxDuration: Int!
var procChance: [Int]!
var skillName: String!
var skillTriggerType: Int!
var skillTriggerValue: Int!
var skillType: String!
var value: Int!
var skillTypeId: Int!
var value2: Int!
var value3: Int!
/**
* Instantiate the instance using the passed json values to set the properties values
*/
init(fromJson json: JSON!) {
super.init()
if json == JSON.null {
return
}
condition = json["condition"].intValue
cutinType = json["cutin_type"].intValue
effectLength = [Int]()
let effectLengthArray = json["effect_length"].arrayValue
for effectLengthJson in effectLengthArray {
effectLength.append(effectLengthJson.intValue)
}
explain = json["explain"].stringValue
explainEn = json["explain_en"].stringValue
id = json["id"].intValue
judgeType = json["judge_type"].intValue
maxChance = json["max_chance"].intValue
maxDuration = json["max_duration"].intValue
procChance = [Int]()
let procChanceArray = json["proc_chance"].arrayValue
for procChanceJson in procChanceArray {
procChance.append(procChanceJson.intValue)
}
skillName = json["skill_name"].stringValue
skillTriggerType = json["skill_trigger_type"].intValue
skillTriggerValue = json["skill_trigger_value"].intValue
skillType = json["skill_type"].stringValue
if skillType == "" {
skillType = NSLocalizedString("未知", comment: "")
}
value = json["value"].intValue
value2 = json["value_2"].intValue
value3 = json["value_3"].intValue
skillTypeId = json["skill_type_id"].intValue
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
condition = aDecoder.decodeObject(forKey: "condition") as? Int
cutinType = aDecoder.decodeObject(forKey: "cutin_type") as? Int
effectLength = aDecoder.decodeObject(forKey: "effect_length") as? [Int]
explain = aDecoder.decodeObject(forKey: "explain") as? String
explainEn = aDecoder.decodeObject(forKey: "explain_en") as? String
id = aDecoder.decodeObject(forKey: "id") as? Int
judgeType = aDecoder.decodeObject(forKey: "judge_type") as? Int
maxChance = aDecoder.decodeObject(forKey: "max_chance") as? Int
maxDuration = aDecoder.decodeObject(forKey: "max_duration") as? Int
procChance = aDecoder.decodeObject(forKey: "proc_chance") as? [Int]
skillName = aDecoder.decodeObject(forKey: "skill_name") as? String
skillTriggerType = aDecoder.decodeObject(forKey: "skill_trigger_type") as? Int
skillTriggerValue = aDecoder.decodeObject(forKey: "skill_trigger_value") as? Int
skillType = aDecoder.decodeObject(forKey: "skill_type") as? String ?? NSLocalizedString("未知", comment: "")
value = aDecoder.decodeObject(forKey: "value") as? Int
skillTypeId = aDecoder.decodeObject(forKey: "skill_type_id") as? Int
value2 = aDecoder.decodeObject(forKey: "value_2") as? Int
value3 = aDecoder.decodeObject(forKey: "value_3") as? Int
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
override func encode(with aCoder: NSCoder)
{
super.encode(with: aCoder)
if condition != nil {
aCoder.encode(condition, forKey: "condition")
}
if cutinType != nil {
aCoder.encode(cutinType, forKey: "cutin_type")
}
if effectLength != nil {
aCoder.encode(effectLength, forKey: "effect_length")
}
if explain != nil {
aCoder.encode(explain, forKey: "explain")
}
if explainEn != nil {
aCoder.encode(explainEn, forKey: "explain_en")
}
if id != nil {
aCoder.encode(id, forKey: "id")
}
if judgeType != nil {
aCoder.encode(judgeType, forKey: "judge_type")
}
if maxChance != nil {
aCoder.encode(maxChance, forKey: "max_chance")
}
if maxDuration != nil {
aCoder.encode(maxDuration, forKey: "max_duration")
}
if procChance != nil {
aCoder.encode(procChance, forKey: "proc_chance")
}
if skillName != nil {
aCoder.encode(skillName, forKey: "skill_name")
}
if skillTriggerType != nil {
aCoder.encode(skillTriggerType, forKey: "skill_trigger_type")
}
if skillTriggerValue != nil {
aCoder.encode(skillTriggerValue, forKey: "skill_trigger_value")
}
if skillType != nil {
aCoder.encode(skillType, forKey: "skill_type")
}
if value != nil {
aCoder.encode(value, forKey: "value")
}
if skillTypeId != nil {
aCoder.encode(skillTypeId, forKey: "skill_type_id")
}
if value2 != nil {
aCoder.encode(value2, forKey: "value_2")
}
if value3 != nil {
aCoder.encode(value3, forKey: "value_3")
}
}
}
|
e0720471064963f6103eaa816f1b3901
| 36.688623 | 224 | 0.612488 | false | false | false | false |
CodaFi/swift-compiler-crashes
|
refs/heads/master
|
crashes-duplicates/05961-swift-bracestmt-create.swift
|
mit
|
11
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var f {
protocol P {
switch x }
struct A {
func b<T where g: U : e(f<T where g: U : T.b<Q
println(T.h == r(T: Int -> U))"\() { p(T.B == b
enum e {
func c<d : c: A {
println() -> {
class n {
var _ = f : A : NSManagedObject {
func e<T where h: A {
}
}
}
struct A {
var f {
class B : NSObject {
func b<T where g: c<T where g.B : T: Int -> {
func e(
|
032bcaa288c85d862d96c789853caa5f
| 20.458333 | 87 | 0.615534 | false | true | false | false |
kirankunigiri/Apple-Family
|
refs/heads/master
|
FamilyDemo/Libraries/Signal/InviteTableViewController.swift
|
mit
|
2
|
//
// InviteTableViewController.swift
// Family
//
// Created by Kiran Kunigiri on 12/20/16.
// Copyright © 2016 Kiran. All rights reserved.
//
import UIKit
protocol InviteDelegate {
func getConnectedPeers() -> [Peer]
func getAvailablePeers() -> [Peer]
func invitePeer(peer: Peer)
}
class InviteTableViewController: UITableViewController {
@IBOutlet weak var nearbyTableView: UITableView!
var delegate: InviteDelegate?
override func viewDidLoad() {
super.viewDidLoad()
}
// Reloads the table view on the main thread
func update() {
OperationQueue.main.addOperation {
self.tableView.reloadData()
}
}
}
// MARK - Table View Delegate
extension InviteTableViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// End if a connected device was selected
if (indexPath.section == 0) {
return
}
// Send invitation to the peer
let peer = delegate?.getAvailablePeers()[indexPath.row]
delegate?.invitePeer(peer: peer!)
}
}
// MARK: - Table View Data Source
extension InviteTableViewController {
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Connected"
case 1:
return "Available"
default:
return ""
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return (delegate?.getConnectedPeers().count)!
case 1:
return (delegate?.getAvailablePeers().count)!
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DeviceCell
// Update text
switch indexPath.section {
case 0:
let peer = delegate?.getConnectedPeers()[indexPath.row]
cell.name.text = peer?.peerID.displayName
cell.status.text = peer?.state.stringValue
case 1:
let peer = delegate?.getAvailablePeers()[indexPath.row]
cell.name.text = peer?.peerID.displayName
cell.status.text = peer?.state.stringValue
default:
cell.name.text = ""
}
// Selection
if (indexPath.section == 0) {
cell.isUserInteractionEnabled = false
} else {
cell.isUserInteractionEnabled = true
}
return cell
}
}
// MARK: - Table View Cell
class DeviceCell: UITableViewCell {
@IBOutlet weak var name: UILabel!
@IBOutlet weak var status: UILabel!
}
|
d888a77b8e73ce1f922936359ec4e4b3
| 21.151079 | 109 | 0.59305 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
refs/heads/master
|
Sources/SpeechToTextV1/Models/SpeechRecognitionResults.swift
|
apache-2.0
|
1
|
/**
* (C) Copyright IBM Corp. 2016, 2022.
*
* 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
/**
The complete results for a speech recognition request.
*/
public struct SpeechRecognitionResults: Codable, Equatable {
/**
An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are
returned only if supported by the method). Final results are guaranteed not to change; interim results might be
replaced by further interim results and eventually final results.
For the HTTP interfaces, all results arrive at the same time. For the WebSocket interface, results can be sent as
multiple separate responses. The service periodically sends updates to the results list. The `result_index` is
incremented to the lowest index in the array that has changed for new results.
For more information, see [Understanding speech recognition
results](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-basic-response).
*/
public var results: [SpeechRecognitionResult]?
/**
An index that indicates a change point in the `results` array. The service increments the index for additional
results that it sends for new audio for the same request. All results with the same index are delivered at the same
time. The same index can include multiple final results that are delivered with the same response.
*/
public var resultIndex: Int?
/**
An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a
multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results
are also requested for methods that support them, it is possible for a `SpeechRecognitionResults` object to include
only the `speaker_labels` field.
*/
public var speakerLabels: [SpeakerLabelsResult]?
/**
If processing metrics are requested, information about the service's processing of the input audio. Processing
metrics are not available with the synchronous [Recognize audio](#recognize) method.
*/
public var processingMetrics: ProcessingMetrics?
/**
If audio metrics are requested, information about the signal characteristics of the input audio.
*/
public var audioMetrics: AudioMetrics?
/**
An array of warning messages associated with the request:
* Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument
strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the form
`"{invalid_arg_1}, {invalid_arg_2}."`
* The following warning is returned if the request passes a custom model that is based on an older version of a
base model for which an updated version is available: `"Using previous version of base model, because your custom
model has been built with it. Please note that this version will be supported only for a limited time. Consider
updating your custom model to the new base model. If you do not do that you will be automatically switched to base
model when you used the non-updated custom model."`
In both cases, the request succeeds despite the warnings.
*/
public var warnings: [String]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case results = "results"
case resultIndex = "result_index"
case speakerLabels = "speaker_labels"
case processingMetrics = "processing_metrics"
case audioMetrics = "audio_metrics"
case warnings = "warnings"
}
}
|
7196634c0eb857912d35c29adb39a57f
| 48.569767 | 120 | 0.731644 | false | false | false | false |
mitchtreece/Spider
|
refs/heads/master
|
Spider/Classes/Core/Authorization/TokenRequestAuth.swift
|
mit
|
1
|
//
// TokenRequestAuth.swift
// Spider-Web
//
// Created by Mitch Treece on 8/22/18.
//
import Foundation
/// `TokenRequestAuth` is a bearer token authorization type.
public struct TokenRequestAuth: RequestAuth {
public var prefix: String? = "Bearer"
public var field: String
private var tokenString: String
public var headerValue: String {
return (self.prefix != nil) ? "\(self.prefix!) \(self.rawValue)" : self.rawValue
}
public var rawValue: String {
return self.tokenString
}
/// Initializes a token auth object.
/// - Parameter field: The HTTP request header field; _defaults to "Authorization"_.
/// - Parameter value: The token value.
public init(field: String = "Authorization", value: String) {
self.field = field
self.tokenString = value
}
}
|
5cd794dab1c68bbf74abd606ac66ef6c
| 23.583333 | 88 | 0.622599 | false | false | false | false |
pdil/PDColorPicker
|
refs/heads/master
|
Source/PDRoundedRectButton.swift
|
mit
|
1
|
//
// PDRoundedRectButton.swift
// PDColorPicker
//
// Created by Paolo Di Lorenzo on 8/8/17.
// Copyright © 2017 Paolo Di Lorenzo. All rights reserved.
//
import UIKit
class PDRoundedRectButton: PDBouncyButton {
var title: String {
didSet {
setTitle(title, for: .normal)
titleLabel?.sizeToFit()
}
}
var backColor: UIColor {
didSet { backgroundColor = backColor }
}
var foreColor: UIColor {
didSet { setTitleColor(foreColor, for: .normal) }
}
override var intrinsicContentSize: CGSize {
guard let labelSize = titleLabel?.intrinsicContentSize else { return .zero }
return CGSize(width: labelSize.width + contentEdgeInsets.left + contentEdgeInsets.right, height: super.intrinsicContentSize.height + contentEdgeInsets.top + contentEdgeInsets.bottom)
}
// MARK: - Initializer
init(title: String, backColor: UIColor, foreColor: UIColor) {
self.title = ""
self.backColor = .black
self.foreColor = .black
super.init(frame: .zero)
defer {
self.title = title
self.backColor = backColor
self.foreColor = foreColor
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowOpacity = 0.6
layer.shadowRadius = 4
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life Cycle
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.height / 2
contentEdgeInsets = UIEdgeInsets(top: 2, left: 6, bottom: 2, right: 6)
}
}
|
13bae1dd7ed6225237f6f091eda09553
| 23.25 | 186 | 0.657975 | false | false | false | false |
Mimieam/CS540_AI
|
refs/heads/master
|
Project2/Sys/Sys/imageManager.swift
|
mit
|
1
|
//
// imageManager.swift
// VysSys
//
// Created by Aman Miezan Echimane on 12/2/15.
// Copyright © 2015 Miezel. All rights reserved.
//
import Foundation
import UIKit
import CoreGraphics
func CreateBitmapContext (inImage:CGImageRef, dividingFactor:Int = 1) -> (cgctx:CGContextRef, pixelPtr:UnsafeMutablePointer<UInt8>, ctxWidth: Int, ctxHeight: Int) {
var context: CGContextRef!;
let bitmapData: UnsafeMutablePointer<UInt8>;
var bitmapByteCount: Int;
var bitmapBytesPerRow: Int;
// Get image width, height. We'll use the entire image.
let pixelsWide = CGImageGetWidth(inImage)/dividingFactor;
let pixelsHigh = CGImageGetHeight(inImage)/dividingFactor;
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes; 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = (pixelsWide * 4);
bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
// Allocate memory for image data. This is the destination in memory
// where any drawing to the bitmap context will be rendered.
bitmapData = UnsafeMutablePointer<UInt8>(malloc(bitmapByteCount))
context = CGBitmapContextCreate (bitmapData,
pixelsWide,
pixelsHigh,
CGImageGetBitsPerComponent(inImage), // bits per component
CGImageGetBytesPerRow(inImage),
CGColorSpaceCreateWithName(kCGColorSpaceGenericGray),
CGImageGetBitmapInfo(inImage).rawValue
);
// let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
let rect:CGRect = CGRectMake(0, 0, CGFloat(pixelsWide) , CGFloat(pixelsHigh))
// UIGraphicsBeginImageContextWithOptions(rect.size, false, scale)
CGContextDrawImage(context, rect, inImage);
// UIImage(CGImage: inImage).drawInRect(rect)
// UIGraphicsEndImageContext()
let data = CGBitmapContextGetData (context)
let pixelPtr = UnsafeMutablePointer<UInt8>(data)
// let imageRef = CGBitmapContextCreateImage(context)
// UIImage(CGImage: imageRef!)
return (context, pixelPtr, pixelsWide, pixelsHigh);
}
func overlayLinesOnImage(let img:UIImage, let lines:[(p1:point2D, p2:point2D )]) -> UIImage {
// UIGraphicsBeginImageContext(CGSizeMake(img.size.width, img.size.height))
UIGraphicsBeginImageContextWithOptions(CGSizeMake(img.size.width, img.size.height), true, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
let rect:CGRect = CGRectMake(0, 0, CGFloat(img.size.width) , CGFloat(img.size.height))
// CGContextDrawImage(context, rect, img.CGImage); // draw IT UPSIDE DOWN !! WTH !!??
img.drawInRect(rect) // USE THIS INSTEAD !
// var context = self.vsimg.original.cgctx
CGContextSetStrokeColorWithColor(context, UIColor.redColor().CGColor)
for line in lines{
CGContextMoveToPoint(context, line.0.x, line.0.y)
CGContextAddLineToPoint(context, line.1.x, line.1.y)
CGContextStrokePath(context)
}
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
class VSPhoto {
var CGRef:CGImageRef!
var pixelPtr:UnsafeMutablePointer<UInt8>;
var width:Int = 0;
var height:Int = 0;
var cgctx: CGContextRef
var count:Int = 0 ;
init(img:UIImage! , scaleDownBy:Int = 1){
CGRef = img.CGImage
(cgctx, pixelPtr, width, height) = CreateBitmapContext(img.CGImage!, dividingFactor: scaleDownBy)
print("\(width) * \(height)")
count = width * height
}
func display() -> UIImage{
let imageRef = CGBitmapContextCreateImage(cgctx)
return UIImage(CGImage: imageRef!)
}
}
// Visual Sytem Image class
class VSImage {
var UIimg: UIImage!
var scaleDownBy:Int!
var original: VSPhoto!
var modified: VSPhoto!
var buffer: VSPhoto!
init(img:UIImage, scaleDownBy:Int = 1){
original = VSPhoto(img: img, scaleDownBy: 1)
buffer = VSPhoto(img: img, scaleDownBy: scaleDownBy)
modified = VSPhoto(img: UIImage(CGImage: CGBitmapContextCreateImage(buffer.cgctx)!), scaleDownBy: 1)
}
func reset(){
modified = VSPhoto(img: UIimg, scaleDownBy: scaleDownBy)
}
func resetWithNewImg (img:UIImage, scaleDownBy:Int = 1) -> UIImage{
original = VSPhoto(img: img, scaleDownBy: 1)
buffer = VSPhoto(img: img, scaleDownBy: scaleDownBy)
modified = VSPhoto(img: UIImage(CGImage: CGBitmapContextCreateImage(buffer.cgctx)!), scaleDownBy: 1)
return img
}
func displayOrignal() -> UIImage{ return UIImage(CGImage: original.CGRef) }
func displayProcessed() -> UIImage{
let imageRef = CGBitmapContextCreateImage(modified.cgctx)
return UIImage(CGImage: imageRef!)
}
}
|
bd003cbb4ead63160f160c8fc03f5044
| 30.06875 | 164 | 0.673305 | false | false | false | false |
Moonsownner/Navigation
|
refs/heads/master
|
JNavigation/JNavigation/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// JNavigation
//
// Created by J HD on 16/7/5.
// Copyright © 2016年 J HD. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
let vc = TestViewController()
vc.navigationStyle = JNavigationStyle.default(color: UIColor.green)
window?.rootViewController = JNavigationController(rootViewController: vc)
window?.makeKeyAndVisible()
return true
}
}
class TestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "title"
view.backgroundColor = UIColor.white
let button = UIButton(frame: CGRect(x: 0,y: 0,width: 100,height: 50))
button.backgroundColor = UIColor.red
button.setTitle("push", for: UIControlState())
button.addTarget(self, action: #selector(TestViewController.push), for: .touchUpInside)
view.addSubview(button)
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(TestViewController.pop))
}
func pop(){
_ = self.navigationController?.popViewController(animated: true)
}
func push(){
let vc = TestViewController()
vc.navigationStyle = JNavigationStyle.default(color: UIColor.green)
self.navigationController?.pushViewController(vc, animated: true)
}
}
|
8bf300cb2ce12c7595fa263139214d0a
| 26.96875 | 164 | 0.651955 | false | true | false | false |
FromPointer/VPNOn
|
refs/heads/develop
|
VPNOn/VPNConfigViewController+Save.swift
|
mit
|
21
|
//
// VPNConfigViewController+Save.swift
// VPNOn
//
// Created by Lex on 1/23/15.
// Copyright (c) 2015 LexTang.com. All rights reserved.
//
import UIKit
import VPNOnKit
extension VPNConfigViewController
{
@IBAction func saveVPN(sender: AnyObject) {
if let currentVPN = vpn {
currentVPN.title = titleTextField.text
currentVPN.server = serverTextField.text
currentVPN.account = accountTextField.text
currentVPN.group = groupTextField.text
currentVPN.alwaysOn = alwaysOnSwitch.on
currentVPN.ikev2 = typeSegment.selectedSegmentIndex == 1
currentVPN.certificateURL = certificateURL
VPNKeychainWrapper.setPassword(passwordTextField.text, forVPNID: currentVPN.ID)
VPNKeychainWrapper.setSecret(secretTextField.text, forVPNID: currentVPN.ID)
VPNDataManager.sharedManager.saveContext()
NSNotificationCenter.defaultCenter().postNotificationName(kVPNDidUpdate, object: currentVPN)
} else {
if let lastVPN = VPNDataManager.sharedManager.createVPN(
titleTextField.text,
server: serverTextField.text,
account: accountTextField.text,
password: passwordTextField.text,
group: groupTextField.text,
secret: secretTextField.text,
alwaysOn: alwaysOnSwitch.on,
ikev2: typeSegment.selectedSegmentIndex == 1,
certificateURL: certificateURL ?? "",
certificate: temporaryCertificateData
) {
NSNotificationCenter.defaultCenter().postNotificationName(kVPNDidCreate, object: lastVPN)
}
}
}
func toggleSaveButtonByStatus() {
if self.titleTextField.text.isEmpty
|| self.accountTextField.text.isEmpty
|| self.serverTextField.text.isEmpty {
self.saveButton?.enabled = false
} else {
self.saveButton?.enabled = true
}
}
}
|
5db423669fdc232b6a68f42425d4f116
| 35.568966 | 109 | 0.611033 | false | false | false | false |
jjatie/Charts
|
refs/heads/master
|
Source/Charts/Highlight/Highlight.swift
|
apache-2.0
|
1
|
//
// Highlight.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 CoreGraphics
import Foundation
open class Highlight: CustomStringConvertible {
/// the x-value of the highlighted value
fileprivate var _x = Double.nan
/// the y-value of the highlighted value
fileprivate var _y = Double.nan
/// the x-pixel of the highlight
private var _xPx = CGFloat.nan
/// the y-pixel of the highlight
private var _yPx = CGFloat.nan
/// the index of the data object - in case it refers to more than one
open var dataIndex = Int(-1)
/// the index of the dataset the highlighted value is in
fileprivate var _dataSetIndex = Int(0)
/// index which value of a stacked bar entry is highlighted
///
/// **default**: -1
fileprivate var _stackIndex = Int(-1)
/// the axis the highlighted value belongs to
private var _axis = YAxis.AxisDependency.left
/// the x-position (pixels) on which this highlight object was last drawn
open var drawX: CGFloat = 0.0
/// the y-position (pixels) on which this highlight object was last drawn
open var drawY: CGFloat = 0.0
public init() {}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - xPx: the x-pixel of the highlighted value
/// - yPx: the y-pixel of the highlighted value
/// - dataIndex: the index of the Data the highlighted value belongs to
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
/// - axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataIndex: Int,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency
) {
_x = x
_y = y
_xPx = xPx
_yPx = yPx
self.dataIndex = dataIndex
_dataSetIndex = dataSetIndex
_stackIndex = stackIndex
_axis = axis
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - xPx: the x-pixel of the highlighted value
/// - yPx: the y-pixel of the highlighted value
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
/// - axis: the axis the highlighted value belongs to
public convenience init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
stackIndex: Int,
axis: YAxis.AxisDependency
) {
self.init(x: x, y: y, xPx: xPx, yPx: yPx,
dataIndex: 0,
dataSetIndex: dataSetIndex,
stackIndex: stackIndex,
axis: axis)
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - xPx: the x-pixel of the highlighted value
/// - yPx: the y-pixel of the highlighted value
/// - dataIndex: the index of the Data the highlighted value belongs to
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
/// - axis: the axis the highlighted value belongs to
public init(
x: Double, y: Double,
xPx: CGFloat, yPx: CGFloat,
dataSetIndex: Int,
axis: YAxis.AxisDependency
) {
_x = x
_y = y
_xPx = xPx
_yPx = yPx
_dataSetIndex = dataSetIndex
_axis = axis
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - y: the y-value of the highlighted value
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
public init(x: Double, y: Double, dataSetIndex: Int, dataIndex: Int = -1) {
_x = x
_y = y
_dataSetIndex = dataSetIndex
self.dataIndex = dataIndex
}
/// - Parameters:
/// - x: the x-value of the highlighted value
/// - dataSetIndex: the index of the DataSet the highlighted value belongs to
/// - stackIndex: references which value of a stacked-bar entry has been selected
public convenience init(x: Double, dataSetIndex: Int, stackIndex: Int) {
self.init(x: x, y: Double.nan, dataSetIndex: dataSetIndex)
_stackIndex = stackIndex
}
open var x: Double { return _x }
open var y: Double { return _y }
open var xPx: CGFloat { return _xPx }
open var yPx: CGFloat { return _yPx }
open var dataSetIndex: Int { return _dataSetIndex }
open var stackIndex: Int { return _stackIndex }
open var axis: YAxis.AxisDependency { return _axis }
open var isStacked: Bool { return _stackIndex >= 0 }
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(x: CGFloat, y: CGFloat) {
drawX = x
drawY = y
}
/// Sets the x- and y-position (pixels) where this highlight was last drawn.
open func setDraw(pt: CGPoint) {
drawX = pt.x
drawY = pt.y
}
// MARK: CustomStringConvertible
open var description: String {
return "Highlight, x: \(_x), y: \(_y), dataIndex (combined charts): \(dataIndex), dataSetIndex: \(_dataSetIndex), stackIndex (only stacked barentry): \(_stackIndex)"
}
}
// MARK: Equatable
extension Highlight: Equatable {
public static func == (lhs: Highlight, rhs: Highlight) -> Bool {
if lhs === rhs {
return true
}
return lhs._x == rhs._x
&& lhs._y == rhs._y
&& lhs.dataIndex == rhs.dataIndex
&& lhs._dataSetIndex == rhs._dataSetIndex
&& lhs._stackIndex == rhs._stackIndex
}
}
|
6639f570f6e042d4a55e15e314d2d8d5
| 32.645161 | 173 | 0.608341 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
UICollectionViewLayout/uicollectionview-layouts-kit-master/collection-layout-ios/Models/Comics.swift
|
mit
|
1
|
//
// Comics.swift
// pinterest-collection-flow-layout-ios
//
// Created by Astemir Eleev on 16/04/2018.
// Copyright © 2018 Astemir Eleev. All rights reserved.
//
import UIKit
struct Comics {
// MARK: - Properties
var image: UIImage
var imageName: String
var caption: String
var comment: String
// MARK: - Initializers
init(image: UIImage, imageName: String, caption: String, comment: String) {
self.image = image
self.caption = caption
self.comment = comment
self.imageName = imageName
}
init?(dictionary: [String : String]) {
guard let image = dictionary["Cover"], let cover = UIImage(named: image), let caption = dictionary["Caption"], let comment = dictionary["Comment"] else {
debugPrint(#function + " one of the data properties from ComicData.plist could not be unwrapped or is nil")
return nil
}
self.init(image: cover, imageName: image, caption: caption, comment: comment)
}
}
|
511e0ec1e7b3bb8cbf6915bdec7e5e29
| 25.948718 | 161 | 0.621313 | false | false | false | false |
ta2yak/MaterialKit
|
refs/heads/master
|
Example/MaterialKit/TableViewController.swift
|
mit
|
1
|
//
// TableViewController.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/16/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var labels = ["MKButton", "MKTextField", "MKTableViewCell", "MKTextView", "MKColor", "MKLayer", "MKAlert", "MKCheckBox"]
var rippleLocations: [MKRippleLocation] = [.TapLocation, .TapLocation, .Center, .Left, .Right, .TapLocation, .TapLocation, .TapLocation]
var circleColors = [UIColor.MKColor.LightBlue, UIColor.MKColor.Grey, UIColor.MKColor.LightGreen]
override func viewDidLoad() {
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return labels.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 65.0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:MyCell = tableView.dequeueReusableCellWithIdentifier("MyCell") as MyCell
cell.setMessage(labels[indexPath.row])
cell.rippleLocation = rippleLocations[indexPath.row]
let index = indexPath.row % circleColors.count
cell.rippleLayerColor = circleColors[index]
return cell
}
}
|
b834fbee65e2e6a69b518f33036b301f
| 36.921053 | 140 | 0.702083 | false | false | false | false |
hotchner/MarkdownView
|
refs/heads/master
|
Example/Example/Example3ViewController.swift
|
mit
|
1
|
import UIKit
import MarkdownView
import SafariServices
class Example3ViewController: UIViewController {
@IBOutlet weak var mdView: MarkdownView!
@IBOutlet weak var mdViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
mdView.isScrollEnabled = false
mdView.onRendered = { [weak self] height in
self?.mdViewHeight.constant = height
self?.view.setNeedsLayout()
}
mdView.onTouchLink = { [weak self] request in
guard let url = request.url else { return false }
if url.scheme == "file" {
return true
} else if url.scheme == "https" {
let safari = SFSafariViewController(url: url)
self?.navigationController?.pushViewController(safari, animated: true)
return false
} else {
return false
}
}
let session = URLSession(configuration: .default)
let url = URL(string: "https://raw.githubusercontent.com/matteocrippa/awesome-swift/master/README.md")!
let task = session.dataTask(with: url) { [weak self] data, res, error in
let str = String(data: data!, encoding: String.Encoding.utf8)
DispatchQueue.main.async {
self?.mdView.load(markdown: str)
}
}
task.resume()
}
}
|
e6b41a5287daa3513f0adeca3a8cb99e
| 26.911111 | 107 | 0.66242 | false | false | false | false |
argon/WordPress-iOS
|
refs/heads/buildAndLearn5.5
|
WordPress/Classes/ViewRelated/Notifications/Views/NoteBlockHeaderTableViewCell.swift
|
gpl-2.0
|
11
|
import Foundation
@objc public class NoteBlockHeaderTableViewCell : NoteBlockTableViewCell
{
// MARK: - Public Properties
public var headerTitle: String? {
set {
headerTitleLabel.text = newValue
}
get {
return headerTitleLabel.text
}
}
public var attributedHeaderTitle: NSAttributedString? {
set {
headerTitleLabel.attributedText = newValue
}
get {
return headerTitleLabel.attributedText
}
}
public var headerDetails: String? {
set {
headerDetailsLabel.text = newValue
}
get {
return headerDetailsLabel.text
}
}
// MARK: - Public Methods
public func downloadGravatarWithURL(url: NSURL?) {
if url == gravatarURL {
return
}
let placeholderImage = WPStyleGuide.Notifications.gravatarPlaceholderImage
let success = { (image: UIImage) in
self.gravatarImageView.displayImageWithFadeInAnimation(image)
}
gravatarImageView.downloadImage(url, placeholderImage: placeholderImage, success: success, failure: nil)
gravatarURL = url
}
// MARK: - View Methods
public override func awakeFromNib() {
super.awakeFromNib()
accessoryType = .DisclosureIndicator
contentView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
backgroundColor = WPStyleGuide.Notifications.blockBackgroundColor
headerTitleLabel.font = WPStyleGuide.Notifications.headerTitleBoldFont
headerTitleLabel.textColor = WPStyleGuide.Notifications.headerTitleColor
headerDetailsLabel.font = WPStyleGuide.Notifications.headerDetailsRegularFont
headerDetailsLabel.textColor = WPStyleGuide.Notifications.headerDetailsColor
gravatarImageView.image = WPStyleGuide.Notifications.gravatarPlaceholderImage!
// iPad: Use a bigger image size!
if UIDevice.isPad() {
gravatarImageView.updateConstraint(.Height, constant: gravatarImageSizePad.width)
gravatarImageView.updateConstraint(.Width, constant: gravatarImageSizePad.height)
}
}
// MARK: - Overriden Methods
public override func refreshSeparators() {
separatorsView.bottomVisible = true
separatorsView.bottomInsets = UIEdgeInsetsZero
}
// MARK: - Private
private let gravatarImageSizePad: CGSize = CGSize(width: 36.0, height: 36.0)
private var gravatarURL: NSURL?
// MARK: - IBOutlets
@IBOutlet private weak var gravatarImageView: UIImageView!
@IBOutlet private weak var headerTitleLabel: UILabel!
@IBOutlet private weak var headerDetailsLabel: UILabel!
}
|
292179729ba4c07fd815dc83a20e459d
| 32.804598 | 112 | 0.629038 | false | false | false | false |
Snowgan/WeiboDemo
|
refs/heads/master
|
WeiboDemo/XLCommonFile.swift
|
mit
|
1
|
//
// XLCommonFile.swift
// WeiboDemo
//
// Created by Jennifer on 29/11/15.
// Copyright © 2015 Snowgan. All rights reserved.
//
import Foundation
// UI
let windowFrame = UIScreen.mainScreen().bounds
let themeColor = UIColor(red: 254/255.0, green: 129/255.0, blue: 0, alpha: 1.0)
let bgColor = UIColor(red: 246.0/255.0, green: 246.0/255.0, blue: 246.0/255.0, alpha: 1.0)
let actionTextColor = UIColor(red: 127.0/255.0, green: 127.0/255.0, blue: 127.0/255.0, alpha: 1.0)
let retweetColor = UIColor(red: 243.0/255.0, green: 243.0/255.0, blue: 243.0/255.0, alpha: 1.0)
let linkColor = UIColor(red: 68.0/255.0, green: 102.0/255.0, blue: 153.0/255.0, alpha: 1.0)
let linkShadowColor = UIColor(red: 176.0/255.0, green: 213.0/255.0, blue: 250.0/255.0, alpha: 1.0)
let windowCenterX = windowFrame.width / 2.0
let kWeiboCellMargin: CGFloat = 10.0
let kWeiboCellInset: CGFloat = 5.0
let bodyFont = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)
let subHeadFont = UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
let homePicWH: CGFloat = 76
let homePicInset: CGFloat = 3.0
// Table View
let kXLHomeCellIdentifier = "homeTableCell"
// Weibo API data
let kAppKey = "2790170142"
// Notification
let WBTokenDidSetNotification = "WBTokenDidSet"
// MARK: - Globle Functions
func delay(seconds seconds: NSTimeInterval, completion: ()->()) {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * seconds))
dispatch_after(delayTime, dispatch_get_main_queue()) {
completion()
}
}
|
50792edccd1dc8fb1a73cd0c2b52dd4a
| 33.222222 | 98 | 0.716234 | false | false | false | false |
pencildrummer/PDFDrumKit
|
refs/heads/master
|
PDFDrumKit/Classes/PDFDocument.swift
|
mit
|
1
|
//
// PDFDocument.swift
// Pods
//
// Created by Fabio Borella on 18/01/17.
//
//
import Foundation
import UIKit
open class PDFDocument {
open var title: String?
fileprivate var _filename: String!
open var filename: String?
open var author: String?
open var pagesHeader: PDFHeader?
open var pagesFooter: PDFFooter?
open var defaultPageSize: PDFPageSize?
open var defaultPageMargins: UIEdgeInsets?
open fileprivate(set) var pdfPath: String?
open fileprivate(set) var pages: [PDFPage] = []
public init() {
}
open var pdfMetadata: [String: Any] {
var metadata: [String: Any] = [
kCGPDFContextCreator as String : "\(kPDFDrumKitDisplayName) v.\(kPDFDrumKitVersion) - \(kPDFDrumKitInfo)"
]
if let title = title {
metadata[kCGPDFContextTitle as String] = title
} else if let _filename = _filename {
metadata[kCGPDFContextTitle as String] = NSString(string: _filename).deletingPathExtension
}
if let author = author {
metadata[kCGPDFContextAuthor as String] = author
}
return metadata
}
open func addPage(_ page: PDFPage) {
if page.pageSize == nil {
page.pageSize = defaultPageSize
}
if page.margins == nil {
page.margins = defaultPageMargins
}
pages.append(page)
}
open func generate(inDirectory: String? = nil) {
if let filename = filename {
_filename = filename
} else {
_filename = String("PDFBuilder_\(ProcessInfo.processInfo.globallyUniqueString).pdf")
}
// Sanitize the pdf filename
_filename = _filename.sanitizedPDFFilenameString
// Define storage path
var storageDirectory: String
if let inDirectory = inDirectory {
storageDirectory = inDirectory
} else {
storageDirectory = NSTemporaryDirectory()
}
let storagePath = NSString(string: storageDirectory).appendingPathComponent(_filename)
pdfPath = storagePath
// Define PDF context
var pagesSize = CGRect.zero
if let defaultPageSize = defaultPageSize {
pagesSize = CGRect(origin: CGPoint.zero,
size: defaultPageSize.size)
}
UIGraphicsBeginPDFContextToFile(storagePath, pagesSize, pdfMetadata)
// Perform draw pages
for page in pages {
if page.pageHeader == nil {
page.pageHeader = pagesHeader
}
if page.pageFooter == nil {
page.pageFooter = pagesFooter
}
do {
try page.draw()
} catch let error as PDFError {
print(error.localizedDescription)
} catch {
print("Unknown error")
}
}
UIGraphicsEndPDFContext()
}
}
|
d3c095e53499a64e3ca1ea59d74cad83
| 26.438596 | 117 | 0.552749 | false | false | false | false |
soffes/clock-saver
|
refs/heads/master
|
Clock/Classes/BN0032.swift
|
mit
|
1
|
import AppKit
final class BN0032: ClockView {
// MARK: - Types
enum Style: String, ClockStyle {
case bkbkg = "BKBKG"
case whbkg = "WHBKG"
var description: String {
switch self {
case .bkbkg:
return "Black"
case .whbkg:
return "White"
}
}
var backgroundColor: NSColor {
return Color.darkBackground
}
var faceColor: NSColor {
switch self {
case .bkbkg:
return backgroundColor
case .whbkg:
return NSColor(white: 0.996, alpha: 1)
}
}
var hourColor: NSColor {
switch self {
case .bkbkg:
return NSColor(white: 0.7, alpha: 1)
case .whbkg:
return NSColor(white: 0.3, alpha: 1)
}
}
var minuteColor: NSColor {
switch self {
case .bkbkg:
return Color.white
case .whbkg:
return Color.black
}
}
var secondColor: NSColor {
return Color.yellow
}
var logoColor: NSColor {
return minuteColor
}
static var `default`: ClockStyle {
return Style.bkbkg
}
static var all: [ClockStyle] {
return [Style.bkbkg, Style.whbkg]
}
}
// MARK: - ClockView
override class var modelName: String {
return "BN0032"
}
override var styleName: String {
set {
style = Style(rawValue: newValue) ?? Style.default
}
get {
return style.description
}
}
override class var styles: [ClockStyle] {
return Style.all
}
override func initialize() {
super.initialize()
style = Style.default
}
override func draw(day: Int) {
let dateArrowColor = Color.red
let dateBackgroundColor = NSColor(srgbRed: 0.894, green: 0.933, blue: 0.965, alpha: 1)
let clockWidth = clockFrame.size.width
let dateWidth = clockWidth * 0.057416268
let dateFrame = CGRect(
x: clockFrame.origin.x + ((clockWidth - dateWidth) / 2.0),
y: clockFrame.origin.y + (clockWidth * 0.199362041),
width: dateWidth,
height: clockWidth * 0.071770335
)
dateBackgroundColor.setFill()
NSBezierPath.fill(dateFrame)
style.minuteColor.setFill()
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = .center
let string = NSAttributedString(string: "\(day)", attributes: [
.font: NSFont(name: "HelveticaNeue-Light", size: clockWidth * 0.044657098)!,
.kern: -1,
.paragraphStyle: paragraph
])
var stringFrame = dateFrame
stringFrame.origin.y -= dateFrame.size.height * 0.12
string.draw(in: stringFrame)
dateArrowColor.setFill()
let y = dateFrame.maxY + (clockWidth * 0.015948963)
let height = clockWidth * 0.022328549
let pointDip = clockWidth * 0.009569378
let path = NSBezierPath()
path.move(to: CGPoint(x: dateFrame.minX, y: y))
path.line(to: CGPoint(x: dateFrame.minX, y: y - height))
path.line(to: CGPoint(x: dateFrame.midX, y: y - height - pointDip))
path.line(to: CGPoint(x: dateFrame.maxX, y: y - height))
path.line(to: CGPoint(x: dateFrame.maxX, y: y))
path.line(to: CGPoint(x: dateFrame.midX, y: y - pointDip))
path.fill()
}
}
|
71a057021fe00790f61783208ced340c
| 20.29927 | 88 | 0.665524 | false | false | false | false |
manfengjun/KYMart
|
refs/heads/master
|
Section/Order/View/KYOrderListFootView.swift
|
mit
|
1
|
//
// KYOrderListFootView.swift
// KYMart
//
// Created by JUN on 2017/7/10.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import PopupDialog
class KYOrderListFootView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var amountL: UILabel!
var buttonArray:[KYOrderButton] = []
var model:KYOrderListModel?{
didSet {
if let text = model?.order_amount {
if let array = model?.goods_list {
let attributedStr = NSMutableAttributedString(string: "共\(array.count)件商品应付:")
attributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName:UIColor.hexStringColor(hex: "#666666")], range: NSRange(location: 0, length: attributedStr.length))
let amountStr = NSMutableAttributedString(string: "¥\(text)")
amountStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 14),NSForegroundColorAttributeName:BAR_TINTCOLOR], range: NSRange(location: 0, length: amountStr.length))
attributedStr.append(amountStr)
amountL.attributedText = attributedStr
}
}
if let text = model?.pay_btn {
if text == 1 {
let button = KYOrderButton(frame: CGRect(x: 0, y: 0, width: 80, height: 25))
button.title = "立即付款"
button.bgColor = BAR_TINTCOLOR
button.borderColor = BAR_TINTCOLOR
button.textColor = UIColor.white
button.selectResult({ (sender) in
if let viewController = self.getCurrentController() {
KYOrderMenuUtil.payOrder(order_id: (self.model?.order_sn)!, order_money: (self.model?.order_amount)!, target: viewController)
}
})
buttonArray.append(button)
}
}
if let text = model?.cancel_btn {
if text == 1 {
let button = KYOrderButton(frame: CGRect(x: 0, y: 0, width: 80, height: 25))
button.title = "取消订单"
button.selectResult({ (sender) in
KYOrderMenuUtil.delOrder(order_id: (self.model?.order_id)!, completion: { (isSuccess) in
if isSuccess {
NotificationCenter.default.post(name:OrderListRefreshNotification, object: nil)
}
else
{
}
})
})
buttonArray.append(button)
}
}
if let text = model?.receive_btn {
if text == 1 {
let button = KYOrderButton(frame: CGRect(x: 0, y: 0, width: 80, height: 25))
button.title = "确认收货"
button.selectResult({ (sender) in
let title = "提示"
let message = "是否确认收货"
let popup = PopupDialog(title: title, message: message, image: nil)
let buttonOne = CancelButton(title: "取消") {
}
let buttonTwo = DefaultButton(title: "确定") {
KYOrderMenuUtil.confirmOrder(order_id: (self.model?.order_id)!, completion: { (isSuccess) in
if isSuccess {
NotificationCenter.default.post(name:OrderListRefreshNotification, object: nil)
}
else
{
}
})
}
popup.addButtons([buttonOne, buttonTwo])
self.getCurrentController()?.present(popup, animated: true, completion: nil)
})
buttonArray.append(button)
}
}
if let text = model?.shipping_btn {
if text == 1 {
// let button = KYOrderButton(frame: CGRect(x: 0, y: 0, width: 80, height: 25))
// button.title = "查看物流"
// buttonArray.append(button)
}
}
if let text = model?.return_btn {
if text == 1 {
// let button = KYOrderButton(frame: CGRect(x: 0, y: 0, width: 80, height: 25))
// button.title = "申请退货"
// button.selectResult({ (sender) in
// print("sdff");
// })
// buttonArray.append(button)
}
}
for (index,item) in buttonArray.enumerated() {
item.frame = CGRect(x: SCREEN_WIDTH - 15 - CGFloat(80*(index + 1)) - CGFloat(10*index), y: 51 + 12.5, width: 80, height: 25)
self.addSubview(item)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView = Bundle.main.loadNibNamed("KYOrderListFootView", owner: self, options: nil)?.first as! UIView
contentView.frame = self.bounds
addSubview(contentView)
awakeFromNib()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// self.addSubview(tagsView)
}
}
|
708c7bd3f1db543f858afcbdba836ac1
| 41.277372 | 229 | 0.471167 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/LazyScrollView/LazyScrollView/LazyScrollView/LazyScrollView.swift
|
mit
|
1
|
//
// LazyScrollView.swift
// LazyScrollView
//
// Created by 伯驹 黄 on 2016/12/9.
// Copyright © 2016年 伯驹 黄. All rights reserved.
//
protocol LazyScrollViewDataSource: class {
/// ScrollView一共展示多少个item
func numberOfItems(in scrollView: LazyScrollView) -> Int
/// 要求根据index直接返回RectModel
func scrollView(_ scrollView: LazyScrollView, rectModelAt index: Int) -> RectModel
/// 返回下标所对应的view
func scrollView(_ scrollView: LazyScrollView, itemBy lazyID: String) -> UIView
}
protocol LazyScrollViewDelegate: class {
func scrollView(_ scrollView: LazyScrollView, didSelectItemAt index: String)
}
class LazyScrollView: UIScrollView {
weak var dataSource: LazyScrollViewDataSource? {
didSet {
if dataSource != nil {
reloadData()
}
}
}
weak var lazyDelegate: LazyScrollViewDelegate?
/// 重用池
private lazy var reuseViews: [String: Set<UIView>] = [:]
/// 当前屏幕已经显示的Views
private lazy var visibleViews: [UIView] = []
/// 所有的View的RectModel
private lazy var allModels: [RectModel] = []
private var numberOfItems = 0
/// 注册的View的Classes类型
private lazy var registerClass: [String: UIView.Type] = [:]
private let kBufferSize: CGFloat = 20
override func layoutSubviews() {
super.layoutSubviews()
let newVisibleViews = visiableViewModels
let newVisiblelazyIDs = newVisibleViews.compactMap { $0.lazyID }
var removeViews: [UIView] = []
for view in visibleViews {
if !newVisiblelazyIDs.contains(view.lazyID ?? "") {
removeViews.append(view)
}
}
for view in removeViews {
visibleViews.remove(view)
enqueueReusableView(view)
view.removeFromSuperview()
}
let alreadyVisibles = visibleViews.compactMap { $0.lazyID }
for model in newVisibleViews {
if alreadyVisibles.contains(model.lazyID) {
continue
}
let view = dataSource!.scrollView(self, itemBy: model.lazyID)
view.frame = model.absRect
view.lazyID = model.lazyID
visibleViews.append(view)
addSubview(view)
}
}
func reloadData() {
subviews.forEach { $0.removeFromSuperview() }
visibleViews.removeAll()
updateAllRects()
}
func enqueueReusableView(_ view: UIView) {
guard let identifier = view.reuseIdentifier else { return }
var reuseSet = self.reuseViews[identifier]
if reuseSet == nil {
reuseSet = Set<UIView>()
reuseViews[identifier] = reuseSet
}
reuseSet?.insert(view)
}
func dequeueReusableItem(with identifier: String) -> UIView {
var reuseSet = reuseViews[identifier]
if let view = reuseSet?.first {
_ = reuseSet?.remove(view)
return view
} else {
let viewClass = registerClass[identifier]
let view = viewClass?.init()
view?.reuseIdentifier = identifier
view?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapItem)))
view?.isUserInteractionEnabled = true
return view!
}
}
func register(viewClass: UIView.Type, forViewReuse identifier: String) {
registerClass[identifier] = viewClass
}
var minEdgeOffset: CGFloat {
return max(contentOffset.y - kBufferSize, 0)
}
var maxEdgeOffset: CGFloat {
let max = contentOffset.y + bounds.height
return min(max + kBufferSize, contentSize.height)
}
func findSet(with minEdge: CGFloat) -> Set<RectModel> {
let ascendingEdgeArray = allModels.sorted { $0.absRect.maxY > $1.absRect.maxY }
var minIndex = 0
var maxIndex = ascendingEdgeArray.count - 1
var midIndex = (minIndex + maxIndex) / 2
var model = ascendingEdgeArray[midIndex]
while minIndex < maxIndex - 1 {
if model.absRect.minY > CGFloat(minEdge) {
maxIndex = midIndex
} else {
minIndex = midIndex
}
midIndex = (minIndex + maxIndex) / 2
model = ascendingEdgeArray[midIndex]
}
midIndex = max(midIndex - 1, 0)
let array = ascendingEdgeArray[midIndex..<ascendingEdgeArray.count]
return Set(array)
}
func findSet(withMaxEdge maxEdge: CGFloat) -> Set<RectModel> {
let descendingEdgeArray = allModels.sorted { $0.absRect.maxY < $1.absRect.maxY }
var minIndex = 0
var maxIndex = descendingEdgeArray.count - 1
var midIndex = (minIndex + maxIndex) / 2
var model = descendingEdgeArray[midIndex]
while minIndex < maxIndex - 1 {
if model.absRect.maxY < CGFloat(maxEdge) {
maxIndex = midIndex
} else {
minIndex = midIndex
}
midIndex = (minIndex + maxIndex) / 2
model = descendingEdgeArray[midIndex]
}
midIndex = max(midIndex - 1, 0)
let array = descendingEdgeArray[midIndex..<descendingEdgeArray.count]
return Set(array)
}
var visiableViewModels: [RectModel] {
let ascendSet = findSet(with: minEdgeOffset)
let descendSet = findSet(withMaxEdge: maxEdgeOffset)
return Array(ascendSet.union(descendSet))
}
func updateAllRects() {
allModels.removeAll(keepingCapacity: true)
numberOfItems = dataSource!.numberOfItems(in: self)
for i in 0..<numberOfItems {
if let model = dataSource?.scrollView(self, rectModelAt: i) {
allModels.append(model)
}
}
let model = allModels.last
contentSize = CGSize(width: bounds.width, height: model?.absRect.maxY ?? 0)
}
/// 获取所有的RectModel
func allModelCount() {
allModels.removeAll(keepingCapacity: true)
let count = dataSource!.numberOfItems(in: self)
for i in 0..<count {
let model = dataSource!.scrollView(self, rectModelAt: i)
allModels.append(model)
}
if let model = allModels.last {
let absRect = model.absRect
contentSize = CGSize(width: bounds.width, height: absRect.minY + model.absRect.height + 15)
}
}
@objc func tapItem(sender: UITapGestureRecognizer) {
if let view = sender.view {
lazyDelegate?.scrollView(self, didSelectItemAt: view.lazyID!)
}
}
}
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(_ object: Element) {
if let index = firstIndex(of: object) {
remove(at: index)
}
}
}
|
970c8d478bee2d26e03f5fb129155666
| 29.541485 | 104 | 0.593509 | false | false | false | false |
Eonil/Editor
|
refs/heads/develop
|
Editor4/WorkspaceDatabaseState.swift
|
mit
|
1
|
//
// RepositoryState.swift
// Editor4
//
// Created by Hoon H. on 2016/05/14.
// Copyright © 2016 Eonil. All rights reserved.
//
import Foundation.NSURL
import EonilToolbox
////////////////////////////////////////////////////////////////
enum IssueState {
case ProjectConfigurationError
case ProjectConfigurationWarning
case CompileWarning
case CompileError
}
struct BreakpointState {
}
/// Logs for one build session.
struct BuildLogState {
private(set) var logs = [String]()
}
////////////////////////////////////////////////////////////////
struct DebuggingState {
private(set) var processes = [DebuggingProcessState]()
private(set) var threads = [DebuggingThreadState]()
private(set) var stackFrames = [DebuggingStackFrameState]()
private(set) var slotValues = [DebuggingSlotValueState]()
}
//enum DebuggingProcessPhase {
// case NotLaunchedYet
// case Running
// case Paused
// case Exited
//}
struct DebuggingProcessState {
private(set) var name: String
private(set) var phase: String
}
struct DebuggingThreadState {
private(set) var name: String?
}
struct DebuggingStackFrameState {
private(set) var name: String?
}
struct DebuggingSlotValueState {
private(set) var name: String?
private(set) var value: String?
}
|
281499021ee6bf1068c72883e3e3de1d
| 15.426829 | 64 | 0.62435 | false | false | false | false |
rmalabuyoc/treehouse-tracks
|
refs/heads/master
|
ios-development-with-swift/Object-Oriented-Exam.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
class Shape
{
let sides: Double
let name: String
init(sides: Double, name: String)
{
self.sides = sides
self.name = name
}
}
class Square: Shape
{
var sideLength: Double
var area: Double {
get {
return sideLength * sideLength
}
set {
sideLength = sqrt(newValue)
}
}
init(sides: Double, name: String, sideLength: Double)
{
self.sideLength = sideLength
super.init(sides: sides, name: name)
}
convenience init(sideLength: Double)
{
self.init(sides: 4, name: "Square", sideLength: sideLength)
}
}
var cube = Square(sideLength: 20)
cube.sideLength
cube.area
|
121e36361631d26dae7f8384aec02b24
| 17.372093 | 67 | 0.573418 | false | false | false | false |
ElijahButers/Swift
|
refs/heads/master
|
CoreAnimationSample3/CoreAnimationSample3/ViewController.swift
|
gpl-3.0
|
27
|
//
// ViewController.swift
// CoreAnimationSample3
//
// Created by Carlos Butron on 02/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// 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 UIKit
class ViewController: UIViewController {
var position = true
@IBOutlet weak var image: UIImageView!
@IBAction func animate(sender: UIButton) {
if (position){ //SAMPLE2
var animation:CABasicAnimation! = CABasicAnimation(keyPath:"position")
animation.toValue = NSValue(CGPoint:CGPointMake(160, 200))
//SAMPLE2
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
var resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size")
resizeAnimation.toValue = NSValue(CGSize:CGSizeMake(240, 60))
//SAMPLE2
resizeAnimation.fillMode = kCAFillModeForwards
resizeAnimation.removedOnCompletion = false
//SAMPLE3
UIView.animateWithDuration(5.0, animations:{
//PROPERTIES CHANGES TO ANIMATE
self.image.alpha = 0.0
//alpha to zero in 5 seconds
}, completion: {(value: Bool) in
//when finished animation do this..
self.image.alpha = 1.0
self.image.layer.addAnimation(animation, forKey: "position")
self.image.layer.addAnimation(resizeAnimation, forKey: "bounds.size")
})
position = false
}
else{
var animation:CABasicAnimation! = CABasicAnimation(keyPath:"position")
animation.fromValue = NSValue(CGPoint:CGPointMake(160, 200))
//SAMPLE2
animation.fillMode = kCAFillModeForwards
animation.removedOnCompletion = false
var resizeAnimation:CABasicAnimation = CABasicAnimation(keyPath:"bounds.size")
resizeAnimation.fromValue = NSValue(CGSize:CGSizeMake(240, 60))
//SAMPLE2
resizeAnimation.fillMode = kCAFillModeForwards
resizeAnimation.removedOnCompletion = false
image.layer.addAnimation(animation, forKey: "position")
image.layer.addAnimation(resizeAnimation, forKey: "bounds.size")
position = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
7b8a8b874952b168b6de5ae0e40f8f3c
| 32.324324 | 121 | 0.572587 | false | false | false | false |
AppLovin/iOS-SDK-Demo
|
refs/heads/master
|
Swift Demo App/iOS-SDK-Demo/ALDemoInterstitialZoneViewController.swift
|
mit
|
1
|
//
// ALDemoInterstitialZoneViewController.swift
// iOS-SDK-Demo-Swift
//
// Created by Suyash Saxena on 6/19/18.
// Copyright © 2018 AppLovin. All rights reserved.
//
import UIKit
class ALDemoInterstitialZoneViewController : ALDemoBaseViewController
{
@IBOutlet weak var showButton: UIBarButtonItem!
var ad: ALAd?
@IBAction func loadInterstitial(_ sender: AnyObject!)
{
log("Interstitial loading...")
ALSdk.shared()?.adService.loadNextAd(forZoneIdentifier: "YOUR_ZONE_ID", andNotify: self)
}
@IBAction func showInterstitial(_ sender: AnyObject!)
{
if let ad = self.ad
{
// Optional: Assign delegates
ALInterstitialAd.shared().adDisplayDelegate = self
ALInterstitialAd.shared().adVideoPlaybackDelegate = self
ALInterstitialAd.shared().show(ad)
log("Interstitial Shown");
}
}
}
extension ALDemoInterstitialZoneViewController : ALAdLoadDelegate
{
func adService(_ adService: ALAdService, didLoad ad: ALAd)
{
log("Interstitial Loaded")
self.ad = ad
self.showButton.isEnabled = true
}
func adService(_ adService: ALAdService, didFailToLoadAdWithError code: Int32)
{
// Look at ALErrorCodes.h for list of error codes
log("Interstitial failed to load with error code \(code)")
}
}
extension ALDemoInterstitialZoneViewController : ALAdDisplayDelegate
{
func ad(_ ad: ALAd, wasDisplayedIn view: UIView)
{
log("Interstitial Displayed")
}
func ad(_ ad: ALAd, wasHiddenIn view: UIView)
{
log("Interstitial Dismissed")
}
func ad(_ ad: ALAd, wasClickedIn view: UIView)
{
log("Interstitial Clicked")
}
}
extension ALDemoInterstitialZoneViewController : ALAdVideoPlaybackDelegate
{
func videoPlaybackBegan(in ad: ALAd)
{
log("Video Started")
}
func videoPlaybackEnded(in ad: ALAd, atPlaybackPercent percentPlayed: NSNumber, fullyWatched wasFullyWatched: Bool)
{
log("Video Ended")
}
}
|
be05b956c8f04bc0e855f52362704415
| 24.547619 | 119 | 0.641193 | false | false | false | false |
accepton/accepton-apple
|
refs/heads/master
|
Pod/Vendor/Alamofire/Response.swift
|
mit
|
1
|
// Response.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Used to store all response data returned from a completed `Request`.
struct Response<Value, Error: ErrorType> {
/// The URL request sent to the server.
let request: NSURLRequest?
/// The server's response to the URL request.
let response: NSHTTPURLResponse?
/// The data returned by the server.
let data: NSData?
/// The result of response serialization.
let result: Result<Value, Error>
/**
Initializes the `Response` instance with the specified URL request, URL response, server data and response
serialization result.
- parameter request: The URL request sent to the server.
- parameter response: The server's response to the URL request.
- parameter data: The data returned by the server.
- parameter result: The result of response serialization.
- returns: the new `Response` instance.
*/
init(request: NSURLRequest?, response: NSHTTPURLResponse?, data: NSData?, result: Result<Value, Error>) {
self.request = request
self.response = response
self.data = data
self.result = result
}
}
// MARK: - CustomStringConvertible
extension Response: CustomStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
var description: String {
return result.debugDescription
}
}
// MARK: - CustomDebugStringConvertible
extension Response: CustomDebugStringConvertible {
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the server data and the response serialization result.
var debugDescription: String {
var output: [String] = []
output.append(request != nil ? "[Request]: \(request!)" : "[Request]: nil")
output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil")
output.append("[Data]: \(data?.length ?? 0) bytes")
output.append("[Result]: \(result.debugDescription)")
return output.joinWithSeparator("\n")
}
}
|
e2bf727d0145a174462ab92084ccd83c
| 39.421687 | 119 | 0.701341 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/ForwardPanelModel.swift
|
gpl-2.0
|
1
|
//
// ForwardPanelModel.swift
// Telegram-Mac
//
// Created by keepcoder on 01/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import Postbox
import TelegramCore
class ForwardPanelModel: ChatAccessoryModel {
private let forwardMessages:[Message]
private let hideNames: Bool
init(forwardMessages:[Message], hideNames: Bool, context: AccountContext) {
self.forwardMessages = forwardMessages
self.hideNames = hideNames
super.init(context: context)
self.make()
}
deinit {
}
func make() -> Void {
var names:[String] = []
var used:Set<PeerId> = Set()
var keys:[Int64:Int64] = [:]
var forwardMessages:[Message] = []
for message in self.forwardMessages {
if let groupingKey = message.groupingKey {
if keys[groupingKey] == nil {
keys[groupingKey] = groupingKey
forwardMessages.append(message)
}
} else {
forwardMessages.append(message)
}
}
for message in forwardMessages {
if let author = message.chatPeer(context.peerId) {
if !used.contains(author.id) {
used.insert(author.id)
if author.isChannel {
names.append(author.displayTitle)
} else {
names.append(author.displayTitle)
}
}
}
}
//hideNames ? strings().chatInputForwardHidden : names.joined(separator: ", ")
let text = hideNames ? strings().chatAccessoryHiddenCountable(forwardMessages.count) : strings().chatAccessoryForwardCountable(forwardMessages.count)
self.header = .init(.initialize(string: text, color: theme.colors.accent, font: .medium(.text)), maximumNumberOfLines: 1)
if forwardMessages.count == 1, !forwardMessages[0].text.isEmpty, forwardMessages[0].media.isEmpty {
let messageText = chatListText(account: context.account, for: forwardMessages[0], isPremium: context.isPremium, isReplied: true).mutableCopy() as! NSMutableAttributedString
let author = forwardMessages[0].forwardInfo?.author ?? forwardMessages[0].effectiveAuthor
if author?.id == context.peerId {
messageText.insert(.initialize(string: "\(strings().chatAccessoryForwardYou): ", color: theme.colors.grayText, font: .normal(.text)), at: 0)
} else if let author = author {
messageText.insert(.initialize(string: "\(author.displayTitle): ", color: theme.colors.grayText, font: .normal(.text)), at: 0)
}
self.message = .init(messageText, maximumNumberOfLines: 1)
} else {
let authors = uniquePeers(from: forwardMessages.compactMap { $0.forwardInfo?.author ?? $0.effectiveAuthor })
let messageText = authors.map { $0.compactDisplayTitle }.joined(separator: ", ")
let text = "\(strings().chatAccessoryForwardFrom): \(messageText)"
self.message = .init(.initialize(string: text, color: theme.colors.grayText, font: .normal(.text)), maximumNumberOfLines: 1)
}
nodeReady.set(.single(true))
self.setNeedDisplay()
}
}
|
f1ff9ddd1b9aeadc699fe2df1bd5ca08
| 36.815217 | 184 | 0.589537 | false | false | false | false |
LeoTuring/iOS_Learning
|
refs/heads/master
|
iOS_Learning/Traveler/Traveler/Helper/CalculateTextHelper.swift
|
mit
|
1
|
//
// CalculateTextHelper.swift
// Traveler
//
// Created by 李冬阳 on 2017/6/3.
// Copyright © 2017年 lidongyang. All rights reserved.
//
import UIKit
class CalculateTextHelper: NSObject {
enum TextType: String {
case label = "label"
case textView = "textView"
}
static func heightForText(text: String, width: CGFloat, font: UIFont, textType: TextType) -> CGFloat {
var result: CGFloat = 0
if 0 < text.characters.count {
switch textType {
case .label:
let textLabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: width, height: 999))
textLabel.font = font
textLabel.text = text
textLabel.sizeToFit()
result = textLabel.frame.size.height
case .textView:
let textView = UITextView.init(frame: CGRect.init(x: 0, y: 0, width: width, height: 999))
textView.font = font
textView.text = text
textView.sizeToFit()
result = textView.frame.size.height
}
}
return result
}
}
|
7cccf29cd19abc654b76896ca400e8c5
| 25.102564 | 104 | 0.624754 | false | false | false | false |
swift-lang/swift-k
|
refs/heads/master
|
tests/stress/internals/x_recursion.swift
|
apache-2.0
|
2
|
/*
Linear tail recursion.
Expect linear growth only, so usual loop numbers match
as for earlier scripts.
stats: 1K -> 25s real (i5 8gb)
10K -> (10% ram 8gb in use by java)
Uncaught exception: java.lang.StackOverflowError in vdl:unitstart @ x_recursion.kml, line: 45
java.lang.StackOverflowError
at java.lang.String.valueOf(String.java:2959)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
...
Exception is: java.lang.StackOverflowError
Near Karajan line: vdl:unitstart @ x_recursion.kml, line: 45
Another uncaught exception while handling an uncaught exception.
java.lang.StackOverflowError
at org.globus.cog.karajan.workflow.nodes.FlowNode.failImmediately(FlowNode.java:77)
at org.globus.cog.karajan.workflow.nodes.FlowNode.failed(FlowNode.java:245)
...
The initial exception was
java.lang.StackOverflowError
at java.lang.String.valueOf(String.java:2959)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
at org.globus.cog.karajan.util.ThreadingContext.toString(ThreadingContext.java:87)
100K -> ?
#NIGHTLY 1000 10000
#WEEKLY 1000 10000 100000
*/
int limit = @toint(@arg("loops"));
(int out) sum (int n){
if ( n == 0 ){
out = 0;
}else{
out = n + sum( n-1 );
}
}
int result = sum(limit);
tracef("Sum(%i) = %i \n", limit, result);
|
53bbf0e7c55e3ece3f36f10149c1b654
| 31.311111 | 93 | 0.734343 | false | false | false | false |
ochan1/OC-PublicCode
|
refs/heads/master
|
MakeSchoolNotes-Swift-V2-Starter-swift3-coredata BONUS ROUND/MakeSchoolNotes/Controllers/ListNotesTableViewController.swift
|
mit
|
1
|
//
// ListNotesTableViewController.swift
// MakeSchoolNotes
//
// Created by Chris Orcutt on 1/10/16.
// Copyright © 2016 MakeSchool. All rights reserved.
//
import UIKit
import CoreData
class ListNotesTableViewController: UITableViewController {
var notes = [Note]() {
didSet {
tableView.reloadData()
}
}
var timeArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
notes = CoreDataHelper.retrieveNotes()
/*
timeArray: String = [notes.modificationTime]
timeArray = [time]
timeArray.sort(by:{$0 < $1})
*/
notes.sort(by: {$0.modificationTime!.convertToString() > $1.modificationTime!.convertToString()}) //Multiple periods OK
/*
let sorted = d.sort { lhs,rhs in
let l = lhs.1["start"] as? NSDate
let r = rhs.1["start"] as? NSDate
return l < r
}
//Convert Date to String
// BEST: https://www.youtube.com/watch?v=tQVvRcF7Z7E&t=194s
// https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html
*/
/*
//func orderTime(_ s1: String, _ s2: String) -> Bool {
//return s1 > s2
//let timer: String = cell.noteModificationTimeLabel.text
//let notes.modificationTime;: String = Date() as NSDate
//notes.sorted(by: orderTime)
//notes.sorted { (Date() as NSDate) -> Bool in
// cell.noteModificationTimeLabel.text
//}
*/
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "listNotesTableViewCell", for: indexPath) as! ListNotesTableViewCell
// 1
let row = indexPath.row
// 2
let note = notes[row]
// 3
cell.noteTitleLabel.text = note.title
// 4
cell.noteModificationTimeLabel.text = note.modificationTime?.convertToString()
cell.textDisplay.text = note.content
return cell
}
// 1
/*
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
*/
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
// 2
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}
*/
/*
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// 1
if let identifier = segue.identifier {
// 2
if identifier == "displayNote" {
// 3
print("Transitioning to the Display Note View Controller")
}
}
}
*/
/*
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if identifier == "displayNote" {
print("Table view cell tapped")
} else if identifier == "addNote" {
print("+ button tapped")
}
}
}
*/
@IBAction func unwindToListNotesViewController(_ segue: UIStoryboardSegue) {
self.notes = CoreDataHelper.retrieveNotes()
}
// 1
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
// 2
if editingStyle == .delete {
// 3
//notes.remove(at: indexPath.row)
//1
CoreDataHelper.delete(note: notes[indexPath.row])
//2
notes = CoreDataHelper.retrieveNotes()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
//
if identifier == "cancel" {
print("Cancel button tapped")
} else if identifier == "save" {
print("Save button tapped")
}
//
if identifier == "displayNote" {
print("Table view cell tapped")
// 1
let indexPath = tableView.indexPathForSelectedRow!
// 2
let note = notes[indexPath.row]
// 3
let displayNoteViewController = segue.destination as! DisplayNoteViewController
// 4
displayNoteViewController.note = note
} else if identifier == "addNote" {
print("+ button tapped")
}
}
}
}
|
51e7db8375aa00897166211ef98204d6
| 28.785276 | 136 | 0.546035 | false | false | false | false |
OpenCraft/OCHuds
|
refs/heads/master
|
OCHuds/Classes/MessageBaseHUD.swift
|
mit
|
1
|
//
// MessageBaseHUD.swift
// Pods
//
// Created by Giovane Berny Possebon on 17/08/16.
//
//
import UIKit
enum Status {
case success
case failure
case warning
case regular
}
open class MessageBaseHUD {
fileprivate static var instance: HudView?
fileprivate static var isHiding = false
fileprivate static let animationDuration = 2.0
internal class func customHud(withViewController viewController: UIViewController, status: Status, message: String?, backgroundColor: UIColor, customImage: UIImage?) -> HudView? {
return nil
}
@discardableResult
fileprivate static func show(withStatus status: Status, message: String?, customImage: UIImage? = nil) -> Bool {
if instance != nil {
return false
}
guard let topMostViewController = topMostViewController else {
return false
}
guard let hudView = customHud(withViewController: topMostViewController, status: status, message: message, backgroundColor: UIColor.white, customImage: customImage) else {
return false
}
instance = hudView
instance?.show()
let time = DispatchTime.now() + Double(Int64(animationDuration * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) { _ in
hide()
}
return true
}
open static func showSuccess(withMessage message: String? = "Success") {
show(withStatus: .success, message: message)
}
open static func showFailure(withMessage message: String? = "Failure") {
show(withStatus: .failure, message: message)
}
open static func showWarning(withMessage message: String) {
show(withStatus: .warning, message: message)
}
open static func show(withCustomImage image: UIImage, message: String) {
show(withStatus: .regular, message: message, customImage: image)
}
open static func showMessage(_ message: String) {
show(withStatus: .regular, message: message)
}
@discardableResult
open static func hide() -> Bool {
guard let instance = instance else {
return false
}
guard isHiding == false else {
return false
}
isHiding = true
if Thread.current.isMainThread {
instance.hide()
} else {
DispatchQueue.main.async {
instance.hide()
}
}
isHiding = false
self.instance = nil
return true
}
}
|
6d13c859f22a653257acf904c0d7b287
| 25.97 | 183 | 0.594735 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift
|
refs/heads/master
|
Solutions/Solutions/Medium/Medium_043_Multiply_Strings.swift
|
mit
|
3
|
/*
https://leetcode.com/problems/multiply-strings/
#43 Multiply Strings
Level: medium
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Inspired by @ChiangKaiShrek at https://leetcode.com/discuss/26602/brief-c-solution-using-only-strings-and-without-reversal
*/
import Foundation
private extension String {
subscript (index: Int) -> Character {
return self[self.startIndex.advancedBy(index)]
}
}
struct Medium_043_Multiply_Strings {
static func multiply(num1 num1: String, num2: String) -> String {
var sum = Array<Character>(count: num1.characters.count+num2.characters.count, repeatedValue: "0")
for var i = num1.characters.count - 1; i >= 0; i-- {
var carry = 0
var dict: [Character: Int] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
]
for var j = num2.characters.count - 1; j >= 0; j-- {
let tmp: Int = dict[sum[i + j + 1]]! + dict[num1[i]]! * dict[num2[j]]! + carry;
sum[i + j + 1] = Character("\(tmp % 10)")
carry = tmp / 10;
}
sum[i] = Character("\(dict[sum[i]]! + carry)")
}
for var i = sum.count - 1; i>=0; i-- {
if sum[i] != "0" {
return String(sum[0...i])
}
}
return "0"
}
}
|
e081e9f5a4a51281c577208f1f9b4b0f
| 28.196429 | 122 | 0.496328 | false | false | false | false |
DarlingXIe/WeiBoProject
|
refs/heads/master
|
WeiBo/WeiBo/Classes/View/compose/未命名文件夹 2/XDLComposeToolBar.swift
|
mit
|
1
|
//
// XDLComposeToolBar.swift
// WeiBo
//
// Created by DalinXie on 16/10/1.
// Copyright © 2016年 itcast. All rights reserved.
//
import UIKit
enum composeToolBarButtonType: Int {
case picture = 0, mention, trend, emotion, add
}
class XDLComposeToolBar: UIView {
//MARK: - define closure
var clickbuttonclosure: ( (_ toolBar: XDLComposeToolBar,_ type:composeToolBarButtonType) ->())?
override init(frame:CGRect)
{
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "compose_toolbar_background"))
addSubview(stackView)
stackView.snp_makeConstraints { (make) in
make.edges.equalTo(self)
}
addChildButtons(imageName: "compose_toolbar_picture",type: .picture)
addChildButtons(imageName: "compose_mentionbutton_background", type: .mention)
addChildButtons(imageName: "compose_trendbutton_background", type: .trend)
addChildButtons(imageName: "compose_emoticonbutton_background", type: .emotion)
addChildButtons(imageName: "compose_add_background", type: .add)
}
private func addChildButtons(imageName: String, type: composeToolBarButtonType){
let button = UIButton()
button.tag = type.rawValue
button.setImage(UIImage(named:imageName), for: .normal)
button.setImage(UIImage(named:"\(imageName)_highlighted"), for: .highlighted)
//MARK: -
button.addTarget(self, action: #selector(clickButton(button:)), for: .touchUpInside)
stackView.addArrangedSubview(button)
}
private lazy var stackView :UIStackView = {()-> UIStackView in
let stackView = UIStackView()
stackView.distribution = .fillEqually
return stackView
}()
@objc private func clickButton(button: UIButton){
let type = composeToolBarButtonType(rawValue: button.tag)!
clickbuttonclosure?(self, type)
}
}
|
f236073c264905557bd1e4babd668298
| 28.573333 | 106 | 0.639766 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK
|
refs/heads/master
|
BridgeAppSDKTests/SBAConsentTests.swift
|
bsd-3-clause
|
1
|
//
// SBAConsentDocumentFactoryTests.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
import BridgeAppSDK
class SBAConsentDocumentFactoryTests: ResourceTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testBuildConsentFactory() {
guard let consentFactory = createConsentFactory() else { return }
XCTAssertNotNil(consentFactory.steps)
guard let steps = consentFactory.steps else { return }
let expectedSteps: [ORKStep] = [SBAInstructionStep(identifier: "reconsentIntroduction"),
ORKVisualConsentStep(identifier: "consentVisual"),
SBANavigationSubtaskStep(identifier: "consentQuiz"),
SBAInstructionStep(identifier: "consentFailedQuiz"),
SBAInstructionStep(identifier: "consentPassedQuiz"),
SBAConsentSharingStep(identifier: "consentSharingOptions"),
SBAConsentReviewStep(identifier: "consentReview"),
SBAInstructionStep(identifier: "consentCompletion")]
XCTAssertEqual(steps.count, expectedSteps.count)
for (idx, expectedStep) in expectedSteps.enumerated() {
if idx < steps.count {
XCTAssertEqual(steps[idx].identifier, expectedStep.identifier)
let stepClass = NSStringFromClass(steps[idx].classForCoder)
let expectedStepClass = NSStringFromClass(expectedStep.classForCoder)
XCTAssertEqual(stepClass, expectedStepClass)
}
}
if (steps.count < expectedSteps.count) { return }
}
func testReconsentSteps() {
guard let consentFactory = createConsentFactory() else { return }
let steps = (consentFactory.reconsentStep().subtask as! SBANavigableOrderedTask).steps
let expectedSteps: [ORKStep] = [SBAInstructionStep(identifier: "reconsentIntroduction"),
ORKVisualConsentStep(identifier: "consentVisual"),
SBANavigationSubtaskStep(identifier: "consentQuiz"),
SBAInstructionStep(identifier: "consentFailedQuiz"),
SBAInstructionStep(identifier: "consentPassedQuiz"),
SBAConsentSharingStep(identifier: "consentSharingOptions"),
SBAConsentReviewStep(identifier: "consentReview"),
SBAInstructionStep(identifier: "consentCompletion")]
XCTAssertEqual(steps.count, expectedSteps.count)
for (idx, expectedStep) in expectedSteps.enumerated() {
if idx < steps.count {
XCTAssertEqual(steps[idx].identifier, expectedStep.identifier)
let stepClass = NSStringFromClass(steps[idx].classForCoder)
let expectedStepClass = NSStringFromClass(expectedStep.classForCoder)
XCTAssertEqual(stepClass, expectedStepClass)
}
}
if (steps.count < expectedSteps.count) { return }
}
func testRegistrationSteps() {
guard let consentFactory = createConsentFactory() else { return }
let steps = (consentFactory.registrationConsentStep().subtask as! SBANavigableOrderedTask).steps
let expectedSteps: [ORKStep] = [ORKVisualConsentStep(identifier: "consentVisual"),
SBANavigationSubtaskStep(identifier: "consentQuiz"),
SBAInstructionStep(identifier: "consentFailedQuiz"),
SBAInstructionStep(identifier: "consentPassedQuiz"),
SBAConsentSharingStep(identifier: "consentSharingOptions"),
SBAConsentReviewStep(identifier: "consentReview"),
SBAInstructionStep(identifier: "consentCompletion")]
XCTAssertEqual(steps.count, expectedSteps.count)
for (idx, expectedStep) in expectedSteps.enumerated() {
if idx < steps.count {
XCTAssertEqual(steps[idx].identifier, expectedStep.identifier)
let stepClass = NSStringFromClass(steps[idx].classForCoder)
let expectedStepClass = NSStringFromClass(expectedStep.classForCoder)
XCTAssertEqual(stepClass, expectedStepClass)
}
}
if (steps.count < expectedSteps.count) { return }
}
func testConsentReview_Default() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview"
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step)
XCTAssertNotNil(nameStep)
XCTAssertNotNil(signatureStep)
guard reviewStep != nil && nameStep != nil && signatureStep != nil else { return }
XCTAssertNotNil(reviewStep!.reasonForConsent)
XCTAssertNotNil(nameStep!.formItems)
let expected: [String: String] = [ "name" : "ORKTextAnswerFormat"]
for (identifier, expectedClassName) in expected {
let formItem = nameStep!.formItemForIdentifier(identifier)
XCTAssertNotNil(formItem)
if let classForCoder = formItem?.answerFormat?.classForCoder {
let className = NSStringFromClass(classForCoder)
XCTAssertEqual(className, expectedClassName)
}
}
}
func testConsentReview_NameAndBirthdate() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"items" : ["name", "birthdate"]
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step)
XCTAssertNotNil(nameStep)
XCTAssertNotNil(signatureStep)
guard reviewStep != nil && nameStep != nil && signatureStep != nil else { return }
XCTAssertNotNil(reviewStep!.reasonForConsent)
XCTAssertNotNil(nameStep!.formItems)
let expected: [String: String] = [ "name" : "ORKTextAnswerFormat",
"birthdate" : "ORKDateAnswerFormat"
]
for (identifier, expectedClassName) in expected {
let formItem = nameStep!.formItemForIdentifier(identifier)
XCTAssertNotNil(formItem)
if let classForCoder = formItem?.answerFormat?.classForCoder {
let className = NSStringFromClass(classForCoder)
XCTAssertEqual(className, expectedClassName)
}
}
}
func testConsentReview_RequiresSignature_YES() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"requiresSignature" : true
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step)
XCTAssertNotNil(nameStep)
XCTAssertNotNil(signatureStep)
guard reviewStep != nil && nameStep != nil && signatureStep != nil else { return }
XCTAssertNotNil(reviewStep!.reasonForConsent)
XCTAssertNotNil(nameStep!.formItems)
let expected: [String: String] = [ "name" : "ORKTextAnswerFormat"]
for (identifier, expectedClassName) in expected {
let formItem = nameStep!.formItemForIdentifier(identifier)
XCTAssertNotNil(formItem)
if let classForCoder = formItem?.answerFormat?.classForCoder {
let className = NSStringFromClass(classForCoder)
XCTAssertEqual(className, expectedClassName)
}
}
}
func testConsentReview_RequiresSignature_NO() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"requiresSignature" : false
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, nameStep, signatureStep) = consentReviewSteps(step)
XCTAssertNotNil(reviewStep?.reasonForConsent)
XCTAssertNil(nameStep)
XCTAssertNil(signatureStep)
}
func testConsentResult_RequiresSignatureAndConsented() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"items" : ["name", "birthdate"]
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, _, _) = consentReviewSteps(step)
guard reviewStep != nil else { return }
let reviewResult = ORKConsentSignatureResult(identifier: "review.consent")
reviewResult.consented = true
reviewResult.signature = reviewStep!.signature
let nameResult = ORKTextQuestionResult(identifier: "name.name")
nameResult.textAnswer = "John Jones"
let birthResult = ORKDateQuestionResult(identifier: "name.birthdate")
birthResult.dateAnswer = Date(timeIntervalSince1970: 0)
let signatureResult = ORKSignatureResult(identifier: "signature.signature")
signatureResult.signatureImage = UIImage()
let inputResult = ORKStepResult(stepIdentifier: step!.identifier, results: [reviewResult, nameResult, birthResult, signatureResult])
let viewController = step?.instantiateStepViewController(with: inputResult)
let outputResult = viewController?.result
XCTAssertNotNil(outputResult)
guard let consentResult = outputResult?.result(forIdentifier: step!.identifier) as? SBAConsentReviewResult else {
XCTAssert(false, "\(outputResult) missing consent review result")
return
}
XCTAssertTrue(consentResult.isConsented)
XCTAssertNotNil(consentResult.consentSignature)
XCTAssertNotNil(consentResult.consentSignature?.signatureImage)
XCTAssertNotNil(consentResult.consentSignature?.signatureName)
XCTAssertNotNil(consentResult.consentSignature?.signatureDate)
XCTAssertNotNil(consentResult.consentSignature?.signatureBirthdate)
}
func testConsentResult_RequiresNoSignature() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"requiresSignature" : false
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, _, _) = consentReviewSteps(step)
guard reviewStep != nil else { return }
let reviewResult = ORKConsentSignatureResult(identifier: "review.consent")
reviewResult.consented = true
reviewResult.signature = reviewStep!.signature
let inputResult = ORKStepResult(stepIdentifier: step!.identifier, results: [reviewResult])
let viewController = step?.instantiateStepViewController(with: inputResult)
let outputResult = viewController?.result
XCTAssertNotNil(outputResult)
guard let consentResult = outputResult?.result(forIdentifier: step!.identifier) as? SBAConsentReviewResult else {
XCTAssert(false, "\(outputResult) missing consent review result")
return
}
XCTAssertTrue(consentResult.isConsented)
}
func testConsentResult_RequiresNotConsented() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"requiresSignature" : true
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (_, reviewStep, _, _) = consentReviewSteps(step)
guard reviewStep != nil else { return }
let reviewResult = ORKConsentSignatureResult(identifier: "review.consent")
reviewResult.consented = false
reviewResult.signature = reviewStep!.signature
let inputResult = ORKStepResult(stepIdentifier: step!.identifier, results: [reviewResult])
let viewController = step?.instantiateStepViewController(with: inputResult)
let outputResult = viewController?.result
XCTAssertNotNil(outputResult)
guard let consentResult = outputResult?.result(forIdentifier: step!.identifier) as? SBAConsentReviewResult else {
XCTAssert(false, "\(outputResult) missing consent review result")
return
}
XCTAssertFalse(consentResult.isConsented)
}
func testConsentReviewStepAfterStep_NotConsented() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"requiresSignature" : true
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (pageStep, reviewStep, _, _) = consentReviewSteps(step)
guard reviewStep != nil else { return }
let taskResult = consentReviewTaskResult(step!.identifier, consented: false)
let nextStep = pageStep?.stepAfterStep(withIdentifier: reviewStep?.identifier, with: taskResult)
XCTAssertNil(nextStep)
}
func testConsentReviewStepAfterStep_Consented() {
guard let consentFactory = createConsentFactory() else { return }
let inputStep: NSDictionary = [
"identifier" : "consentReview",
"type" : "consentReview",
"requiresSignature" : true
]
let step = consentFactory.createSurveyStepWithDictionary(inputStep)
let (pageStep, reviewStep, _, _) = consentReviewSteps(step)
guard reviewStep != nil else { return }
let taskResult = consentReviewTaskResult(step!.identifier, consented: true)
let nextStep = pageStep?.stepAfterStep(withIdentifier: reviewStep?.identifier, with: taskResult)
XCTAssertNotNil(nextStep)
}
// MARK: helper methods
func consentReviewTaskResult(_ identifier: String, consented: Bool) -> ORKTaskResult {
let reviewResult = ORKConsentSignatureResult(identifier: "consent")
reviewResult.consented = consented
let stepResult = ORKStepResult(stepIdentifier: "review", results: [reviewResult])
let taskResult = ORKTaskResult(identifier: identifier)
taskResult.results = [stepResult]
return taskResult
}
func consentReviewSteps(_ step: ORKStep?) -> (pageStep:SBAConsentReviewStep?, reviewStep: ORKConsentReviewStep?, nameStep: ORKFormStep?, signatureStep: ORKSignatureStep?) {
guard let pageStep = step as? SBAConsentReviewStep else {
XCTAssert(false, "\(step) not of expected type")
return (nil, nil, nil, nil)
}
guard let reviewStep = pageStep.step(withIdentifier: "review") as? ORKConsentReviewStep else {
XCTAssert(false, "\(pageStep.steps) does not include a review step (required)")
return (nil, nil, nil, nil)
}
if let signature = reviewStep.signature {
// Review step should have either a nil signature or not require name/image
XCTAssertFalse(signature.requiresName)
XCTAssertFalse(signature.requiresSignatureImage)
}
let formStep = pageStep.step(withIdentifier: "name") as? ORKFormStep
let signatureStep = pageStep.step(withIdentifier: "signature") as? ORKSignatureStep
return (pageStep, reviewStep, formStep, signatureStep)
}
func createConsentFactory() -> SBAConsentDocumentFactory? {
guard let input = jsonForResource("Consent") else { return nil }
return SBAConsentDocumentFactory(dictionary: input)
}
}
|
534699e49d129f2aaa717bad5cb84fa3
| 45.319048 | 176 | 0.624499 | false | false | false | false |
leizh007/HiPDA
|
refs/heads/master
|
HiPDA/HiPDA/Sections/Message/Friend/FriendMessageViewModel.swift
|
mit
|
1
|
//
// FriendMessageTableViewModel.swift
// HiPDA
//
// Created by leizh007 on 2017/6/28.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import RxSwift
class FriendMessageViewModel: MessageTableViewModel {
var friendMessageModels = [FriendMessageModel]()
override var models: [BaseMessageModel] {
get {
return friendMessageModels
}
set {
friendMessageModels = newValue as? [FriendMessageModel] ?? []
}
}
override func modelTransform(_ html: String) throws -> [BaseMessageModel] {
return try HtmlParser.friendMessages(from: html)
}
override func api(at page: Int) -> HiPDA.API {
return .friendMessage(page: page)
}
override func getDataFromCache(for account: Account) {
friendMessageModels = CacheManager.friendMessage.shared?.messages(for: account) ?? []
page = 1
totalPage = (CacheManager.friendMessage.shared?.object(forKey: totalPageKey(for: account)) as? NSNumber)?.intValue ?? 1
lastUpdateTime = (CacheManager.friendMessage.shared?.object(forKey: lastUpdateTimeKey(for: account)) as? NSNumber)?.doubleValue ?? 0.0
}
override func saveModelsToCache(for account: Account) {
guard let cache = CacheManager.friendMessage.shared else { return }
cache.setMessages(friendMessageModels, for: account)
cache.setObject(totalPage as NSNumber, forKey: totalPageKey(for: account))
cache.setObject(lastUpdateTime as NSNumber, forKey: lastUpdateTimeKey(for: account))
}
func addFriend(at index: Int, completion: @escaping (HiPDA.Result<String, NSError>) -> Void) {
let uid = friendMessageModels[index].sender.uid
NetworkUtilities.addFriend(uid: uid, completion: completion)
}
}
// MARK: - DataSource
extension FriendMessageViewModel {
func title(at index: Int) -> String {
return "\(friendMessageModels[index].sender.name) 添加您为好友"
}
func time(at index: Int) -> String {
return friendMessageModels[index].time
}
func isRead(at index: Int) -> Bool {
return friendMessageModels[index].isRead
}
func model(at index: Int) -> FriendMessageModel {
return friendMessageModels[index]
}
}
|
41b84e64da15119927537f817f912715
| 31.914286 | 142 | 0.668403 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
stdlib/public/core/Repeat.swift
|
apache-2.0
|
10
|
//===--- Repeat.swift - A Collection that repeats a value N times ---------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection whose elements are all identical.
///
/// You create an instance of the `Repeated` collection by calling the
/// `repeatElement(_:count:)` function. The following example creates a
/// collection containing the name "Humperdinck" repeated five times:
///
/// let repeatedName = repeatElement("Humperdinck", count: 5)
/// for name in repeatedName {
/// print(name)
/// }
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
/// // "Humperdinck"
@frozen
public struct Repeated<Element> {
/// The number of elements in this collection.
public let count: Int
/// The value of every element in this collection.
public let repeatedValue: Element
/// Creates an instance that contains `count` elements having the
/// value `repeatedValue`.
@inlinable // trivial-implementation
internal init(_repeating repeatedValue: Element, count: Int) {
_precondition(count >= 0, "Repetition count should be non-negative")
self.count = count
self.repeatedValue = repeatedValue
}
}
extension Repeated: RandomAccessCollection {
public typealias Indices = Range<Int>
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a "past the
/// end" position that's not valid for use as a subscript.
public typealias Index = Int
/// The position of the first element in a nonempty collection.
///
/// In a `Repeated` collection, `startIndex` is always equal to zero. If the
/// collection is empty, `startIndex` is equal to `endIndex`.
@inlinable // trivial-implementation
public var startIndex: Index {
return 0
}
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// In a `Repeated` collection, `endIndex` is always equal to `count`. If the
/// collection is empty, `endIndex` is equal to `startIndex`.
@inlinable // trivial-implementation
public var endIndex: Index {
return count
}
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
@inlinable // trivial-implementation
public subscript(position: Int) -> Element {
_precondition(position >= 0 && position < count, "Index out of range")
return repeatedValue
}
}
/// Creates a collection containing the specified number of the given element.
///
/// The following example creates a `Repeated<Int>` collection containing five
/// zeroes:
///
/// let zeroes = repeatElement(0, count: 5)
/// for x in zeroes {
/// print(x)
/// }
/// // 0
/// // 0
/// // 0
/// // 0
/// // 0
///
/// - Parameters:
/// - element: The element to repeat.
/// - count: The number of times to repeat `element`.
/// - Returns: A collection that contains `count` elements that are all
/// `element`.
@inlinable // trivial-implementation
public func repeatElement<T>(_ element: T, count n: Int) -> Repeated<T> {
return Repeated(_repeating: element, count: n)
}
extension Repeated: Sendable where Element: Sendable { }
|
f8a082af6443e01bb8bd504ccd2f2842
| 33.342342 | 80 | 0.657922 | false | false | false | false |
SoySauceLab/CollectionKit
|
refs/heads/master
|
Sources/Other/CollectionReuseViewManager.swift
|
mit
|
1
|
//
// CollectionReuseViewManager.swift
// CollectionKit
//
// Created by Luke Zhao on 2017-07-21.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
public protocol CollectionViewReusableView: class {
func prepareForReuse()
}
public class CollectionReuseViewManager: NSObject {
/// Time it takes for CollectionReuseViewManager to
/// dump all reusableViews to save memory
public var lifeSpan: TimeInterval = 5.0
/// When `removeFromCollectionViewWhenReuse` is enabled,
/// cells will always be removed from Collection View during reuse.
/// This is slower but it doesn't influence the `isHidden` property
/// of individual cells.
public var removeFromCollectionViewWhenReuse = false
var reusableViews: [String: [UIView]] = [:]
var cleanupTimer: Timer?
public func queue(view: UIView) {
let identifier = NSStringFromClass(type(of: view))
view.reuseManager = nil
if removeFromCollectionViewWhenReuse {
view.removeFromSuperview()
} else {
view.isHidden = true
}
if reusableViews[identifier] != nil && !reusableViews[identifier]!.contains(view) {
reusableViews[identifier]?.append(view)
} else {
reusableViews[identifier] = [view]
}
if let cleanupTimer = cleanupTimer {
cleanupTimer.fireDate = Date().addingTimeInterval(lifeSpan)
} else {
cleanupTimer = Timer.scheduledTimer(timeInterval: lifeSpan, target: self,
selector: #selector(cleanup), userInfo: nil, repeats: false)
}
}
public func dequeue<T: UIView> (_ defaultView: @autoclosure () -> T) -> T {
let identifier = NSStringFromClass(T.self)
let queuedView = reusableViews[identifier]?.popLast() as? T
let view = queuedView ?? defaultView()
if let view = view as? CollectionViewReusableView {
view.prepareForReuse()
}
if !removeFromCollectionViewWhenReuse {
view.isHidden = false
}
view.reuseManager = self
return view
}
public func dequeue<T: UIView> (type: T.Type) -> T {
return dequeue(type.init())
}
@objc func cleanup() {
for views in reusableViews.values {
for view in views {
view.removeFromSuperview()
}
}
reusableViews.removeAll()
cleanupTimer?.invalidate()
cleanupTimer = nil
}
}
|
f85b4f46bd147a7343df5cfbae182a0d
| 28.379747 | 102 | 0.67514 | false | false | false | false |
WitcherHunter/DouyuZhibo
|
refs/heads/master
|
DouyuZhibo/DouyuZhibo/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
|
mit
|
1
|
//
// UIBarButtonItem-Extension.swift
// DouyuZhibo
//
// Created by 毛豆 on 2017/10/18.
// Copyright © 2017年 毛豆. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
convenience init(imageName: String, highlightedImageName: String = "", size: CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
if highlightedImageName != "" {
btn.setImage(UIImage(named: highlightedImageName), for: .highlighted)
}
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: .zero, size: size)
}
self.init(customView: btn)
}
}
|
cfa07458512349aa1e6b14016bd2a1b5
| 24.964286 | 104 | 0.581843 | false | false | false | false |
pjk1129/SONetwork
|
refs/heads/master
|
Demo/SwiftOne/Classes/Util/SOUtil.swift
|
mit
|
1
|
//
// SOUtil.swift
// SwiftOne
//
// Created by JK.PENG on 2017/3/20.
// Copyright © 2017年 XXXXX. All rights reserved.
//
import UIKit
import Foundation
// 屏幕宽度
let kScreenH = UIScreen.main.bounds.height
// 屏幕高度
let kScreenW = UIScreen.main.bounds.width
let SERVER_DOMAIN = "http://api.xxxx.com"
//自定义 log
func DLog<T>(_ message : T, file : String = #file, funcName : String = #function, lineNum : Int = #line) {
#if DEBUG
let fileName = (file as NSString).lastPathComponent
print("\(fileName):\(lineNum))-\(message)");
#endif
}
func parametersFromQuery(_ string: String) -> NSDictionary {
let array = string.components(separatedBy: "?")
let queryDic = NSMutableDictionary()
if array.count == 2{
let query = array[1]
let queryArray = query.components(separatedBy: "&")
for queryStr in queryArray {
let valueArray = queryStr.components(separatedBy: "=")
if valueArray.count == 2 {
let key = valueArray[0].removingPercentEncoding
let value = valueArray[1].removingPercentEncoding
queryDic.setValue(value, forKey: key!)
}
}
}
return queryDic
}
/*
NSCharacterSet常用的类型有以下:
urlHostAllowed "#%/<>?@\^`{|}
urlFragmentAllowed "#%<>[\]^`{|}
urlPasswordAllowed "#%/:<>?@[\]^`{|}
urlPathAllowed "#%;<>?[\]^`{|}
urlQueryAllowed "#%<>[\]^`{|}
urlUserAllowed "#%/:<>?@[\]^`
*/
func urlEncode(string: String) -> String {
return string.addingPercentEncoding(withAllowedCharacters: NSCharacterSet(charactersIn:"!*'();:@&=+$,/?%#[]").inverted)!
}
|
dde26481859614653bb2bf959eab313e
| 26.278689 | 124 | 0.593149 | false | false | false | false |
parkboo/ios-charts
|
refs/heads/master
|
Charts/Classes/Charts/HorizontalBarChartView.swift
|
apache-2.0
|
2
|
//
// HorizontalBarChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched.
public class HorizontalBarChartView: BarChartView
{
internal override func initialize()
{
super.initialize()
_leftAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler)
renderer = HorizontalBarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
_leftYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer)
_rightYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer)
_xAxisRenderer = ChartXAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self)
_highlighter = HorizontalBarChartHighlighter(chart: self)
}
internal override func calculateOffsets()
{
var offsetLeft: CGFloat = 0.0,
offsetRight: CGFloat = 0.0,
offsetTop: CGFloat = 0.0,
offsetBottom: CGFloat = 0.0
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
else if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = _legend.textHeightMax
offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
else if (_legend.position == .AboveChartLeft
|| _legend.position == .AboveChartRight
|| _legend.position == .AboveChartCenter)
{
// It's possible that we do not need this offset anymore as it
// is available through the extraOffsets, but changing it can mean
// changing default visibility for existing apps.
let yOffset = _legend.textHeightMax
offsetTop += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
}
// offsets for y-labels
if (_leftAxis.needsOffset)
{
offsetTop += _leftAxis.getRequiredHeightSpace()
}
if (_rightAxis.needsOffset)
{
offsetBottom += _rightAxis.getRequiredHeightSpace()
}
let xlabelwidth = _xAxis.labelRotatedWidth
if (_xAxis.isEnabled)
{
// offsets for x-labels
if (_xAxis.labelPosition == .Bottom)
{
offsetLeft += xlabelwidth
}
else if (_xAxis.labelPosition == .Top)
{
offsetRight += xlabelwidth
}
else if (_xAxis.labelPosition == .BothSided)
{
offsetLeft += xlabelwidth
offsetRight += xlabelwidth
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
_viewPortHandler.restrainViewPort(
offsetLeft: max(self.minOffset, offsetLeft),
offsetTop: max(self.minOffset, offsetTop),
offsetRight: max(self.minOffset, offsetRight),
offsetBottom: max(self.minOffset, offsetBottom))
prepareOffsetMatrix()
prepareValuePxMatrix()
}
internal override func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _rightAxis.axisMinimum, deltaX: CGFloat(_rightAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _leftAxis.axisMinimum, deltaX: CGFloat(_leftAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin)
}
internal override func calcModulus()
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelRotatedHeight) / (_viewPortHandler.contentHeight * viewPortHandler.touchMatrix.d)))
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1
}
}
public override func getBarBounds(e: BarChartDataEntry) -> CGRect
{
let set = _data.getDataSetForEntry(e) as! BarChartDataSet!
if (set === nil)
{
return CGRectNull
}
let barspace = set.barSpace
let y = CGFloat(e.value)
let x = CGFloat(e.xIndex)
let spaceHalf = barspace / 2.0
let top = x - 0.5 + spaceHalf
let bottom = x + 0.5 - spaceHalf
let left = y >= 0.0 ? y : 0.0
let right = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
public override func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.value), y: CGFloat(e.xIndex))
getTransformer(axis).pointValueToPixel(&vals)
return vals
}
public override func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight?
{
if (_dataNotSet || _data === nil)
{
print("Can't select by touch. No data set.", terminator: "\n")
return nil
}
return _highlighter?.getHighlight(x: Double(pt.y), y: Double(pt.x))
}
public override var lowestVisibleXIndex: Int
{
let step = CGFloat(_data.dataSetCount)
let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom)
getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
return Int(((pt.y <= 0.0) ? 0.0 : pt.y / div) + 1.0)
}
public override var highestVisibleXIndex: Int
{
let step = CGFloat(_data.dataSetCount)
let div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace
var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentTop)
getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt)
return Int((pt.y >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.y / div))
}
}
|
4199255414f4e8637a4c7a0d2d35634e
| 37.216346 | 166 | 0.598692 | false | false | false | false |
AaronMT/firefox-ios
|
refs/heads/main
|
Client/Frontend/Browser/FirefoxTabContentBlocker.swift
|
mpl-2.0
|
7
|
/* 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 WebKit
import Shared
struct ContentBlockingConfig {
struct Prefs {
static let StrengthKey = "prefkey.trackingprotection.strength"
static let EnabledKey = "prefkey.trackingprotection.normalbrowsing"
}
struct Defaults {
static let NormalBrowsing = !AppInfo.isChinaEdition
}
}
enum BlockingStrength: String {
case basic
case strict
static let allOptions: [BlockingStrength] = [.basic, .strict]
}
/**
Firefox-specific implementation of tab content blocking.
*/
class FirefoxTabContentBlocker: TabContentBlocker, TabContentScript {
let userPrefs: Prefs
class func name() -> String {
return "TrackingProtectionStats"
}
var isUserEnabled: Bool? {
didSet {
guard let tab = tab as? Tab else { return }
setupForTab()
TabEvent.post(.didChangeContentBlocking, for: tab)
tab.reload()
}
}
override var isEnabled: Bool {
if let enabled = isUserEnabled {
return enabled
}
return isEnabledInPref
}
var isEnabledInPref: Bool {
return userPrefs.boolForKey(ContentBlockingConfig.Prefs.EnabledKey) ?? ContentBlockingConfig.Defaults.NormalBrowsing
}
var blockingStrengthPref: BlockingStrength {
return userPrefs.stringForKey(ContentBlockingConfig.Prefs.StrengthKey).flatMap(BlockingStrength.init) ?? .basic
}
init(tab: ContentBlockerTab, prefs: Prefs) {
userPrefs = prefs
super.init(tab: tab)
setupForTab()
}
func setupForTab() {
guard let tab = tab else { return }
let rules = BlocklistFileName.listsForMode(strict: blockingStrengthPref == .strict)
ContentBlocker.shared.setupTrackingProtection(forTab: tab, isEnabled: isEnabled, rules: rules)
}
@objc override func notifiedTabSetupRequired() {
setupForTab()
if let tab = tab as? Tab {
TabEvent.post(.didChangeContentBlocking, for: tab)
}
}
override func currentlyEnabledLists() -> [BlocklistFileName] {
return BlocklistFileName.listsForMode(strict: blockingStrengthPref == .strict)
}
override func notifyContentBlockingChanged() {
guard let tab = tab as? Tab else { return }
TabEvent.post(.didChangeContentBlocking, for: tab)
}
func noImageMode(enabled: Bool) {
guard let tab = tab else { return }
ContentBlocker.shared.noImageMode(enabled: enabled, forTab: tab)
}
}
// Static methods to access user prefs for tracking protection
extension FirefoxTabContentBlocker {
static func setTrackingProtection(enabled: Bool, prefs: Prefs) {
let key = ContentBlockingConfig.Prefs.EnabledKey
prefs.setBool(enabled, forKey: key)
ContentBlocker.shared.prefsChanged()
}
static func isTrackingProtectionEnabled(prefs: Prefs) -> Bool {
return prefs.boolForKey(ContentBlockingConfig.Prefs.EnabledKey) ?? ContentBlockingConfig.Defaults.NormalBrowsing
}
static func toggleTrackingProtectionEnabled(prefs: Prefs) {
let isEnabled = FirefoxTabContentBlocker.isTrackingProtectionEnabled(prefs: prefs)
setTrackingProtection(enabled: !isEnabled, prefs: prefs)
}
}
|
fef13fc1a435710cbf728cbe5bd221ef
| 30.243243 | 124 | 0.682526 | false | true | false | false |
vector-im/vector-ios
|
refs/heads/master
|
Riot/Modules/Rooms/ShowDirectory/ShowDirectoryCoordinator.swift
|
apache-2.0
|
1
|
// File created from ScreenTemplate
// $ createScreen.sh Rooms/ShowDirectory ShowDirectory
/*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
final class ShowDirectoryCoordinator: ShowDirectoryCoordinatorType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let dataSource: PublicRoomsDirectoryDataSource
private var showDirectoryViewModel: ShowDirectoryViewModelType
private let showDirectoryViewController: ShowDirectoryViewController
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
weak var delegate: ShowDirectoryCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, dataSource: PublicRoomsDirectoryDataSource) {
self.session = session
self.dataSource = dataSource
let showDirectoryViewModel = ShowDirectoryViewModel(session: self.session, dataSource: dataSource)
let showDirectoryViewController = ShowDirectoryViewController.instantiate(with: showDirectoryViewModel)
self.showDirectoryViewModel = showDirectoryViewModel
self.showDirectoryViewController = showDirectoryViewController
}
// MARK: - Public methods
func start() {
self.showDirectoryViewModel.coordinatorDelegate = self
}
func toPresentable() -> UIViewController {
return self.showDirectoryViewController
}
// MARK: - Private
private func createDirectoryServerPickerViewController() -> DirectoryServerPickerViewController {
let controller = DirectoryServerPickerViewController()
controller.finalizeInit()
let dataSource: MXKDirectoryServersDataSource = MXKDirectoryServersDataSource(matrixSession: session)
dataSource.finalizeInitialization()
dataSource.roomDirectoryServers = BuildSettings.publicRoomsDirectoryServers
controller.display(with: dataSource) { [weak self] (cellData) in
guard let self = self else { return }
guard let cellData = cellData else { return }
self.showDirectoryViewModel.updatePublicRoomsDataSource(with: cellData)
}
return controller
}
}
// MARK: - ShowDirectoryViewModelCoordinatorDelegate
extension ShowDirectoryCoordinator: ShowDirectoryViewModelCoordinatorDelegate {
func showDirectoryViewModel(_ viewModel: ShowDirectoryViewModelType, didSelectRoomWithIdOrAlias roomIdOrAlias: String) {
self.delegate?.showDirectoryCoordinator(self, didSelectRoomWithIdOrAlias: roomIdOrAlias)
}
func showDirectoryViewModelDidSelect(_ viewModel: ShowDirectoryViewModelType, room: MXPublicRoom) {
self.delegate?.showDirectoryCoordinator(self, didSelectRoom: room)
}
func showDirectoryViewModelDidTapCreateNewRoom(_ viewModel: ShowDirectoryViewModelType) {
self.delegate?.showDirectoryCoordinatorDidTapCreateNewRoom(self)
}
func showDirectoryViewModelDidCancel(_ viewModel: ShowDirectoryViewModelType) {
self.delegate?.showDirectoryCoordinatorDidCancel(self)
}
func showDirectoryViewModelWantsToShowDirectoryServerPicker(_ viewModel: ShowDirectoryViewModelType) {
let controller = self.createDirectoryServerPickerViewController()
self.delegate?.showDirectoryCoordinatorWantsToShow(self, viewController: controller)
}
}
|
13a369b6292c6e31514cffc7948f3834
| 37.471154 | 124 | 0.740315 | false | false | false | false |
exoplatform/exo-ios
|
refs/heads/acceptance
|
eXo/Sources/defines.swift
|
lgpl-3.0
|
1
|
//
// defines.swift
// eXoHybrid
//
// Created by Nguyen Manh Toan on 10/7/15.
// This is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of
// the License, or (at your option) any later version.
//
// This software 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this software; if not, write to the Free
// Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301 USA, or see the FSF site: http://www.fsf.org.
import Foundation
import UIKit
struct ShortcutType {
static let connectRecentServer:String = "ios.exo.connect-recent-server"
static let addNewServer:String = "ios.exo.add-new-server"
}
struct Config {
// eXo Apple Store link
static let eXoAppleStoreUrl:String = "https://apps.apple.com/us/app/exo/id410476273"
static let communityURL:String = "https://community.exoplatform.com"
static let minimumPlatformVersionSupported:Float = 4.3
static let maximumShortcutAllow:Int = 4
static let timeout:TimeInterval = 60.0 // in seconds
static let onboardingDidShow: String = "onboardingDidShow"
// based on hex code #FFCB08
static let eXoYellowColor: UIColor = UIColor(red: 255.0/255, green: 203.0/255.0, blue: 8.0/255.0, alpha: 1.0)
// based on hex code #2F5E92
static let eXoBlueColor: UIColor = UIColor(red: 68/255, green: 93/255, blue: 147/255, alpha: 1.0)
static let kTableCellHeight: CGFloat = 80.0
static let kTableHeaderHeight: CGFloat = 50.0
// eXo Jitsi Server Path
static let eXoJitsiWebServer = "/jitsi"
static let eXoJitsiJWTPath = "/jitsi/api/v1/token/"
static let avatarURL = "/portal/rest/v1/social/users/*_*/avatar"
}
struct ShareExtension {
static let NSUserDefaultSuite:String = "group.com.exoplatform.mob.eXoPlatformiPHone"
static let AllUserNameKey:String = "exo_share_all_usernames"
}
enum Cookies: String {
case username = "last_login_username"
case domain = "last_login_domain"
case session = "JSESSIONID"
case sessionSso = "JSESSIONIDSSO"
case rememberMe = "rememberme"
}
struct ConnectionError {
static let URLError = 400
static let ServerVersionNotSupport = 403
static let ServerVersionNotFound = 404
}
|
c25b45dde42d6a37c625db346b42994c
| 37.367647 | 113 | 0.723266 | false | false | false | false |
GuyKahlon/UICollaborativeFilteringServer
|
refs/heads/master
|
Sources/App/Models/Event.swift
|
mit
|
1
|
import Vapor
enum EventType: String {
case startApplication
case manualEditPreference
case acceptRecommendation
case rejectRecommendation
}
final class EventItem: Model {
var id: Node?
var exists: Bool = false
var eventType: EventType
init(eventType: EventType) {
self.id = nil
self.eventType = eventType
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
eventType = EventType(rawValue: try node.extract("eventtype"))!
}
public func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"eventtype": eventType.rawValue
])
}
static func prepare(_ database: Database) throws {
try database.create("eventitems") { users in
users.id()
users.string("eventtype")
}
}
static func revert(_ database: Database) throws {
try database.delete("eventitems")
}
}
|
ccf961843ff6037f2f0fa9836fbb92b3
| 15.872727 | 67 | 0.648707 | false | false | false | false |
wrengels/Amplify4
|
refs/heads/master
|
Amplify4/Amplify4/AppDelegate.swift
|
gpl-2.0
|
1
|
//
// AppDelegate.swift
// Amplify4
//
// Created by Bill Engels on 1/15/15.
// Copyright (c) 2015 Bill Engels. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var targetView: NSTextView!
@IBOutlet weak var targDelegate: TargDelegate!
@IBOutlet weak var targetScrollView: NSScrollView!
@IBOutlet weak var substrateDelegate: AMsubstrateDelegate!
var settings = NSMutableDictionary()
override init() {
super.init()
NSUserDefaults.standardUserDefaults().registerDefaults(globals.factory as [NSObject : AnyObject])
NSUserDefaultsController.sharedUserDefaultsController().initialValues = globals.factory as [NSObject : AnyObject]
let docController: AnyObject = NSDocumentController.sharedDocumentController()
let maxdocs = docController.maximumRecentDocumentCount
let doclist = docController.recentDocumentURLs
let docnum = doclist.count
if let oldDocList = NSUserDefaults.standardUserDefaults().arrayForKey(globals.recentDocs) {
for doc in (oldDocList as! [String]) {
if let url = NSURL(fileURLWithPath: doc) {
docController.noteNewRecentDocumentURL(url)
}
}
}
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
targetScrollView.contentView.postsBoundsChangedNotifications = true
let settings = NSUserDefaults.standardUserDefaults()
var targetURL = NSURL()
var primerURL = NSURL()
if (substrateDelegate.primerFile.path == nil) && settings.boolForKey(globals.useRecentPrimers) {
// No primers were opened at startup and user wants to use recent file
if let primerPath = settings.stringForKey(globals.recentPrimerPath) {
if let primerURL = NSURL(fileURLWithPath: primerPath) {
if primerURL.checkResourceIsReachableAndReturnError(nil) {
// There is a recent file path and it does point to an actual file
substrateDelegate.openURLArray([primerURL])
}
}
}
}
if (substrateDelegate.targetFile.path == nil) && settings.boolForKey(globals.useRecentTarget) {
// No target was opened at startup and user wants to use recent file
if let targetPath = settings.stringForKey(globals.recentTargetPath) {
if let targetURL = NSURL(fileURLWithPath: targetPath) {
if targetURL.checkResourceIsReachableAndReturnError(nil) {
// There is a recent file path and it does point to an actual file
substrateDelegate.openURLArray([targetURL])
}
}
}
}
if (substrateDelegate.targetFile.path == nil) { // still
if let welcomePath = NSBundle.mainBundle().pathForResource("Welcome", ofType: "rtf") {
let didit = targetView.readRTFDFromFile(welcomePath)
}
}
}
func application(sender: NSApplication, openFiles filenames: [AnyObject]) {
var urlArray = NSMutableArray()
for name in filenames {
if let furl = NSURL(fileURLWithPath: (name as? String)!) {
urlArray.addObject(furl)
}
}
if urlArray.count < 1 {
sender.replyToOpenOrPrint(NSApplicationDelegateReply.Failure)
} else {
substrateDelegate.openURLArray(urlArray)
sender.replyToOpenOrPrint(NSApplicationDelegateReply.Success)
}
}
@IBAction func openBuiltinSamples(sender: AnyObject) {
if let primerSamplePath = NSBundle.mainBundle().pathForResource(globals.samplePrimers, ofType: "primers") {
if let targetSamplePath = NSBundle.mainBundle().pathForResource(globals.sampleTarget, ofType: "rtf") {
let primerURL = NSURL(fileURLWithPath: primerSamplePath)!
let targetURL = NSURL(fileURLWithPath: targetSamplePath)!
substrateDelegate.openURLArray([primerURL, targetURL])
// Now blank out the current file URLs so that we don't try to save into the application bundle
substrateDelegate.primerFile = NSURL()
substrateDelegate.targetFile = NSURL()
}
}
}
let prefsWindow = AMprefsController(windowNibName: "AMprefsController")
let helpWindowController = AmplifyHelpController(windowNibName: "AmplifyHelp")
@IBAction func doPrefs(sender: AnyObject) {
prefsWindow.initialSettings = prefsWindow.currentSettings()
prefsWindow.showWindow(self)
let didit = prefsWindow.windowLoaded
}
@IBAction func doHelp(sender: AnyObject) {
helpWindowController.showWindow(self)
let didit = helpWindowController.windowLoaded
let helpWindow = helpWindowController.helpWindow
helpWindow.display()
helpWindow.makeKeyAndOrderFront(self)
return
}
@IBAction func findMeInHelp(sender: AnyObject) {
if let btn = sender as? NSButton, senderId = btn.identifier {
helpWindowController.showWindow(self)
let didit = helpWindowController.windowLoaded
let helpWindow = helpWindowController.helpWindow
helpWindow.display()
helpWindow.makeKeyAndOrderFront(self)
let nsname = senderId as NSString
helpWindowController.scrollToString(nsname)
}
}
func applicationWillTerminate(aNotification: NSNotification) {
let docController: AnyObject = NSDocumentController.sharedDocumentController()
if let doclist = docController.recentDocumentURLs as? [NSURL] {
var docpaths = [String]()
for doc in doclist {
docpaths.append(doc.path!)
}
NSUserDefaults.standardUserDefaults().setObject(docpaths, forKey: globals.recentDocs)
if let ppath = substrateDelegate.primerFile.path {
NSUserDefaults.standardUserDefaults().setObject(ppath, forKey: globals.recentPrimerPath)
} else {
NSUserDefaults.standardUserDefaults().removeObjectForKey(globals.recentPrimerPath)
}
if let tpath = substrateDelegate.targetFile.path {
NSUserDefaults.standardUserDefaults().setObject(tpath, forKey: globals.recentTargetPath)
} else {
NSUserDefaults.standardUserDefaults().removeObjectForKey(globals.recentTargetPath)
}
NSUserDefaults.standardUserDefaults().synchronize()
}
}
@IBAction func amplify(sender: AnyObject) {
targDelegate.cleanupTarget()
let newDoc: Document = NSDocumentController.sharedDocumentController().openUntitledDocumentAndDisplay(true, error: nil)! as! Document
}
@IBAction func amplifyCircular(sender: AnyObject) {
let theDC: NSDocumentController = NSDocumentController.sharedDocumentController() as! NSDocumentController
if let newDoc: DocumentCircular = theDC.makeUntitledDocumentOfType("CircularDocumentType", error: nil)! as? DocumentCircular {
theDC.addDocument(newDoc)
newDoc.makeWindowControllers()
newDoc.showWindows()
}
}
}
|
5dbf53c201ff881ba77819efbc7d79d8
| 42.477011 | 141 | 0.647588 | false | false | false | false |
FreddyZeng/Charts
|
refs/heads/develop
|
Pods/Charts/Source/Charts/Charts/BarChartView.swift
|
apache-2.0
|
7
|
//
// BarChartView.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
/// Chart that draws bars.
open class BarChartView: BarLineChartViewBase, BarChartDataProvider
{
/// if set to true, all values are drawn above their bars, instead of below their top
private var _drawValueAboveBarEnabled = true
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
private var _drawBarShadowEnabled = false
internal override func initialize()
{
super.initialize()
renderer = BarChartRenderer(dataProvider: self, animator: _animator, viewPortHandler: _viewPortHandler)
self.highlighter = BarHighlighter(chart: self)
self.xAxis.spaceMin = 0.5
self.xAxis.spaceMax = 0.5
}
internal override func calcMinMax()
{
guard let data = self.data as? BarChartData
else { return }
if fitBars
{
_xAxis.calculate(
min: data.xMin - data.barWidth / 2.0,
max: data.xMax + data.barWidth / 2.0)
}
else
{
_xAxis.calculate(min: data.xMin, max: data.xMax)
}
// calculate axis range (min / max) according to provided data
leftAxis.calculate(
min: data.getYMin(axis: .left),
max: data.getYMax(axis: .left))
rightAxis.calculate(
min: data.getYMin(axis: .right),
max: data.getYMax(axis: .right))
}
/// - returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the BarChart.
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight?
{
if _data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y)
else { return nil }
if !isHighlightFullBarEnabled { return h }
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataIndex: h.dataIndex,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis)
}
/// - returns: The bounding box of the specified Entry in the specified DataSet. Returns null if the Entry could not be found in the charts data.
@objc open func getBarBounds(entry e: BarChartDataEntry) -> CGRect
{
guard let
data = _data as? BarChartData,
let set = data.getDataSetForEntry(e) as? IBarChartDataSet
else { return CGRect.null }
let y = e.y
let x = e.x
let barWidth = data.barWidth
let left = x - barWidth / 2.0
let right = x + barWidth / 2.0
let top = y >= 0.0 ? y : 0.0
let bottom = y <= 0.0 ? y : 0.0
var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top)
getTransformer(forAxis: set.axisDependency).rectValueToPixel(&bounds)
return bounds
}
/// Groups all BarDataSet objects this data object holds together by modifying the x-value of their entries.
/// Previously set x-values of entries will be overwritten. Leaves space between bars and groups as specified by the parameters.
/// Calls `notifyDataSetChanged()` afterwards.
///
/// - parameter fromX: the starting point on the x-axis where the grouping should begin
/// - parameter groupSpace: the space between groups of bars in values (not pixels) e.g. 0.8f for bar width 1f
/// - parameter barSpace: the space between individual bars in values (not pixels) e.g. 0.1f for bar width 1f
@objc open func groupBars(fromX: Double, groupSpace: Double, barSpace: Double)
{
guard let barData = self.barData
else
{
Swift.print("You need to set data for the chart before grouping bars.", terminator: "\n")
return
}
barData.groupBars(fromX: fromX, groupSpace: groupSpace, barSpace: barSpace)
notifyDataSetChanged()
}
/// Highlights the value at the given x-value in the given DataSet. Provide -1 as the dataSetIndex to undo all highlighting.
/// - parameter x:
/// - parameter dataSetIndex:
/// - parameter stackIndex: the index inside the stack - only relevant for stacked entries
@objc open func highlightValue(x: Double, dataSetIndex: Int, stackIndex: Int)
{
highlightValue(Highlight(x: x, dataSetIndex: dataSetIndex, stackIndex: stackIndex))
}
// MARK: Accessors
/// if set to true, all values are drawn above their bars, instead of below their top
@objc open var drawValueAboveBarEnabled: Bool
{
get { return _drawValueAboveBarEnabled }
set
{
_drawValueAboveBarEnabled = newValue
setNeedsDisplay()
}
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
@objc open var drawBarShadowEnabled: Bool
{
get { return _drawBarShadowEnabled }
set
{
_drawBarShadowEnabled = newValue
setNeedsDisplay()
}
}
/// Adds half of the bar width to each side of the x-axis range in order to allow the bars of the barchart to be fully displayed.
/// **default**: false
@objc open var fitBars = false
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values (relevant only for stacked).
/// If enabled, highlighting operations will highlight the whole bar, even if only a single stack entry was tapped.
@objc open var highlightFullBarEnabled: Bool = false
/// - returns: `true` the highlight is be full-bar oriented, `false` ifsingle-value
open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled }
// MARK: - BarChartDataProvider
open var barData: BarChartData? { return _data as? BarChartData }
/// - returns: `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled }
/// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled }
}
|
b49fdab2cb1bfcc32a3a2008b0342c68
| 35.989071 | 149 | 0.620771 | false | false | false | false |
OpenTimeApp/OpenTimeIOSSDK
|
refs/heads/master
|
OpenTimeSDK/Classes/OTDeserializedConnection.swift
|
mit
|
1
|
//
// ConnectionData.swift
// OpenTime
//
// Created by Josh Woodcock on 10/23/15.
// Copyright © 2015 Connecting Open Time, LLC. All rights reserved.
//
public class OTDeserializedConnection : OTDeserializer{
private struct Keys {
static let ORG_ID = "org_id";
static let STATUS = "status";
static let LAST_UPDATED = "last_updated";
static let PERSON = "person";
}
private var _orgID: OpenTimeOrgID;
private var _status: ConnectionStatus;
private var _lastUpdated: OpenTimeTimeStamp;
private var _deserializedPerson: OTDeserializedPerson;
public required init(dictionary: NSDictionary){
self._orgID = dictionary.value(forKey: Keys.ORG_ID) as! OpenTimeOrgID;
self._status = dictionary.value(forKey: Keys.STATUS) as! ConnectionStatus;
self._lastUpdated = dictionary.value(forKey: Keys.LAST_UPDATED) as! OpenTimeTimeStamp;
let personDictionary = dictionary.value(forKey: Keys.PERSON) as! NSDictionary;
self._deserializedPerson = OTDeserializedPerson(dictionary: personDictionary);
}
public func getPerson() -> OTDeserializedPerson {
return self._deserializedPerson;
}
public func getStatus() -> ConnectionStatus {
return self._status;
}
public func getLastUpdated() -> OpenTimeTimeStamp {
return self._lastUpdated;
}
public func getOrgID()->OpenTimeOrgID {
return self._orgID;
}
}
|
c4a0b67d9c4db9322ba1dfb836705ff1
| 31.446809 | 94 | 0.650492 | false | false | false | false |
Tinkertanker/intro-coding-swift
|
refs/heads/master
|
rTurtles/rTurtles/rTurtle.swift
|
mit
|
1
|
//
// rTurtle.swift
// rTurtles
//
// Created by Zhang Hongyi on 1/7/15.
// Copyright (c) 2015 Tinkertanker. All rights reserved.
//
import Foundation
import Cocoa
import SpriteKit
import AppKit
public class RTurtle : NSObject {
var view:SKView = SKView(frame: CGRectMake(0,0,900,600))
var scene:SKScene = SKScene(size: CGSizeMake(1024, 768))
var turtle:SKSpriteNode = SKSpriteNode(imageNamed: "karel.png", normalMapped: false)
let squareSize:Int=50
var moveSequence = [SKAction]()
var rotation:Double = 0.0
var pickups=[SKSpriteNode]();
var walls=[SKSpriteNode]();
var xcord = 0;
var ycord = 0;
var dead = false;
var score = 0;
var won = true;
var maze = [
/*Start*/[0,1,0,0,0,0,0,1,1,1,1,1,0,0,0],//bottom right
[0,1,0,1,1,1,1,1,0,0,0,0,1,0,0],
[0,1,0,1,0,0,0,1,0,1,1,1,1,0,0], // 0 denotes space, 1 denotes wall
[0,1,1,1,0,1,1,1,0,1,1,1,1,1,0], // 2 denotes pickup
[0,0,0,0,0,1,0,0,0,0,0,0,0,3,0], // 3 denotes goal
[1,1,1,1,0,1,1,1,1,0,1,1,1,1,0],
[0,0,0,1,0,0,0,0,0,0,1,0,0,0,0],
[0,0,0,1,1,1,1,0,1,1,1,0,0,0,0],
[0,0,0,0,0,0,1,1,1,0,0,0,0,0,0],//top right
]
public func start(newMaze: [Array<Int>]? ) -> SKView{
if(newMaze != nil) {
maze = newMaze!;
}
scene.scaleMode = SKSceneScaleMode.AspectFit
view.presentScene(scene)
// Create the scene and add it to the view
turtle.size = CGSizeMake(CGFloat(squareSize),CGFloat(squareSize));
turtle.position = positionAtGrid(0 , y:0)
// turtle.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(6, duration: 2)))
//Generate terrain, assuming that it's rectangular
var i=0;
var j=0;
for row in maze {
j=0;
for cell in row{
if(cell != 0){
switch(cell){
case 1:
walls.append(SKSpriteNode(color: SKColor.redColor(), size: CGSizeMake(CGFloat(squareSize),CGFloat(squareSize))));
walls[walls.count-1].position=positionAtGrid(j, y: i)
scene.addChild(walls[walls.count-1])
break
case 2:
pickups.append(SKSpriteNode(imageNamed:"cherry.png",normalMapped:false));
pickups[pickups.count-1].size=CGSizeMake(CGFloat(squareSize),CGFloat(squareSize))
pickups[pickups.count-1].position=positionAtGrid(j, y: i)
scene.addChild(pickups[pickups.count-1])
break
case 3:
walls.append(SKSpriteNode(color: SKColor.yellowColor(), size: CGSizeMake(CGFloat(squareSize),CGFloat(squareSize))));
walls[walls.count-1].position=positionAtGrid(j, y: i)
scene.addChild(walls[walls.count-1])
break
default:
break
}
}
j++;
}
i++;
}
//last so it's on top of everything else
scene.addChild(turtle)
return view
}
public func moveForward()->String{
if(!dead){
var dx=sin(rotation)*Double(squareSize)*Double(-1)
var dy=cos(rotation)*Double(squareSize)
xcord-=Int(sin(rotation))
ycord+=Int(cos(rotation))
moveSequence.append(SKAction.moveBy(CGVector(dx: dx, dy: dy), duration: 0.5))
}
return "Okay, I'll move forward next."
}
public func turnRight()->String{
if(!dead){
rotation=rotation-M_PI_2
moveSequence.append(SKAction.rotateToAngle(CGFloat(rotation), duration: 0.5))
}
return "Okay, I'll turn right next."
}
public func turnLeft()->String{
/*if(!dead){
rotation=rotation+M_PI_2
moveSequence.append(SKAction.rotateToAngle(CGFloat(rotation), duration: 0.5))
}*/
return "Sorry, I can't turn left."
}
// public func moveRight(){
// moveSequence.append(SKAction.moveBy(CGVector(dx: squareSize, dy: 0), duration: 0.5))
// }
public func move()->String{
doMove(0)
return "Moving~"
}
private func doMove(step:Int){
if(step>=moveSequence.count){
print("Done! I picked up ")
print(score)
print(" cherries!")
}
else{
print(self.roundPosition(self.turtle.position))
var action=self.moveSequence[step]
turtle.runAction(action,completion:{
var mazeValue = self.mazeValueAtPosition(self.turtle.position)
if(mazeValue==1){
print("I died!")
self.dead=true
self.turtle.runAction(SKAction.repeatActionForever(SKAction.rotateByAngle(6,duration: 2)))
}
else if(mazeValue==2){
for pickup in self.pickups {
print(pickup.position)
print(self.roundPosition(self.turtle.position))
if(pickup.position==self.roundPosition(self.turtle.position)){
if(!pickup.hidden){
print(self.score)
self.score++
pickup.hidden=true;
}
}
}
self.doMove(step+1)
}
else if(mazeValue==3){
print("I'm done!")
}
else{
self.doMove(step+1)
}
})
}
}
private func positionAtGrid(x:Int,y:Int)->CGPoint{
return CGPointMake(CGFloat(60+x*squareSize),CGFloat(60+y*squareSize))
}
private func mazeValueAtPosition(position:CGPoint)->Int{
var xcord=round((position.x-60)/CGFloat(squareSize))
var ycord=round((position.y-60)/CGFloat(squareSize))
return maze[Int(ycord)][Int(xcord)]
}
private func roundPosition(position:CGPoint) -> CGPoint{
return CGPointMake(CGFloat(round(position.x*10)/10), CGFloat(round(position.y*10)/10))
}
public func getScore()->Int{
return score;
}
}
|
67dd43a14074688b256a7b34bd2c6dcb
| 36.434286 | 140 | 0.514883 | false | false | false | false |
JonathanRitchey03/JRMutableArray
|
refs/heads/master
|
JRMutableArrayTests/JRMutableArrayTests.swift
|
mit
|
1
|
import XCTest
@testable import JRMutableArray
class JRMutableArrayTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testSequentialIntInsertion() {
let array = JRMutableArray()
for i in 0...100 {
array[i] = i
}
for i in 0...100 {
let num = array[i]
if num is Int {
XCTAssertEqual(num as? Int, i, "numbers inserted must match")
} else {
XCTAssert(false, "expected numbers to be ints")
}
}
XCTAssert(array.debugQuickLookObject() != nil, "quicklook should return something")
}
func testSequentialDoubleInsertion() {
let array = JRMutableArray()
for i in 0...100 {
array[i] = Double(i) * 3.14
}
for i in 0...100 {
let num = array[i]
if num is Double {
XCTAssertEqual(num as? Double, Double(i) * 3.14, "numbers inserted must match")
} else {
XCTAssert(false, "expected numbers to be doubles")
}
}
XCTAssert(array.debugQuickLookObject() != nil, "quicklook should return something")
}
func testSequentialFloatInsertion() {
let array = JRMutableArray()
for i in 0...100 {
array[i] = Float(i) * 3.14
}
for i in 0...100 {
let num = array[i]
if num is Float {
XCTAssertEqual(num as? Float, Float(i) * 3.14, "numbers inserted must match")
} else {
XCTAssert(false, "expected numbers to be floats")
}
}
XCTAssert(array.debugQuickLookObject() != nil, "quicklook should return something")
}
func testSparseInsertion() {
let array = JRMutableArray()
for i in stride(from: 2, to: 100, by: 7) {
array[i] = i
}
for i in 0..<array.count() {
if (i - 2) % 7 == 0 {
let num = array[i]
if num is Int {
XCTAssertEqual(num as? Int, i, "numbers inserted must match")
} else {
XCTAssert(false, "expected numbers to be ints")
}
} else {
if array[i] is NSNull {
// ok
} else {
XCTAssert(false, "empty cells should be NSNull")
}
}
}
XCTAssert(array.debugQuickLookObject() != nil, "quicklook should return something")
}
func testQuicksort() {
let array = JRMutableArray()
let size = 50
for i in 0..<size {
array[i] = -10 + Int(arc4random() % 30)
}
self.quicksort(array, lo: 0, hi: array.count() - 1)
var previous : Int = array[0] as! Int
for i in 1..<array.count() {
let current : Int = array[i] as! Int
XCTAssert(previous <= current, "order must be ascending")
previous = current
}
}
func quicksort(_ array: JRMutableArray, lo: Int, hi: Int) {
if lo < hi {
array.markRange(NSMakeRange(lo,hi-lo+1))
let p = quicksortPartition(array, lo: lo, hi: hi)
quicksort(array,lo:lo,hi:p-1)
quicksort(array,lo:p+1,hi:hi)
}
}
func quicksortPartition(_ array: JRMutableArray, lo: Int, hi: Int) -> Int {
let p : Double = array[hi] as! Double
var i = lo
for j in lo..<hi {
let aj : Double = array[j] as! Double
if aj < p {
array.swap(i,withObjectAtIndex:j)
i += 1
}
}
array.swap(i, withObjectAtIndex: hi)
return i
}
}
|
f766254c787ac8553c27eebf052b0ce8
| 31.56 | 111 | 0.503194 | false | true | false | false |
varun-naharia/VNOfficeHourPicker
|
refs/heads/master
|
Example/VNOfficeHourPickerExample/Pods/VNOfficeHourPicker/VNOfficeHourPicker/VNOfficeHourPicker/VNOfficeHourView.swift
|
mit
|
1
|
//
// VNOfficeHourView.swift
// OfficeHourPicker
//
// Created by Varun Naharia on 14/07/17.
// Copyright © 2017 Varun. All rights reserved.
//
import UIKit
@IBDesignable
class VNOfficeHourView: UIView, UIGestureRecognizerDelegate, VNOfficeHourViewDelegate {
@IBOutlet weak var lblMondayValue: UILabel!
@IBOutlet weak var lblTuesdayValue: UILabel!
@IBOutlet weak var lblWednesdayValue: UILabel!
@IBOutlet weak var lblThruesdayValue: UILabel!
@IBOutlet weak var lblFridayValue: UILabel!
@IBOutlet weak var lblSaturdayValue: UILabel!
@IBOutlet weak var lblSundayValue: UILabel!
@IBOutlet weak var viewHeight: NSLayoutConstraint!
var arrayValuesForCell:[[String:Any]] = []
var view: UIView!
var numberOfRows = 0
@IBInspectable
public var cornerRadius :CGFloat {
set { layer.cornerRadius = newValue }
get {
return layer.cornerRadius
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setUpView()
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
override func awakeFromNib() {
super.awakeFromNib()
self.setUpView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
}
func xibSetup() {
view = loadViewFromNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "VNOfficeHourView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
//var underline = UILabel()
func setUpView() {
//underline.backgroundColor = UIColor.lightGray
//self.addSubview(underline)
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
tap.delegate = self
self.addGestureRecognizer(tap)
}
override func layoutSubviews() {
//underline.frame = CGRect(x: 0, y: self.frame.size.height - 1, width: self.frame.size.width, height: 1)
}
func handleTap(sender: UITapGestureRecognizer? = nil) {
// handling code
print("Tap")
let bundle = Bundle(for: type(of: self))
let storyboard = UIStoryboard.init(name: "VNOfficeHour", bundle: bundle)
let vc:VNOfficeHourViewController = storyboard.instantiateViewController(withIdentifier: "VNOfficeHourViewController") as! VNOfficeHourViewController
vc.delegate = self
if(self.arrayValuesForCell.count > 0)
{
vc.arrayValuesForCell = self.arrayValuesForCell
}
if(numberOfRows != 0)
{
vc.rowCount = numberOfRows
}
self.getParentViewController()?.present(vc, animated: true, completion: nil)
}
func save(arrData: [[String : Any]], numberOfRow: Int) {
self.arrayValuesForCell = arrData
if(arrayValuesForCell.count > 0)
{
viewHeight.constant = 211
}
else
{
viewHeight.constant = 0
}
self.numberOfRows = numberOfRow
lblMondayValue.text = getDayTime(data: arrData, For: "Mon")
lblTuesdayValue.text = getDayTime(data: arrData, For: "Tue")
lblWednesdayValue.text = getDayTime(data: arrData, For: "Wed")
lblThruesdayValue.text = getDayTime(data: arrData, For: "Thu")
lblFridayValue.text = getDayTime(data: arrData, For: "Fri")
lblSaturdayValue.text = getDayTime(data: arrData, For: "Sat")
lblSundayValue.text = getDayTime(data: arrData, For: "Sun")
lblMondayValue.textColor = lblMondayValue.text == "Closed" ? UIColor.red :UIColor.blue
lblTuesdayValue.textColor = lblTuesdayValue.text == "Closed" ? UIColor.red :UIColor.blue
lblWednesdayValue.textColor = lblWednesdayValue.text == "Closed" ? UIColor.red :UIColor.blue
lblThruesdayValue.textColor = lblThruesdayValue.text == "Closed" ? UIColor.red :UIColor.blue
lblFridayValue.textColor = lblFridayValue.text == "Closed" ? UIColor.red :UIColor.blue
lblSaturdayValue.textColor = lblSaturdayValue.text == "Closed" ? UIColor.red :UIColor.blue
lblSundayValue.textColor = lblSundayValue.text == "Closed" ? UIColor.red :UIColor.blue
}
func getDayTime(data:[[String:Any]], For:String) -> String {
for item in data {
if(item[For] != nil)
{
if((item[For] as! String) == "true" && (item["start"] as! String) != "" && (item["end"] as! String) != "" )
{
return "\((item["start"] as! String)) To \((item["end"] as! String))"
}
}
}
return "Closed"
}
}
|
a8ad18655889e70ad88c60a6f458014f
| 33.070064 | 157 | 0.611142 | false | false | false | false |
dbahat/conventions-ios
|
refs/heads/sff
|
Conventions/Conventions/extentions/StringExtentions.swift
|
apache-2.0
|
1
|
//
// StringExtentions.swift
// Conventions
//
// Created by Bahat David on 10/09/2022.
// Copyright © 2022 Amai. All rights reserved.
//
import Foundation
extension String {
func htmlAttributedString(color: UIColor = UIColor.white) -> NSAttributedString? {
let htmlTemplate = """
<!doctype html>
<html>
<head>
<style>
body {
font-family: -apple-system;
font-size: 14px;
color: \(color.hexString);
line-height: 1.4;
}
</style>
</head>
<body>
<div dir='rtl' style='-webkit-text-size-adjust: none;'>
\(self)
</div>
</body>
</html>
"""
guard let data = htmlTemplate.data(using: .utf8) else {
return nil
}
guard let attributedString = try? NSAttributedString(
data: data,
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil
) else {
return nil
}
return attributedString
}
}
|
836e4305f8795103709f52b6959132b8
| 24.458333 | 126 | 0.507365 | false | false | false | false |
davidcat/CYzoneDemo
|
refs/heads/master
|
Cyzone/Classes/APPEntrance/AppDelegate.swift
|
apache-2.0
|
1
|
//
// AppDelegate.swift
// Cyzone
//
// Created by 海大旺(外包) on 17/2/10.
// Copyright © 2017年 davidcat. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Cyzone")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
1c3cef59787a58813866c7831287424e
| 48.247312 | 285 | 0.684934 | false | false | false | false |
ChaselAn/ACTagView
|
refs/heads/master
|
ACTagViewDemo/ACTagView/ACTagViewOneLineLayout.swift
|
mit
|
1
|
//
// ACTagViewOneLineLayout.swift
// ACTagViewDemo
//
// Created by ac on 2017/7/30.
// Copyright © 2017年 ac. All rights reserved.
//
import UIKit
class ACTagViewOneLineLayout: ACTagViewFlowLayout {
private var offsetX: CGFloat = 0
override var collectionViewContentSize: CGSize {
guard let collectionView = collectionView else {
return CGSize.zero
}
collectionView.layoutIfNeeded()
collectionView.superview?.layoutIfNeeded()
return CGSize(width: max(collectionView.bounds.width, offsetX), height: collectionView.bounds.height)
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let array = super.layoutAttributesForElements(in: rect), let collectionView = collectionView else { return nil }
collectionView.layoutIfNeeded()
collectionView.superview?.layoutIfNeeded()
var finalAttrs: [UICollectionViewLayoutAttributes] = []
var offsetX = tagViewMargin.horizontal
let offsetY = tagViewMargin.vertical
for attribute in array {
let attrCopy = attribute.copy() as! UICollectionViewLayoutAttributes
attrCopy.frame.origin.x = offsetX
attrCopy.frame.origin.y = offsetY
if !collectionView.isScrollEnabled && offsetX + attribute.frame.width + tagViewMargin.horizontal > collectionView.bounds.width {
self.offsetX = offsetX
return finalAttrs
}
offsetX += tagMargin.horizontal + attribute.frame.width
finalAttrs += [attrCopy]
}
if offsetX > tagViewMargin.horizontal {
offsetX = offsetX - tagMargin.horizontal + tagViewMargin.horizontal
}
self.offsetX = offsetX
return finalAttrs
}
override func getEstimatedSize(in tagView: ACTagView) -> CGSize {
guard let dataSource = tagView.tagDataSource else { return CGSize.zero }
tagView.layoutIfNeeded()
tagView.superview?.layoutIfNeeded()
var offsetX = tagViewMargin.horizontal
for i in 0 ..< dataSource.numberOfTags(in: tagView) {
let attribute = dataSource.tagView(tagView, tagAttributeForIndexAt: i)
let width = attribute.getWidth(height: tagHeight)
offsetX += tagMargin.horizontal + width
}
if offsetX > tagViewMargin.horizontal {
offsetX = offsetX - tagMargin.horizontal + tagViewMargin.horizontal
}
return CGSize(width: offsetX, height: tagHeight + 2 * tagViewMargin.vertical)
}
}
|
b7cc965c56d1be3de373e94430c89948
| 28.103448 | 134 | 0.687204 | false | false | false | false |
devpunk/velvet_room
|
refs/heads/master
|
Source/Model/Connected/MConnectedActions.swift
|
mit
|
1
|
import Foundation
extension MConnected
{
//MARK: private
private func addLogs(logs:[MVitaLinkLogProtocol])
{
let events:[MConnectedEventProtocol] = MConnected.factoryEvents(
logs:logs)
self.events.append(contentsOf:events)
view?.updateEvents()
}
//MARK: internal
func start(vitaLink:MVitaLink)
{
self.vitaLink = vitaLink
vitaLink.delegate = self
}
func updateEvents(logs:[MVitaLinkLogProtocol])
{
var logs:[MVitaLinkLogProtocol] = logs
let currentEvents:Int = events.count
let removeRange:Range<Int> = Range<Int>(
0 ..< currentEvents)
logs.removeSubrange(removeRange)
addLogs(logs:logs)
}
func closeConnection()
{
vitaLink?.userCloseConnection()
}
func cancelAndClean()
{
vitaLink?.cancel()
vitaLink = nil
}
func foundError(errorMessage:String)
{
statusError(errorMessage:errorMessage)
view?.updateStatus()
}
}
|
04fdc16fa221e046dc521eb72cc6a752
| 20.352941 | 72 | 0.585859 | false | false | false | false |
Alan881/AAPlayer
|
refs/heads/master
|
AAPlayer/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// AAPlayer
//
// Created by Alan on 2017/6/28.
// Copyright © 2017年 Alan. All rights reserved.
//
import UIKit
class ViewController: UIViewController, AAPlayerDelegate {
@IBOutlet weak var player: AAPlayer!
fileprivate var sourceArray: Array<Any>!
fileprivate var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
sourceArray = ["http://live.zzbtv.com:80/live/live123/800K/tzwj_video.m3u8","http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8","http://bos.nj.bpc.baidu.com/tieba-smallvideo/0173bbaf5acf62b815a7de0544730d6c.mp4","http://bos.nj.bpc.baidu.com/tieba-smallvideo/00a52c5e2213216ce0ce3795d40e9492.mp4","http://bos.nj.bpc.baidu.com/tieba-smallvideo/0045ab5a9e440defb2611658c0914724.mp4"]
player.delegate = self
player.playVideo(sourceArray[currentIndex] as! String)
}
@IBAction func beforeBtn(_ sender: Any) {
currentIndex = currentIndex - 1
if currentIndex < 0 {
currentIndex = 0
return
}
player.playVideo(sourceArray[currentIndex] as! String)
}
@IBAction func nextBtn(_ sender: Any) {
currentIndex = currentIndex + 1
if currentIndex > sourceArray.count - 1 {
currentIndex = sourceArray.count - 1
return
}
player.playVideo(sourceArray[currentIndex] as! String)
}
//optional method
func callBackDownloadDidFinish(_ status: playerItemStatus?) {
let status:playerItemStatus = status!
switch status {
case .readyToPlay:
break
case .failed:
break
default:
break
}
}
func startPlay() {
//optional method
player.startPlayback()
}
func stopPlay() {
//optional method
player.pausePlayback()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
a25c33f9e5c79078565a509dea7787e2
| 24.034091 | 402 | 0.592828 | false | false | false | false |
adow/SecrecySwift
|
refs/heads/master
|
SecrecySwift/RSA.swift
|
mit
|
1
|
//
// RSA.swift
// TestCommonCrypto
//
// Created by 秦 道平 on 15/12/15.
// Copyright © 2015年 秦 道平. All rights reserved.
//
import Foundation
import Security
public enum RSAAlgorithm:Int {
case sha1 = 0, sha224, sha256, sha384, sha512, md2, md5
public var padding:SecPadding {
switch self {
case .sha1:
return SecPadding.PKCS1SHA1
case .sha224:
return SecPadding.PKCS1SHA224
case .sha256:
return SecPadding.PKCS1SHA256
case .sha384:
return SecPadding.PKCS1SHA384
case .sha512:
return SecPadding.PKCS1SHA512
case .md2:
// return SecPadding.PKCS1MD2
return SecPadding.PKCS1
case .md5:
// return SecPadding.PKCS1MD5
return SecPadding.PKCS1
}
}
public var digestAlgorithm:DigestAlgorithm {
switch self {
case .sha1:
return DigestAlgorithm.sha1
case .sha224:
return DigestAlgorithm.sha224
case .sha256:
return DigestAlgorithm.sha256
case .sha384:
return DigestAlgorithm.sha384
case .sha512:
return DigestAlgorithm.sha512
case .md2:
return DigestAlgorithm.md2
case .md5:
return DigestAlgorithm.md5
}
}
}
// MARK: - func
/// encrypt
private func rsa_encrypt(_ inputData:Data, withKey key:SecKey) -> Data?{
guard inputData.count > 0 && inputData.count < SecKeyGetBlockSize(key) - 11 else {
return nil
}
let key_size = SecKeyGetBlockSize(key)
var encrypt_bytes = [UInt8](repeating: 0, count: key_size)
var output_size : Int = key_size
if SecKeyEncrypt(key, SecPadding.PKCS1,
inputData.arrayOfBytes(), inputData.count,
&encrypt_bytes, &output_size) == errSecSuccess {
return Data(bytes: UnsafePointer<UInt8>(encrypt_bytes), count: output_size)
}
return nil
}
/// decrypt
private func rsa_decrypt(_ inputData:Data, withKey key:SecKey) -> Data? {
guard inputData.count == SecKeyGetBlockSize(key) else {
return nil
}
let key_size = SecKeyGetBlockSize(key)
var decrypt_bytes = [UInt8](repeating: 0, count: key_size)
var output_size: Int = key_size
if SecKeyDecrypt(key, SecPadding.PKCS1, inputData.arrayOfBytes(), inputData.count, &decrypt_bytes, &output_size) == errSecSuccess {
return Data(bytes: UnsafePointer<UInt8>(decrypt_bytes), count: output_size)
}
else {
return nil
}
}
/// sign
private func rsa_sign(_ inputData:Data,withAlgorithm algorithm:RSAAlgorithm, withKey key:SecKey) -> Data? {
let digestInputData = inputData.digestData(algorithm.digestAlgorithm)
// print("digestInput:\(digestInputData.hexString)")
guard digestInputData.count > 0 && digestInputData.count < SecKeyGetBlockSize(key) - 11 else {
return nil
}
let key_size = SecKeyGetBlockSize(key)
var sign_bytes = [UInt8](repeating: 0, count: key_size)
var sign_size : Int = key_size
let result = SecKeyRawSign(key, algorithm.padding, digestInputData.arrayOfBytes(), digestInputData.count, &sign_bytes, &sign_size)
// print("result:\(result)")
if result == errSecSuccess {
return Data(bytes: UnsafePointer<UInt8>(sign_bytes), count: sign_size)
}
return nil
}
/// verify
private func rsa_verify(_ inputData:Data, signedData:Data,
withAlgorithm algorithm:RSAAlgorithm, whthKey key:SecKey) -> Bool {
let digestInputData = inputData.digestData(algorithm.digestAlgorithm)
// print("digestInput:\(digestInputData.hexString)")
guard digestInputData.count > 0 && digestInputData.count < SecKeyGetBlockSize(key) - 11 else {
return false
}
let result = SecKeyRawVerify(key, algorithm.padding, digestInputData.arrayOfBytes(), digestInputData.count, signedData.arrayOfBytes(), signedData.count)
return result == errSecSuccess
}
/// publicKey
private func rsa_publickey_from_data(_ keyData:Data) -> SecKey?{
if let certificate = SecCertificateCreateWithData(kCFAllocatorDefault, keyData as CFData) {
let policy = SecPolicyCreateBasicX509()
var trust : SecTrust?
if SecTrustCreateWithCertificates(certificate, policy, &trust) == errSecSuccess {
var trustResultType : SecTrustResultType = SecTrustResultType.invalid
if SecTrustEvaluate(trust!, &trustResultType) == errSecSuccess {
return SecTrustCopyPublicKey(trust!)
}
}
}
return nil
}
/// privateKey
private func rsa_privatekey_from_data(_ keyData:Data, withPassword password:String) -> SecKey? {
var privateKey: SecKey? = nil
let options : [String:String] = [kSecImportExportPassphrase as String:password]
var items : CFArray?
if SecPKCS12Import(keyData as CFData, options as CFDictionary, &items) == errSecSuccess {
// print("items:\(CFArrayGetCount(items))")
if CFArrayGetCount(items) > 0 {
let d = unsafeBitCast(CFArrayGetValueAtIndex(items, 0),to: CFDictionary.self)
let k = Unmanaged.passUnretained(kSecImportItemIdentity as NSString).toOpaque()
let v = CFDictionaryGetValue(d, k)
// print("identity:\(identity)")
let secIdentity = unsafeBitCast(v, to: SecIdentity.self)
// print("secIdentity:\(secIdentity)")
if SecIdentityCopyPrivateKey(secIdentity, &privateKey) == errSecSuccess {
return privateKey
}
}
}
return nil
}
// MARK: - RSA
public struct RSA {
fileprivate let publicKey:SecKey!
fileprivate let privateKey:SecKey!
// MARK: init
/// PublicKey must be in .der format and private must be in .p12 format
public init(publicKey:SecKey!, privateKey:SecKey!){
self.publicKey = publicKey
self.privateKey = privateKey
}
public init(dataOfPublicKey publicKeyData:Data,
dataOfPrivateKey privateKeyData:Data,
withPasswordOfPrivateKey password:String = ""){
self.publicKey = rsa_publickey_from_data(publicKeyData)!
self.privateKey = rsa_privatekey_from_data(privateKeyData, withPassword: password)!
}
/* Generate RSA instance from file of public key and private key
- parameter publicKeyFilename: filename of publicKey
- parameter privateKeyFilename: filename of privateKey
- parameter password: password or empty if not set
- returns: RSA instance if succeed or nil if failed
*/
public init?(filenameOfPulbicKey publicKeyFilename:String,
filenameOfPrivateKey privateKeyFilename:String, withPasswordOfPrivateKey password:String = ""){
let publicKeyData = try? Data(contentsOf: URL(fileURLWithPath: publicKeyFilename))
let privateKeyData = try? Data(contentsOf: URL(fileURLWithPath: privateKeyFilename))
guard let _publicKeyData = publicKeyData, let _privateKeyData = privateKeyData else {
return nil
}
self.publicKey = rsa_publickey_from_data(_publicKeyData)
self.privateKey = rsa_privatekey_from_data(_privateKeyData, withPassword: password)!
}
}
// MARK: - encrypt
extension RSA {
/// Encrypt with privateKey
public func encrypt(_ data:Data) -> Data? {
return rsa_encrypt(data, withKey: self.publicKey)
}
/// Decrypt with publicKey
public func decrypt(_ data:Data) -> Data? {
return rsa_decrypt(data, withKey: self.privateKey)
}
/// Decrypt a hexadecimal string with publicKey
public func decrypt(fromHexString hexString:String) -> Data? {
let data = hexString.dataFromHexadecimalString()
guard let _data = data else {
return nil
}
return self.decrypt(_data as Data)
}
/// Decrypt a base64 string with publicKey
public func decrypt(fromBase64String base64String:String) -> Data? {
let data = Data(base64Encoded: base64String, options: NSData.Base64DecodingOptions())
guard let _data = data else {
return nil
}
return self.decrypt(_data)
}
}
// MARK: - sign
extension RSA {
/// Sign data with digest algorithm
public func sign(_ algorithm:RSAAlgorithm,inputData:Data) -> Data? {
return rsa_sign(inputData, withAlgorithm: algorithm, withKey: self.privateKey)
}
/// Verify signature with algorithm
public func verify(_ algorithm:RSAAlgorithm,inputData:Data, signedData:Data) -> Bool {
return rsa_verify(inputData, signedData: signedData, withAlgorithm: algorithm, whthKey: self.publicKey)
}
}
|
7c57e1f79deafde8302985dc8acd6aad
| 38.459091 | 156 | 0.659832 | false | false | false | false |
edx/edx-app-ios
|
refs/heads/master
|
Source/ChromeCastButtonDelegate.swift
|
apache-2.0
|
1
|
//
// ChromeCastButtonDelegate.swift
// edX
//
// Created by Muhammad Umer on 10/7/19.
// Copyright © 2019 edX. All rights reserved.
//
import Foundation
import GoogleCast
/// Chrome cast button will always be added to the index one in case of more than one right navbar items
let ChromeCastButtonIndex = 1
/// Handles chrome cast button addition and removal from the navigation bar
/// This protocol will handle button addition/removal to navigation bar without consedering the video cast state
protocol ChromeCastButtonDelegate {
var chromeCastButton: GCKUICastButton { get }
var chromeCastButtonItem: UIBarButtonItem { get }
func addChromeCastButton()
func removeChromecastButton()
}
/// Handles chrome cast button addition and removal from the navigation bar
/// This protocol will handle button addition/removal to navigation bar when the video is being casted: connected state
protocol ChromeCastConnectedButtonDelegate: ChromeCastButtonDelegate {
}
/// Default implementation of Protocol ChromeCastButtonDelegate,
/// This way Controller just needs to add 'ChromeCastButtonDelegate' and it will have all desired functionality
extension ChromeCastButtonDelegate where Self: UIViewController {
/// Provides Reference to ChromeCastButton that will be added to Navigationbar
var chromeCastButton: GCKUICastButton {
let castButton = GCKUICastButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24))
castButton.tintColor = OEXStyles.shared().primaryBaseColor()
castButton.oex_addAction({ _ in
ChromeCastManager.shared.viewExpanded = true
}, for: .touchUpInside)
return castButton
}
var chromeCastButtonItem: UIBarButtonItem {
return UIBarButtonItem(customView: chromeCastButton)
}
func addChromeCastButton() {
guard let count = navigationItem.rightBarButtonItems?.count, count >= 1 else {
navigationItem.rightBarButtonItem = chromeCastButtonItem
return
}
var isAdded = false
navigationItem.rightBarButtonItems?.forEach({ item in
if item.customView is GCKUICastButton {
isAdded = true
return
}
})
if isAdded { return }
navigationItem.rightBarButtonItems?.insert(chromeCastButtonItem, at: ChromeCastButtonIndex)
}
func removeChromecastButton() {
guard let navigationBarItems = navigationItem.rightBarButtonItems else {
navigationItem.rightBarButtonItem = nil
return
}
for (index, element) in navigationBarItems.enumerated() {
if element.customView is GCKUICastButton {
navigationItem.rightBarButtonItems?.remove(at: index)
break
}
}
}
}
|
4ac85e6ad1c68b26ea503db212798cf3
| 35.512821 | 119 | 0.691713 | false | false | false | false |
NunoAlexandre/broccoli_mobile
|
refs/heads/master
|
Project Civ-1/Pods/Eureka/Source/Rows/Common/DateInlineFieldRow.swift
|
mit
|
2
|
// DateInlineFieldRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class DateInlineCell : Cell<Date>, CellType {
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
open class _DateInlineFieldRow: Row<DateInlineCell>, DatePickerRowProtocol, NoValueDisplayTextConformance {
/// The minimum value for this row's UIDatePicker
open var minimumDate : Date?
/// The maximum value for this row's UIDatePicker
open var maximumDate : Date?
/// The interval between options for this row's UIDatePicker
open var minuteInterval : Int?
/// The formatter for the date picked by the user
open var dateFormatter: DateFormatter?
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
dateFormatter = DateFormatter()
dateFormatter?.locale = Locale.current
displayValueFor = { [unowned self] value in
guard let val = value, let formatter = self.dateFormatter else { return nil }
return formatter.string(from: val)
}
}
}
|
59303ee3072399e5ee872c5b517abfc5
| 33.950617 | 107 | 0.689862 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.