repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ymkim50/MFImageSlider
|
refs/heads/master
|
MFImageSlider/Classes/ImageSlider.swift
|
mit
|
1
|
//
// ImageSlider.swift
// Pods
//
// Created by Youngmin Kim on 2016. 12. 19..
//
//
import UIKit
public protocol FImageSliderDelegate: class {
func sliderValueChanged(slider: FImageSlider) // call when user is swiping slider
func sliderValueChangeEnded(slider: FImageSlider) // calls when user touchUpInside or touchUpOutside slider
}
let handleWidth: CGFloat = 14.0
let borderWidth: CGFloat = 2.0
let viewCornerRadius: CGFloat = 5.0
let animationDuration: TimeInterval = 0.1// speed when slider change position on tap
public class FImageSlider: UIView {
public enum Orientation {
case vertical
case horizontal
}
public weak var delegate: FImageSliderDelegate? = nil
lazy var imageView: UIImageView = {
var imageView = UIImageView()
imageView.backgroundColor = .red
imageView.frame = self.bounds
imageView.isHidden = true
return imageView
}()
public var backgroundImage: UIImage? {
get {
return imageView.image
}
set {
if let image = newValue {
imageView.image = image
imageView.isHidden = false
} else {
imageView.image = nil
imageView.isHidden = true
}
}
}
lazy var foregroundView: UIView = {
var view = UIView()
return view
}()
lazy var handleView: UIView = {
var view = UIView()
view.layer.cornerRadius = viewCornerRadius
view.layer.masksToBounds = true
return view
}()
lazy var label: UILabel = {
var label = UILabel()
switch self.orientation {
case .vertical:
label.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI / 2.0))
label.frame = self.bounds
case .horizontal:
label.frame = self.bounds
}
label.textAlignment = .center
label.font = UIFont(name: "Helvetica", size: 24)
return label
}()
var _value: Float = 0.0
public var value: Float {
get {
return _value
}
set {
_value = newValue
self.setValue(value: _value, animated: false, completion: nil)
}
}
var orientation: Orientation = .vertical
public var isCornersHidden: Bool = false {
didSet {
if isCornersHidden {
self.layer.cornerRadius = 0.0
self.layer.masksToBounds = true
} else {
self.layer.cornerRadius = viewCornerRadius
self.layer.masksToBounds = true
}
}
}
public var isBordersHidden: Bool = false {
didSet {
if isBordersHidden {
self.layer.borderWidth = 0.0
} else {
self.layer.borderWidth = borderWidth
}
}
}
public var isHandleHidden: Bool = false {
didSet {
if isHandleHidden {
handleView.isHidden = true
handleView.removeFromSuperview()
} else {
insertSubview(handleView, aboveSubview: label)
handleView.isHidden = false
}
}
}
public var foregroundColor: UIColor? {
get {
return foregroundView.backgroundColor
}
set {
foregroundView.backgroundColor = newValue
}
}
public var handleColor: UIColor? {
get {
return handleView.backgroundColor
}
set {
handleView.backgroundColor = newValue
}
}
public var borderColor: UIColor? {
get {
if let cgColor = self.layer.borderColor {
return UIColor(cgColor: cgColor)
} else {
return nil
}
}
set {
return self.layer.borderColor = newValue?.cgColor
}
}
public var text: String? {
get {
return self.label.text
}
set {
self.label.text = newValue
}
}
public var font: UIFont! {
get {
return self.label.font
}
set {
self.label.font = newValue
}
}
public var textColor: UIColor! {
get {
return self.label.textColor
}
set {
self.label.textColor = newValue
}
}
public init(frame: CGRect, orientation: Orientation) {
super.init(frame: frame)
self.orientation = orientation
initSlider()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
if self.frame.width > self.frame.height {
orientation = .horizontal
} else {
orientation = .vertical
}
initSlider()
}
}
extension FImageSlider {
func initSlider() {
addSubview(imageView)
addSubview(foregroundView)
addSubview(label)
addSubview(handleView)
self.layer.cornerRadius = viewCornerRadius
self.layer.masksToBounds = true
self.layer.borderWidth = borderWidth
// set default value for slider. Value should be between 0 and 1
self.setValue(value: 0.0, animated: false, completion: nil)
}
func setValue(value: Float, animated: Bool, completion: ((Bool) -> Void)? = nil) {
assert(value >= 0.0 && value <= 1.0, "Value must between 0 and 1")
let calcValue = max(0, min(value, 1))
var point: CGPoint = .zero
switch orientation {
case .vertical:
point = CGPoint(x: 0, y: CGFloat(1 - calcValue) * self.frame.height)
case .horizontal:
point = CGPoint(x: CGFloat(calcValue) * self.frame.width, y: 0)
}
if animated {
UIView.animate(withDuration: animationDuration, animations: {
self.changeStartForegroundView(withPoint: point)
}, completion: { (completed) in
if completed {
completion?(completed)
}
})
} else {
changeStartForegroundView(withPoint: point)
}
}
}
// MARK: - Change slider forground with point
extension FImageSlider {
func changeStartForegroundView(withPoint point: CGPoint) {
var calcPoint = point
switch orientation {
case .vertical:
calcPoint.y = max(0, min(calcPoint.y, self.frame.height))
self._value = Float(1.0 - (calcPoint.y / self.frame.height))
self.foregroundView.frame = CGRect(x: 0.0, y: self.frame.height, width: self.frame.width, height: calcPoint.y - self.frame.height)
if !isHandleHidden {
if foregroundView.frame.origin.y <= 0 {
handleView.frame = CGRect(x: borderWidth,
y: 0.0,
width: self.frame.width - borderWidth * 2,
height: handleWidth)
} else if foregroundView.frame.origin.y >= self.frame.height {
handleView.frame = CGRect(x: borderWidth,
y: self.frame.height - handleWidth,
width: self.frame.width - borderWidth * 2,
height: handleWidth)
} else {
handleView.frame = CGRect(x: borderWidth,
y: foregroundView.frame.origin.y - handleWidth / 2,
width: self.frame.width - borderWidth * 2,
height: handleWidth)
}
}
case .horizontal:
calcPoint.x = max(0, min(calcPoint.x, self.frame.width))
self._value = Float(calcPoint.x / self.frame.width)
self.foregroundView.frame = CGRect(x: 0, y: 0, width: calcPoint.x, height: self.frame.height)
if !isHandleHidden {
if foregroundView.frame.width <= 0 {
handleView.frame = CGRect(x: 0,
y: borderWidth,
width: handleWidth,
height: foregroundView.frame.height - borderWidth)
self.delegate?.sliderValueChanged(slider: self) // or use sliderValueChangeEnded method
} else if foregroundView.frame.width >= self.frame.width {
handleView.frame = CGRect(x: foregroundView.frame.width - handleWidth,
y: borderWidth,
width: handleWidth,
height: foregroundView.frame.height - borderWidth * 2)
self.delegate?.sliderValueChanged(slider: self) // or use sliderValueChangeEnded method
} else {
handleView.frame = CGRect(x: foregroundView.frame.width - handleWidth / 2,
y: borderWidth,
width: handleWidth,
height: foregroundView.frame.height - borderWidth * 2)
}
}
}
}
}
// MARK: - Touch events
extension FImageSlider {
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let point = touch.location(in: self)
switch orientation {
case .vertical:
if !(point.y < 0) && !(point.y > self.frame.height) {
changeStartForegroundView(withPoint: point)
}
case .horizontal:
if !(point.x < 0) && !(point.x > self.frame.width) {
changeStartForegroundView(withPoint: point)
}
}
if point.x > 0 && point.x <= self.frame.width - handleWidth {
delegate?.sliderValueChanged(slider: self)
}
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else {
return
}
let point = touch.location(in: self)
UIView.animate(withDuration: animationDuration, animations: {
self.changeStartForegroundView(withPoint: point)
}) { (completed) in
self.delegate?.sliderValueChangeEnded(slider: self)
}
}
}
|
26756bea65a27d3b7fff933291ad13ae
| 23.396694 | 133 | 0.630759 | false | false | false | false |
BridgeTheGap/KRWalkThrough
|
refs/heads/master
|
KRWalkThrough/Classes/TutorialManager.swift
|
mit
|
1
|
//
// TutorialManager.swift
// Tutorial
//
// Created by Joshua Park on 5/27/16.
// Copyright © 2016 Knowre. All rights reserved.
//
import UIKit
open class TutorialManager: NSObject {
open static let shared = TutorialManager()
open var shouldShowTutorial = true
open private(set) var items = [String: TutorialItem]()
open private(set) var currentItem: TutorialItem?
fileprivate let blankItem: TutorialItem
fileprivate let transparentItem: TutorialItem
fileprivate override init() {
let blankView = TutorialView(frame: UIScreen.main.bounds)
blankItem = TutorialItem(view: blankView, identifier: "blankItem")
let transparentView = TutorialView(frame: UIScreen.main.bounds)
transparentView.backgroundColor = UIColor.clear
transparentItem = TutorialItem(view: transparentView, identifier: "transparentItem")
}
open func register(item: TutorialItem) {
items[item.identifier] = item
}
open func deregister(item: TutorialItem) {
items[item.identifier] = nil
}
open func deregisterAllItems() {
for key in items.keys {
items[key] = nil
}
}
open func performNextAction() {
currentItem?.nextAction?()
}
open func showTutorial(withIdentifier identifier: String) {
guard shouldShowTutorial else {
print("TutorialManager.shouldShowTutorial = false\nTutorial Manager will return without showing tutorial.")
return
}
guard let window = UIApplication.shared.delegate?.window else {
fatalError("UIApplication delegate's window is missing.")
}
guard let item = items[identifier] else {
print("ERROR: \(TutorialManager.self) line #\(#line) - \(#function)\n** Reason: No registered item with identifier: \(identifier)")
return
}
if blankItem.view.superview != nil { blankItem.view.removeFromSuperview() }
if transparentItem.view.superview != nil { transparentItem.view.removeFromSuperview() }
window?.addSubview(item.view)
window?.setNeedsLayout()
if currentItem?.view.superview != nil { currentItem?.view.removeFromSuperview() }
currentItem = item
}
open func showBlankItem(withAction action: Bool = false) {
UIApplication.shared.delegate!.window!!.addSubview(blankItem.view)
UIApplication.shared.delegate!.window!!.setNeedsLayout()
if action { currentItem?.nextAction?() }
currentItem?.view.removeFromSuperview()
currentItem = nil
}
open func showTransparentItem(withAction action: Bool = false) {
UIApplication.shared.delegate!.window!!.addSubview(transparentItem.view)
UIApplication.shared.delegate!.window!!.setNeedsLayout()
if action { currentItem?.nextAction?() }
currentItem?.view.removeFromSuperview()
currentItem = nil
}
open func hideTutorial(withAction action: Bool = false) {
if action { currentItem?.nextAction?() }
currentItem?.view.removeFromSuperview()
currentItem = nil
}
}
|
56d25d18d577a807bcd7746fed70ddaf
| 32.84375 | 143 | 0.643583 | false | false | false | false |
Egibide-DAM/swift
|
refs/heads/master
|
02_ejemplos/06_tipos_personalizados/03_propiedades/05_sintaxis_abreviada_setter.playground/Contents.swift
|
apache-2.0
|
1
|
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct AlternativeRect {
var origin = Point()
var size = Size()
var center: Point {
get {
let centerX = origin.x + (size.width / 2)
let centerY = origin.y + (size.height / 2)
return Point(x: centerX, y: centerY)
}
set {
origin.x = newValue.x - (size.width / 2)
origin.y = newValue.y - (size.height / 2)
}
}
}
|
62609f00667fe9347f8a9e6b5c924063
| 21.217391 | 54 | 0.48728 | false | false | false | false |
WangWenzhuang/ZKProgressHUD
|
refs/heads/master
|
Demo/Demo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Demo
//
// Created by 王文壮 on 2017/3/10.
// Copyright © 2017年 WangWenzhuang. All rights reserved.
//
import UIKit
class ViewController: UITableViewController {
var screenWidth: CGFloat {
return UIScreen.main.bounds.size.width
}
let cellIdentifier = "cell"
lazy var actionTexts = ["show", "show with status", "showProgress", "showProgress with status", "shwoImage", "showImage with status", "showInfo", "showSuccess", "showError", "showMessage", "showGif", "showGif with status"]
lazy var headerTexts = ["动画显示/隐藏样式","遮罩样式", "加载样式", "方法", "其它"]
var progressValue: CGFloat = 0
lazy var animationShowStyles = [(text: "fade", animationShowStyle: ZKProgressHUDAnimationShowStyle.fade), (text: "zoom", animationShowStyle: ZKProgressHUDAnimationShowStyle.zoom), (text: "flyInto", animationShowStyle: ZKProgressHUDAnimationShowStyle.flyInto)]
var currentAnimationShowStyleIndex = 0
lazy var maskStyles = [(text: "visible", maskStyle: ZKProgressHUDMaskStyle.visible), (text: "hide", maskStyle: ZKProgressHUDMaskStyle.hide)]
var currentMaskStyleIndex = 0
lazy var animationStyles = [(text: "circle", animationStyle: ZKProgressHUDAnimationStyle.circle), (text: "system", animationStyle: ZKProgressHUDAnimationStyle.system)]
var currentAnimationStyleIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
let backBarButtonItem = UIBarButtonItem()
backBarButtonItem.title = ""
self.navigationItem.backBarButtonItem = backBarButtonItem
self.title = "ZKProgressHUD"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return self.headerTexts.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 3:
return self.actionTexts.count
case 4:
return 2
default:
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier)
cell?.accessoryType = .none
if indexPath.section == 0 {
cell?.textLabel?.text = self.animationShowStyles[self.currentAnimationShowStyleIndex].text
cell?.accessoryType = .disclosureIndicator
} else if indexPath.section == 1 {
cell?.textLabel?.text = self.maskStyles[self.currentMaskStyleIndex].text
cell?.accessoryType = .disclosureIndicator
} else if indexPath.section == 2 {
cell?.textLabel?.text = self.animationStyles[self.currentAnimationStyleIndex].text
cell?.accessoryType = .disclosureIndicator
} else if indexPath.section == 3 {
cell?.textLabel?.text = self.actionTexts[indexPath.row]
} else {
if indexPath.row == 0 {
cell?.textLabel?.text = "临时使用一次字体"
} else {
cell?.textLabel?.text = "临时使用一次自动消失时间"
}
}
return cell!
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
if indexPath.section == 0 {
self.pushSelectView(tag: 0, title: "选择动画显示/隐藏样式", data: self.animationShowStyles)
} else if indexPath.section == 1 {
self.pushSelectView(tag: 1, title: "选择遮罩样式", data: self.maskStyles)
} else if indexPath.section == 2 {
self.pushSelectView(tag: 2, title: "选择加载样式", data: self.animationStyles)
} else if indexPath.section == 3 {
if indexPath.row > 9 {
ZKProgressHUD.setEffectStyle(.extraLight)
} else {
ZKProgressHUD.setEffectStyle(.dark)
}
if indexPath.row == 0 {
ZKProgressHUD.show()
ZKProgressHUD.dismiss(2.5)
} else if indexPath.row == 1 {
ZKProgressHUD.show("正在拼命的加载中🏃🏃🏃")
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + .seconds(2), execute: {
DispatchQueue.main.async {
ZKProgressHUD.dismiss()
ZKProgressHUD.showInfo("加载完成😁😁😁")
}
})
} else if indexPath.row == 2 {
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.showProgressTimerHandler(timer:)), userInfo: nil, repeats: true)
} else if indexPath.row == 3 {
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.showProgressTimerHandler(timer:)), userInfo: "上传中...", repeats: true)
} else if indexPath.row == 4 {
ZKProgressHUD.showImage(UIImage(named: "image"))
} else if indexPath.row == 5 {
ZKProgressHUD.showImage(UIImage(named: "image"), status: "图片会自动消失😏😏😏")
} else if indexPath.row == 6 {
ZKProgressHUD.showInfo("Star 一下吧😙😙😙")
} else if indexPath.row == 7 {
ZKProgressHUD.showSuccess("操作成功👏👏👏")
} else if indexPath.row == 8 {
ZKProgressHUD.showError("出现错误了😢😢😢")
} else if indexPath.row == 9 {
ZKProgressHUD.showMessage("开始使用 ZKProgressHUD 吧")
} else if indexPath.row == 10 {
ZKProgressHUD.showGif(gifUrl: Bundle.main.url(forResource: "loding", withExtension: "gif"), gifSize: 80)
ZKProgressHUD.dismiss(2)
} else if indexPath.row == 11 {
ZKProgressHUD.showGif(gifUrl: Bundle.main.url(forResource: "loding", withExtension: "gif"), gifSize: 80, status: "正在拼命的加载中🏃🏃🏃")
ZKProgressHUD.dismiss(2)
}
} else if indexPath.section == 4 {
if indexPath.row == 0 {
ZKProgressHUD.showMessage("临时使用一次字体", onlyOnceFont: UIFont.boldSystemFont(ofSize: 20))
} else {
ZKProgressHUD.showMessage("临时使用一次自动消失时间:10秒", autoDismissDelay: 10)
}
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.headerTexts[section]
}
@objc func showProgressTimerHandler(timer: Timer) {
if self.progressValue >= 100 {
if timer.isValid {
timer.invalidate()
}
ZKProgressHUD.dismiss()
self.progressValue = 0
} else {
self.progressValue += 5
if let status = timer.userInfo {
ZKProgressHUD.showProgress(self.progressValue / 100, status: status as? String)
} else {
ZKProgressHUD.showProgress(self.progressValue / 100)
}
}
}
func pushSelectView(tag: Int, title: String, data: [Any]) {
let selectViewController = SelectViewController()
selectViewController.tag = tag
selectViewController.title = title
selectViewController.data = data
selectViewController.delegate = self
self.navigationController?.pushViewController(selectViewController, animated: true)
}
}
extension ViewController: SelectViewControllerDelegate {
func selected(selectViewController: SelectViewController, selectIndex: Int) {
if selectViewController.tag == 0 {
self.currentAnimationShowStyleIndex = selectIndex
ZKProgressHUD.setAnimationShowStyle(self.animationShowStyles[self.currentAnimationShowStyleIndex].animationShowStyle)
} else if selectViewController.tag == 1 {
self.currentMaskStyleIndex = selectIndex
ZKProgressHUD.setMaskStyle(self.maskStyles[self.currentMaskStyleIndex].maskStyle)
} else {
self.currentAnimationStyleIndex = selectIndex
ZKProgressHUD.setAnimationStyle(self.animationStyles[self.currentAnimationStyleIndex].animationStyle)
}
self.tableView.reloadData()
}
func tableViewCellValue(selectViewController: SelectViewController, obj: Any) -> (text: String, isCheckmark: Bool) {
if selectViewController.tag == 0 {
let animationShowStyle = obj as! (text: String, animationShowStyle: ZKProgressHUDAnimationShowStyle)
return (text: animationShowStyle.text, isCheckmark: animationShowStyle.text == self.animationShowStyles[self.currentAnimationShowStyleIndex].text)
} else if selectViewController.tag == 1 {
let maskStyle = obj as! (text: String, maskStyle: ZKProgressHUDMaskStyle)
return (text: maskStyle.text, isCheckmark: maskStyle.text == self.maskStyles[self.currentMaskStyleIndex].text)
} else {
let animationStyle = obj as! (text: String, animationStyle: ZKProgressHUDAnimationStyle)
return (text: animationStyle.text, isCheckmark: animationStyle.text == self.animationStyles[self.currentAnimationStyleIndex].text)
}
}
}
|
4d47abe4dc9e563a56d74b73d16e40e4
| 45.960199 | 263 | 0.632164 | false | false | false | false |
firebase/firebase-ios-sdk
|
refs/heads/master
|
scripts/health_metrics/generate_code_coverage_report/Sources/BinarySizeReportGenerator/BinarySizeReportGeneration.swift
|
apache-2.0
|
1
|
/*
* Copyright 2021 Google LLC
*
* 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 ArgumentParser
import Foundation
import Utils
private enum Constants {}
extension Constants {
// Binary Size Metrics flag for the Metrics Service.
static let metric = "BinarySize"
static let cocoapodSizeReportFile = "binary_report.json"
}
/// Pod Config
struct PodConfigs: Codable {
let pods: [Pod]
}
struct Pod: Codable {
let sdk: String
let path: String
}
/// Cocoapods-size tool report,
struct SDKBinaryReport: Codable {
let combinedPodsExtraSize: Int
enum CodingKeys: String, CodingKey {
case combinedPodsExtraSize = "combined_pods_extra_size"
}
}
/// Metrics Service API request data
public struct BinaryMetricsReport: Codable {
let metric: String
let results: [Result]
let log: String
}
public struct Result: Codable {
let sdk, type: String
let value: Int
}
extension BinaryMetricsReport {
func toData() -> Data {
let jsonData = try! JSONEncoder().encode(self)
return jsonData
}
}
func CreatePodConfigJSON(of sdks: [String], from sdk_dir: URL) throws {
var pods: [Pod] = []
for sdk in sdks {
let pod = Pod(sdk: sdk, path: sdk_dir.path)
pods.append(pod)
}
let podConfigs = PodConfigs(pods: pods)
try JSONParser.writeJSON(of: podConfigs, to: "./cocoapods_source_config.json")
}
// Create a JSON format data prepared to send to the Metrics Service.
func CreateMetricsRequestData(of sdks: [String], type: String,
log: String) throws -> BinaryMetricsReport {
var reports: [Result] = []
// Create a report for each individual SDK and collect all of them into reports.
for sdk in sdks {
// Create a report, generated by cocoapods-size, for each SDK. `.stdout` is used
// since `pipe` could cause the tool to hang. That is probably caused by cocopod-size
// is using pipe and a pipe is shared by multiple parent/child process and cause
// deadlock. `.stdout` is a quick way to resolve at the moment. The difference is
// that `.stdout` will print out logs in the console while pipe can assign logs a
// variable.
Shell.run(
"cd cocoapods-size && python3 measure_cocoapod_size.py --cocoapods \(sdk) --spec_repos specsstaging master --cocoapods_source_config ../cocoapods_source_config.json --json \(Constants.cocoapodSizeReportFile)",
stdout: .stdout
)
let SDKBinarySize = try JSONParser.readJSON(
of: SDKBinaryReport.self,
from: "cocoapods-size/\(Constants.cocoapodSizeReportFile)"
)
// Append reports for data for API request to the Metrics Service.
reports.append(Result(sdk: sdk, type: type, value: SDKBinarySize.combinedPodsExtraSize))
}
let metricsRequestReport = BinaryMetricsReport(
metric: Constants.metric,
results: reports,
log: log
)
return metricsRequestReport
}
public func CreateMetricsRequestData(SDK: [String], SDKRepoDir: URL,
logPath: String) throws -> BinaryMetricsReport? {
try CreatePodConfigJSON(of: SDK, from: SDKRepoDir)
let data = try CreateMetricsRequestData(
of: SDK,
type: "CocoaPods",
log: logPath
)
return data
}
|
6a37a28ed60d67ef9ca8dd988e68137b
| 30.649573 | 215 | 0.704294 | false | true | false | false |
narner/AudioKit
|
refs/heads/master
|
Playgrounds/AudioKitPlaygrounds/Playgrounds/Effects.playground/Pages/Flat Frequency Response Reverb.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: ## Flat Frequency Response Reverb
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var reverb = AKFlatFrequencyResponseReverb(player, loopDuration: 0.1)
reverb.reverbDuration = 1
AudioKit.output = reverb
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Flat Frequency Response Reverb")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKSlider(property: "Duration", value: reverb.reverbDuration, range: 0 ... 5) { sliderValue in
reverb.reverbDuration = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
|
e424eb989300897a6778fbe4f8d875dd
| 25.25 | 109 | 0.752381 | false | false | false | false |
laurentVeliscek/AudioKit
|
refs/heads/master
|
AudioKit/Common/Playgrounds/Synthesis.playground/Pages/Noise Generators.xcplaygroundpage/Contents.swift
|
mit
|
2
|
//: ## Pink and White Noise Generators
//:
import XCPlayground
import AudioKit
var white = AKWhiteNoise(amplitude: 0.1)
var pink = AKPinkNoise(amplitude: 0.1)
var whitePinkMixer = AKDryWetMixer(white, pink, balance: 0.5)
AudioKit.output = whitePinkMixer
AudioKit.start()
pink.start()
white.start()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
override func setup() {
addTitle("Pink and White Noise")
addSubview(AKPropertySlider(
property: "Volume",
format: "%0.2f",
value: pink.amplitude,
color: AKColor.cyanColor()
) { amplitude in
pink.amplitude = amplitude
white.amplitude = amplitude
})
addSubview(AKPropertySlider(
property: "White to Pink Balance",
format: "%0.2f",
value: whitePinkMixer.balance,
color: AKColor.magentaColor()
) { balance in
whitePinkMixer.balance = balance
})
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = PlaygroundView()
|
beb32c0fbdc81ee830b056572be01526
| 24.355556 | 61 | 0.629273 | false | false | false | false |
oisdk/ProtocolTester
|
refs/heads/master
|
ProtocolTesterTests/RangeReplaceableCollectionType.swift
|
mit
|
1
|
import XCTest
import Foundation
extension RangeReplaceableCollectionType where
Self : SameOrder,
Self : MutableSliceable,
Generator.Element == Int,
SubSequence.Generator.Element == Int,
SubSequence : FlexibleInitable {
static func test() {
testMultiPass()
testCount()
testSeqInit()
testSameEls()
testIndexing()
testFirst()
testRangeIndexing()
testSplit()
testMutIndexing()
testMutIndexSlicing()
testEmptyInit()
testReplaceRange()
}
static internal func testEmptyInit() {
let empty = Self()
XCTAssert(empty.isEmpty, "Empty initializer did not yield empty self.\nReceived: \(Array(empty))")
}
static internal func testReplaceRange() {
for randAr in randArs() {
let seq = Self(randAr)
for (iA, iS) in zip(randAr.indices, seq.indices) {
for (jA, jS) in zip(iA..<randAr.endIndex, iS..<seq.endIndex) {
var mutAr = randAr
var mutSe = seq
let replacement = (0..<arc4random_uniform(10)).map { _ in Int(arc4random_uniform(10000)) }
mutAr.replaceRange(iA...jA, with: replacement)
mutSe.replaceRange(iS...jS, with: replacement)
XCTAssert(mutAr.elementsEqual(mutSe), "Range subscript replacement did not produce expected result.\nInitialized from array: \(randAr)\nTried to replace range: \(iA...jA) with \(replacement)\nExpected: \(mutAr)\nReceived: \(Array(mutSe))")
XCTAssert(mutSe.invariantPassed, "Invariant broken: \(Array(mutSe))")
}
}
}
}
}
|
cf7d3f5b2559330ba4825d3231387b66
| 33.704545 | 249 | 0.661861 | false | true | false | false |
jengelsma/cis657-summer2016-class-demos
|
refs/heads/master
|
Lecture12-PuppyFlixDemoWithUnitTests/PuppyFlix/VideoInfo.swift
|
mit
|
1
|
//
// VideoInfo.swift
// PuppyFlix
//
// Created by Jonathan Engelsma on 11/20/15.
// Copyright © 2015 Jonathan Engelsma. All rights reserved.
//
import Foundation
class VideoInfo : Equatable {
let id:String
let title:String
let description:String
let smallImageUrl:String?
let mediumImageUrl:String?
init(id: String, title: String, description: String, smallImageUrl: String?, mediumImageUrl: String?) {
self.id = id;
self.title = title;
self.description = description
self.smallImageUrl = smallImageUrl
self.mediumImageUrl = mediumImageUrl
}
}
func ==(lhs: VideoInfo, rhs: VideoInfo) -> Bool {
return lhs.id == rhs.id &&
lhs.title == rhs.title &&
lhs.description == rhs.description &&
lhs.smallImageUrl == rhs.smallImageUrl &&
lhs.mediumImageUrl == rhs.mediumImageUrl
}
|
7fec3d9261c5cbad4b06f0def956938e
| 23.324324 | 107 | 0.642222 | false | false | false | false |
zhangjk4859/MyWeiBoProject
|
refs/heads/master
|
sinaWeibo/sinaWeibo/Classes/Compose/表情选择器/EmoticonTextAttachment.swift
|
mit
|
1
|
//
// EmoticonTextAttachment.swift
// sinaWeibo
//
// Created by 张俊凯 on 16/7/27.
// Copyright © 2016年 张俊凯. All rights reserved.
//
import UIKit
class EmoticonTextAttachment: NSTextAttachment {
// 保存对应表情的文字
var chs: String?
/// 根据表情模型, 创建表情字符串
class func imageText(emoticon: Emoticon, font: UIFont) -> NSAttributedString{
// 1.创建附件
let attachment = EmoticonTextAttachment()
attachment.chs = emoticon.chs
attachment.image = UIImage(contentsOfFile: emoticon.imagePath!)
// 设置了附件的大小
let s = font.lineHeight
attachment.bounds = CGRectMake(0, -4, s, s)
// 2. 根据附件创建属性字符串
return NSAttributedString(attachment: attachment)
}
}
|
7111fa6d32d5f8e88d661d4804558a0e
| 24.517241 | 81 | 0.632432 | false | false | false | false |
tryswift/TryParsec
|
refs/heads/swift/4.0
|
excludedTests/TryParsec/Specs/HelperSpec.swift
|
mit
|
1
|
@testable import TryParsec
import Result
import Quick
import Nimble
class HelperSpec: QuickSpec
{
override func spec()
{
describe("splitAt") {
it("splitAt(1)") {
let (heads, tails) = splitAt(1)("abc" as USV)
expect(String(heads).unicodeScalars) == ["a"]
expect(String(tails).unicodeScalars) == ["b", "c"]
}
it("splitAt(0)") {
let (heads, tails) = splitAt(0)("abc" as USV)
expect(String(heads).unicodeScalars) == []
expect(String(tails).unicodeScalars) == ["a", "b", "c"]
}
it("splitAt(999)") {
let (heads, tails) = splitAt(999)("abc" as USV)
expect(String(heads).unicodeScalars) == ["a", "b", "c"]
expect(String(tails).unicodeScalars) == []
}
it("splitAt(0)(\"\")") {
let (heads, tails) = splitAt(0)("" as USV)
expect(String(heads).unicodeScalars) == []
expect(String(tails).unicodeScalars) == []
}
}
describe("trim") {
it("trims head & tail whitespaces") {
let trimmed = trim(" Trim me! ")
expect(trimmed) == "Trim me!"
}
it("doesn't trim middle whitespaces") {
let trimmed = trim("Dooooon't trrrrrim meeeee!")
expect(trimmed) == "Dooooon't trrrrrim meeeee!"
}
}
describe("RangeReplaceableCollectionType (RRC)") {
it("any RRC e.g. `ArraySlice` can initialize with SequenceType") {
let arr = ArraySlice<UnicodeScalar>("abc" as USV)
expect(Array(arr)) == Array(["a", "b", "c"])
}
}
}
}
|
6dfd4bdefe907c11ad32e3e37552f1e7
| 29.032787 | 78 | 0.465611 | false | false | false | false |
Elm-Tree-Island/Shower
|
refs/heads/master
|
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSCollectionViewSpec.swift
|
gpl-3.0
|
7
|
import Quick
import Nimble
import ReactiveCocoa
import ReactiveSwift
import Result
import AppKit
@available(macOS 10.11, *)
final class NSCollectionViewSpec: QuickSpec {
override func spec() {
var collectionView: TestCollectionView!
beforeEach {
collectionView = TestCollectionView()
}
describe("reloadData") {
var bindingSignal: Signal<(), NoError>!
var bindingObserver: Signal<(), NoError>.Observer!
var reloadDataCount = 0
beforeEach {
let (signal, observer) = Signal<(), NoError>.pipe()
(bindingSignal, bindingObserver) = (signal, observer)
reloadDataCount = 0
collectionView.reloadDataSignal.observeValues {
reloadDataCount += 1
}
}
it("invokes reloadData whenever the bound signal sends a value") {
collectionView.reactive.reloadData <~ bindingSignal
bindingObserver.send(value: ())
bindingObserver.send(value: ())
expect(reloadDataCount) == 2
}
}
}
}
@available(macOS 10.11, *)
private final class TestCollectionView: NSCollectionView {
let reloadDataSignal: Signal<(), NoError>
private let reloadDataObserver: Signal<(), NoError>.Observer
override init(frame: CGRect) {
(reloadDataSignal, reloadDataObserver) = Signal.pipe()
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
(reloadDataSignal, reloadDataObserver) = Signal.pipe()
super.init(coder: aDecoder)
}
override func reloadData() {
super.reloadData()
reloadDataObserver.send(value: ())
}
}
|
8f7d041465795aa6a9997732a543870c
| 21.846154 | 69 | 0.717845 | false | false | false | false |
material-motion/motion-transitioning-objc
|
refs/heads/develop
|
examples/PhotoAlbumTransition.swift
|
apache-2.0
|
2
|
/*
Copyright 2017-present The Material Motion Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import UIKit
import MotionTransitioning
protocol PhotoAlbumTransitionForeDelegate: class {
func foreContextView(for transition: PhotoAlbumTransition) -> UIImageView?
func toolbar(for transition: PhotoAlbumTransition) -> UIToolbar?
}
protocol PhotoAlbumTransitionBackDelegate: class {
func backContextView(for transition: PhotoAlbumTransition,
with foreViewController: UIViewController) -> UIImageView?
}
final class PhotoAlbumTransition: NSObject, Transition, TransitionWithFeasibility {
weak var backDelegate: PhotoAlbumTransitionBackDelegate?
weak var foreDelegate: PhotoAlbumTransitionForeDelegate?
init(backDelegate: PhotoAlbumTransitionBackDelegate,
foreDelegate: PhotoAlbumTransitionForeDelegate) {
self.backDelegate = backDelegate
self.foreDelegate = foreDelegate
}
func canPerformTransition(with context: TransitionContext) -> Bool {
guard let backDelegate = backDelegate else {
return false
}
return backDelegate.backContextView(for: self, with: context.foreViewController) != nil
}
func start(with context: TransitionContext) {
guard let backDelegate = backDelegate, let foreDelegate = foreDelegate else {
return
}
guard let contextView = backDelegate.backContextView(for: self,
with: context.foreViewController) else {
return
}
guard let foreImageView = foreDelegate.foreContextView(for: self) else {
return
}
let snapshotter = TransitionViewSnapshotter(containerView: context.containerView)
context.defer {
snapshotter.removeAllSnapshots()
}
foreImageView.isHidden = true
context.defer {
foreImageView.isHidden = false
}
let imageSize = foreImageView.image!.size
let fitScale = min(foreImageView.bounds.width / imageSize.width,
foreImageView.bounds.height / imageSize.height)
let fitSize = CGSize(width: fitScale * imageSize.width, height: fitScale * imageSize.height)
let snapshotContextView = snapshotter.snapshot(of: contextView,
isAppearing: context.direction == .backward)
context.compose(with: FadeTransition(target: .foreView, style: .fadeIn))
context.compose(with: SpringFrameTransition(target: .target(snapshotContextView),
size: fitSize))
if let toolbar = foreDelegate.toolbar(for: self) {
context.compose(with: SlideUpTransition(target: .target(toolbar)))
}
// This transition doesn't directly produce any animations, so we inform the context that it is
// complete here, otherwise the transition would never complete:
context.transitionDidEnd()
}
}
|
360e65041b7fc3abe776826529219cde
| 37.366667 | 99 | 0.706922 | false | false | false | false |
banxi1988/Staff
|
refs/heads/master
|
Staff/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Staff
//
// Created by Haizhen Lee on 16/2/29.
// Copyright © 2016年 banxi1988. All rights reserved.
//
import UIKit
import BXiOSUtils
import SwiftyBeaver
let log = SwiftyBeaver.self
let Images = UIImage.Asset.self
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
setupLog()
setUpAppearanceProxy()
AppUserDefaults.registerDefaults()
setupLocalNotification()
start()
return true
}
func start(){
log.debug("start")
window?.rootViewController = startEntry()
window?.makeKeyAndVisible()
log.debug("makeKeyAndVisible Down")
}
func startEntry() -> UIViewController{
#if DEBUG
// return currentDebugEntry()
#endif
let vc = MainViewController()
return UINavigationController(rootViewController: vc)
}
func currentDebugEntry() -> UIViewController{
// let vc = CompanyGeoRegionPickerViewController()
// let vc = SettingsViewController()
let vc = ArtClockViewController()
return UINavigationController(rootViewController: vc)
}
func setupLocalNotification(){
let app = UIApplication.sharedApplication()
let settings = UIUserNotificationSettings(forTypes: [.Sound,.Alert,.Badge], categories: nil)
app.registerUserNotificationSettings(settings)
app.cancelAllLocalNotifications()
}
func setupLog(){
let file = FileDestination() // log to default swiftybeaver.log file
#if DEBUG
// add log destinations. at least one is needed!
let console = ConsoleDestination() // log to Xcode Console
log.addDestination(console)
file.minLevel = .Debug
#else
file.minLevel = .Info
#endif
log.addDestination(file)
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
log.info("notification:\(notification)")
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
0693992a2c9ce50952775ac1da3646d0
| 34.111111 | 281 | 0.743935 | false | false | false | false |
witekbobrowski/Stanford-CS193p-Winter-2017
|
refs/heads/master
|
Faceit/Faceit/EmotionsViewController.swift
|
mit
|
1
|
//
// EmotionsViewController.swift
// Faceit
//
// Created by Witek on 24/04/2017.
// Copyright © 2017 Witek Bobrowski. All rights reserved.
//
import UIKit
class EmotionsViewController: UITableViewController {
fileprivate var emotionalFaces: [(name: String, expression: FacialExpression)] = [
("sad", FacialExpression(eyes: .closed, mouth: .frown)),
("happy", FacialExpression(eyes: .open, mouth: .smile)),
("worried", FacialExpression(eyes: .open, mouth: .smirk))
]
@IBAction func addEmotionalFace(from segue: UIStoryboardSegue) {
if let editor = segue.source as? ExpressionEditorViewController {
emotionalFaces.append((editor.name, editor.expression))
tableView.reloadData()
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
var destinationViewController = segue.destination
if let navigationController = destinationViewController as? UINavigationController {
destinationViewController = navigationController.visibleViewController ?? destinationViewController
}
if let faceViewController = destinationViewController as? FaceViewController,
let cell = sender as? UITableViewCell,
let indexPath = tableView.indexPath(for: cell) {
faceViewController.expression = emotionalFaces[indexPath.row].expression
faceViewController.navigationItem.title = (sender as? UIButton)?.currentTitle
} else if destinationViewController is ExpressionEditorViewController {
if let popoverPresentationController = segue.destination.popoverPresentationController {
popoverPresentationController.delegate = self
}
}
}
}
extension EmotionsViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return emotionalFaces.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Emotion Cell", for: indexPath)
cell.textLabel?.text = emotionalFaces[indexPath.row].name
return cell
}
}
extension EmotionsViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
if traitCollection.verticalSizeClass == .compact {
return .none
} else if traitCollection.horizontalSizeClass == .compact {
return .overFullScreen
} else {
return .none
}
}
}
|
12536200dcc4c04300bedaee49e75657
| 37.164384 | 142 | 0.685212 | false | false | false | false |
ymkjp/NewsPlayer
|
refs/heads/master
|
NewsPlayer/VideoTableViewCell.swift
|
mit
|
1
|
//
// VideoTableViewCell.swift
// NewsPlayer
//
// Created by YAMAMOTOKenta on 9/19/15.
// Copyright © 2015 ymkjp. All rights reserved.
//
import UIKit
import FLAnimatedImage
class VideoTableViewCell: UITableViewCell {
@IBOutlet weak var thumbnail: UIImageView!
@IBOutlet weak var abstract: UILabel!
@IBOutlet weak var indicator: UIView!
let animatedImageView = FLAnimatedImageView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// :param: index Let them know the indexPath.row, cell does not remember wchich indexPath it belongs
func render(index: Int) -> VideoTableViewCell {
if let video = ChannelModel.sharedInstance.getVideoByIndex(index) {
abstract?.numberOfLines = 0
abstract?.text = "\(video.title)\n\(video.description)"
thumbnail?.sd_setImageWithURL(NSURL(string: video.thumbnail.url))
} else {
abstract.text = "textLabel #\(index)"
}
return self
}
func addPlayingIndicator() {
indicator?.addSubview(createIndicationView())
}
func removeAllIndicator() {
guard let subviews = indicator?.subviews else {
return
}
for subview in subviews {
subview.removeFromSuperview()
}
}
func startPlayingAnimation() {
animatedImageView.startAnimating()
}
func stopPlayingAnimation() {
animatedImageView.stopAnimating()
}
private func createIndicationView() -> UIImageView {
let path = NSBundle.mainBundle().pathForResource("equalizer", ofType: "gif")!
let url = NSURL(fileURLWithPath: path)
let animatedImage = FLAnimatedImage(animatedGIFData: NSData(contentsOfURL: url))
animatedImageView.animatedImage = animatedImage
animatedImageView.frame = indicator.bounds
animatedImageView.contentMode = UIViewContentMode.ScaleAspectFit
return animatedImageView
}
}
|
3dd4dbbab722f13cbf469170f8455bb7
| 29.39726 | 104 | 0.653898 | false | false | false | false |
apatronl/Left
|
refs/heads/master
|
Left/Services/FavoritesManager.swift
|
mit
|
1
|
//
// FavoritesManager.swift
// Left
//
// Created by Alejandrina Patron on 3/4/16.
// Copyright © 2016 Ale Patrón. All rights reserved.
//
import Foundation
class FavoritesManager {
// Singleton
static let shared = FavoritesManager()
private var favoriteRecipes = [RecipeItem]()
func addRecipe(recipe: RecipeItem) {
favoriteRecipes.append(recipe)
save()
}
func deleteRecipeAtIndex(index: Int) {
favoriteRecipes.remove(at: index)
save()
}
func recipeAtIndex(index: Int) -> RecipeItem? {
return favoriteRecipes[index]
}
func recipeCount() -> Int {
return favoriteRecipes.count
}
func archivePath() -> String? {
let directoryList = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
if let documentsPath = directoryList.first {
return documentsPath + "/Favorites"
}
assertionFailure("Could not determine where to save file.")
return nil
}
func save() {
if let theArchivePath = archivePath() {
if NSKeyedArchiver.archiveRootObject(favoriteRecipes, toFile: theArchivePath) {
print("We saved!")
} else {
assertionFailure("Could not save to \(theArchivePath)")
}
}
}
func unarchivedSavedItems() {
if let theArchivePath = archivePath() {
if FileManager.default.fileExists(atPath: theArchivePath) {
favoriteRecipes = NSKeyedUnarchiver.unarchiveObject(withFile: theArchivePath) as! [RecipeItem]
}
}
}
init() {
unarchivedSavedItems()
}
}
|
9b80d897e5ec638db8a2df7bde68969f
| 25.30303 | 110 | 0.599078 | false | false | false | false |
naoty/qiita-swift
|
refs/heads/master
|
Qiita/Qiita/Item.swift
|
mit
|
1
|
//
// Item.swift
// Qiita
//
// Created by Naoto Kaneko on 2014/12/13.
// Copyright (c) 2014年 Naoto Kaneko. All rights reserved.
//
extension Qiita {
public class Item {
public let body: String?
public let coediting: Bool?
public let createdAt: NSDate?
public let id: String?
public let isPrivate: Bool?
public let title: String?
public let updatedAt: NSDate?
public let url: NSURL?
public let user: User?
private var dateFormatter: NSDateFormatter {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
return formatter
}
public init?(json: AnyObject) {
if let jsonObject = json as? NSDictionary {
if let body = jsonObject["body"] as? String {
self.body = body
}
if let coediting = jsonObject["coediting"] as? Bool {
self.coediting = coediting
}
if let createdAtTimestamp = jsonObject["created_at"] as? String {
self.createdAt = dateFormatter.dateFromString(createdAtTimestamp)
}
if let id = jsonObject["id"] as? String {
self.id = id
}
if let isPrivate = jsonObject["private"] as? Bool {
self.isPrivate = isPrivate
}
if let title = jsonObject["title"] as? String {
self.title = title
}
if let updatedAtTimestamp = jsonObject["updated_at"] as? String {
self.updatedAt = dateFormatter.dateFromString(updatedAtTimestamp)
}
if let urlString = jsonObject["url"] as? String {
self.url = NSURL(string: urlString)!
}
if let userJSONObject: AnyObject = jsonObject["user"] {
self.user = User(json: userJSONObject)
}
} else {
return nil
}
}
}
}
|
46b0c1d6e075b9f3cdacaad26541ab91
| 34.344262 | 85 | 0.499768 | false | false | false | false |
robpeach/test
|
refs/heads/master
|
SwiftPages/PagedScrollViewController.swift
|
mit
|
1
|
//
// PagedScrollViewController.swift
// Britannia v2
//
// Created by Rob Mellor on 11/07/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import SDWebImage
class PagedScrollViewController: UIViewController, UIScrollViewDelegate, UIGestureRecognizerDelegate {
var arrGallery : NSMutableArray!
var imageCache : [String:UIImage]!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet var lblPhotoCount: UILabel!
var pageViews: [UIImageView?] = []
var intPage : NSInteger!
@IBOutlet var viewLower: UIView!
@IBOutlet var viewUpper: UIView!
@IBOutlet weak var newPageView: UIView!
//var newPageView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
scrollView.delegate = self
scrollView.needsUpdateConstraints()
scrollView.setNeedsLayout()
scrollView.layoutIfNeeded()
//
//
//Manually added constraints at runtime
let constraintTS = NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: viewUpper, attribute: .Bottom, multiplier: 1.0, constant: 0)
let constraintBS = NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: viewLower, attribute: .Top, multiplier: 1.0, constant: 0)
let constraintLS = NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0)
let constraintRS = NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1.0, constant: 0)
view.addConstraint(constraintTS)
view.addConstraint(constraintBS)
view.addConstraint(constraintLS)
view.addConstraint(constraintRS)
}
override func viewWillAppear(animated: Bool) {
centerScrollViewContents()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
centerScrollViewContents()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let pageCount = arrGallery.count
for _ in 0..<pageCount {
pageViews.append(nil)
}
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * CGFloat(arrGallery.count), pagesScrollViewSize.height)
scrollView.contentOffset.x = CGFloat(intPage) * self.view.frame.size.width
lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count)
loadVisiblePages()
let recognizer = UITapGestureRecognizer(target: self, action:#selector(PagedScrollViewController.handleTap(_:)))
// 4
recognizer.delegate = self
scrollView.addGestureRecognizer(recognizer)
scrollView.showsVerticalScrollIndicator = false
viewUpper.alpha = 1.0
viewLower.alpha = 1.0
}
func handleTap(recognizer: UITapGestureRecognizer) {
viewUpper.alpha = 1.0
viewLower.alpha = 1.0
}
func loadPage(page: Int) {
if page < 0 || page >= arrGallery.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let page = pageViews[page] {
// Do nothing. The view is already loaded.
} else {
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
let rowData: NSDictionary = arrGallery[page] as! NSDictionary
let urlString: String = rowData["pic"] as! String
let imgURL = NSURL(string: urlString)
// If this image is already cached, don't re-download
if let img = imageCache[urlString] {
let newPageView = UIImageView(image: img)
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
scrollView.addSubview(newPageView)
pageViews[page] = newPageView
}
else {
SDWebImageManager.sharedManager().downloadImageWithURL(imgURL, options: [],progress: nil, completed: {[weak self] (image, error, cached, finished, url) in
if error == nil {
// let image = UIImage(data: data!)
//On Main Thread
dispatch_async(dispatch_get_main_queue()){
self?.imageCache[urlString] = image
// Update the cell
let newPageView = UIImageView(image: image)
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
self?.scrollView.addSubview(newPageView)
// 4
self?.pageViews[page] = newPageView
}
}
else {
print("Error: \(error!.localizedDescription)")
}
})
}
}
}
func purgePage(page: Int) {
if page < 0 || page >= arrGallery.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let pageView = pageViews[page] {
pageView.removeFromSuperview()
pageViews[page] = nil
}
}
func loadVisiblePages() {
// First, determine which page is currently visible
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
intPage = page
// Update the page control
lblPhotoCount.text = String(format: "%d of %d Photos",intPage+1, arrGallery.count)
// Work out which pages you want to load
let firstPage = max(0,page - 1)
let lastPage = min(page + 1, arrGallery.count - 1)
// Purge anything before the first page
for index in 0..<firstPage {
purgePage(index)
}
// Load pages in our range
for index in firstPage...lastPage {
loadPage(index)
}
// Purge anything after the last page
for index in (lastPage + 1)..<(arrGallery.count) {
purgePage(index)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
// Load the pages that are now on screen
if scrollView.contentSize.width > 320{
viewLower.alpha = 1
viewUpper.alpha = 1
loadVisiblePages()
}
}
@IBAction func btnBackTapped(sender: AnyObject) {
scrollView.delegate = nil
if let navController = self.navigationController {
navController.popToRootViewControllerAnimated(true)
}
}
@IBAction func btnShareTapped(sender: AnyObject) {
var sharingItems = [AnyObject]()
let rowData: NSDictionary = arrGallery[intPage] as! NSDictionary
// Grab the artworkUrl60 key to get an image URL for the app's thumbnail
let urlString: String = rowData["pic"] as! String
// let imgURL = NSURL(string: urlString)
let img = imageCache[urlString]
sharingItems.append(img!)
// sharingItems.append(imgURL!)
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
@IBAction func btnGalleryTapped(sender: AnyObject) {
scrollView.delegate = nil
if let navController = self.navigationController {
navController.popViewControllerAnimated(true)
}
}
func centerScrollViewContents() {
let boundsSize = scrollView.bounds.size
var contentsFrame = newPageView.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.height - self.topLayoutGuide.length) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
newPageView.frame = contentsFrame
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
//LightContent
return UIStatusBarStyle.LightContent
//Default
//return UIStatusBarStyle.Default
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
c06e302c831f4434f2e8926011118974
| 31.156667 | 170 | 0.561107 | false | false | false | false |
terietor/GTForms
|
refs/heads/master
|
Source/Forms/ControlLabelView.swift
|
mit
|
1
|
// Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import SnapKit
class ControlLabelView<V: UILabel>: UIView {
var formAxis = FormAxis.horizontal
let controlLabel: UILabel = {
let label = V()
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var control: UIView! {
didSet {
self.control.translatesAutoresizingMaskIntoConstraints = false
addSubview(self.control)
}
}
init() {
super.init(frame: CGRect.zero)
self.translatesAutoresizingMaskIntoConstraints = false
addSubview(self.controlLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("Missing Implementation")
}
func configureView(_ makeConstraints: (UILabel, UIView) -> ()) {
makeConstraints(self.controlLabel, self.control)
}
}
|
e7f402d1fdad6b86b550a0597c2dfe38
| 34.736842 | 82 | 0.709867 | false | false | false | false |
JohnEstropia/CoreStore
|
refs/heads/develop
|
Sources/ObjectSnapshot.swift
|
mit
|
1
|
//
// ObjectSnapshot.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreData
#if canImport(UIKit)
import UIKit
#elseif canImport(AppKit)
import AppKit
#endif
// MARK: - ObjectSnapshot
/**
The `ObjectSnapshot` is a full copy of a `DynamicObject`'s properties at a given point in time. This is useful especially when keeping thread-safe state values, in ViewModels for example. Since this is a value type, any changes in this `struct` does not affect the actual object.
*/
@dynamicMemberLookup
public struct ObjectSnapshot<O: DynamicObject>: ObjectRepresentation, Hashable {
// MARK: Public
public func dictionaryForValues() -> [String: Any] {
return self.values
}
// MARK: AnyObjectRepresentation
public func objectID() -> O.ObjectID {
return self.id
}
public func cs_dataStack() -> DataStack? {
return self.context.parentStack
}
// MARK: ObjectRepresentation
public typealias ObjectType = O
public func asPublisher(in dataStack: DataStack) -> ObjectPublisher<O> {
let context = dataStack.unsafeContext()
return context.objectPublisher(objectID: self.id)
}
public func asReadOnly(in dataStack: DataStack) -> O? {
return dataStack.unsafeContext().fetchExisting(self.id)
}
public func asEditable(in transaction: BaseDataTransaction) -> O? {
return transaction.unsafeContext().fetchExisting(self.id)
}
public func asSnapshot(in dataStack: DataStack) -> ObjectSnapshot<O>? {
let context = dataStack.unsafeContext()
return ObjectSnapshot<O>(objectID: self.id, context: context)
}
public func asSnapshot(in transaction: BaseDataTransaction) -> ObjectSnapshot<O>? {
let context = transaction.unsafeContext()
return ObjectSnapshot<O>(objectID: self.id, context: context)
}
// MARK: Equatable
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
return lhs.id == rhs.id
&& (lhs.generation == rhs.generation || lhs.valuesRef == rhs.valuesRef)
}
// MARK: Hashable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
hasher.combine(self.valuesRef)
}
// MARK: Internal
internal init?(objectID: O.ObjectID, context: NSManagedObjectContext) {
guard let values = O.cs_snapshotDictionary(id: objectID, context: context) else {
return nil
}
self.id = objectID
self.context = context
self.values = values
self.generation = .init()
}
internal var cs_objectID: O.ObjectID {
return self.objectID()
}
// MARK: FilePrivate
fileprivate var values: [String: Any] {
didSet {
self.generation = .init()
}
}
// MARK: Private
private let id: O.ObjectID
private let context: NSManagedObjectContext
private var generation: UUID
private var valuesRef: NSDictionary {
return self.values as NSDictionary
}
}
// MARK: - ObjectSnapshot where O: NSManagedObject
extension ObjectSnapshot where O: NSManagedObject {
/**
Returns the value for the property identified by a given key.
*/
public subscript<V: AllowedObjectiveCKeyPathValue>(dynamicMember member: KeyPath<O, V>) -> V! {
get {
let key = String(keyPath: member)
return self.values[key] as! V?
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
}
// MARK: - ObjectSnapshot where O: CoreStoreObject
extension ObjectSnapshot where O: CoreStoreObject {
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Stored<V>>) -> V {
get {
let key = String(keyPath: member)
return self.values[key] as! V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Virtual<V>>) -> V {
get {
let key = String(keyPath: member)
return self.values[key] as! V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Coded<V>>) -> V {
get {
let key = String(keyPath: member)
return self.values[key] as! V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, FieldContainer<OBase>.Relationship<V>>) -> V.PublishedType {
get {
let key = String(keyPath: member)
let context = self.context
let snapshotValue = self.values[key] as! V.SnapshotValueType
return V.cs_toPublishedType(from: snapshotValue, in: context)
}
set {
let key = String(keyPath: member)
self.values[key] = V.cs_toSnapshotType(from: newValue)
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, ValueContainer<OBase>.Required<V>>) -> V {
get {
let key = String(keyPath: member)
return self.values[key] as! V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, ValueContainer<OBase>.Optional<V>>) -> V? {
get {
let key = String(keyPath: member)
return self.values[key] as? V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, TransformableContainer<OBase>.Required<V>>) -> V {
get {
let key = String(keyPath: member)
return self.values[key] as! V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, V>(dynamicMember member: KeyPath<O, TransformableContainer<OBase>.Optional<V>>) -> V? {
get {
let key = String(keyPath: member)
return self.values[key] as? V
}
set {
let key = String(keyPath: member)
self.values[key] = newValue
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, D>(dynamicMember member: KeyPath<O, RelationshipContainer<OBase>.ToOne<D>>) -> ObjectPublisher<D>? {
get {
let key = String(keyPath: member)
guard let id = self.values[key] as? D.ObjectID else {
return nil
}
return self.context.objectPublisher(objectID: id)
}
set {
let key = String(keyPath: member)
self.values[key] = newValue?.objectID()
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, D>(dynamicMember member: KeyPath<O, RelationshipContainer<OBase>.ToManyOrdered<D>>) -> [ObjectPublisher<D>] {
get {
let key = String(keyPath: member)
let context = self.context
let ids = self.values[key] as! [D.ObjectID]
return ids.map(context.objectPublisher(objectID:))
}
set {
let key = String(keyPath: member)
self.values[key] = newValue.map({ $0.objectID() })
}
}
/**
Returns the value for the property identified by a given key.
*/
public subscript<OBase, D>(dynamicMember member: KeyPath<O, RelationshipContainer<OBase>.ToManyUnordered<D>>) -> Set<ObjectPublisher<D>> {
get {
let key = String(keyPath: member)
let context = self.context
let ids = self.values[key] as! Set<D.ObjectID>
return Set(ids.map(context.objectPublisher(objectID:)))
}
set {
let key = String(keyPath: member)
self.values[key] = Set(newValue.map({ $0.objectID() }))
}
}
}
|
b4a3ba76a69f8b17d209e6653e20b538
| 25.688312 | 280 | 0.600389 | false | false | false | false |
lyimin/EyepetizerApp
|
refs/heads/master
|
EyepetizerApp/EyepetizerApp/Controllers/PopularViewController/EYEPopularController.swift
|
mit
|
1
|
//
// EYEPopularController.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/3/10.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
import Alamofire
class EYEPopularController: EYEBaseViewController, LoadingPresenter {
var loaderView : EYELoaderView!
//MARK: --------------------------- Life Cycle --------------------------
override func viewDidLoad() {
super.viewDidLoad()
// 添加headerView
self.view.addSubview(headerView)
headerView.headerViewTitleDidClick { [unowned self](targetBtn, index) in
self.itemDidClick(index)
}
// 添加控制器
// 默认选中第一个
itemDidClick(0)
}
//MARK: --------------------------- Private Methods --------------------------
private func itemDidClick(index : Int) {
var actionController : UIViewController!
// 再添加控制器
switch index {
case 0:
if weekController == nil {
weekController = EYEPopularWeekController()
}
actionController = weekController
break
case 1:
if monthController == nil {
monthController = EYEPopularMonthController()
}
actionController = monthController
break
case 2:
if historyController == nil {
historyController = EYEPopularHistoryController()
}
actionController = historyController
break
default:
break
}
self.addChildViewController(actionController)
self.view.addSubview(actionController.view)
self.setupControllerFrame(actionController.view)
// 动画
if let currentVC = currentController {
startAnimation(currentVC, toVC: actionController)
} else {
// 首次运行会来这里,将weekcontroller 赋值给当前控制器
currentController = actionController
}
}
// 设置控制器frame
private func startAnimation(fromVC: UIViewController, toVC: UIViewController) {
toVC.view.alpha = 0
UIView.animateWithDuration(0.5, animations: {
fromVC.view.alpha = 0
toVC.view.alpha = 1
}) {[unowned self] (_) in
// 先清空currentview
fromVC.view.removeFromSuperview()
self.currentController = nil
// 在赋值
self.currentController = toVC
}
}
private func setupControllerFrame (view : UIView) {
view.snp_makeConstraints { (make) in
make.left.trailing.equalTo(self.view)
make.top.equalTo(self.headerView).offset(headerView.height)
make.bottom.equalTo(self.view).offset(-UIConstant.UI_TAB_HEIGHT)
}
}
//MARK: --------------------------- Getter or Setter --------------------------
// controller
private var weekController: EYEPopularWeekController?
private var monthController: EYEPopularMonthController?
private var historyController: EYEPopularHistoryController?
// 当前选中控制器
private var currentController : UIViewController?
private let titleArray = ["周排行", "月排行", "总排行"]
// headerView
private lazy var headerView : EYEPopularHeaderView = {
let headerView = EYEPopularHeaderView(frame: CGRect(x: 0, y: UIConstant.UI_NAV_HEIGHT, width: UIConstant.SCREEN_WIDTH, height: UIConstant.UI_CHARTS_HEIGHT), titleArray: self.titleArray)
return headerView
}()
}
|
c02885eca4e9596c4932ebdb7ee63828
| 31.618182 | 193 | 0.568999 | false | false | false | false |
Punch-In/PunchInIOSApp
|
refs/heads/master
|
PunchIn/LoginViewController.swift
|
mit
|
1
|
//
// LoginViewController.swift
// PunchIn
//
// Created by Nilesh Agrawal on 10/20/15.
// Copyright © 2015 Nilesh Agrawal. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController {
static let loginSegueName = "loginSegue"
static let userTypes = [ "Student", "Instructor" ]
private let initialEmailAddress = "[email protected]"
private let initialPassword = "password"
private static let noUserProvidedText = "Please provide an email address"
private static let noPasswordProvidedText = "Please provide a password"
private static let badUserText = "Email and/or Password is not valid"
private static let notInstructorText = " is not an Instructor"
private static let notStudentText = " is not a Student"
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var invalidEntryLabel: UILabel!
@IBOutlet var studentIndicatorTapGesture: UITapGestureRecognizer!
@IBOutlet weak var studentIndicatorImage: UIImageView!
private var isStudent: Bool = false
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ParseDB.BadLoginNotificationName, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: ParseDB.BadTypeNotificationName, object:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupGestureRecognizer()
isStudent = false
studentIndicatorImage.image = UIImage(named: "unselected_button_login.png")
// Do any additional setup after loading the view.
invalidEntryLabel.hidden = true
NSNotificationCenter.defaultCenter().addObserver(self, selector: "badUser", name:ParseDB.BadLoginNotificationName, object:nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "badType", name:ParseDB.BadTypeNotificationName, object:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupUI() {
// set color schemes, etc
// set background color
self.view.backgroundColor = ThemeManager.theme().primaryDarkBlueColor()
// set background color for email address & password field
nameTextField.backgroundColor = ThemeManager.theme().primaryBlueColor()
nameTextField.textColor = UIColor.whiteColor()
nameTextField.placeholder = initialEmailAddress
passwordTextField.backgroundColor = ThemeManager.theme().primaryBlueColor()
passwordTextField.textColor = UIColor.whiteColor()
passwordTextField.placeholder = initialPassword
// set login
loginButton.layer.borderColor = UIColor.whiteColor().CGColor
loginButton.layer.borderWidth = 1.0
loginButton.tintColor = UIColor.whiteColor()
// set color for invalid entry
invalidEntryLabel.textColor = ThemeManager.theme().primaryYellowColor()
}
private func setupGestureRecognizer() {
studentIndicatorTapGesture.addTarget(self, action: "didTapStudentIndicator")
}
func didTapStudentIndicator() {
if isStudent {
// change to not student
isStudent = false
studentIndicatorImage.image = UIImage(named: "unselected_button_login.png")
}else{
// change to student
isStudent = true
studentIndicatorImage.image = UIImage(named: "selected_button_login.png")
}
}
func validateInput() -> Bool {
var goodInput: Bool = true
goodInput = goodInput && !nameTextField.text!.isEmpty
goodInput = goodInput && !passwordTextField.text!.isEmpty
goodInput = goodInput && !(nameTextField.text==initialEmailAddress)
goodInput = goodInput && !(passwordTextField.text==initialPassword)
return goodInput
}
private func updateInvalidDataText(status: String) {
self.invalidEntryLabel.alpha = 0
self.invalidEntryLabel.hidden = false
self.invalidEntryLabel.text = status
UIView.animateWithDuration(0.5) { () -> Void in
self.invalidEntryLabel.alpha = 1
}
}
func badUser() {
updateInvalidDataText(LoginViewController.badUserText)
}
func badType() {
let errorText = isStudent ? LoginViewController.notStudentText : LoginViewController.notInstructorText
updateInvalidDataText(self.nameTextField.text! + errorText)
}
@IBAction func accountLogin(sender: AnyObject) {
guard !nameTextField.text!.isEmpty else {
updateInvalidDataText(LoginViewController.noUserProvidedText)
return
}
guard !passwordTextField.text!.isEmpty else {
updateInvalidDataText(LoginViewController.noPasswordProvidedText)
return
}
self.invalidEntryLabel.hidden = true
ParseDB.login(nameTextField!.text!, password: passwordTextField!.text!,
type: isStudent ? LoginViewController.userTypes[0] : LoginViewController.userTypes[1])
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
}
}
|
e8e730bc325d375094efd0a25d76ac73
| 35.570513 | 134 | 0.675723 | false | false | false | false |
jonkykong/SideMenu
|
refs/heads/master
|
Pod/Classes/SideMenuPushCoordinator.swift
|
mit
|
1
|
//
// PushCoordinator.swift
// SideMenu
//
// Created by Jon Kent on 9/4/19.
//
import UIKit
protocol CoordinatorModel {
var animated: Bool { get }
var fromViewController: UIViewController { get }
var toViewController: UIViewController { get }
}
protocol Coordinator {
associatedtype Model: CoordinatorModel
init(config: Model)
@discardableResult func start() -> Bool
}
internal final class SideMenuPushCoordinator: Coordinator {
struct Model: CoordinatorModel {
var allowPushOfSameClassTwice: Bool
var alongsideTransition: (() -> Void)?
var animated: Bool
var fromViewController: UIViewController
var pushStyle: SideMenuPushStyle
var toViewController: UIViewController
}
private let config: Model
init(config: Model) {
self.config = config
}
@discardableResult func start() -> Bool {
guard config.pushStyle != .subMenu,
let fromNavigationController = config.fromViewController as? UINavigationController else {
return false
}
let toViewController = config.toViewController
let presentingViewController = fromNavigationController.presentingViewController
let splitViewController = presentingViewController as? UISplitViewController
let tabBarController = presentingViewController as? UITabBarController
let potentialNavigationController = (splitViewController?.viewControllers.first ?? tabBarController?.selectedViewController) ?? presentingViewController
guard let navigationController = potentialNavigationController as? UINavigationController else {
Print.warning(.cannotPush, arguments: String(describing: potentialNavigationController.self), required: true)
return false
}
// To avoid overlapping dismiss & pop/push calls, create a transaction block where the menu
// is dismissed after showing the appropriate screen
CATransaction.begin()
defer { CATransaction.commit() }
UIView.animationsEnabled { [weak self] in
self?.config.alongsideTransition?()
}
if let lastViewController = navigationController.viewControllers.last,
!config.allowPushOfSameClassTwice && type(of: lastViewController) == type(of: toViewController) {
return false
}
toViewController.navigationItem.hidesBackButton = config.pushStyle.hidesBackButton
switch config.pushStyle {
case .default:
navigationController.pushViewController(toViewController, animated: config.animated)
return true
// subMenu handled earlier
case .subMenu:
return false
case .popWhenPossible:
for subViewController in navigationController.viewControllers.reversed() {
if type(of: subViewController) == type(of: toViewController) {
navigationController.popToViewController(subViewController, animated: config.animated)
return true
}
}
navigationController.pushViewController(toViewController, animated: config.animated)
return true
case .preserve, .preserveAndHideBackButton:
var viewControllers = navigationController.viewControllers
let filtered = viewControllers.filter { preservedViewController in type(of: preservedViewController) == type(of: toViewController) }
guard let preservedViewController = filtered.last else {
navigationController.pushViewController(toViewController, animated: config.animated)
return true
}
viewControllers = viewControllers.filter { subViewController in subViewController !== preservedViewController }
viewControllers.append(preservedViewController)
navigationController.setViewControllers(viewControllers, animated: config.animated)
return true
case .replace:
navigationController.setViewControllers([toViewController], animated: config.animated)
return true
}
}
}
|
684427dea2f87371b5cda95416eb7da9
| 38.065421 | 160 | 0.684928 | false | true | false | false |
bryant81pts/PhotoBrowser
|
refs/heads/master
|
PhotoBrowser/PhotoBrowser/Classes/Home/HomeCollectionViewLayout.swift
|
mit
|
1
|
//
// HomeCollectionViewLayout.swift
// PhotoBrowser
//
// Created by Mac on 16/4/28.
// Copyright © 2016年 dalpha. All rights reserved.
//
import UIKit
class HomeCollectionViewLayout: UICollectionViewFlowLayout {
/**
Tells the layout object to update the current layout.
Layout updates occur the first time the collection view presents its content and whenever the layout is invalidated explicitly or implicitly because of a change to the view. During each layout update, the collection view calls this method first to give your layout object a chance to prepare for the upcoming layout operation.
The default implementation of this method does nothing. Subclasses can override it and use it to set up data structures or perform any initial computations needed to perform the layout later.
*/
override func prepareLayout() {
//item之间的间距
let margin : CGFloat = 10
//列数
let colums : CGFloat = 3
//计算item的宽度
let itemWidth : CGFloat = (UIScreen.mainScreen().bounds.width - (colums + 1) * margin) / colums
minimumLineSpacing = margin
minimumInteritemSpacing = margin
itemSize = CGSize(width: itemWidth, height: itemWidth)
//假如scroll view嵌套了navigation controller 那么为了不让scroll view的内容被 navigation bar挡住 所以系统会将scroll view的内边距增加64,但如果自己设置scroll view的contentInset,系统就不会帮增加内边距,需要自己设置
collectionView?.contentInset = UIEdgeInsets(top: margin + 64, left: margin, bottom: margin, right: margin)
}
}
|
9ab15f89062abacdfbe72c4c83856311
| 39.333333 | 331 | 0.701208 | false | false | false | false |
JerrySir/YCOA
|
refs/heads/master
|
YCOA/Main/DetailPage/View/DetailPageTableVC_ReplyTableViewCell.swift
|
mit
|
1
|
//
// DetailPageTableVC_ReplyTableViewCell.swift
// YCOA
//
// Created by Jerry on 2017/2/1.
// Copyright © 2017年 com.baochunsteel. All rights reserved.
//
// 回复Cell
import UIKit
class DetailPageTableVC_ReplyTableViewCell: UITableViewCell {
open var infoStringTextView: UITextView!
private var submitButton: UIButton!
private var selectActionOptionButton: UIButton!
open func configure(selectedOptionString: String, didSelectTap: @escaping (_ sender: UIButton)-> Swift.Void, didSubmitTap: @escaping (_ sender: UIButton,_ infoString: String)-> Swift.Void)
{
self.selectActionOptionButton.setTitle(selectedOptionString, for: .normal)
self.selectActionOptionButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (sender) in
didSelectTap((sender as! UIButton))
}
self.submitButton.rac_signal(for: .touchUpInside).take(until: self.rac_prepareForReuseSignal).subscribeNext { (sender) in
didSubmitTap((sender as! UIButton), self.infoStringTextView.text)
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
self.contentView.backgroundColor = UIColor.groupTableViewBackground
let titleLabel = UILabel()
titleLabel.text = "任务回复"
titleLabel.textColor = UIColor.darkText
titleLabel.font = UIFont.systemFont(ofSize: 22)
self.contentView.addSubview(titleLabel)
let bgView = UIView()
bgView.backgroundColor = UIColor.white
self.contentView.addSubview(bgView)
let selectActionOptionLabel = UILabel()
selectActionOptionLabel.text = "*处理动作:"
selectActionOptionLabel.font = UIFont.systemFont(ofSize: 17)
selectActionOptionLabel.textColor = UIColor.lightGray
bgView.addSubview(selectActionOptionLabel)
self.selectActionOptionButton = UIButton(type: .system)
self.selectActionOptionButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
self.selectActionOptionButton.setTitle("请选择", for: .normal)
self.selectActionOptionButton.backgroundColor = UIColor.white
self.selectActionOptionButton.setTitleColor(UIColor.darkText, for: .normal)
self.selectActionOptionButton.titleLabel?.textAlignment = .left
self.selectActionOptionButton.layer.masksToBounds = true
self.selectActionOptionButton.layer.borderColor = UIColor.lightGray.cgColor
self.selectActionOptionButton.layer.borderWidth = 1
self.selectActionOptionButton.layer.cornerRadius = 0.1
bgView.addSubview(self.selectActionOptionButton)
let infoStringLabel = UILabel()
infoStringLabel.text = "说明:"
infoStringLabel.font = UIFont.systemFont(ofSize: 17)
infoStringLabel.textColor = UIColor.lightGray
bgView.addSubview(infoStringLabel)
self.infoStringTextView = UITextView()
self.infoStringTextView.font = UIFont.systemFont(ofSize: 16)
self.infoStringTextView.layer.masksToBounds = true
self.infoStringTextView.layer.borderColor = UIColor.lightGray.cgColor
self.infoStringTextView.layer.borderWidth = 1
self.infoStringTextView.layer.cornerRadius = 0.1
bgView.addSubview(self.infoStringTextView)
self.submitButton = UIButton(type: .system)
self.submitButton.setTitle("提交处理", for: .normal)
self.submitButton.backgroundColor = UIColor.init(colorLiteralRed: 30/255.0, green: 160/255.0, blue: 80/255.0, alpha: 1)
self.submitButton.setTitleColor(UIColor.white, for: .normal)
bgView.addSubview(self.submitButton)
//AutoLayout
titleLabel.snp.makeConstraints { (make) in
make.left.top.equalTo(8)
}
bgView.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(titleLabel.snp.bottom).offset(8)
make.right.bottom.equalTo(-8)
make.bottom.equalTo(-8)
}
selectActionOptionLabel.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.centerY.equalTo(self.selectActionOptionButton.snp.centerY)
make.width.lessThanOrEqualTo(self.selectActionOptionButton.snp.width)
}
self.selectActionOptionButton.snp.makeConstraints { (make) in
make.left.equalTo(selectActionOptionLabel.snp.right).offset(8)
make.top.equalTo(8)
make.right.equalTo(-8)
make.height.equalTo(44)
}
infoStringLabel.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.centerY.equalTo(infoStringTextView.snp.centerY)
}
self.infoStringTextView.snp.makeConstraints { (make) in
make.left.equalTo(infoStringLabel.snp.right).offset(8)
make.top.equalTo(self.selectActionOptionButton.snp.bottom).offset(8)
make.right.equalTo(-8)
make.height.equalTo(55)
}
self.submitButton.snp.makeConstraints { (make) in
make.left.equalTo(8)
make.top.equalTo(infoStringTextView.snp.bottom).offset(8)
make.right.bottom.equalTo(-8)
make.height.equalTo(50)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
a763df07377298fa81742ac017a814e3
| 40.104895 | 192 | 0.666553 | false | false | false | false |
DanielOYC/Tools
|
refs/heads/master
|
YCEmoticonKeyboard/YCEmoticonKeyboard/YCEmoticonView/YCEmoticonView.swift
|
mit
|
1
|
//
// YCEmoticonView.swift
// YCEmoticonKeyboard
//
// Created by daniel on 2017/8/20.
// Copyright © 2017年 daniel. All rights reserved.
//
import UIKit
import SnapKit
fileprivate let kEmoticonCollectionViewCellId = "kEmoticonCollectionViewCellId"
class YCEmoticonView: UIView {
fileprivate let kEmoticonToolBarH: CGFloat = 45.0 // 表情键盘底部工具条高度
fileprivate let kEmoticonContentViewH: CGFloat = 226.0 // 表情键盘内容高度
fileprivate lazy var packages: [YCEmoticons] = { // 表情包数据源
return YCEmoticonsViewModel().packages!
}()
// fileprivate var clickEmoticonCallBack: (YCEmoticon) -> ()
weak var targetTextView: UITextView?
// init(clickEmoticon: @escaping (YCEmoticon) -> ()) {
//
// clickEmoticonCallBack = clickEmoticon
//
// let tempFrame = CGRect(x: 0, y: 0, width: 0, height: kEmoticonToolBarH + kEmoticonContentViewH)
// super.init(frame: tempFrame)
//
// setupUI()
//
// //准备历史表情数据
// prepareHistoryEmoticons()
//
// }
init(targetView: UITextView) {
targetTextView = targetView
// targetTextView?.font = UIFont.systemFont(ofSize: 34)
let tempFrame = CGRect(x: 0, y: 0, width: 0, height: kEmoticonToolBarH + kEmoticonContentViewH)
super.init(frame: tempFrame)
setupUI()
//准备历史表情数据
prepareHistoryEmoticons()
}
//准备历史表情数据
fileprivate func prepareHistoryEmoticons() {
let historyEmoticons = YCEmoticons(dic: ["emoticons" : ["" : ""]])
packages.insert(historyEmoticons, at: 0)
}
@objc fileprivate func toolBarItemClick(item: UIBarButtonItem) {
let index = item.tag - 1000
emoticonContentView.scrollToItem(at: NSIndexPath(item: 0, section: index) as IndexPath, at: .left, animated: true)
}
// 底部工具条
fileprivate lazy var toolBar: UIToolbar = UIToolbar()
// 表情内容视图
fileprivate lazy var emoticonContentViewLayout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.width / 7
layout.itemSize = CGSize(width: width, height: width)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = UICollectionViewScrollDirection.horizontal
return layout
}()
fileprivate lazy var emoticonContentView: UICollectionView = {
let contentView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.emoticonContentViewLayout)
return contentView
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - 设置界面
extension YCEmoticonView {
fileprivate func setupUI() {
addSubview(toolBar)
addSubview(emoticonContentView)
emoticonContentView.backgroundColor = UIColor.white
toolBar.snp.makeConstraints { (make) in
make.bottom.equalToSuperview()
make.left.equalToSuperview()
make.right.equalToSuperview()
make.height.equalTo(kEmoticonToolBarH)
}
emoticonContentView.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalToSuperview()
make.right.equalToSuperview()
make.bottom.equalTo(toolBar.snp.top)
}
// 设置工具条内容
setupToolBar()
// 设置表情内容视图
setupEmoticonContentView()
}
// 设置工具条内容
fileprivate func setupToolBar() {
var items = [UIBarButtonItem]()
let historyItem = UIBarButtonItem.init(title: "历史", style: .plain, target: self, action: #selector(YCEmoticonView.toolBarItemClick(item:)))
historyItem.tag = 1000
historyItem.tintColor = UIColor.darkGray
items.append(historyItem)
var index = 1
for emoticons in packages {
items.append(UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
let item = UIBarButtonItem.init(title: emoticons.group_name_cn, style: .plain, target: self, action: #selector(YCEmoticonView.toolBarItemClick(item:)))
item.tag = 1000 + index
item.tintColor = UIColor.darkGray
items.append(item)
index += 1
}
toolBar.items = items
}
// 设置表情内容视图
fileprivate func setupEmoticonContentView() {
let margin = (kEmoticonContentViewH - (UIScreen.main.bounds.width / 7 * 3)) / 2
emoticonContentView.contentInset = UIEdgeInsetsMake(margin, 0, margin, 0)
emoticonContentView.register(YCEmoticonViewCell.self, forCellWithReuseIdentifier: kEmoticonCollectionViewCellId)
emoticonContentView.isPagingEnabled = true
emoticonContentView.bounces = false
emoticonContentView.dataSource = self
emoticonContentView.delegate = self
}
}
// MARK: - UICollectionView DataSource
extension YCEmoticonView: UICollectionViewDataSource,UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return packages.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return packages[section].emoticons.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kEmoticonCollectionViewCellId, for: indexPath) as! YCEmoticonViewCell
cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let emoticon = packages[indexPath.section].emoticons[indexPath.row]
if emoticon.isDelete {
targetTextView?.deleteBackward()
return
}
if emoticon.code != nil {
targetTextView?.replace(targetTextView!.selectedTextRange!, withText: emoticon.code!.emoji)
return
}
if emoticon.pngPath != nil {
let attachment = NSTextAttachment()
attachment.image = UIImage(named: emoticon.pngPath!)
let lineHeight = (targetTextView!.font?.lineHeight)! + 1.8
attachment.bounds = CGRect.init(x: 0, y: -4, width: lineHeight, height: lineHeight)
let imageAttributeString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
imageAttributeString.addAttributes([NSFontAttributeName : targetTextView!.font!], range: NSRange.init(location: 0, length: 1))
let attributeString = NSMutableAttributedString(attributedString: targetTextView!.attributedText)
attributeString.replaceCharacters(in: targetTextView!.selectedRange, with: imageAttributeString)
// 4. 替换属性文本
// 1) 记录住`光标`位置
let range = targetTextView!.selectedRange
targetTextView!.attributedText = attributeString
// 3) 恢复光标
targetTextView!.selectedRange = NSRange(location: range.location + 1, length: 0)
return
}
}
}
/// 表情Cell
fileprivate class YCEmoticonViewCell: UICollectionViewCell {
var emoticon: YCEmoticon? {
didSet {
contentBtn.setTitle("", for: .normal)
contentBtn.setImage(UIImage.init(named: ""), for: .normal)
if emoticon!.isEmpty {
contentBtn.setImage(UIImage.init(named: ""), for: .normal)
return
}
if emoticon!.isDelete {
contentBtn.setImage(UIImage.init(named: "compose_emotion_delete"), for: .normal)
return
}
if emoticon!.pngPath != nil {
contentBtn.setImage(UIImage.init(named: emoticon!.pngPath!), for: .normal)
return
}
if emoticon!.emoji != nil {
contentBtn.setTitle(emoticon?.emoji, for: .normal)
}
}
}
fileprivate lazy var contentBtn: UIButton = {
let btn = UIButton()
btn.titleLabel?.font = UIFont.systemFont(ofSize: 32)
btn.isUserInteractionEnabled = false
return btn
}()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(contentBtn)
contentBtn.snp.makeConstraints { (make) in
make.edges.equalToSuperview().offset(5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
189c89039729a2de98b21bd432e86ff0
| 32.148014 | 163 | 0.612176 | false | false | false | false |
JulianGindi/Critiq
|
refs/heads/master
|
Critiq/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// Critiq
//
// Created by Thomas Degry and Julian Gindi on 3/3/15.
// Copyright (c) 2015 Thomas Degry and Julian Gindi. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, APIHelperDelegate, NSUserNotificationCenterDelegate {
var menuBarController : MenuBarController?
var apiHelper:APIHelper?
func applicationDidFinishLaunching(aNotification: NSNotification) {
self.apiHelper = APIHelper()
self.apiHelper?.delegate = self;
menuBarController = MenuBarController.init()
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func uploadClipboard() {
let content = getMostRecentClipboardContents()
if content != "" {
self.apiHelper?.makeRequest(content)
}
}
func didReceiveUrl(url: String) {
// We will copy url to clipboard
let clipboard = NSPasteboard.generalPasteboard()
let outputArray = [url]
clipboard.clearContents()
clipboard.writeObjects(outputArray)
// Send out notification to change icon again
NSNotificationCenter.defaultCenter().postNotificationName("DID_UPLOAD", object: nil)
// Now display a notification
displayNotification()
}
func getMostRecentClipboardContents() -> String {
let clipboard = NSPasteboard.generalPasteboard()
let contents = clipboard.stringForType(NSPasteboardTypeString)
if let actualContent = contents {
return actualContent
}
return ""
}
func displayNotification() {
let notification = NSUserNotification()
notification.title = "Critiq Upload"
notification.informativeText = "The URL of your snippet has been copied to your clipboard"
notification.hasActionButton = true
var center:NSUserNotificationCenter = NSUserNotificationCenter.defaultUserNotificationCenter()
center.delegate = self
center.scheduleNotification(notification)
}
func notify (center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification){
center.delegate = self
println("clicked") //this does not print
}
}
|
b0b0d5cd11edc1cc7f63a91de8c68b4e
| 31.351351 | 109 | 0.671261 | false | false | false | false |
billhsu0913/VideBounceButtonView
|
refs/heads/master
|
VideBounceButtonView/VideBounceButtonView.swift
|
mit
|
1
|
//
// VideBounceButtonView.swift
// VideBounceButtonViewExample
//
// Created by Oreki Houtarou on 11/29/14.
// Copyright (c) 2014 Videgame. All rights reserved.
//
import UIKit
class VideBounceButtonView: UIView {
var exclusiveButtons: [UIButton]?
var currentSelectedButton: UIButton?
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let hitTestView = super.hitTest(point, withEvent: event)
if (hitTestView is UIButton) && (exclusiveButtons == nil || !contains(exclusiveButtons!, hitTestView as UIButton)) {
return self
}
return hitTestView
}
// MARK: Touch-Event Handling Methods
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
if touch.view != self {
super.touchesBegan(touches, withEvent: event)
return
}
let button = buttonForTouch(touch)
if button != nil {
currentSelectedButton = button
bounceInButton(button!)
} else {
currentSelectedButton = nil
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
if touch.view != self {
super.touchesMoved(touches, withEvent: event)
return
}
let button = buttonForTouch(touch)
if button != nil && button != currentSelectedButton {
if currentSelectedButton != nil {
bounceOutButton(currentSelectedButton!)
}
currentSelectedButton = button
bounceInButton(button!)
return
}
if button == nil && currentSelectedButton != nil {
bounceOutButton(currentSelectedButton!)
currentSelectedButton = nil
}
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
if touch.view != self {
super.touchesEnded(touches, withEvent: event)
return
}
let button = buttonForTouch(touch)
if button != nil {
bounceOutButton(button!)
button!.sendActionsForControlEvents(.TouchUpInside)
} else {
startBlackAtPoint(touch.locationInView(self))
}
if currentSelectedButton != nil {
bounceOutButton(currentSelectedButton!)
currentSelectedButton = nil
}
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
startBlackAtPoint((touches.anyObject() as UITouch).locationInView(self))
if currentSelectedButton != nil {
bounceOutButton(currentSelectedButton!)
currentSelectedButton = nil
}
}
// MARK: Private Methods
private func buttonForTouch(touch: UITouch) -> UIButton? {
let location = touch.locationInView(self)
for subView in self.subviews.reverse() {
if let button = subView as? UIButton {
if (exclusiveButtons == nil || !contains(exclusiveButtons!, button)) && button.frame.contains(location) {
return button;
}
}
}
return nil
}
private func bounceInButton(button: UIButton) {
if button.transform.a < CGAffineTransformIdentity.a && button.transform.d < CGAffineTransformIdentity.d {
return
}
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(0.85, 0.85)
}) { (finished) -> Void in
if finished {
UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(0.90, 0.90)
}, completion: nil)
}
}
}
private func bounceOutButton(button: UIButton) {
if button.transform.a >= CGAffineTransformIdentity.a && button.transform.d >= CGAffineTransformIdentity.d {
return
}
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
button.transform = CGAffineTransformMakeScale(1.10, 1.10)
}) { (finished) -> Void in
if finished {
UIView.animateWithDuration(0.1, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
button.transform = CGAffineTransformIdentity
}, completion: nil)
}
}
}
private func startBlackAtPoint(point: CGPoint) {
let sideLength: CGFloat = 10
let snapView = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: sideLength, height: sideLength)))
snapView.center = point
snapView.layer.cornerRadius = sideLength / 2.0
snapView.backgroundColor = UIColor.blackColor()
self.insertSubview(snapView, atIndex: 0)
let maxScale = max(self.frame.width / snapView.frame.width * 2.0, self.frame.height / snapView.frame.height * 2.0)
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
snapView.transform = CGAffineTransformMakeScale(maxScale, maxScale)
}) { (finished) -> Void in
if finished {
self.backgroundColor = UIColor.blackColor()
snapView.removeFromSuperview()
}
}
}
}
|
0bae3715cce2b47ee61a9f23c51140a4
| 37.94 | 134 | 0.594932 | false | false | false | false |
urklc/UKHorizontalPicturePicky
|
refs/heads/master
|
UKPickyDemo/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// UKPickyDemo
//
// Created by ugur on 27/02/15.
// Copyright (c) 2015 urklc. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UKHorizontalPicturePicky!
let imagesData = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagesData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as UICollectionViewCell
if let imgView = cell.contentView.viewWithTag(hppImageViewTag) as? UIImageView {
imgView.image = UIImage(named: imagesData[indexPath.row])
} else {
let img = UIImageView(frame: CGRect(x: 6, y: 6, width: 128, height: 128))
img.tag = hppImageViewTag
img.image = UIImage(named: imagesData[indexPath.row])
cell.contentView.addSubview(img)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let imgView = cell.contentView.viewWithTag(hppImageViewTag) {
if let imgView = imgView as? UIImageView {
imgView.image = nil
}
}
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let collectionSelectorViewController = CollectionSelectorViewController()
collectionSelectorViewController.imagename = imagesData[indexPath.row]
collectionSelectorViewController.modalPresentationStyle = .popover
collectionSelectorViewController.preferredContentSize = CGSize(width: 400, height: 400)
collectionSelectorViewController.delegate = self
let popoverViewController = collectionSelectorViewController.popoverPresentationController
popoverViewController?.permittedArrowDirections = UIPopoverArrowDirection.down
popoverViewController?.passthroughViews = [collectionView]
popoverViewController?.sourceView = collectionView.cellForItem(at: indexPath)?.contentView.viewWithTag(hppImageViewTag)
popoverViewController?.sourceRect = CGRect(x: 50, y: 0, width: 1, height: 1)
present(collectionSelectorViewController, animated: true, completion: nil)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
dismiss(animated: false, completion: nil)
}
}
extension ViewController: ImagePanGestureHandler {
func handlePan(_ recognizer: UIPanGestureRecognizer) {
let imageView = recognizer.view as? UIImageView
switch (recognizer.state) {
case UIGestureRecognizerState.began:
dismiss(animated: false, completion: nil);
let rect = imageView?.frame
let frame = imageView?.convert(rect!, to: self.view)
imageView?.frame = frame!
// To prevent flashing when started mobving the UIImageView object
let fakeCopy = UIImageView(frame: rect!)
fakeCopy.image = imageView?.image
imageView?.superview?.addSubview(fakeCopy)
// Move the actual UIImageView to self
imageView?.tag = kFakeCopyImageViewTag
self.view.addSubview(imageView!)
UIView.animate(withDuration: 0.3,
delay: 0.0,
options: UIViewAnimationOptions(),
animations: {
self.view.viewWithTag(kFakeCopyImageViewTag)?.transform = CGAffineTransform(scaleX: 0.4, y: 0.4)
return
},
completion: { finished in })
break;
case UIGestureRecognizerState.cancelled, UIGestureRecognizerState.failed, UIGestureRecognizerState.ended:
self.view.viewWithTag(kFakeCopyImageViewTag)?.tag = 0
break;
default:
break;
}
imageView?.center = recognizer.location(in: imageView?.superview);
}
}
|
bb0ce54171f510706f855920a1f8073e
| 39.661157 | 145 | 0.654268 | false | false | false | false |
TerryCK/GogoroBatteryMap
|
refs/heads/master
|
GogoroMap/NetworkActivityIndicatorManager.swift
|
mit
|
1
|
//
// NetworkActivityIndicatorManager.swift
// SwiftyStoreKit
//
// Created by Andrea Bizzotto on 28/09/2015.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
final class NetworkActivityIndicatorManager: NSObject {
private override init() { super.init() }
static let shared = NetworkActivityIndicatorManager()
private var loadingCount = 0
func networkOperationStarted() {
#if os(iOS)
if loadingCount == 0 {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
}
}
loadingCount += 1
#endif
}
func networkOperationFinished() {
#if os(iOS)
if loadingCount > 0 {
loadingCount -= 1
}
if loadingCount == 0 {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
}
#endif
}
}
|
dcacc3eb1cfaf9bf3d188248fca2f79b
| 32.984127 | 83 | 0.641289 | false | false | false | false |
midoks/Swift-Learning
|
refs/heads/master
|
GitHubStar/GitHubStar/GitHubStar/Controllers/common/issues/GsUserCommentCell.swift
|
apache-2.0
|
1
|
//
// GsUserCommentCell.swift
// GitHubStar
//
// Created by midoks on 16/4/24.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
//用户提交Cell
class GsUserCommentCell: UITableViewCell {
//头像视图
var userIcon = UIImageView()
//项目名
var userName = UILabel()
//项目创建时间
var userCommentTime = UILabel()
//项目介绍
var userCommentContent = UILabel()
let repoH:CGFloat = 40
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initView()
}
//初始化视图
func initView(){
let w = self.getWinWidth()
//提交人头像
userIcon.image = UIImage(named: "avatar_default")
userIcon.layer.cornerRadius = 15
userIcon.frame = CGRect(x:5, y: 5, width:30, height:30)
userIcon.clipsToBounds = true
userIcon.backgroundColor = UIColor.white
contentView.addSubview(userIcon)
//提交用户名
userName = UILabel(frame: CGRect(x: 40, y: 5, width: w-40-140, height: 18))
userName.font = UIFont.systemFont(ofSize: 16)
userName.text = "项目名"
userName.textColor = UIColor(red: 64/255, green: 120/255, blue: 192/255, alpha: 1)
userName.font = UIFont.boldSystemFont(ofSize: 16)
contentView.addSubview(userName)
//提交时间
userCommentTime = UILabel(frame: CGRect(x: 40, y: 23, width: 140, height: 17))
userCommentTime.font = UIFont.systemFont(ofSize: 12)
userCommentTime.text = "create at:2008-12-12"
contentView.addSubview(userCommentTime)
//userCommentTime.backgroundColor = UIColor.blueColor()
//
//提交内容
userCommentContent.frame = CGRect(x: 40, y: repoH, width: w - 50, height:0)
userCommentContent.font = UIFont.systemFont(ofSize: 14)
userCommentContent.text = ""
userCommentContent.numberOfLines = 0
userCommentContent.lineBreakMode = .byWordWrapping
contentView.addSubview(userCommentContent)
//userCommentContent.backgroundColor = UIColor.blueColor()
}
func getCommentSize(text:String) -> CGSize{
userCommentContent.text = text
userCommentContent.frame.size.width = self.getWinWidth() - 50
let size = self.getLabelSize(label: userCommentContent)
return size
}
override func layoutSubviews() {
super.layoutSubviews()
if userCommentContent.text != "" {
let size = self.getCommentSize(text: userCommentContent.text!)
userCommentContent.frame.size.height = size.height
}
}
}
|
a8e27e56fadc1063fb2da01a1bf31842
| 29.959184 | 90 | 0.625247 | false | false | false | false |
cdmx/MiniMancera
|
refs/heads/master
|
miniMancera/View/Option/ReformaCrossing/Scene/VOptionReformaCrossingScene.swift
|
mit
|
1
|
import SpriteKit
class VOptionReformaCrossingScene:ViewGameScene<MOptionReformaCrossing>
{
required init(controller:ControllerGame<MOptionReformaCrossing>)
{
super.init(controller:controller)
physicsWorld.gravity = CGVector.zero
factoryNodes()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func factoryNodes()
{
let model:MOptionReformaCrossing = controller.model
let background:VOptionReformaCrossingBackground = VOptionReformaCrossingBackground(
controller:controller)
let player:VOptionReformaCrossingPlayer = VOptionReformaCrossingPlayer(
controller:controller)
model.player.view = player
let hud:VOptionReformaCrossingHud = VOptionReformaCrossingHud(
controller:controller)
model.hud.view = hud
let menu:ViewGameNodeMenu<MOptionReformaCrossing> = ViewGameNodeMenu<MOptionReformaCrossing>(
controller:controller,
texture:model.textures.menu)
model.viewMenu = menu
let title:VOptionReformaCrossingTitle = VOptionReformaCrossingTitle()
model.title.view = title
let stop:VOptionReformaCrossingStop = VOptionReformaCrossingStop(
controller:controller)
model.stop.view = stop
addChild(background)
addChild(player)
addChild(hud)
addChild(menu)
addChild(stop)
addChild(title)
}
//MARK: public
func showCoin(coin:MOptionReformaCrossingCoinItem)
{
let soundCoin:SKAction = controller.model.sounds.soundCoin
controller.playSound(actionSound:soundCoin)
let view:VOptionReformaCrossingCoin = VOptionReformaCrossingCoin(
controller:controller,
positionY:coin.positionY)
coin.view = view
addChild(view)
}
}
|
f3163c4c4bfe7cc53f04e72c0eef97d0
| 28.367647 | 101 | 0.645468 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/PanelUtils.swift
|
gpl-2.0
|
1
|
//
// InputFinderPanelUtils.swift
// Telegram-Mac
//
// Created by keepcoder on 24/10/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import Foundation
import Postbox
import TelegramCore
let mediaExts:[String] = ["png","jpg","jpeg","tiff", "heic","mp4","mov","avi", "gif", "m4v"]
let photoExts:[String] = ["png","jpg","jpeg","tiff", "heic"]
let videoExts:[String] = ["mp4","mov","avi", "m4v"]
let audioExts:[String] = ["mp3","wav", "m4a", "ogg"]
func filePanel(with exts:[String]? = nil, allowMultiple:Bool = true, canChooseDirectories: Bool = false, for window:Window, completion:@escaping ([String]?)->Void) {
delay(0.01, closure: {
var result:[String] = []
let panel:NSOpenPanel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = canChooseDirectories
panel.canCreateDirectories = true
panel.allowedFileTypes = exts
panel.allowsMultipleSelection = allowMultiple
panel.beginSheetModal(for: window) { (response) in
if response.rawValue == NSFileHandlingPanelOKButton {
for url in panel.urls {
let path:String = url.path
if let exts = exts {
let ext:String = path.nsstring.pathExtension.lowercased()
if exts.contains(ext) || (canChooseDirectories && path.isDirectory) {
result.append(path)
}
} else {
result.append(path)
}
}
completion(result)
} else {
completion(nil)
}
}
})
}
func selectFolder(for window:Window, completion:@escaping (String)->Void) {
delay(0.01, closure: {
var result:[String] = []
let panel:NSOpenPanel = NSOpenPanel()
panel.canChooseFiles = false
panel.canChooseDirectories = true
panel.canCreateDirectories = true
panel.allowsMultipleSelection = false
panel.beginSheetModal(for: window) { (response) in
if response.rawValue == NSFileHandlingPanelOKButton {
for url in panel.urls {
let path:String = url.path
result.append(path)
}
if let first = result.first {
completion(first)
}
}
}
})
}
func savePanel(file:String, ext:String, for window:Window, defaultName: String? = nil, completion:((String?)->Void)? = nil) {
delay(0.01, closure: {
let savePanel:NSSavePanel = NSSavePanel()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH.mm.ss"
savePanel.nameFieldStringValue = defaultName ?? "\(dateFormatter.string(from: Date())).\(ext)"
let wLevel = window.level
// if wLevel == .screenSaver {
window.level = .normal
//}
savePanel.begin { (result) in
if result == NSApplication.ModalResponse.OK, let saveUrl = savePanel.url {
try? FileManager.default.removeItem(atPath: saveUrl.path)
try? FileManager.default.copyItem(atPath: file, toPath: saveUrl.path)
completion?(saveUrl.path)
#if !SHARE
delay(0.3, closure: {
appDelegate?.showSavedPathSuccess(saveUrl.path)
})
#endif
} else {
completion?(nil)
}
window.level = wLevel
}
})
}
func savePanel(file:String, named:String, for window:Window) {
delay(0.01, closure: {
let savePanel:NSSavePanel = NSSavePanel()
let dateFormatter = DateFormatter()
savePanel.nameFieldStringValue = named
savePanel.beginSheetModal(for: window, completionHandler: {(result) in
if result == NSApplication.ModalResponse.OK, let saveUrl = savePanel.url {
try? FileManager.default.copyItem(atPath: file, toPath: saveUrl.path)
}
})
})
}
func alert(for window:Window, header:String = appName, info:String?, runModal: Bool = false, completion: (()->Void)? = nil, appearance: NSAppearance? = nil) {
delay(0.01, closure: {
let alert:NSAlert = NSAlert()
alert.window.appearance = appearance ?? theme.appearance
alert.alertStyle = .informational
alert.messageText = header
alert.informativeText = info ?? ""
alert.addButton(withTitle: strings().alertOK)
if runModal {
alert.runModal()
} else {
alert.beginSheetModal(for: window, completionHandler: { (_) in
completion?()
})
}
})
}
func notSupported() {
alert(for: mainWindow, header: "Not Supported", info: "This feature is not available in this app yet. Sorry! Keep calm and use the stable version.")
}
enum ConfirmResult {
case thrid
case basic
}
func confirm(for window:Window, header: String? = nil, information:String?, okTitle:String? = nil, cancelTitle:String = strings().alertCancel, thridTitle:String? = nil, fourTitle: String? = nil, successHandler:@escaping (ConfirmResult)->Void, cancelHandler: (()->Void)? = nil, appearance: NSAppearance? = nil) {
delay(0.01, closure: {
let alert:NSAlert = NSAlert()
alert.window.appearance = appearance ?? theme.appearance
alert.alertStyle = .informational
alert.messageText = header ?? appName
alert.informativeText = information ?? ""
alert.addButton(withTitle: okTitle ?? strings().alertOK)
if !cancelTitle.isEmpty {
alert.addButton(withTitle: cancelTitle)
alert.buttons.last?.keyEquivalent = "\u{1b}"
}
if let thridTitle = thridTitle {
alert.addButton(withTitle: thridTitle)
}
if let fourTitle = fourTitle {
alert.addButton(withTitle: fourTitle)
}
alert.beginSheetModal(for: window, completionHandler: { response in
Queue.mainQueue().justDispatch {
if response.rawValue == 1000 {
successHandler(.basic)
} else if response.rawValue == 1002 {
successHandler(.thrid)
} else if response.rawValue == 1001, cancelTitle == "" {
successHandler(.thrid)
} else if response.rawValue == 1001 {
cancelHandler?()
}
}
})
})
}
func modernConfirm(for window:Window, account: Account? = nil, peerId: PeerId? = nil, header: String = appName, information:String? = nil, okTitle:String = strings().alertOK, cancelTitle:String = strings().alertCancel, thridTitle:String? = nil, thridAutoOn: Bool = true, successHandler:@escaping(ConfirmResult)->Void, appearance: NSAppearance? = nil) {
delay(0.01, closure: {
let alert:NSAlert = NSAlert()
alert.window.appearance = appearance ?? theme.appearance
alert.alertStyle = .informational
alert.messageText = header
alert.informativeText = information ?? ""
alert.addButton(withTitle: okTitle)
alert.addButton(withTitle: cancelTitle)
if let thridTitle = thridTitle {
alert.showsSuppressionButton = true
alert.suppressionButton?.title = thridTitle
alert.suppressionButton?.state = thridAutoOn ? .on : .off
// alert.addButton(withTitle: thridTitle)
}
var shown: Bool = false
let readyToShow:() -> Void = {
if !shown {
shown = true
alert.beginSheetModal(for: window, completionHandler: { [weak alert] response in
if let alert = alert {
if alert.showsSuppressionButton, let button = alert.suppressionButton, response.rawValue != 1001 {
switch button.state {
case .off:
successHandler(.basic)
case .on:
successHandler(.thrid)
default:
break
}
} else {
if response.rawValue == 1000 {
successHandler(.basic)
} else if response.rawValue == 1002 {
successHandler(.thrid)
}
}
}
})
}
}
readyToShow()
})
}
func modernConfirmSignal(for window:Window, account: Account?, peerId: PeerId?, header: String = appName, information:String? = nil, okTitle:String = strings().alertOK, cancelTitle:String = strings().alertCancel, thridTitle: String? = nil, thridAutoOn: Bool = true) -> Signal<ConfirmResult, NoError> {
let value:ValuePromise<ConfirmResult> = ValuePromise(ignoreRepeated: true)
delay(0.01, closure: {
modernConfirm(for: window, account: account, peerId: peerId, header: header, information: information, okTitle: okTitle, cancelTitle: cancelTitle, thridTitle: thridTitle, thridAutoOn: thridAutoOn, successHandler: { response in
value.set(response)
})
})
return value.get() |> take(1)
}
func confirmSignal(for window:Window, header: String? = nil, information:String?, okTitle:String? = nil, cancelTitle:String? = nil, appearance: NSAppearance? = nil) -> Signal<Bool, NoError> {
let value:ValuePromise<Bool> = ValuePromise(ignoreRepeated: true)
delay(0.01, closure: {
let alert:NSAlert = NSAlert()
alert.alertStyle = .informational
alert.messageText = header ?? appName
alert.window.appearance = appearance ?? theme.appearance
alert.informativeText = information ?? ""
alert.addButton(withTitle: okTitle ?? strings().alertOK)
alert.addButton(withTitle: cancelTitle ?? strings().alertCancel)
alert.beginSheetModal(for: window, completionHandler: { response in
value.set(response.rawValue == 1000)
})
})
return value.get() |> take(1)
}
|
d2f566b2b2b6399c64ffc032bc906cfb
| 36.413428 | 352 | 0.564413 | false | false | false | false |
qutheory/vapor
|
refs/heads/master
|
Sources/Development/routes.swift
|
mit
|
1
|
import Vapor
import _Vapor3
struct Creds: Content {
var email: String
var password: String
}
public func routes(_ app: Application) throws {
app.on(.GET, "ping") { req -> StaticString in
return "123" as StaticString
}
// ( echo -e 'POST /slow-stream HTTP/1.1\r\nContent-Length: 1000000000\r\n\r\n'; dd if=/dev/zero; ) | nc localhost 8080
app.on(.POST, "slow-stream", body: .stream) { req -> EventLoopFuture<String> in
let done = req.eventLoop.makePromise(of: String.self)
var total = 0
req.body.drain { result in
let promise = req.eventLoop.makePromise(of: Void.self)
switch result {
case .buffer(let buffer):
req.eventLoop.scheduleTask(in: .milliseconds(1000)) {
total += buffer.readableBytes
promise.succeed(())
}
case .error(let error):
done.fail(error)
case .end:
promise.succeed(())
done.succeed(total.description)
}
// manually return pre-completed future
// this should balloon in memory
// return req.eventLoop.makeSucceededFuture(())
// return real future that indicates bytes were handled
// this should use very little memory
return promise.futureResult
}
return done.futureResult
}
app.post("login") { req -> String in
let creds = try req.content.decode(Creds.self)
return "\(creds)"
}
app.on(.POST, "large-file", body: .collect(maxSize: 1_000_000_000)) { req -> String in
return req.body.data?.readableBytes.description ?? "none"
}
app.get("json") { req -> [String: String] in
return ["foo": "bar"]
}.description("returns some test json")
app.webSocket("ws") { req, ws in
ws.onText { ws, text in
ws.send(text.reversed())
if text == "close" {
ws.close(promise: nil)
}
}
let ip = req.remoteAddress?.description ?? "<no ip>"
ws.send("Hello 👋 \(ip)")
}
app.on(.POST, "file", body: .stream) { req -> EventLoopFuture<String> in
let promise = req.eventLoop.makePromise(of: String.self)
req.body.drain { result in
switch result {
case .buffer(let buffer):
debugPrint(buffer)
case .error(let error):
promise.fail(error)
case .end:
promise.succeed("Done")
}
return req.eventLoop.makeSucceededFuture(())
}
return promise.futureResult
}
app.get("shutdown") { req -> HTTPStatus in
guard let running = req.application.running else {
throw Abort(.internalServerError)
}
running.stop()
return .ok
}
let cache = MemoryCache()
app.get("cache", "get", ":key") { req -> String in
guard let key = req.parameters.get("key") else {
throw Abort(.internalServerError)
}
return "\(key) = \(cache.get(key) ?? "nil")"
}
app.get("cache", "set", ":key", ":value") { req -> String in
guard let key = req.parameters.get("key") else {
throw Abort(.internalServerError)
}
guard let value = req.parameters.get("value") else {
throw Abort(.internalServerError)
}
cache.set(key, to: value)
return "\(key) = \(value)"
}
app.get("hello", ":name") { req in
return req.parameters.get("name") ?? "<nil>"
}
app.get("search") { req in
return req.query["q"] ?? "none"
}
let sessions = app.grouped("sessions")
.grouped(app.sessions.middleware)
sessions.get("set", ":value") { req -> HTTPStatus in
req.session.data["name"] = req.parameters.get("value")
return .ok
}
sessions.get("get") { req -> String in
req.session.data["name"] ?? "n/a"
}
sessions.get("del") { req -> String in
req.session.destroy()
return "done"
}
app.get("client") { req in
return req.client.get("http://httpbin.org/status/201").map { $0.description }
}
app.get("client-json") { req -> EventLoopFuture<String> in
struct HTTPBinResponse: Decodable {
struct Slideshow: Decodable {
var title: String
}
var slideshow: Slideshow
}
return req.client.get("http://httpbin.org/json")
.flatMapThrowing { try $0.content.decode(HTTPBinResponse.self) }
.map { $0.slideshow.title }
}
let users = app.grouped("users")
users.get { req in
return "users"
}
users.get(":userID") { req in
return req.parameters.get("userID") ?? "no id"
}
app.directory.viewsDirectory = "/Users/tanner/Desktop"
app.get("view") { req in
req.view.render("hello.txt", ["name": "world"])
}
app.get("error") { req -> String in
throw TestError()
}
app.get("secret") { (req) -> EventLoopFuture<String> in
return Environment
.secret(key: "PASSWORD_SECRET", fileIO: req.application.fileio, on: req.eventLoop)
.unwrap(or: Abort(.badRequest))
}
app.on(.POST, "max-256", body: .collect(maxSize: 256)) { req -> HTTPStatus in
print("in route")
return .ok
}
app.on(.POST, "upload", body: .stream) { req -> EventLoopFuture<HTTPStatus> in
enum BodyStreamWritingToDiskError: Error {
case streamFailure(Error)
case fileHandleClosedFailure(Error)
case multipleFailures([BodyStreamWritingToDiskError])
}
return req.application.fileio.openFile(
path: "/Users/tanner/Desktop/foo.txt",
mode: .write,
flags: .allowFileCreation(),
eventLoop: req.eventLoop
).flatMap { fileHandle in
let promise = req.eventLoop.makePromise(of: HTTPStatus.self)
req.body.drain { part in
switch part {
case .buffer(let buffer):
return req.application.fileio.write(
fileHandle: fileHandle,
buffer: buffer,
eventLoop: req.eventLoop
)
case .error(let drainError):
do {
try fileHandle.close()
promise.fail(BodyStreamWritingToDiskError.streamFailure(drainError))
} catch {
promise.fail(BodyStreamWritingToDiskError.multipleFailures([
.fileHandleClosedFailure(error),
.streamFailure(drainError)
]))
}
return req.eventLoop.makeSucceededFuture(())
case .end:
do {
try fileHandle.close()
promise.succeed(.ok)
} catch {
promise.fail(BodyStreamWritingToDiskError.fileHandleClosedFailure(error))
}
return req.eventLoop.makeSucceededFuture(())
}
}
return promise.futureResult
}
}
}
struct TestError: AbortError, DebuggableError {
var status: HTTPResponseStatus {
.internalServerError
}
var reason: String {
"This is a test."
}
var source: ErrorSource?
var stackTrace: StackTrace?
init(
file: String = #file,
function: String = #function,
line: UInt = #line,
column: UInt = #column,
range: Range<UInt>? = nil,
stackTrace: StackTrace? = .capture(skip: 1)
) {
self.source = .init(
file: file,
function: function,
line: line,
column: column,
range: range
)
self.stackTrace = stackTrace
}
}
|
07cd3f6c22e671fb614ec3e164ef9332
| 30.638132 | 123 | 0.525889 | false | false | false | false |
udark/underdark-cocoa
|
refs/heads/master
|
UDApp/UDApp/LogViewController.swift
|
apache-2.0
|
1
|
//
// LogViewController.swift
// UDApp
//
// Created by Virl on 23/03/16.
// Copyright © 2016 Underdark. All rights reserved.
//
import UIKit
class LogViewController: UIViewController, FormLoggerDelegate {
@IBOutlet weak var textView: UITextView!
fileprivate let formatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
formatter.dateStyle = .none
formatter.timeStyle = .medium
AppModel.shared.formLogger.updateDelegate(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
}
@IBAction func clearLog(_ sender: AnyObject) {
textView.text = ""
}
func scrollToBottom() {
let range = NSMakeRange(textView.text.characters.count - 1, 1);
textView.scrollRangeToVisible(range);
}
// MARK: - UDLoggerDelegate
func logMessage(_ message: String)
{
textView.text = textView.text + message + "\n"// + "\n"
}
}
|
c95122fb2fa4db96fa837ddad39a7da7
| 19.156863 | 68 | 0.68677 | false | false | false | false |
LOTUM/ModularAnimation
|
refs/heads/master
|
ModularAnimation/AnimationModule.swift
|
apache-2.0
|
1
|
/*
Copyright (c) 2017 LOTUM GmbH
Licensed under Apache License v2.0
See https://github.com/LOTUM/ModularAnimation/blob/master/LICENSE for license information
*/
import Foundation
import UIKit
public protocol AnimationModule {
typealias Block = () -> Void
var duration: TimeInterval { get }
func animationBlock(completion: Block?) -> Block?
func play(completion: Block?)
}
extension AnimationModule {
public func play(completion: Block? = nil) {
let animation = animationBlock(completion: completion)
animation?()
}
}
public struct BasicAnimationModule: AnimationModule {
public let duration: TimeInterval
public let delay: TimeInterval
public let options: UIViewAnimationOptions
public let animations: Block
public init(duration: TimeInterval, delay: TimeInterval = 0, options: UIViewAnimationOptions = [], animations: @escaping Block) {
self.duration = duration
self.animations = animations
self.delay = delay
self.options = options
}
public func animationBlock(completion: Block? = nil) -> Block? {
return { _ in
let completionWrapper: (Bool) -> Void = { _ in completion?() }
UIView.animate(
withDuration: self.duration,
delay: self.delay,
options: self.options,
animations: self.animations,
completion: completionWrapper
)
}
}
}
public struct SpringAnimationModule: AnimationModule {
public let duration: TimeInterval
public let delay: TimeInterval
public let dampingRatio: CGFloat
public let velocity: CGFloat
public let options: UIViewAnimationOptions
public let animations: Block
public init(duration: TimeInterval, delay: TimeInterval = 0, dampingRatio: CGFloat = 0.8, velocity: CGFloat = 4, options: UIViewAnimationOptions = [], animations: @escaping Block) {
self.duration = duration
self.delay = delay
self.dampingRatio = dampingRatio
self.velocity = velocity
self.options = options
self.animations = animations
}
public func animationBlock(completion: Block? = nil) -> Block? {
return { _ in
let completionWrapper: (Bool) -> Void = { _ in completion?() }
UIView.animate(
withDuration: self.duration,
delay: self.delay,
usingSpringWithDamping: self.dampingRatio,
initialSpringVelocity: self.velocity,
options: self.options,
animations: self.animations,
completion: completionWrapper
)
}
}
}
public class SerialAnimation: AnimationModule {
private var animationModules: [AnimationModule]
public init() {
animationModules = []
}
public convenience init(_ modules: AnimationModule...) {
self.init()
animationModules.append(contentsOf: modules)
}
public func append(_ animationModule: AnimationModule) {
animationModules.append(animationModule)
}
public var duration: TimeInterval {
let durationSum = animationModules.reduce(0, {$0 + $1.duration})
return durationSum
}
public func animationBlock(completion: Block? = nil) -> Block? {
var animations: [Block?] = [completion]
for (index, animationModule) in animationModules.reversed().enumerated() {
let completion = animations[index]
let animation = animationModule.animationBlock(completion: completion)
animations.append(animation)
}
return animations.last!
}
}
public class ParallelAnimation: AnimationModule {
private var animationModules: [AnimationModule]
public init() {
animationModules = []
}
public convenience init(_ modules: AnimationModule...) {
self.init()
animationModules.append(contentsOf: modules)
}
public func add(_ animationModule: AnimationModule) {
animationModules.append(animationModule)
}
public var duration: TimeInterval {
let longestDuration = animationModules.reduce(0, {max($0, $1.duration)})
return longestDuration
}
public func animationBlock(completion: Block? = nil) -> Block? {
if animationModules.isEmpty {
return completion
}
// return a function which plays all animations at once and passes the completion to longest
return { _ in
let longestDuration = self.duration
var completionUsed = false // in case of multiple animations with same duration
for animationModule in self.animationModules {
if !completionUsed && animationModule.duration == longestDuration {
animationModule.play(completion: completion)
completionUsed = true
} else {
animationModule.play()
}
}
}
}
}
|
c9fad77e706bd437c14c9efc5a67abf2
| 31.207547 | 185 | 0.621754 | false | false | false | false |
ibm-wearables-sdk-for-mobile/ibm-wearables-swift-sdk
|
refs/heads/master
|
IBMMobileEdge/IBMMobileEdge/Classification.swift
|
epl-1.0
|
2
|
//
// Classification.swift
// IBMMobileEdge
//
// Created by Cirill Aizenberg on 1/4/16.
// Copyright © 2016 IBM. All rights reserved.
//
import Foundation
public class Classification : BaseInterpretation{
let jsEngine = JSEngine.instance
var accelerometerDataArrays = [[Double]]()
var gyroscopeDataArrays = [[Double]]()
var timer: NSTimer!
let accelerometerListenerName = "accelerometerListener"
let gyroscopeListenerName = "gyroscopeListener"
public init(){
super.init(interpretationName: "Classification")
jsEngine.loadJS("commonClassifier")
}
public func loadGesturesByNames(gesturesFileNames:[String]){
for name in gesturesFileNames {
jsEngine.loadJS(name)
}
}
public func loadGesturesByFilePath(gesturesFilePaths:[String]){
for filePath in gesturesFilePaths {
jsEngine.loadJSFromPath(filePath)
}
}
public func setSensitivity(payload:Dictionary<String,Double>){
if payload.count > 0 {
print("set sensitivity payload = \(payload)")
jsEngine.executeMethod("setGesturesSensitivity", payload: payload)
}
}
override public func registerForEvents(sensors: Sensors) {
sensors.accelerometer.registerListener(accelerometerDataChanged,withName: accelerometerListenerName)
sensors.gyroscope.registerListener(gyroscopeDataChanged, withName: gyroscopeListenerName)
}
override public func unregisterEvents(sensors: Sensors){
sensors.accelerometer.unregisterListener(accelerometerListenerName)
sensors.gyroscope.unregisterListener(gyroscopeListenerName)
}
func accelerometerDataChanged(data:AccelerometerData) {
accelerometerDataArrays.append([data.x,data.y,data.z])
executeCalassification()
}
func gyroscopeDataChanged(data:GyroscopeData){
gyroscopeDataArrays.append([data.x,data.y,data.z])
executeCalassification()
}
func executeCalassification(){
if (accelerometerDataArrays.count > 2 && gyroscopeDataArrays.count > 2){
//make correction to data syncronization
makeDataSyncronizationFix()
//build the payload using the first 3 values
var payload = Dictionary<String,AnyObject>()
payload["accelerometer"] = [accelerometerDataArrays[0],accelerometerDataArrays[1],accelerometerDataArrays[2]]
payload["gyroscope"] = [gyroscopeDataArrays[0],gyroscopeDataArrays[1],gyroscopeDataArrays[2]]
//execute the js engine
let result = jsEngine.executeMethod("detectGesture", payload: payload).toDictionary()
//remove the first 3 value from the buffer
accelerometerDataArrays.removeFirst(3)
gyroscopeDataArrays.removeFirst(3)
if result["detected"] as! Bool == true{
notifyResult(result["additionalInfo"])
}
else if let scores = result["additionalInfo"]{
nofifyStatusUpdate(scores)
}
/*
if let resultFromJs = result{
print("Result from Calassification \(NSDate())")
print(resultFromJs)
}
*/
}
}
func makeDataSyncronizationFix(){
let accelerometerLength = accelerometerDataArrays.count
let gyroscopeLenght = gyroscopeDataArrays.count
if (accelerometerLength > gyroscopeLenght){
accelerometerDataArrays.removeFirst(accelerometerLength - gyroscopeLenght)
print("Info: Data correction fix, dropped first \(accelerometerLength - gyroscopeLenght) reads of accelerometer")
}
else if (gyroscopeLenght > accelerometerLength){
gyroscopeDataArrays.removeFirst(gyroscopeLenght - accelerometerLength)
print("Info: Data correction fix, dropped first \(gyroscopeLenght - accelerometerLength) reads of gyroscope")
}
}
}
|
1f7a50092521dd9f5ab926b5cf33969e
| 33.801653 | 125 | 0.634054 | false | false | false | false |
DimensionSrl/Acapulco
|
refs/heads/master
|
AcapulcoSample/MainViewController.swift
|
bsd-3-clause
|
1
|
//
// ViewController.swift
// AcapulcoSample
//
// Created by Nicolo' on 25/02/15.
// Copyright (c) 2015 Dimension s.r.l. All rights reserved.
//
import UIKit
public class MainViewController: UIViewController {
public override func viewDidLoad() {
super.viewDidLoad()
// Load the webview content
let URL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("README", ofType: "html")!)
let request = NSURLRequest(URL: URL)
if let webView = view as? UIWebView {
webView.loadRequest(request)
}
// Renew registrations to NSNotificationCenter
NSNotificationCenter.defaultCenter().removeObserver(self)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleApplicationDidEnterBackgroundNotification:", name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleApplicationDidBecomeActiveNotification:", name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: NotificationFactory.Names.PushReceivedNotificationName, object: nil)
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Check if we have already registered on Acapulco. If not,
// start the registration flow
if !(Acapulco.sharedInstance.isRegistered()) {
print("Acapulco is not registered, yet")
performSegueWithIdentifier("registration", sender: self)
} else {
print("Acapulco is already registered")
}
}
public func handleApplicationDidEnterBackgroundNotification(notification: NSNotification) {
// Stop accepting local notification while in background
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFactory.Names.PushReceivedNotificationName, object: nil)
}
public func handleApplicationDidBecomeActiveNotification(notification: NSNotification) {
// Resume handling local notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleNotification:", name: NotificationFactory.Names.PushReceivedNotificationName, object: nil)
}
public func handleNotification(notification: NSNotification) {
if let userInfo = notification.object as? [NSObject : AnyObject] {
if let navController = self.presentedViewController as? UINavigationController,
let contentViewController = navController.viewControllers[0] as? ContentViewController {
contentViewController.userInfo = userInfo
} else {
performSegueWithIdentifier("showContent", sender: userInfo) // We use the sender to pass the notification content
}
}
}
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let navController = segue.destinationViewController as? UINavigationController,
let contentViewController = navController.viewControllers[0] as? ContentViewController {
if let userInfo = sender as? [NSObject : AnyObject] {
contentViewController.userInfo = userInfo
}
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
f97f12a73441470f3dda52da1cd4a810
| 40.37931 | 188 | 0.677778 | false | false | false | false |
cmoulton/grokRouter
|
refs/heads/master
|
grokRouter/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// grokRouter
//
// Created by Christina Moulton on 2015-10-19.
// Copyright © 2015 Teak Mobile Inc. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class ViewController: UIViewController {
func getFirstPost() {
// Get first post
let request = Alamofire.request(PostRouter.Get(1))
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /posts/1")
print(response.result.error!)
return
}
if let value: AnyObject = response.result.value {
// handle the results as JSON, without a bunch of nested if loops
let post = JSON(value)
// now we have the results, let's just print them though a tableview would definitely be better UI:
print("The post is: " + post.description)
if let title = post["title"].string {
// to access a field:
print("The title is: " + title)
} else {
print("error parsing /posts/1")
}
}
}
debugPrint(request)
}
func createPost() {
let newPost = ["title": "Frist Psot", "body": "I iz fisrt", "userId": 1]
Alamofire.request(PostRouter.Create(newPost))
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET on /posts/1")
print(response.result.error!)
return
}
if let value: AnyObject = response.result.value {
// handle the results as JSON, without a bunch of nested if loops
let post = JSON(value)
print("The post is: " + post.description)
}
}
}
func deleteFirstPost() {
Alamofire.request(PostRouter.Delete(1))
.responseJSON { response in
if let error = response.result.error {
// got an error while deleting, need to handle it
print("error calling DELETE on /posts/1")
print(error)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getFirstPost()
//createPost()
//deleteFirstPost()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
b38a505f1cfd92b64ec351e1a7be5465
| 27.772727 | 109 | 0.596761 | false | false | false | false |
iluuu1994/Conway-s-Game-of-Life
|
refs/heads/master
|
Conway's Game of Life/Conway's Game of Life/TwoWayBinding.swift
|
bsd-2-clause
|
1
|
//
// TwoWayBinding.swift
// Conway's Game of Life
//
// Created by Ilija Tovilo on 26/08/14.
// Copyright (c) 2014 Ilija Tovilo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
public class TwoWayBinding: NSObject {
public let leadingElement: NSObject
public let leadingKeyPath: String
public let followingElement: NSObject
public let followingKeyPath: String
public init(leadingElement: NSObject, leadingKeyPath: String, followingElement: NSObject, followingKeyPath: String) {
self.leadingElement = leadingElement
self.leadingKeyPath = leadingKeyPath
self.followingElement = followingElement
self.followingKeyPath = followingKeyPath
super.init()
bind()
}
deinit {
unbind()
}
public func bind() {
leadingElement.addObserver(
self,
forKeyPath: leadingKeyPath,
options: NSKeyValueObservingOptions.New,
context: nil
)
followingElement.addObserver(
self,
forKeyPath: followingKeyPath,
options: NSKeyValueObservingOptions.New,
context: nil
)
}
public func unbind() {
leadingElement.removeObserver(self, forKeyPath: leadingKeyPath)
followingElement.removeObserver(self, forKeyPath: followingKeyPath)
}
override public func observeValueForKeyPath(
keyPath: String!,
ofObject object: AnyObject!,
change: [NSObject : AnyObject]!,
context: UnsafeMutablePointer<Void>)
{
let (from, fromKP, to, toKP) = object === leadingElement ?
(leadingElement, leadingKeyPath, followingElement, followingKeyPath) :
(followingElement, followingKeyPath, leadingElement, leadingKeyPath)
let oldValue = to.valueForKeyPath(toKP) as NSNumber
let newValue = from.valueForKeyPath(fromKP) as NSNumber
if oldValue !== newValue {
to.setValue(newValue, forKeyPath: toKP)
}
}
}
|
0768b03a3c5699f6bbf30341bab34ccf
| 35.390805 | 121 | 0.674984 | false | false | false | false |
juliangrosshauser/PercentAge
|
refs/heads/master
|
PercentAge/Classes/View Controllers/BirthdayViewController.swift
|
mit
|
1
|
//
// BirthdayViewController.swift
// PercentAge
//
// Created by Julian Grosshauser on 14/03/15.
// Copyright (c) 2015 Julian Grosshauser. All rights reserved.
//
import UIKit
import PercentAgeKit
class BirthdayViewController: UIViewController {
//MARK: Properties
private let viewModel = BirthdayViewModel()
private var longPressTimer: NSTimer?
//MARK: Initialization
init() {
super.init(nibName: nil, bundle: nil)
viewModel.addObserver(self, forKeyPath: "day", options: .New, context: &BirthdayViewModel.observeContext)
viewModel.addObserver(self, forKeyPath: "month", options: .New, context: &BirthdayViewModel.observeContext)
viewModel.addObserver(self, forKeyPath: "year", options: .New, context: &BirthdayViewModel.observeContext)
modalTransitionStyle = .CrossDissolve
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//MARK: Deinitialization
deinit {
viewModel.removeObserver(self, forKeyPath: "day", context: &BirthdayViewModel.observeContext)
viewModel.removeObserver(self, forKeyPath: "month", context: &BirthdayViewModel.observeContext)
viewModel.removeObserver(self, forKeyPath: "year", context: &BirthdayViewModel.observeContext)
}
//MARK: Key-Value Observing
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if (context == &BirthdayViewModel.observeContext) {
if let newValue = change[NSKeyValueChangeNewKey] as? Int {
let birthdayView = view as! BirthdayView
switch keyPath {
case "day":
birthdayView.dayValueLabel.text = String(newValue)
case "month":
birthdayView.monthValueLabel.text = String(newValue)
case "year":
birthdayView.yearValueLabel.text = String(newValue)
default:
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
//MARK: UIViewController
override func loadView() {
view = BirthdayView()
}
override func viewDidLoad() {
super.viewDidLoad()
let birthdayView = view as! BirthdayView
birthdayView.dayValueLabel.text = String(viewModel.day)
birthdayView.monthValueLabel.text = String(viewModel.month)
birthdayView.yearValueLabel.text = String(viewModel.year)
birthdayView.incrementDayButton.addTarget(self, action: "incrementDayButtonDown:", forControlEvents: .TouchDown)
birthdayView.incrementDayButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside)
birthdayView.decrementDayButton.addTarget(self, action: "decrementDayButtonDown:", forControlEvents: .TouchDown)
birthdayView.decrementDayButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside)
birthdayView.incrementMonthButton.addTarget(self, action: "incrementMonthButtonDown:", forControlEvents: .TouchDown)
birthdayView.incrementMonthButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside)
birthdayView.decrementMonthButton.addTarget(self, action: "decrementMonthButtonDown:", forControlEvents: .TouchDown)
birthdayView.decrementMonthButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside)
birthdayView.incrementYearButton.addTarget(self, action: "incrementYearButtonDown:", forControlEvents: .TouchDown)
birthdayView.incrementYearButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside)
birthdayView.decrementYearButton.addTarget(self, action: "decrementYearButtonDown:", forControlEvents: .TouchDown)
birthdayView.decrementYearButton.addTarget(self, action: "resetButtonTransform:", forControlEvents: .TouchUpInside)
birthdayView.saveButton.addTarget(self, action: "saveBirthday:", forControlEvents: .TouchUpInside)
let longPressIncrementDay = UILongPressGestureRecognizer(target: self, action: "longPressIncrementDay:")
longPressIncrementDay.minimumPressDuration = 0.3
birthdayView.incrementDayButton.addGestureRecognizer(longPressIncrementDay)
let longPressIncrementMonth = UILongPressGestureRecognizer(target: self, action: "longPressIncrementMonth:")
longPressIncrementMonth.minimumPressDuration = 0.3
birthdayView.incrementMonthButton.addGestureRecognizer(longPressIncrementMonth)
let longPressIncrementYear = UILongPressGestureRecognizer(target: self, action: "longPressIncrementYear:")
longPressIncrementYear.minimumPressDuration = 0.3
birthdayView.incrementYearButton.addGestureRecognizer(longPressIncrementYear)
let longPressDecrementDay = UILongPressGestureRecognizer(target: self, action: "longPressDecrementDay:")
longPressDecrementDay.minimumPressDuration = 0.3
birthdayView.decrementDayButton.addGestureRecognizer(longPressDecrementDay)
let longPressDecrementMonth = UILongPressGestureRecognizer(target: self, action: "longPressDecrementMonth:")
longPressDecrementMonth.minimumPressDuration = 0.3
birthdayView.decrementMonthButton.addGestureRecognizer(longPressDecrementMonth)
let longPressDecrementYear = UILongPressGestureRecognizer(target: self, action: "longPressDecrementYear:")
longPressDecrementYear.minimumPressDuration = 0.3
birthdayView.decrementYearButton.addGestureRecognizer(longPressDecrementYear)
}
//MARK: Button Actions
@objc
private func incrementDayButtonDown(sender: UIButton) {
tranformButton(sender)
viewModel.incrementDay()
}
@objc
private func decrementDayButtonDown(sender: UIButton) {
tranformButton(sender)
viewModel.decrementDay()
}
@objc
private func incrementMonthButtonDown(sender: UIButton) {
tranformButton(sender)
viewModel.incrementMonth()
}
@objc
private func decrementMonthButtonDown(sender: UIButton) {
tranformButton(sender)
viewModel.decrementMonth()
}
@objc
private func incrementYearButtonDown(sender: UIButton) {
tranformButton(sender)
viewModel.incrementYear()
}
@objc
private func decrementYearButtonDown(sender: UIButton) {
tranformButton(sender)
viewModel.decrementYear()
}
@objc
private func saveBirthday(sender: AnyObject) {
let userDefaults = NSUserDefaults(suiteName: "group.com.juliangrosshauser.PercentAge")!
viewModel.saveBirthdayIntoUserDefaults(userDefaults)
presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
//MARK: Gesture Recognizer Actions
@objc
private func longPressIncrementDay(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if (longPressGestureRecognizer.state == .Began) {
longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "incrementDay", userInfo: nil, repeats: true)
}
if (longPressGestureRecognizer.state == .Ended) {
longPressTimer?.invalidate()
let birthdayView = view as! BirthdayView
resetButtonTransform(birthdayView.incrementDayButton)
}
}
@objc
private func longPressIncrementMonth(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if (longPressGestureRecognizer.state == .Began) {
longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "incrementMonth", userInfo: nil, repeats: true)
}
if (longPressGestureRecognizer.state == .Ended) {
longPressTimer?.invalidate()
let birthdayView = view as! BirthdayView
resetButtonTransform(birthdayView.incrementMonthButton)
}
}
@objc
private func longPressIncrementYear(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if (longPressGestureRecognizer.state == .Began) {
longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "incrementYear", userInfo: nil, repeats: true)
}
if (longPressGestureRecognizer.state == .Ended) {
longPressTimer?.invalidate()
let birthdayView = view as! BirthdayView
resetButtonTransform(birthdayView.incrementYearButton)
}
}
@objc
private func longPressDecrementDay(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if (longPressGestureRecognizer.state == .Began) {
longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "decrementDay", userInfo: nil, repeats: true)
}
if (longPressGestureRecognizer.state == .Ended) {
longPressTimer?.invalidate()
let birthdayView = view as! BirthdayView
resetButtonTransform(birthdayView.decrementDayButton)
}
}
@objc
private func longPressDecrementMonth(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if (longPressGestureRecognizer.state == .Began) {
longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "decrementMonth", userInfo: nil, repeats: true)
}
if (longPressGestureRecognizer.state == .Ended) {
longPressTimer?.invalidate()
let birthdayView = view as! BirthdayView
resetButtonTransform(birthdayView.decrementMonthButton)
}
}
@objc
private func longPressDecrementYear(longPressGestureRecognizer: UILongPressGestureRecognizer) {
if (longPressGestureRecognizer.state == .Began) {
longPressTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: viewModel, selector: "decrementYear", userInfo: nil, repeats: true)
}
if (longPressGestureRecognizer.state == .Ended) {
longPressTimer?.invalidate()
let birthdayView = view as! BirthdayView
resetButtonTransform(birthdayView.decrementYearButton)
}
}
//MARK: Button Transform
private func tranformButton(button: UIButton) {
UIView.animateWithDuration(0.1, animations: {
button.layer.transform = CATransform3DMakeScale(0.8, 0.8, 1.0)
})
}
@objc
private func resetButtonTransform(button: UIButton) {
UIView.animateWithDuration(0.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .CurveEaseInOut, animations: {
button.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
|
8b1a675b0e5ddc0975f369922ec49928
| 39.512635 | 156 | 0.704331 | false | false | false | false |
KellenYangs/KLSwiftTest_05_05
|
refs/heads/master
|
CoreGraphicsTest/CoreGraphicsTest/Flo/CounterView.swift
|
mit
|
1
|
//
// CounterView.swift
// CoreGraphicsTest
//
// Created by bcmac3 on 16/5/26.
// Copyright © 2016年 KellenYangs. All rights reserved.
//
import UIKit
let NoOfGlasses = 8
let π: CGFloat = CGFloat(M_PI)
@IBDesignable
class CounterView: UIView {
/// 当前计数
@IBInspectable var counter: Int = 5 {
didSet {
if counter <= NoOfGlasses && counter >= 0 {
setNeedsDisplay()
}
}
}
@IBInspectable var outlineColor: UIColor = UIColor.blueColor()
@IBInspectable var counterColor: UIColor = UIColor.orangeColor()
override func drawRect(rect: CGRect) {
// 1. 外轮廓
let center: CGPoint = CGPoint(x: bounds.width / 2, y: bounds.height / 2)
let radius: CGFloat = max(bounds.width, bounds.height) / 2
let arcWidth: CGFloat = radius * 2 / 3
let startAngle: CGFloat = 3 * π / 4
let endAngle: CGFloat = π / 4
let path = UIBezierPath(arcCenter: center, radius: radius - arcWidth / 2, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.lineWidth = arcWidth
counterColor.setStroke()
path.stroke()
// 2. 当前计数轮廓
let angleDifference: CGFloat = 2 * π - startAngle + endAngle
let arcLengthPerGlass = angleDifference / CGFloat(NoOfGlasses)
let outlineEndAngle = arcLengthPerGlass * CGFloat(counter) + startAngle
let outlinePath = UIBezierPath(arcCenter: center, radius: radius - 2.5, startAngle: startAngle, endAngle:outlineEndAngle, clockwise: true)
outlinePath.addArcWithCenter(center, radius: radius - arcWidth + 2.5, startAngle: outlineEndAngle, endAngle: startAngle, clockwise: false)
outlinePath.closePath()
outlineColor.setStroke()
outlinePath.lineWidth = 5.0
outlinePath.stroke()
// 3.小指标
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
outlineColor.setFill()
let markerWidth: CGFloat = 5.0
let markerSize: CGFloat = 10.0
let markerPath = UIBezierPath(rect: CGRect(x: -markerWidth/2, y: 0, width: markerWidth, height: markerSize))
// 移动
CGContextTranslateCTM(context, rect.width/2, rect.height/2)
for i in 1...NoOfGlasses {
CGContextSaveGState(context)
let angle = arcLengthPerGlass * CGFloat(i) + startAngle - π/2
CGContextRotateCTM(context, angle)
CGContextTranslateCTM(context, 0, rect.height/2 - markerSize)
markerPath.fill()
CGContextRestoreGState(context)
}
CGContextRestoreGState(context)
}
}
|
2a6c6e5c88f285414fe50be2fd7b9747
| 31.593023 | 146 | 0.601498 | false | false | false | false |
fjtrujy/FTMTableSectionModules
|
refs/heads/master
|
Tests/ModuleServicesTests/TableSectionModuleTest.swift
|
mit
|
1
|
//
// TableSectionModuleTest.swift
// ModuleServices
//
// Created by Francisco Trujillo on 16/05/2016.
// Copyright © 2016 FJTRUJY. All rights reserved.
//
import UIKit
import XCTest
import ModuleServices
class TableSectionModuleTest: XCTestCase {
}
// MARK: - Fetching functions
extension TableSectionModuleTest {
func testStartFetchDefault() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
XCTAssert(!module.isFetching, "The module shouldnt be fecthing by default")
}
func testStartFetchTrue() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
module.startFetch()
XCTAssert(module.isFetching, "The module should be fecthing")
}
func testStartFetch() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
XCTAssert(!module.isFetching, "The module shouldn't be fecthing")
module.startFetch()
XCTAssert(module.isFetching, "The module should be fecthing")
}
func testStopFetchDefault() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
XCTAssert(!module.isFetching, "The module shouldnt be fecthing by default")
}
func testStopFetchTrue() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
module.startFetch()
module.stopFetch()
XCTAssert(!module.isFetching, "The module shouldnt be fecthing")
}
func testStopFetchFalse() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
module.startFetch()
XCTAssert(module.isFetching, "The module should be fecthing")
}
func testStopFetch() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
module.startFetch()
XCTAssert(module.isFetching, "The module should be fecthing")
module.stopFetch()
XCTAssert(!module.isFetching, "The module should be fecthing")
}
func testFetchCicle() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
XCTAssert(!module.isFetching, "The module shouldnt be fecthing by default")
module.startFetch()
XCTAssert(module.isFetching, "The module should be fecthing")
module.stopFetch()
XCTAssert(!module.isFetching, "The module should be fecthing")
}
}
//MARK: - isPresented Functions
extension TableSectionModuleTest {
func testDefaultPresentedValue() {
let tableView : UITableView = UITableView()
let module : TableSectionModule = TableSectionModule(tableView: tableView)
XCTAssert(!module.isPresented, "The module shouldnt be presented by default")
}
}
//MARK: - Registers Functions
extension TableSectionModuleTest {
func testRegisterNotNilHeader() {
let tableView : UITableView = UITableView()
let module : TestModule1 = TestModule1(tableView: tableView)
let header : UITableViewHeaderFooterView = module.tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TestExample1HeaderFooterView.self))!
XCTAssertNotNil(header, "The TestExample1HeaderFooterView should be dequeued")
}
func testRegisterNotNilCells() {
let tableView : UITableView = UITableView()
let module : TestModule1 = TestModule1(tableView: tableView)
let cell : UITableViewCell = module.tableView.dequeueReusableCell(withIdentifier: String(describing: TestExample1TableViewCell.self))!
XCTAssertNotNil(cell, "The TestExample1TableViewCell should be dequeued")
}
func testRegisterFullModule() {
let tableView : UITableView = UITableView()
let module : TestModule3 = TestModule3(tableView: tableView)
var header : UITableViewHeaderFooterView
var cell : UITableViewCell
header = module.tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TestExample1HeaderFooterView.self))!
XCTAssertNotNil(header, "The TestExample1HeaderFooterView should be dequeued")
header = module.tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: TestExample2HeaderFooterView.self))!
XCTAssertNotNil(header, "The TestExample2HeaderFooterView should be dequeued")
cell = module.tableView.dequeueReusableCell(withIdentifier: String(describing: TestExample1TableViewCell.self))!
XCTAssertNotNil(cell, "The TestExample1TableViewCell should be dequeued")
cell = module.tableView.dequeueReusableCell(withIdentifier: String(describing: TestExample2TableViewCell.self))!
XCTAssertNotNil(cell, "The TestExample2TableViewCell should be dequeued")
}
}
|
efa46381701018aa9738e950cfa020c1
| 35.744966 | 171 | 0.680548 | false | true | false | false |
sirhans/ListeningTest
|
refs/heads/master
|
HelloWorld/ViewController.swift
|
unlicense
|
1
|
//
// ViewController.swift
// ListeningTest
//
// Created by hans anderson on 12/4/15.
// Anyone may use this file without restrictions
//
import AudioKit
import UIKit
class ViewController: UIViewController {
var oscillator1 = AKOscillator()
var oscillator2 = AKOscillator()
var mixer = AKMixer()
var file: AKAudioFile!
var playerA: AKAudioPlayer!
var playerB: AKAudioPlayer!
var playerReference: AKAudioPlayer!
var audioFolderURL: URL!
var folderList: [String]!
var totalQuestions = 0
var currentQuestion = 1
var correctAnswers = [answerChoice]()
var userAnswers = [answerChoice]()
var activeQuestions = [Bool]()
var orangeColour = UIColor(hue: 38.0/360.0, saturation: 1.0, brightness: 1.0, alpha: 1.0)
var blueColour = UIColor(hue: 196.0/360.0, saturation: 1.0, brightness: 1.0, alpha: 1.0)
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var resultsView: UITextView!
@IBOutlet weak var questionNumberLabel: UILabel!
@IBOutlet weak var BButton: UIButton!
@IBOutlet weak var AButton: UIButton!
@IBOutlet weak var questionDataLabel: UILabel!
@IBOutlet weak var copyButton: UIButton!
enum answerChoice {
case A, B, unknown
}
func segmentedControlIndex(ac: answerChoice) -> Int {
switch ac {
case .A:
return 0
case .unknown:
return 1
case .B:
return 2
}
}
func indexToAnswerChoice(idx: Int) -> answerChoice {
switch idx {
case 0:
return answerChoice.A
case 1:
return answerChoice.unknown
case 2:
return answerChoice.B
default:
return answerChoice.unknown
}
}
// hide status bar
override var prefersStatusBarHidden: Bool {
return true
}
func sortFunc(num1: String, num2: String) -> Bool {
return num1 < num2
}
func randomiseCorrectAnswers() {
correctAnswers.removeAll()
for _ in 1...totalQuestions {
// set correct answers randomly
let randomAnswer = 2*Int(arc4random_uniform(2));
correctAnswers.append(indexToAnswerChoice(idx: randomAnswer));
// initialise all user answers to unknown
userAnswers.append(answerChoice.unknown);
activeQuestions.append(true);
}
}
func updateResults(copy: Bool = false) {
var results = "";
for i in 1...totalQuestions{
// generate a right or wrong string
var correctQ = String(userAnswers[i-1]==correctAnswers[i-1])
// don't show anyresult if the user didn't answer the question
if (userAnswers[i-1] == answerChoice.unknown){
correctQ = " ";
}
// append the result of question i
results.append(String(i) + ": " + correctQ + "\n")
}
// update the results text view
resultsView.text = results
// copy to pasteboard
if(copy){
UIPasteboard.general.setValue(results, forPasteboardType: "public.plain-text");
}
}
func updateQuestion(){
// update the label text at the top of the screen
updateQuestionLabel()
// load the answer previously given by the user into the
// segmented control
loadAnswer()
// update results page to show how the user scored
updateResults()
// if at the end of the test,
// show the results
if(currentQuestion > totalQuestions){
// otherwise load the audio
} else {
AudioKit.stop()
let questionFolderURL = URL(fileURLWithPath: folderList[currentQuestion-1], relativeTo: audioFolderURL)
let referenceAudioURL = URL(fileURLWithPath: "reference.wav", relativeTo: questionFolderURL)
let whiteAudioURL = URL(fileURLWithPath: "white.wav", relativeTo: questionFolderURL)
let filteredAudioURL = URL(fileURLWithPath: "filtered.wav", relativeTo: questionFolderURL)
questionDataLabel.text = questionFolderURL.relativeString
do {
// load the reference audio file
let referenceAudioFile = try AKAudioFile(forReading: referenceAudioURL)
playerReference = try AKAudioPlayer(file: referenceAudioFile)
let audioFileA: AKAudioFile!
let audioFileB: AKAudioFile!
// switch the order of samples A and B according to the random
// selection determined at the start of the test
if (correctAnswers[currentQuestion-1] == answerChoice.A) {
audioFileB = try AKAudioFile(forReading: whiteAudioURL)
audioFileA = try AKAudioFile(forReading: filteredAudioURL)
} else {
audioFileA = try AKAudioFile(forReading: whiteAudioURL)
audioFileB = try AKAudioFile(forReading: filteredAudioURL)
}
// load the A and B audio files
playerA = try AKAudioPlayer(file: audioFileA)
playerB = try AKAudioPlayer(file: audioFileB)
} catch let error {
print("Error: \(error.localizedDescription)")
}
mixer = AKMixer(playerA, playerB, playerReference)
AudioKit.output = mixer
AudioKit.start()
}
}
override func viewDidLoad() {
let font = UIFont.systemFont(ofSize: 20)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],for: .normal)
// set the colour for buttons in disabled state
//backButton.setTitleColor(UIColor.darkGray, for: .disabled)
//nextButton.setTitleColor(UIColor.darkGray, for: .disabled)
// hide the question data label
questionDataLabel.alpha = 0.0;
// get the list of subfolders in the audio folder
// audioFolderURL = URL(fileURLWithPath: "audio", relativeTo: Bundle.main.bundleURL)
audioFolderURL = URL(fileURLWithPath: "audio", relativeTo: Bundle.main.bundleURL)
do {
folderList = try FileManager.default.contentsOfDirectory(atPath: audioFolderURL.path) as [String]
folderList = folderList.sorted { $0.localizedStandardCompare($1) == ComparisonResult.orderedAscending }
print (folderList);
} catch let error {
print("Error loading audio files: \(error.localizedDescription)")
}
// each folder is one question; update the question label
// to show the correct number of questions
totalQuestions = folderList.count
updateQuestionLabel()
// randomly generate correct answers
randomiseCorrectAnswers()
// start the test
updateQuestion()
super.viewDidLoad()
}
@IBAction func playReferenceSound(_ sender: Any) {
if !playerReference.isPlaying {
playerReference.start()
}
}
@IBAction func stopReferenceSound(_ sender: Any) {
if playerReference.isPlaying {
playerReference.stop()
}
}
@IBAction func playSoundA(_ sender: UIButton) {
if !playerA.isPlaying {
//sender.setTitle("Stop", for: .normal)
playerA.start()
}
}
@IBAction func stopSoundA(_ sender: UIButton) {
if playerA.isPlaying {
//sender.setTitle("Play", for: .normal)
playerA.stop()
}
}
@IBAction func playSoundB(_ sender: UIButton) {
if !playerB.isPlaying {
//sender.setTitle("Stop", for: .normal)
playerB.start()
}
}
@IBAction func stopSoundB(_ sender: UIButton) {
if playerB.isPlaying {
//sender.setTitle("Play", for: .normal)
playerB.stop()
}
}
func updateQuestionLabel(){
questionNumberLabel.text = String(currentQuestion) + " / " + String(totalQuestions)
// show results at the end
if(currentQuestion == totalQuestions + 1){
questionNumberLabel.text = "results";
}
}
func recordAnswer() {
if (currentQuestion <= totalQuestions){
userAnswers[currentQuestion - 1] = indexToAnswerChoice(idx: segmentedControl.selectedSegmentIndex)
}
}
func loadAnswer() {
// load the answer unless we are on the results page
if (currentQuestion <= totalQuestions){
// load the answer to the segmented control
segmentedControl.selectedSegmentIndex = segmentedControlIndex(ac: userAnswers[currentQuestion - 1])
// don't allow the user to change the
// answer for questions after viewing
// the correct answer
segmentedControl.isEnabled = activeQuestions[currentQuestion - 1]
}
}
func advanceQuestion(amount: Int){
// record the answer to the current question
recordAnswer()
// increment the question number
currentQuestion += amount
// wrap back to the beginning when we reach the end
if(currentQuestion > totalQuestions + 1){
currentQuestion = 1
}
// show results when we reach the end
resultsView.isHidden = !(currentQuestion == totalQuestions+1)
copyButton.isHidden = resultsView.isHidden
updateQuestion()
}
@IBAction func nextButtonTouched(_ sender: Any) {
advanceQuestion(amount:1);
}
@IBAction func fastNextTouched(_ sender: Any) {
advanceQuestion(amount:10);
}
@IBAction func doubleFastNextTouched(_ sender: Any) {
advanceQuestion(amount:100);
}
func toPreviousQuestion(amount: Int){
// record the answer to the current question
recordAnswer()
// decrement the question number
currentQuestion -= amount
// wrap to the end if we are at the beginning
if (currentQuestion < 1){
currentQuestion = totalQuestions + 1
}
// hide results when we are not yet at the end
resultsView.isHidden = !(currentQuestion == totalQuestions+1)
copyButton.isHidden = resultsView.isHidden
updateQuestion()
}
@IBAction func backButtonTouched(_ sender: Any) {
toPreviousQuestion(amount:1)
}
@IBAction func fastBackTouched(_ sender: Any) {
toPreviousQuestion(amount:10)
}
@IBAction func doubleFastBackTouched(_ sender: Any) {
toPreviousQuestion(amount:100)
}
@IBAction func showAnswer(_ sender: Any) {
if correctAnswers[currentQuestion-1] == answerChoice.A {
AButton.backgroundColor = orangeColour
} else {
BButton.backgroundColor = orangeColour
}
questionDataLabel.alpha = 1.0
// set the current question inactive
// now that the user has seen the answer
activeQuestions[currentQuestion-1] = false;
// disable the control so that the user
// can not change the answer
segmentedControl.isEnabled = false;
}
@IBAction func hideAnswer(_ sender: Any) {
AButton.backgroundColor = blueColour
BButton.backgroundColor = blueColour
questionDataLabel.alpha = 0.0
}
@IBAction func copyResults(_ sender: Any) {
updateResults(copy: true);
}
}
|
4b9f2fe24f37a7bcc1e6cc0f1fda51c9
| 27.377574 | 115 | 0.56689 | false | false | false | false |
illescasDaniel/Questions
|
refs/heads/master
|
Questions/Models/Question.swift
|
mit
|
1
|
//
// QuestionType.swift
// Questions
//
// Created by Daniel Illescas Romero on 24/05/2018.
// Copyright © 2018 Daniel Illescas Romero. All rights reserved.
//
import Foundation
class Question: Codable, CustomStringConvertible {
let question: String
let answers: [String]
var correctAnswers: Set<UInt8>! = []
let correct: UInt8?
let imageURL: String?
init(question: String, answers: [String], correct: Set<UInt8>, singleCorrect: UInt8? = nil, imageURL: String? = nil) {
self.question = question.trimmingCharacters(in: .whitespacesAndNewlines)
self.answers = answers.map({ $0.trimmingCharacters(in: .whitespacesAndNewlines) })
self.correctAnswers = correct
self.correct = singleCorrect
self.imageURL = imageURL?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
extension Question: Equatable {
static func ==(lhs: Question, rhs: Question) -> Bool {
return lhs.question == rhs.question && lhs.answers == rhs.answers && lhs.correctAnswers == rhs.correctAnswers
}
}
extension Question: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(self.question.hash)
}
}
|
344ed7553de3d84f9e9e86375077a2c5
| 28.236842 | 119 | 0.730873 | false | false | false | false |
KogiMobileSAS/KeyboardResize
|
refs/heads/master
|
Example/TableViewController.swift
|
mit
|
1
|
//
// TableViewController.swift
// Example
//
// Created by Juan Alberto Uribe on 6/16/16.
// Copyright © 2016 Kogi Mobile. All rights reserved.
//
import UIKit
class TableViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
configureTable()
kr_resizeViewWhenKeyboardAppears = true
}
private func configureTable() {
tableView.dataSource = self
let footerFrame = CGRect(x: 0, y: 0, width: view.bounds.width, height: 50)
let footerLabel = UILabel(frame: footerFrame)
footerLabel.text = "FOOTER"
tableView.tableFooterView = footerLabel
}
}
extension TableViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 15
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell",
forIndexPath: indexPath)
return cell
}
}
|
8dd989dd7d0326b18e2a831a59746655
| 26.431818 | 109 | 0.63546 | false | false | false | false |
EugeneVegner/sws-copyleaks-sdk-test
|
refs/heads/master
|
PlagiarismChecker/Classes/CopyleaksToken.swift
|
mit
|
1
|
/*
* The MIT License(MIT)
*
* Copyright(c) 2016 Copyleaks LTD (https://copyleaks.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
private let copyleaksToken = "copyleaksToken"
class CopyleaksToken: NSObject, NSCoding {
var accessToken: String?
var issued: String?
var expires: String?
private let copyleaksTokenKey = "copyleaksTokenKey"
private let copyleaksTokenIssued = "copyleaksTokenIssued"
private let copyleaksTokenExpired = "copyleaksTokenExpired"
init(response: CopyleaksResponse<AnyObject, NSError>) {
if let accessTokenVal = response.result.value?["access_token"] as? String,
let issuedVal = response.result.value?[".issued"] as? String,
let expiresVal = response.result.value?[".expires"] as? String {
accessToken = accessTokenVal
issued = issuedVal
expires = expiresVal
}
}
required init(coder aDecoder: NSCoder) {
accessToken = aDecoder.decodeObjectForKey(copyleaksTokenKey) as? String
issued = aDecoder.decodeObjectForKey(copyleaksTokenIssued) as? String
expires = aDecoder.decodeObjectForKey(copyleaksTokenExpired) as? String
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(accessToken, forKey: copyleaksTokenKey)
aCoder.encodeObject(issued, forKey: copyleaksTokenIssued)
aCoder.encodeObject(expires, forKey: copyleaksTokenExpired)
}
func save() {
let data = NSKeyedArchiver.archivedDataWithRootObject(self)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(data, forKey:copyleaksToken )
}
func isValid() -> Bool {
guard let accessTokenVal = accessToken, issuedVal = issued, expiresVal = expires else {
return false
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = CopyleaksConst.dateTimeFormat
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let issuedDate = dateFormatter.dateFromString(issuedVal)
let expiresDate = dateFormatter.dateFromString(expiresVal)
return true
}
func generateAccessToken() -> String {
if self.isValid() {
return "Bearer " + accessToken!
} else {
return ""
}
}
class func hasAccessToken() -> Bool {
guard let _ = getAccessToken() else {
return false
}
return true
}
class func getAccessToken() -> CopyleaksToken? {
if let data = NSUserDefaults.standardUserDefaults().objectForKey(copyleaksToken) as? NSData {
return (NSKeyedUnarchiver.unarchiveObjectWithData(data) as? CopyleaksToken)!
}
return nil
}
class func clear() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(copyleaksToken)
}
}
|
d741a0a9b515ab9c308665b84932f6df
| 33.86087 | 101 | 0.676727 | false | false | false | false |
mkrisztian95/iOS
|
refs/heads/master
|
Tardis/ScheduleItem.swift
|
apache-2.0
|
1
|
//
// ScheduleItem.swift
// Tardis
//
// Created by Molnar Kristian on 7/25/16.
// Copyright © 2016 Molnar Kristian. All rights reserved.
//
import UIKit
import Firebase
@IBDesignable class ScheduleItem: UIView {
@IBOutlet weak var eventTitle: UILabel!
@IBOutlet weak var locationLabel: UILabel!
var view: UIView!
let storage = FIRStorage.storage()
var tapped = false
func xibSetup() {
view = loadViewFromNib()
// use bounds not frame or it'll be offset
view.frame = bounds
// Make the view stretch with containing view
view.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
// Adding custom subview on top of our view (over any custom drawing > see note below)
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "ScheduleItem", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
view.layer.cornerRadius = 5.0
return view
}
override init(frame: CGRect) {
// 1. setup any properties here
// 2. call super.init(frame:)
super.init(frame: frame)
// 3. Setup view from .xib file
xibSetup()
}
func setUp(time:String, title:String, location:String) {
self.eventTitle.text = title
self.locationLabel.text = "Location: \(location)"
self.eventTitle.adjustsFontSizeToFitWidth = true
}
required init?(coder aDecoder: NSCoder) {
// 1. setup any properties here
// 2. call super.init(coder:)
super.init(coder: aDecoder)
// 3. Setup view from .xib file
xibSetup()
}
}
|
283daca4540eb159241b72b9f9def824
| 24.455882 | 97 | 0.65338 | false | false | false | false |
SmallPlanetSwift/PlanetSwift
|
refs/heads/master
|
Sources/PlanetSwift/PlanetCollectionViewController.swift
|
mit
|
1
|
//
// PlanetCollectionViewController.swift
// Planned
//
// Created by Quinn McHenry on 12/2/15.
// Copyright (c) 2015 Small Planet Digital. All rights reserved.
//
// swiftlint:disable line_length
// swiftlint:disable force_cast
import UIKit
public protocol PlanetCollectionViewTemplate {
var reuseId: String { get }
var size: TemplateSize { get }
func decorate(_ cell: UICollectionViewCell)
}
public typealias TemplateSize = (width: TemplateConstraint, height: TemplateConstraint)
public enum TemplateConstraint {
case unconstrained
case full
case half
case fixed(points: Float)
}
public func == (lhs: TemplateConstraint, rhs: TemplateConstraint) -> Bool {
switch (lhs, rhs) {
case (.unconstrained, .unconstrained): return true
case (.full, .full): return true
case (.half, .half): return true
case (.fixed(let aaa), .fixed(let bbb)) where aaa == bbb: return true
default: return false
}
}
public func != (lhs: TemplateConstraint, rhs: TemplateConstraint) -> Bool {
return !(lhs == rhs)
}
public func == (lhs: TemplateSize, rhs: TemplateSize) -> Bool {
return lhs.width == rhs.width && lhs.height == rhs.height
}
public func != (lhs: TemplateSize, rhs: TemplateSize) -> Bool {
return !(lhs == rhs)
}
public protocol PlanetCollectionViewCell: class {
var bundlePath: String { get }
var xmlView: View? { get set }
func loadView()
}
public extension PlanetCollectionViewCell where Self: UICollectionViewCell {
func loadView() {
guard xmlView == nil else { return }
xmlView = PlanetUI.readFromFile(String(bundlePath: bundlePath)) as? View
guard let xmlView = xmlView else {
// failed to create xml view from bundlePath \(bundlePath)
return
}
contentView.addSubview(xmlView.view)
xmlView.visit { $0.gaxbDidPrepare() }
let mirror = Mirror(reflecting: self)
for case let (label?, _) in mirror.children {
if let element = xmlView.elementForId(label) as? View {
setValue(element.view, forKey: label)
}
}
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .width))
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .height))
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .left))
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: contentView, equalAttribute: .top))
xmlView.view.translatesAutoresizingMaskIntoConstraints = false
contentView.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .width))
addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .height))
addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .left))
addConstraint(NSLayoutConstraint(item: self, toItem: contentView, equalAttribute: .top))
}
}
public extension PlanetCollectionViewCell where Self: UICollectionReusableView {
func loadView() {
guard xmlView == nil else { return }
xmlView = PlanetUI.readFromFile(String(bundlePath: bundlePath)) as? View
guard let xmlView = xmlView else {
// failed to create xml view from bundlePath \(bundlePath)
return
}
addSubview(xmlView.view)
xmlView.visit { $0.gaxbDidPrepare() }
let mirror = Mirror(reflecting: self)
for case let (label?, _) in mirror.children {
if let element = xmlView.elementForId(label) as? View {
setValue(element.view, forKey: label)
}
}
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .width))
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .height))
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .left))
addConstraint(NSLayoutConstraint(item: xmlView.view, toItem: self, equalAttribute: .top))
xmlView.view.translatesAutoresizingMaskIntoConstraints = false
}
}
open class PlanetCollectionViewController: PlanetViewController, UICollectionViewDelegateFlowLayout {
@IBOutlet open var collectionView: UICollectionView!
open var cellReferences = [String: PlanetCollectionViewCell]()
open var cellMapping: [String: PlanetCollectionViewCell.Type] { return [:] }
open var cellSizes: [[CGSize]] = []
open var objects: [[PlanetCollectionViewTemplate]] = [] {
didSet {
cellSizes.removeAll(keepingCapacity: false)
for subarray in objects {
cellSizes.append([CGSize](repeating: CGSize.zero, count: subarray.count))
}
}
}
override open func viewDidLoad() {
super.viewDidLoad()
configureCollectionView()
collectionView.contentOffset = CGPoint.zero
}
open func configureCollectionView() {
for (cellId, cellClass) in cellMapping {
collectionView?.register(cellClass, forCellWithReuseIdentifier: cellId)
}
if collectionView?.collectionViewLayout == nil {
collectionView?.setCollectionViewLayout(UICollectionViewFlowLayout(), animated: false)
}
}
// MARK: - Collection View Cell Handling
open func configure(_ cell: PlanetCollectionViewCell?, atIndexPath indexPath: IndexPath) {
guard cell?.xmlView == nil else { return } // only configure each cell once
cell?.loadView()
guard let xmlView = cell?.xmlView,
let template = cellObject(indexPath as IndexPath),
let cell = cell as? UICollectionViewCell
else { return }
switch template.size.width {
case .unconstrained: break
case .full:
let insets = collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: indexPath.section)
let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: collectionView.frame.size.width - insets.left - insets.right)
xmlView.view.addConstraint(constraint)
case .half:
let insets = collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: indexPath.section)
let constant = (collectionView.frame.size.width - insets.left - insets.right - max(insets.right, insets.left)) / 2
let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: floor(constant))
xmlView.view.addConstraint(constraint)
case .fixed(let points):
let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: CGFloat(points))
xmlView.view.addConstraint(constraint)
}
switch template.size.height {
case .unconstrained: break
case .full:
let insets = collectionView(collectionView, layout: collectionView.collectionViewLayout, insetForSectionAt: indexPath.section)
let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: collectionView.frame.size.height - insets.top - insets.bottom)
xmlView.view.addConstraint(constraint)
case .half:
break
case .fixed(let points):
let constraint = NSLayoutConstraint(item: xmlView.view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: CGFloat(points))
xmlView.view.addConstraint(constraint)
}
cell.contentView.translatesAutoresizingMaskIntoConstraints = false
}
open func cellMapping(_ reuseId: String) -> PlanetCollectionViewCell.Type? {
return cellMapping[reuseId]
}
open func reuseIdentifier(_ indexPath: IndexPath) -> String {
return cellObject(indexPath)?.reuseId ?? "invalidReuseId"
}
open func cellObject(_ indexPath: IndexPath) -> PlanetCollectionViewTemplate? {
guard objects.count > indexPath.section && objects[indexPath.section].count > indexPath.row else { return nil }
return objects[indexPath.section][indexPath.row]
}
// MARK: - UICollectionViewDelegateFlowLayout
open func cellSize(_ indexPath: IndexPath) -> CGSize? {
guard cellSizes.count > indexPath.section && cellSizes[indexPath.section].count > indexPath.row else { return nil }
return cellSizes[indexPath.section][indexPath.row]
}
open func setCellSize(_ size: CGSize, forIndexPath indexPath: IndexPath) {
guard cellSizes.count > indexPath.section && cellSizes[indexPath.section].count > indexPath.row else { return }
cellSizes[indexPath.section][indexPath.row] = size
}
open func cellHeight(_ indexPath: IndexPath) -> CGFloat? {
return (cellSize(indexPath) ?? CGSize.zero).height
}
open func setCellHeight(_ height: CGFloat, forIndexPath indexPath: IndexPath) {
if let size = cellSize(indexPath) {
setCellSize(CGSize(width: size.width, height: height), forIndexPath: indexPath)
}
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var size = cellSize(indexPath) ?? CGSize.zero
if let template = cellObject(indexPath), size == CGSize.zero {
let reuseId = reuseIdentifier(indexPath)
var cellReference: PlanetCollectionViewCell? = cellReferences[reuseId]
if cellReference == nil {
if let cellReferenceType = cellMapping(reuseId) as? UICollectionViewCell.Type {
cellReference = cellReferenceType.init() as? PlanetCollectionViewCell
}
if cellReference == nil {
assertionFailure("Could not create cell from reuseId \"\(reuseId)\"")
return CGSize.zero
}
configure(cellReference!, atIndexPath: indexPath)
cellReferences[reuseId] = cellReference
}
configure(cellReference!, atIndexPath: indexPath)
template.decorate(cellReference as! UICollectionViewCell)
let xmlView = cellReference?.xmlView
size = xmlView?.view.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) ?? CGSize.zero
setCellSize(size, forIndexPath: indexPath)
}
return size
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: section == 0 ? 64 : 0, left: 0, bottom: 0, right: 0)
}
public init(frame: CGRect) {
super.init(nibName: nil, bundle: nil)
let cvv = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: UICollectionViewFlowLayout())
cvv.delegate = self
cvv.dataSource = self
self.collectionView = cvv
self.view = cvv
self.configureCollectionView()
}
public init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
extension PlanetCollectionViewController: UICollectionViewDataSource {
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return objects.count
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return objects[section].count
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier(indexPath), for: indexPath)
configure(cell as? PlanetCollectionViewCell, atIndexPath: indexPath)
cellObject(indexPath)?.decorate(cell)
return cell
}
open func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "", for: indexPath)
return cell
}
}
extension PlanetCollectionViewController: UICollectionViewDelegate {
open func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {
collectionView.cellForItem(at: indexPath)?.isHighlighted = true
}
open func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {
collectionView.cellForItem(at: indexPath)?.isHighlighted = false
}
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
|
3e84610252127bda814e1154d8961d55
| 41.913183 | 229 | 0.68455 | false | false | false | false |
duliodenis/cs193p-Spring-2016
|
refs/heads/master
|
democode/Smashtag-L11/Smashtag/TweetTableViewController.swift
|
mit
|
1
|
//
// TweetTableViewController.swift
// Smashtag
//
// Created by CS193p Instructor.
// Copyright © 2016 Stanford University. All rights reserved.
//
import UIKit
import Twitter
import CoreData
class TweetTableViewController: UITableViewController, UITextFieldDelegate
{
// MARK: Model
// if this is nil, then we simply don't update the database
// having this default to the AppDelegate's context is a little bit of "demo cheat"
// probably it would be better to subclass TweetTableViewController
// and set this var in that subclass and then use that subclass in our storyboard
// (the only purpose of that subclass would be to pick what database we're using)
var managedObjectContext: NSManagedObjectContext? =
(UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext
var tweets = [Array<Twitter.Tweet>]() {
didSet {
tableView.reloadData()
}
}
var searchText: String? {
didSet {
tweets.removeAll()
lastTwitterRequest = nil
searchForTweets()
title = searchText
}
}
// MARK: Fetching Tweets
private var twitterRequest: Twitter.Request? {
if lastTwitterRequest == nil {
if let query = searchText where !query.isEmpty {
return Twitter.Request(search: query + " -filter:retweets", count: 100)
}
}
return lastTwitterRequest?.requestForNewer
}
private var lastTwitterRequest: Twitter.Request?
private func searchForTweets()
{
if let request = twitterRequest {
lastTwitterRequest = request
request.fetchTweets { [weak weakSelf = self] newTweets in
dispatch_async(dispatch_get_main_queue()) {
if request == weakSelf?.lastTwitterRequest {
if !newTweets.isEmpty {
weakSelf?.tweets.insert(newTweets, atIndex: 0)
weakSelf?.updateDatabase(newTweets)
}
}
weakSelf?.refreshControl?.endRefreshing()
}
}
} else {
self.refreshControl?.endRefreshing()
}
}
// add the Twitter.Tweets to our database
private func updateDatabase(newTweets: [Twitter.Tweet]) {
managedObjectContext?.performBlock {
for twitterInfo in newTweets {
// the _ = just lets readers of our code know
// that we are intentionally ignoring the return value
_ = Tweet.tweetWithTwitterInfo(twitterInfo, inManagedObjectContext: self.managedObjectContext!)
}
// there is a method in AppDelegate
// which will save the context as well
// but we're just showing how to save and catch any error here
do {
try self.managedObjectContext?.save()
} catch let error {
print("Core Data Error: \(error)")
}
}
printDatabaseStatistics()
// note that even though we do this print()
// AFTER printDatabaseStatistics() is called
// it will print BEFORE because printDatabaseStatistics()
// returns immediately after putting a closure on the context's queue
// (that closure then runs sometime later, after this print())
print("done printing database statistics")
}
// print out how many Tweets and TwitterUsers are in the database
// uses two different ways of counting them
// the second way (countForFetchRequest) is much more efficient
// (since it does the count in the database itself)
private func printDatabaseStatistics() {
managedObjectContext?.performBlock {
if let results = try? self.managedObjectContext!.executeFetchRequest(NSFetchRequest(entityName: "TwitterUser")) {
print("\(results.count) TwitterUsers")
}
// a more efficient way to count objects ...
let tweetCount = self.managedObjectContext!.countForFetchRequest(NSFetchRequest(entityName: "Tweet"), error: nil)
print("\(tweetCount) Tweets")
}
}
// prepare for the segue that happens
// when the user hits the Tweeters bar button item
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "TweetersMentioningSearchTerm" {
if let tweetersTVC = segue.destinationViewController as? TweetersTableViewController {
tweetersTVC.mention = searchText
tweetersTVC.managedObjectContext = managedObjectContext
}
}
}
@IBAction func refresh(sender: UIRefreshControl) {
searchForTweets()
}
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "\(tweets.count - section)"
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return tweets.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets[section].count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(Storyboard.TweetCellIdentifier, forIndexPath: indexPath)
let tweet = tweets[indexPath.section][indexPath.row]
if let tweetCell = cell as? TweetTableViewCell {
tweetCell.tweet = tweet
}
return cell
}
// MARK: Constants
private struct Storyboard {
static let TweetCellIdentifier = "Tweet"
}
// MARK: Outlets
@IBOutlet weak var searchTextField: UITextField! {
didSet {
searchTextField.delegate = self
searchTextField.text = searchText
}
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
searchText = textField.text
return true
}
// MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
fb8a2a5ffc063b378d0d7ac82d692aa3
| 34.147208 | 125 | 0.628827 | false | false | false | false |
bartekchlebek/SwiftHelpers
|
refs/heads/master
|
Example/Tests/DiffTests.swift
|
mit
|
1
|
import XCTest
import Nimble
import SwiftHelpers
struct DiffedItem {
var ID: String
var property: String
}
struct EquatableDiffedItem: Equatable {
var ID: String
var property: String
}
struct IdentifiableDiffedItem: Identifiable {
var ID: String
var property: String
}
struct FastIdentifiableDiffedItem: FastIdentifiable {
var ID: String
var property: String
}
struct IdentifiableEquatableDiffedItem: Identifiable, Equatable {
var ID: String
var property: String
}
struct FastIdentifiableEquatableDiffedItem: FastIdentifiable, Equatable {
var ID: String
var property: String
}
func ==(lhs: EquatableDiffedItem, rhs: EquatableDiffedItem) -> Bool {
return (lhs.ID == rhs.ID) && (lhs.property == rhs.property)
}
func ==(lhs: IdentifiableEquatableDiffedItem, rhs: IdentifiableEquatableDiffedItem) -> Bool {
return (lhs.ID == rhs.ID) && (lhs.property == rhs.property)
}
func ==(lhs: FastIdentifiableEquatableDiffedItem, rhs: FastIdentifiableEquatableDiffedItem) -> Bool {
return (lhs.ID == rhs.ID) && (lhs.property == rhs.property)
}
struct TestScenario<T> {
var oldItems: [T]
var newItems: [T]
var added: [T]
var removed: [T]
var updatedFrom: [T]
var updatedTo: [T]
var addedIndexes: [Int]
var removedIndexes: [Int]
var updatedIndexes: [Int]
var movedFromIndexes: [Int]
var movedToIndexes: [Int]
init(oldItems: [T],
newItems: [T],
added: [T],
removed: [T],
updatedFrom: [T],
updatedTo: [T],
addedIndexes: [Int],
removedIndexes: [Int],
updatedIndexes: [Int],
movedFromIndexes: [Int],
movedToIndexes: [Int]) {
self.oldItems = oldItems
self.newItems = newItems
self.added = added
self.removed = removed
self.updatedFrom = updatedFrom
self.updatedTo = updatedTo
self.addedIndexes = addedIndexes
self.removedIndexes = removedIndexes
self.updatedIndexes = updatedIndexes
self.movedFromIndexes = movedFromIndexes
self.movedToIndexes = movedToIndexes
}
init<U>(fromScenario scenario: TestScenario<U>, conversionBlock: (U) -> T) {
self.oldItems = scenario.oldItems.map(conversionBlock)
self.newItems = scenario.newItems.map(conversionBlock)
self.added = scenario.added.map(conversionBlock)
self.removed = scenario.removed.map(conversionBlock)
self.updatedFrom = scenario.updatedFrom.map(conversionBlock)
self.updatedTo = scenario.updatedTo.map(conversionBlock)
self.addedIndexes = scenario.addedIndexes
self.removedIndexes = scenario.removedIndexes
self.updatedIndexes = scenario.updatedIndexes
self.movedFromIndexes = scenario.movedFromIndexes
self.movedToIndexes = scenario.movedToIndexes
}
}
let testScenarioSource = TestScenario(
oldItems: [
(ID: "1", property: "a"), // stays
(ID: "2", property: "b"), // stays
(ID: "3", property: "c"), // is removed
(ID: "4", property: "d"), // is removed
(ID: "5", property: "e"), // is updated
(ID: "6", property: "f"), // is updated
(ID: "7", property: "g"), // is moved
(ID: "8", property: "h"), // is moved
// (ID: "9", property: "i"), // is added
// (ID: "10", property: "j"), // is added
],
newItems: [
(ID: "1", property: "a"), // stays
(ID: "2", property: "b"), // stays
// (ID: "3", property: "c"), // is removed
// (ID: "4", property: "d"), // is removed
(ID: "5", property: "E"), // is updated
(ID: "6", property: "F"), // is updated
(ID: "8", property: "h"), // is moved
(ID: "7", property: "g"), // is moved
(ID: "9", property: "i"), // is added
(ID: "10", property: "j"), // is added
],
added: [
(ID: "9", property: "i"),
(ID: "10", property: "j"),
],
removed: [
(ID: "3", property: "c"),
(ID: "4", property: "d"),
],
updatedFrom: [
(ID: "5", property: "e"),
(ID: "6", property: "f"),
],
updatedTo: [
(ID: "5", property: "E"),
(ID: "6", property: "F"),
],
addedIndexes: [6, 7],
removedIndexes: [2, 3],
updatedIndexes: [4, 5],
movedFromIndexes: [6, 7],
movedToIndexes: [5, 4]
)
let testScenario = TestScenario(fromScenario: testScenarioSource) {
DiffedItem(ID: $0.ID, property: $0.property)
}
let equatableTestScenario = TestScenario(fromScenario: testScenarioSource) {
EquatableDiffedItem(ID: $0.ID, property: $0.property)
}
let identifiableTestScenario = TestScenario(fromScenario: testScenarioSource) {
IdentifiableDiffedItem(ID: $0.ID, property: $0.property)
}
let fastIdentifiableTestScenario = TestScenario(fromScenario: testScenarioSource) {
FastIdentifiableDiffedItem(ID: $0.ID, property: $0.property)
}
let identifiableEquatableTestScenario = TestScenario(fromScenario: testScenarioSource) {
IdentifiableEquatableDiffedItem(ID: $0.ID, property: $0.property)
}
let fastIdentifiableEquatableTestScenario = TestScenario(fromScenario: testScenarioSource) {
FastIdentifiableEquatableDiffedItem(ID: $0.ID, property: $0.property)
}
final class DiffTests: XCTestCase {
func performTestWithContext<T>(_ context: DiffContext<T>,
testScenario: TestScenario<T>,
elementComparison: @escaping (T, T) -> Bool) {
let diff = Diff(context)
print(diff.added)
print(testScenario.added)
expect(diff.added.elementsEqual(testScenario.added, by: elementComparison)).to(beTrue())
expect(diff.added.elementsEqual(testScenario.added, by: elementComparison)) == true
expect(diff.removed.elementsEqual(testScenario.removed, by: elementComparison)) == true
expect(diff.updated.map{ $0.from }.elementsEqual(testScenario.updatedFrom, by: elementComparison)) == true
expect(diff.updated.map{ $0.to }.elementsEqual(testScenario.updatedTo, by: elementComparison)) == true
let indexDiff = IndexDiff(context)
expect(indexDiff.addedIndexes) == testScenario.addedIndexes
expect(indexDiff.removedIndexes) == testScenario.removedIndexes
expect(indexDiff.updatedIndexes) == testScenario.updatedIndexes
expect(indexDiff.movedIndexes.map({ $0.from })) == testScenario.movedFromIndexes
expect(indexDiff.movedIndexes.map({ $0.to })) == testScenario.movedToIndexes
}
func performTestWithContext<T: Equatable>(_ context: DiffContext<T>, testScenario: TestScenario<T>) {
self.performTestWithContext(context, testScenario: testScenario, elementComparison: ==)
}
func testDiffWithVerboseDiffContext() {
let context = DiffContext<DiffedItem>(
oldItems: testScenario.oldItems,
newItems: testScenario.newItems,
oldItemsContainItem: { item in testScenario.oldItems.contains { $0.ID == item.ID} },
newItemsContainItem: { item in testScenario.newItems.contains { $0.ID == item.ID} },
oldItemWithSameIDAsItem: { item in
testScenario.oldItems.index { $0.ID == item.ID }.map { testScenario.oldItems[$0] }
},
newItemWithSameIDAsItem: { item in
testScenario.newItems.index { $0.ID == item.ID }.map { testScenario.newItems[$0] }
},
isSameInstanceComparator: { $0.ID == $1.ID },
isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) }
)
self.performTestWithContext(context, testScenario: testScenario) {
($0.ID == $1.ID) && ($0.property == $1.property)
}
}
func testDiffWithConciseDiffContext1() {
let context = DiffContext<DiffedItem>(
oldItems: testScenario.oldItems,
newItems: testScenario.newItems,
isSameInstanceComparator: { $0.ID == $1.ID },
isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) }
)
self.performTestWithContext(context, testScenario: testScenario) {
($0.ID == $1.ID) && ($0.property == $1.property)
}
}
func testDiffWithConciseDiffContext2() {
let context = DiffContext<DiffedItem>(
oldItems: testScenario.oldItems,
newItems: testScenario.newItems,
itemsContainItem: { (items, item) -> Bool in return items.contains { $0.ID == item.ID } },
indexOfItemInItems: { (item, items) -> Int? in return items.index { $0.ID == item.ID } },
isSameInstanceComparator: { $0.ID == $1.ID },
isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) }
)
self.performTestWithContext(context, testScenario: testScenario) {
($0.ID == $1.ID) && ($0.property == $1.property)
}
}
func testDiffWithConciseDiffContext3() {
let context = DiffContext<DiffedItem>(
oldItems: testScenario.oldItems,
newItems: testScenario.newItems,
instanceIdentifierGetter: { $0.ID },
isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) }
)
self.performTestWithContext(context, testScenario: testScenario) {
($0.ID == $1.ID) && ($0.property == $1.property)
}
}
func testDiffWithDiffContextOfEquatableType() {
let context = DiffContext<EquatableDiffedItem>(
oldItems: equatableTestScenario.oldItems,
newItems: equatableTestScenario.newItems,
isSameInstanceComparator: { $0.ID == $1.ID }
)
self.performTestWithContext(context, testScenario: equatableTestScenario)
}
func testDiffWithDiffContextOfIdentifiableType() {
let context = DiffContext<IdentifiableDiffedItem>(
oldItems: identifiableTestScenario.oldItems,
newItems: identifiableTestScenario.newItems,
isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) }
)
self.performTestWithContext(context, testScenario: identifiableTestScenario) {
($0.ID == $1.ID) && ($0.property == $1.property)
}
}
func testDiffWithDiffContextOfIdentifiableAndEquatableType() {
let context = DiffContext<IdentifiableEquatableDiffedItem>(
oldItems: identifiableEquatableTestScenario.oldItems,
newItems: identifiableEquatableTestScenario.newItems
)
self.performTestWithContext(context, testScenario: identifiableEquatableTestScenario)
}
func testDiffWithDiffContextOfFastIdentifiableType() {
let context = DiffContext<FastIdentifiableDiffedItem>(
oldItems: fastIdentifiableTestScenario.oldItems,
newItems: fastIdentifiableTestScenario.newItems,
isEqualComparator: { ($0.ID == $1.ID) && ($0.property == $1.property) }
)
self.performTestWithContext(context, testScenario: fastIdentifiableTestScenario) {
($0.ID == $1.ID) && ($0.property == $1.property)
}
}
func testDiffWithDiffContextOfFastIdentifiableAndEquatableType() {
let context = DiffContext<FastIdentifiableEquatableDiffedItem>(
oldItems: fastIdentifiableEquatableTestScenario.oldItems,
newItems: fastIdentifiableEquatableTestScenario.newItems
)
self.performTestWithContext(context, testScenario: fastIdentifiableEquatableTestScenario)
}
func testIndexDiffWithOneInsertion() {
let a = [
"1",
"2",
"3",
"4",
]
let b = [
"1",
"NEW",
"2",
"3",
"4",
]
let context = DiffContext(oldItems: a, newItems: b)
let indexDiff = IndexDiff(context)
expect(indexDiff.addedIndexes) == [1]
expect(indexDiff.removedIndexes) == []
expect(indexDiff.updatedIndexes) == []
expect(indexDiff.movedIndexes.count) == 0
}
}
extension String: FastIdentifiable {
public var ID: String { return self }
}
|
2a987d7a38dcec251b14081f96ce70d1
| 32.103976 | 108 | 0.700693 | false | true | false | false |
prey/prey-ios-client
|
refs/heads/master
|
Prey/Classes/AlertVC.swift
|
gpl-3.0
|
1
|
//
// AlertVC.swift
// Prey
//
// Created by Javier Cala Uribe on 29/06/16.
// Copyright © 2016 Prey, Inc. All rights reserved.
//
import UIKit
class AlertVC: UIViewController {
// MARK: Properties
@IBOutlet var messageLbl : UILabel!
@IBOutlet var subtitleLbl : UILabel!
var messageToShow = ""
// MARK: Init
override func viewDidLoad() {
super.viewDidLoad()
// View title for GAnalytics
// self.screenName = "Alert"
// Set message
messageLbl.text = messageToShow
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool){
// Hide navigationBar when appear this ViewController
self.navigationController?.isNavigationBarHidden = true
super.viewWillAppear(animated)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
// Hide navigationBar when appear this ViewController
self.navigationController?.isNavigationBarHidden = false
}
}
|
9961cfbeecce2d12bef9dd336b07330b
| 23.215686 | 64 | 0.616194 | false | false | false | false |
kickstarter/ios-oss
|
refs/heads/main
|
Kickstarter-iOS/Features/SettingsPrivacy/Views/Cells/SettingsPrivacyDeleteAccountCell.swift
|
apache-2.0
|
1
|
import KsApi
import Library
import Prelude
import ReactiveExtensions
import ReactiveSwift
import UIKit
internal protocol SettingsPrivacyDeleteAccountCellDelegate: AnyObject {
func settingsPrivacyDeleteAccountCellTapped(_ cell: SettingsPrivacyDeleteAccountCell, with url: URL)
}
internal final class SettingsPrivacyDeleteAccountCell: UITableViewCell, ValueCell {
fileprivate let viewModel: SettingsDeleteAccountCellViewModelType = SettingsDeleteAccountCellViewModel()
internal weak var delegate: SettingsPrivacyDeleteAccountCellDelegate?
@IBOutlet fileprivate var deleteAccountButton: UIButton!
@IBOutlet fileprivate var deleteAccountLabel: UILabel!
@IBOutlet fileprivate var separatorView: [UIView]!
internal override func awakeFromNib() {
super.awakeFromNib()
_ = self
|> \.accessibilityElements .~ [self.deleteAccountButton].compact()
_ = self.deleteAccountButton
|> \.accessibilityLabel %~ { _ in Strings.Delete_my_Kickstarter_Account() }
self.deleteAccountButton.addTarget(self, action: #selector(self.deleteAccountTapped), for: .touchUpInside)
}
internal func configureWith(value user: User) {
self.viewModel.inputs.configureWith(user: user)
}
internal override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> UITableViewCell.lens.contentView.layoutMargins %~~ { _, cell in
cell.traitCollection.isRegularRegular
? .init(topBottom: Styles.grid(2), leftRight: Styles.grid(20))
: .init(topBottom: Styles.grid(1), leftRight: Styles.grid(2))
}
_ = self.separatorView
||> settingsSeparatorStyle
_ = self.deleteAccountLabel
|> UILabel.lens.textColor .~ .ksr_alert
|> UILabel.lens.font .~ .ksr_body()
|> UILabel.lens.numberOfLines .~ 2
|> UILabel.lens.text %~ { _ in Strings.Delete_my_Kickstarter_Account() }
}
internal override func bindViewModel() {
super.bindViewModel()
self.viewModel.outputs.notifyDeleteAccountTapped
.observeForUI()
.observeValues { [weak self] url in
guard let _self = self else { return }
self?.delegate?.settingsPrivacyDeleteAccountCellTapped(_self, with: url)
}
}
@objc fileprivate func deleteAccountTapped() {
self.viewModel.inputs.deleteAccountTapped()
}
}
|
e8fd8d2c1fc9a38fa03e3f9d5b98a6c7
| 31.830986 | 110 | 0.723724 | false | false | false | false |
parthdubal/MyNewyorkTimes
|
refs/heads/master
|
MyNewyorkTimes/Modules/NewsDetails/View/NewsDetailController.swift
|
mit
|
1
|
//
// NewsDetailController.swift
// MyNewyorkTimes
//
// Created by Parth Dubal on 7/10/17.
// Copyright © 2017 Parth Dubal. All rights reserved.
//
import UIKit
import WebKit
import SVProgressHUD
class NewsDetailController: BaseViewController , NewsDetailViewInterface, UICollectionViewDelegate, UICollectionViewDataSource, WKNavigationDelegate {
@IBOutlet weak var collectionView: UICollectionView!
weak var newsDetailPresenter : NewsDetailsModuleInterface!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setupView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// showing selected news detail information in view
let selectedIndexPath = IndexPath(item: newsDetailPresenter.currentNewsIndex, section: 0)
self.collectionView.scrollToItem(at: selectedIndexPath, at: .left, animated: true)
}
func setupView()
{
self.title = "News Details"
self.setCellSize()
self.collectionView.isPagingEnabled = true
self.updateNewsDetailsViewInterface()
self.setNavigationIndicatorItem()
}
func setCellSize()
{
// Update cell size according to device screen size.
var size = self.navigationController!.navigationBar.frame.size
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
size.height += statusBarHeight
// updateing item size according to self.view size
if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout
{
layout.itemSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height-size.height)
}
}
// MARK:- View Interface implementation
func updateNewsDetailsViewInterface()
{
collectionView.reloadData()
}
func requestErrorOccured(errorMessage:String)
{
SVProgressHUD.dismissHUD(error: errorMessage)
}
//MARK:- Collection View datasource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return newsDetailPresenter.newsInfoList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewsDetailsCell.cellIdentifer, for: indexPath) as! NewsDetailsCell
let newsInfo = newsDetailPresenter.newsInfoList[indexPath.item]
cell.loadUrl(stringUrl: newsInfo.webUrl)
cell.wkwebView.navigationDelegate = self
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if let newsDetailCell = cell as? NewsDetailsCell
{
newsDetailCell.wkwebView.tag = indexPath.row + 1
activityIndicator?.tag = indexPath.row + 1
if newsDetailCell.wkwebView.isLoading
{
activityIndicator?.startAnimating()
}
}
if indexPath.item >= newsDetailPresenter.newsInfoList.count - 3 && newsDetailPresenter.canLoadMore
{
newsDetailPresenter.requestMoreNewsInfoList()
}
}
// MARK: - WKWebView Navigation delegates
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if webView.tag == activityIndicator?.tag
{
activityIndicator?.startAnimating()
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
if webView.tag == activityIndicator?.tag
{
activityIndicator?.stopAnimating()
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
6199b471deca727ef38f063842b98c9c
| 31.669065 | 150 | 0.659546 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
refs/heads/master
|
Modules/Platform/Sources/PlatformUIKit/Components/ExplainedActionView/ExplainedActionViewModel.swift
|
lgpl-3.0
|
1
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxCocoa
import RxSwift
public struct DescriptionTitle {
public var title: String
public var titleColor: UIColor
public var titleFontSize: CGFloat
public init(title: String, titleColor: UIColor, titleFontSize: CGFloat) {
self.title = title
self.titleColor = titleColor
self.titleFontSize = titleFontSize
}
}
public struct ExplainedActionViewModel {
// MARK: - Types
private typealias AccessibilityId = Accessibility.Identifier.ExplainedActionView
// MARK: - Setup
let thumbBadgeImageViewModel: BadgeImageViewModel
let titleLabelContent: LabelContent
let descriptionLabelContents: [LabelContent]
let badgeViewModel: BadgeViewModel?
// MARK: - Accessors
public var tap: Signal<Void> {
tapRelay.asSignal()
}
let tapRelay = PublishRelay<Void>()
// MARK: - Setup
public init(
thumbImage: String,
title: String,
descriptions: [DescriptionTitle],
badgeTitle: String?,
uniqueAccessibilityIdentifier: String,
thumbRenderDefault: Bool = false
) {
if thumbRenderDefault {
thumbBadgeImageViewModel = .default(
image: .local(name: thumbImage, bundle: .platformUIKit),
backgroundColor: .clear,
cornerRadius: .none,
accessibilityIdSuffix: uniqueAccessibilityIdentifier
)
} else {
thumbBadgeImageViewModel = .primary(
image: .local(name: thumbImage, bundle: .platformUIKit),
cornerRadius: .round,
accessibilityIdSuffix: uniqueAccessibilityIdentifier
)
thumbBadgeImageViewModel.marginOffsetRelay.accept(6)
}
titleLabelContent = .init(
text: title,
font: .main(.semibold, 16),
color: .titleText,
accessibility: .id(uniqueAccessibilityIdentifier + AccessibilityId.titleLabel)
)
descriptionLabelContents = descriptions
.enumerated()
.map { payload in
.init(
text: payload.element.title,
font: .main(.medium, 14),
color: payload.element.titleColor,
accessibility: .id(
uniqueAccessibilityIdentifier + AccessibilityId.descriptionLabel + ".\(payload.offset)"
)
)
}
if let badgeTitle = badgeTitle {
badgeViewModel = .affirmative(
with: badgeTitle,
accessibilityId: uniqueAccessibilityIdentifier + AccessibilityId.badgeView
)
} else { // hide badge
badgeViewModel = nil
}
}
}
extension ExplainedActionViewModel: Equatable {
public static func == (lhs: ExplainedActionViewModel, rhs: ExplainedActionViewModel) -> Bool {
lhs.badgeViewModel == rhs.badgeViewModel
&& lhs.titleLabelContent == rhs.titleLabelContent
&& lhs.thumbBadgeImageViewModel == rhs.thumbBadgeImageViewModel
&& lhs.descriptionLabelContents == rhs.descriptionLabelContents
}
}
|
20f4c8ee4a8b9587ac6ea3aa19529a29
| 31.019608 | 111 | 0.609308 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/Classes/ViewRelated/Aztec/Processors/VideoUploadProcessor.swift
|
gpl-2.0
|
2
|
import Foundation
import Aztec
import WordPressEditor
class VideoUploadProcessor: Processor {
let mediaUploadID: String
let remoteURLString: String
let videoPressID: String?
init(mediaUploadID: String, remoteURLString: String, videoPressID: String?) {
self.mediaUploadID = mediaUploadID
self.remoteURLString = remoteURLString
self.videoPressID = videoPressID
}
lazy var videoPostMediaUploadProcessor = ShortcodeProcessor(tag: "video", replacer: { (shortcode) in
guard let uploadValue = shortcode.attributes[MediaAttachment.uploadKey]?.value,
case let .string(uploadID) = uploadValue,
self.mediaUploadID == uploadID else {
return nil
}
var html = ""
if let videoPressGUID = self.videoPressID {
html = "[wpvideo "
html += videoPressGUID
html += " ]"
} else {
html = "[video "
var updatedAttributes = shortcode.attributes
updatedAttributes.set(.string(self.remoteURLString), forKey: "src")
//remove the uploadKey
updatedAttributes.remove(key: MediaAttachment.uploadKey)
let attributeSerializer = ShortcodeAttributeSerializer()
html += attributeSerializer.serialize(updatedAttributes)
html += "]"
}
return html
})
func process(_ text: String) -> String {
return videoPostMediaUploadProcessor.process(text)
}
}
|
77780e9eca8c88e272ae17ff056bf405
| 31.042553 | 104 | 0.634794 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios
|
refs/heads/master
|
the-blue-alliance-ios/Operations/App Setup/AppSetupOperation.swift
|
mit
|
1
|
import CoreData
import Foundation
import Search
import TBAKit
import TBAOperation
import UIKit
class AppSetupOperation: TBAOperation {
var destroyPersistentStoreOperation: DestroyPersistentStoreOperation
var persistentContainerOperation: PersistentContainerOperation
let appSetupOperationQueue = OperationQueue()
init(indexDelegate: TBACoreDataCoreSpotlightDelegate, persistentContainer: NSPersistentContainer, tbaKit: TBAKit, userDefaults: UserDefaults) {
self.destroyPersistentStoreOperation = DestroyPersistentStoreOperation(persistentContainer: persistentContainer, tbaKit: tbaKit, userDefaults: userDefaults)
self.persistentContainerOperation = PersistentContainerOperation(indexDelegate: indexDelegate, persistentContainer: persistentContainer)
self.persistentContainerOperation.addDependency(self.destroyPersistentStoreOperation)
super.init()
}
override func execute() {
let blockOperation = BlockOperation { [unowned self] in
self.completionError = [self.destroyPersistentStoreOperation, self.persistentContainerOperation].compactMap({ $0.completionError }).first
self.finish()
}
let dependentOperations = [destroyPersistentStoreOperation, persistentContainerOperation]
for op in dependentOperations {
blockOperation.addDependency(op)
}
appSetupOperationQueue.addOperations(dependentOperations + [blockOperation], waitUntilFinished: false)
}
}
|
bf60b595ad8f269aa7d70606ed2147e2
| 39.675676 | 164 | 0.780066 | false | false | false | false |
safx/TypetalkApp
|
refs/heads/master
|
TypetalkApp/DataSources/TopicsDataSource.swift
|
mit
|
1
|
//
// TopicsDataSource.swift
// TypetalkApp
//
// Created by Safx Developer on 2014/11/09.
// Copyright (c) 2014年 Safx Developers. All rights reserved.
//
import TypetalkKit
import RxSwift
import ObservableArray
class TopicsDataSource {
typealias OArray = ObservableArray<TopicWithUserInfo>
typealias Event = Observable<OArray.EventType>
var topics = OArray()
let disposeBag = DisposeBag()
func fetch(observe: Bool = false) -> Event {
let s = TypetalkAPI.rx_sendRequest(GetTopics())
s.subscribe(
onNext: { res in
self.topics.appendContentsOf(res.topics)
},
onError: { err in
print("\(err)")
},
onCompleted:{ () in
if (observe) {
self.startObserving()
}
}
)
.addDisposableTo(disposeBag)
return topics.rx_events()
}
private func startObserving() {
TypetalkAPI.rx_streamimg
.subscribeNext { event in
switch event {
case .CreateTopic(let res): self.insertTopic(res)
case .DeleteTopic(let res): self.deleteTopic(res)
case .UpdateTopic(let res): self.updateTopic(res)
case .JoinTopics(let res): self.insertTopics(res.topics)
case .LeaveTopics(let res): self.deleteTopics(res.topics)
case .FavoriteTopic(let res): self.updateTopic(res)
case .UnfavoriteTopic(let res): self.updateTopic(res)
case .PostMessage(let res): self.updateTopic(res.topic!, post: res.post!, advance: +1)
case .DeleteMessage(let res): self.updateTopic(res.topic!, post: res.post!, advance: -1)
case .SaveBookmark(let res): self.updateTopic(res.unread)
default: ()
}
}
.addDisposableTo(disposeBag)
}
private func insertTopic(topic: TopicWithUserInfo) {
topics.insert(topic, atIndex: 0)
}
private func insertTopics(topics: [TopicWithUserInfo]) {
topics.forEach { self.insertTopic($0) }
}
private func find(topicId: TopicID, closure: (TopicWithUserInfo, Int) -> ()) {
for i in 0..<topics.count {
if topics[i].topic.id == topicId {
closure(topics[i], i)
return
}
}
}
private func updateTopic(topic: Topic) {
find(topic.id) { oldValue, i in
self.topics[i] = TopicWithUserInfo(topic: topic, favorite: oldValue.favorite, unread: oldValue.unread)
}
}
private func updateTopic(topicWithUserInfo: TopicWithUserInfo) {
find(topicWithUserInfo.topic.id) { oldValue, i in
self.topics[i] = topicWithUserInfo
}
}
private func updateTopic(unread: Unread) {
find(unread.topicId) { oldValue, i in
self.topics[i] = TopicWithUserInfo(topic: oldValue.topic, favorite: oldValue.favorite, unread: unread)
}
}
private func updateTopic(topic: Topic, post: Post, advance: Int) {
find(topic.id) { oldValue, i in
let c = (oldValue.unread?.count ?? 0) + advance
let unread = Unread(topicId: topic.id, postId: post.id, count: max(c, 0))
self.topics[i] = TopicWithUserInfo(topic: topic, favorite: oldValue.favorite, unread: unread)
}
}
private func deleteTopic(topic: Topic) {
find(topic.id) { oldValue, i in
self.topics.removeAtIndex(i)
()
}
}
private func deleteTopics(topics: [Topic]) {
topics.forEach { self.deleteTopic($0) }
}
// MARK: Acting to REST client
func createTopic(topicName: String) -> Observable<CreateTopic.Response> {
let teamId: TeamID? = nil
let inviteMembers = [String]()
let inviteMessage = ""
return TypetalkAPI.rx_sendRequest(CreateTopic(name: topicName, teamId: teamId, inviteMembers: inviteMembers, inviteMessage: inviteMessage))
}
func deleteTopic(topicId: TopicID) -> Observable<DeleteTopic.Response> {
return TypetalkAPI.rx_sendRequest(DeleteTopic(topicId: topicId))
}
func favoriteTopic(topicId: TopicID) -> Observable<FavoriteTopic.Response> {
return TypetalkAPI.rx_sendRequest(FavoriteTopic(topicId: topicId))
}
func unfavoriteTopic(topicId: TopicID) -> Observable<UnfavoriteTopic.Response> {
return TypetalkAPI.rx_sendRequest(UnfavoriteTopic(topicId: topicId))
}
}
|
953c8974d3314a66161ae94e53278f9d
| 32.674074 | 147 | 0.606247 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
UICollectionViewLayout/Blueprints-master/Tests/Shared/BlueprintLayoutAnimatorTests.swift
|
mit
|
1
|
import XCTest
import Blueprints
class BlueprintLayoutAnimatorTests: XCTestCase {
class MockCollectionViewUpdateItem: CollectionViewUpdateItem {
var beforeIndexPath: IndexPath?
var afterIndexPath: IndexPath?
var action: CollectionViewUpdateAction = .none
init(action: CollectionViewUpdateAction? = nil, beforeIndexPath: IndexPath? = nil, afterIndexPath: IndexPath? = nil) {
self.beforeIndexPath = beforeIndexPath
self.afterIndexPath = afterIndexPath
super.init()
switch (beforeIndexPath != nil, afterIndexPath != nil) {
case (true, true):
self.action = .move
case (false, true):
self.action = .insert
case (true, false):
self.action = .delete
default:
self.action = .none
}
if let action = action {
self.action = action
}
}
override var indexPathBeforeUpdate: IndexPath? { return beforeIndexPath }
override var indexPathAfterUpdate: IndexPath? { return afterIndexPath }
override var updateAction: UICollectionViewUpdateItem.Action { return action }
}
let dataSource = MockDataSource(numberOfItems: 15)
func testDefaultAnimatorFadeInsertion() {
let (animator, collectionView, layout) = Helper.createAnimator(dataSource: dataSource)
let indexPath = IndexPath(item: 0, section: 0)
let insertion = MockCollectionViewUpdateItem(afterIndexPath: indexPath)
animator.prepare(forCollectionViewUpdates: [insertion])
XCTAssertTrue(animator.indexPathsToAnimate.contains(indexPath))
let attributes = LayoutAttributes()
attributes.size = .init(width: 100, height: 100)
XCTAssertEqual(attributes.alpha, 1.0)
animator.animation = .fade
_ = animator.initialLayoutAttributesForAppearingItem(at: indexPath, with: attributes)
XCTAssertEqual(attributes.alpha, 0.0)
}
func testDefaultAnimatorFadeDeletion() {
let (animator, collectionView, layout) = Helper.createAnimator(dataSource: dataSource)
let indexPath = IndexPath(item: 0, section: 0)
let deletion = MockCollectionViewUpdateItem(beforeIndexPath: indexPath)
animator.prepare(forCollectionViewUpdates: [deletion])
XCTAssertTrue(animator.indexPathsToAnimate.contains(indexPath))
let attributes = LayoutAttributes()
attributes.size = .init(width: 100, height: 100)
XCTAssertEqual(attributes.alpha, 1.0)
animator.animation = .fade
_ = animator.finalLayoutAttributesForDisappearingItem(at: indexPath, with: attributes)
XCTAssertEqual(attributes.alpha, 0.0)
}
func testDefaultAnimatorFadeMultipleAttributes() {
let (animator, collectionView, layout) = Helper.createAnimator(dataSource: dataSource)
let beforeIndexPath = IndexPath(item: 0, section: 0)
let afterIndexPath = IndexPath(item: 1, section: 0)
let move = MockCollectionViewUpdateItem(
beforeIndexPath: beforeIndexPath,
afterIndexPath: afterIndexPath
)
animator.prepare(forCollectionViewUpdates: [move])
XCTAssertTrue(animator.indexPathsToMove.contains(beforeIndexPath))
let attributes = LayoutAttributes()
attributes.size = .init(width: 100, height: 100)
attributes.alpha = 0.0
animator.animation = .fade
_ = animator.initialLayoutAttributesForAppearingItem(at: beforeIndexPath, with: attributes)
XCTAssertEqual(attributes.alpha, 1.0)
}
}
|
3ea2ef4a1db9bf22b33b48121767aeb0
| 35.053763 | 122 | 0.731882 | false | true | false | false |
chrislavender/Thumbafon
|
refs/heads/master
|
Thumbafon/Extensions/ModelAdditions/Scale+Create.swift
|
cc0-1.0
|
1
|
//
// ScaleCreation.swift
// Thumbafon
//
// Created by Chris Lavender on 9/15/15.
// Copyright (c) 2015 Gnarly Dog Music. All rights reserved.
//
import Foundation
import CoreData
extension Scale {
// MARK: CoreData
static func baseNoteNumbers() -> [Int] {
// let tempIntervals = [2, 2, 3, 2, 2]
let tempIntervals = [2, 2, 3, 2]
var noteNumbers = [0]
var prevNote = noteNumbers[0]
for index in 0...tempIntervals.count - 1 {
let interval = tempIntervals[index]
let nextNote = prevNote + interval
noteNumbers.append(nextNote)
prevNote = nextNote
}
return noteNumbers
}
static func scale(name:String, context: NSManagedObjectContext) -> Scale? {
var match: (Scale)? = nil
do {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Scale")
fetchRequest.predicate = NSPredicate(format: "name == \(name)")
if let fetchResults = try context.fetch(fetchRequest) as? [Scale] {
match = fetchResults.first
}
} catch {
print(error)
}
return match
}
}
|
0d0226c9716b60fe9ecc0f280259677b
| 24.078431 | 88 | 0.542611 | false | false | false | false |
grantjbutler/Artikolo
|
refs/heads/master
|
Carthage/Checkouts/Dip/Tests/DipTests/Utils.swift
|
mit
|
2
|
//
// Dip
//
// Copyright (c) 2015 Olivier Halligon <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
#if os(Linux)
typealias NSObject = AnyObject
#endif
func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T) {
AssertThrows(file, line: line, expression: expression, "")
}
func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, _ message: String) {
AssertThrows(expression: expression, checkError: { _ in true }, message)
}
func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, checkError: (Error) -> Bool) {
AssertThrows(file, line: line, expression: expression, checkError: checkError, "")
}
func AssertThrows<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, checkError: (Error) -> Bool, _ message: String) {
do {
let _ = try expression()
XCTFail(message, file: file, line: line)
}
catch {
XCTAssertTrue(checkError(error), "Thrown unexpected error: \(error)", file: file, line: line)
}
}
func AssertNoThrow<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T) {
AssertNoThrow(file, line: line, expression: expression, "")
}
func AssertNoThrow<T>(_ file: StaticString = #file, line: UInt = #line, expression: @autoclosure () throws -> T, _ message: String) {
do {
let _ = try expression()
}
catch {
XCTFail(message, file: file, line: line)
}
}
#if os(Linux)
import Glibc
typealias TMain = @convention(c) (UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
private func startThread(_ block: @escaping TMain) -> pthread_t {
var pid: pthread_t = 0
pthread_create(&pid, nil, block, nil)
return pid
}
func dispatch_async(block: @escaping TMain) -> pthread_t {
return startThread(block)
}
func dispatch_sync(block: @escaping TMain) -> UnsafeMutableRawPointer? {
var result: UnsafeMutableRawPointer? = UnsafeMutableRawPointer.allocate(bytes: 1, alignedTo: 0)
let pid = startThread(block)
pthread_join(pid, &result)
return result
}
extension pthread_spinlock_t {
mutating func lock() {
pthread_spin_lock(&self)
}
mutating func unlock() {
pthread_spin_unlock(&self)
}
}
#endif
|
0771d22339bdff1363d4369c544708a2
| 34.642105 | 161 | 0.709392 | false | false | false | false |
NordRosann/Analysis
|
refs/heads/master
|
Tests/Analysis/ListTests.swift
|
mit
|
1
|
import XCTest
@testable import Analysis
class ListTests: XCTestCase {
func testListMap() {
let list: List = [2, 3, 5, "andrey"]
let changed: List = list.map {
switch $0 {
case .integerValue(let number):
return .stringValue(String(number))
default: return $0
}
}
let awaited: List = ["2", "3", "5", "andrey"]
XCTAssertEqual(changed, awaited)
}
func testUnifiedMap() {
let list: List = [2, 3, 5, "andrey", 12, "peter"]
let numbers: [Int] = list.map { (number: Int) -> Int in
return number * 2
}
XCTAssertEqual(numbers, [4, 6, 10, 24])
let strings: [String] = list.map { (string: String) -> String in
return string.uppercased()
}
XCTAssertEqual(strings, ["ANDREY", "PETER"])
}
func testAdvancedUnifiedMap() {
let list: List = [2, 3, 5, "andrey", 12, "peter"]
let numbers: [Int] = list.map { $0 * 2 }
XCTAssertEqual(numbers, [4, 6, 10, 24])
let strings: [String] = list.map { ($0 as String).uppercased() }
XCTAssertEqual(strings, ["ANDREY", "PETER"])
}
func testEnumMapping() {
enum Name: String, DataPointConvertible {
case andrey, peter
}
let list: List = [2, 3, 5, "andrey", 12, "peter", "bjorn"]
let names: [String] = list.map { ($0 as Name).rawValue }
XCTAssertEqual(names, ["andrey", "peter"])
}
func testFilter() {
let list: List = [2, 3, 5, false, nil, nil, "human", 4.0]
let changed: [Int] = list.filter { $0 > 2 }
XCTAssertEqual(changed, [3, 5])
}
func testKeying() {
let year = Variable(name: "year", type: Int.self)
let code = Variable(name: "code", type: String.self)
let value = Variable(name: "value", type: Int.self)
let schema = RowSchema(variables: year, code, value)
let list: List = [2015, "UA", 4]
let keyed = list.keyed(with: schema)
let expected: [String: DataPoint] = ["year": 2015, "code": "UA", "value": 4]
XCTAssertEqual(keyed, expected)
}
func testCoupling() {
let year = Variable(name: "year", type: Int.self)
let code = Variable(name: "code", type: String.self)
let value = Variable(name: "value", type: Int.self)
let schema = RowSchema(variables: year, code, value)
let list: List = [2015, "UA", 4]
let keyed = list.coupled(with: schema)
let expected: [Variable: DataPoint] = [year: 2015, code: "UA", value: 4]
XCTAssertEqual(keyed, expected)
}
func testUnifiedSorting() {
let list: List = [2, 5, 0, 4, "key", 8, -1, "fake", false, nil, nil, 15]
let unifiedSorted: [Int] = list.unified().sorted { $0 < $1 }
let unifiedStrignsSorted: [String] = list.unified().sorted { $0.characters.count < $1.characters.count }
let expected = [-1, 0, 2, 4, 5, 8, 15]
let expectedStrings = ["key", "fake"]
XCTAssertEqual(unifiedSorted, expected)
XCTAssertEqual(unifiedStrignsSorted, expectedStrings)
}
}
|
00fb337c4321d998d32bc19d755709b5
| 36.302326 | 112 | 0.548488 | false | true | false | false |
voloshynslavik/MVx-Patterns-In-Swift
|
refs/heads/master
|
MVX Patterns In Swift/PatternsTableViewController.swift
|
mit
|
1
|
//
// PatternsTableViewController.swift
// MVX Patterns In Swift
//
// Created by Yaroslav Voloshyn on 18/07/2017.
//
import UIKit
final class PatternsTableViewController: UITableViewController {
private lazy var mvvvmcCoordinator: MVVMCCoordinator? = {
guard let nc = self.navigationController else {
return nil
}
return MVVMCCoordinator(navigationController: nc)
}()
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let mvvmViewController = segue.destination as? MVVMViewController {
let viewModel = ViewModel()
viewModel.delegate = mvvmViewController
mvvmViewController.viewModel = viewModel
} else if let mvpViewController = segue.destination as? MVPViewController {
let presenter = ConcretePresenter(view: mvpViewController)
mvpViewController.presenter = presenter
}
}
@IBAction func onSelectMVVMC(_ sender: UITapGestureRecognizer) {
mvvvmcCoordinator?.start()
}
}
|
ff88bdf1a49277eba9880153d74fe5e6
| 28.638889 | 83 | 0.671978 | false | false | false | false |
wyp767363905/GiftSay
|
refs/heads/master
|
GiftSay/GiftSay/classes/hot/hotDetail/view/HotDetailView.swift
|
mit
|
1
|
//
// HotDetailView.swift
// GiftSay
//
// Created by qianfeng on 16/9/3.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class HotDetailView: UIView {
private var tbView: UITableView?
var itemModel: HotItemModel?{
didSet {
tbView?.reloadData()
}
}
var likeModel: HotLikeModel?{
didSet {
tbView?.reloadData()
}
}
init() {
super.init(frame: CGRectZero)
tbView = UITableView(frame: CGRectZero, style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
addSubview(tbView!)
tbView?.separatorStyle = .None
tbView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.edges.equalTo(self!)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension HotDetailView : UITableViewDelegate,UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var sectionNum = 0
if itemModel?.data != nil {
sectionNum += 1
}
if likeModel?.data?.recommend_posts?.count > 0 {
sectionNum += 1
}
if likeModel?.data?.recommend_items?.count > 0 {
sectionNum += 1
}
return sectionNum
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowNum = 0
if itemModel?.data != nil && likeModel?.data?.recommend_posts?.count > 0 && likeModel?.data?.recommend_items?.count > 0 {
rowNum = 1
}
return rowNum
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height: CGFloat = 0
if indexPath.section == 0 {
let model = itemModel?.data
if model != nil {
height = ItemCell.heightForModel(model!)
}
}else if indexPath.section == 1 {
let num = likeModel?.data?.recommend_posts?.count
if num > 0 {
height = 160
}
}else if indexPath.section == 2 {
let model = likeModel?.data
if model != nil {
height = HMyLayout.ToObtainHeight(model!)
}
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if indexPath.section == 0 {
cell = ItemCell.createItemCellFor(tableView, atIndexPath: indexPath, withDataModel: (itemModel?.data)!)
}else if indexPath.section == 1 {
cell = ItemRecommendCell.createItemCellFor(tableView, atIndexPath: indexPath, withDataModel: (likeModel?.data)!)
}else if indexPath.section == 2 {
cell = ItemLikeCell.createItemCellFor(tableView, atIndexPath: indexPath, withDataModel: (likeModel?.data)!)
}
return cell
}
}
|
4d091d2ffde5b42cc2929903ff52659f
| 22 | 129 | 0.513389 | false | false | false | false |
AirChen/ACSwiftDemoes
|
refs/heads/master
|
Target9-backgroundLogin/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Target9-backgroundLogin
//
// Created by Air_chen on 2016/11/4.
// Copyright © 2016年 Air_chen. All rights reserved.
//
import UIKit
import AVKit
import MediaPlayer
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let sourcePath = NSURL.fileURL(withPath: Bundle.main.path(forResource: "moments", ofType: "mp4")!)
let mediaPlayer = AVPlayerViewController()
mediaPlayer.player = AVPlayer(url: sourcePath)
mediaPlayer.view.frame = self.view.bounds
self.addChildViewController(mediaPlayer)
self.view.insertSubview(mediaPlayer.view, at: 0)
mediaPlayer.player?.volume = 1
mediaPlayer.showsPlaybackControls = false
mediaPlayer.player?.play()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.playEndAction), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: mediaPlayer.player?.currentItem)
}
func playEndAction() {
for vc in self.childViewControllers {
if vc.isKind(of: AVPlayerViewController.classForCoder()){
let player = vc as! AVPlayerViewController
player.player?.seek(to: kCMTimeZero)
player.player?.play()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
}
|
298fc1018e2d219de7a6d56a17f4b080
| 30.910714 | 200 | 0.655288 | false | false | false | false |
VladislavJevremovic/Exchange-Rates-NBS
|
refs/heads/master
|
Exchange Rates NBS/Logic/Constants.swift
|
mit
|
1
|
//
// Constants.swift
// Exchange Rates NBS
//
// Created by Vladislav Jevremovic on 12/6/14.
// Copyright (c) 2014 Vladislav Jevremovic. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
struct CustomColor {
static let Manatee = UIColor(red: 142.0 / 255.0, green: 142.0 / 255.0, blue: 147.0 / 255.0, alpha: 1.0)
static let RadicalRed = UIColor(red: 255.0 / 255.0, green: 45.0 / 255.0, blue: 85.0 / 255.0, alpha: 1.0)
static let RedOrange = UIColor(red: 255.0 / 255.0, green: 59.0 / 255.0, blue: 48.0 / 255.0, alpha: 1.0)
static let Pizazz = UIColor(red: 255.0 / 255.0, green: 149.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0)
static let Supernova = UIColor(red: 255.0 / 255.0, green: 204.0 / 255.0, blue: 0.0 / 255.0, alpha: 1.0)
static let Emerald = UIColor(red: 76.0 / 255.0, green: 217.0 / 255.0, blue: 100.0 / 255.0, alpha: 1.0)
static let Malibu = UIColor(red: 90.0 / 255.0, green: 200.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
static let CuriousBlue = UIColor(red: 52.0 / 255.0, green: 170.0 / 255.0, blue: 220.0 / 255.0, alpha: 1.0)
static let AzureRadiance = UIColor(red: 0.0 / 255.0, green: 122.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
static let Indigo = UIColor(red: 88.0 / 255.0, green: 86.0 / 255.0, blue: 214.0 / 255.0, alpha: 1.0)
static let TableBackgroundColor = UIColor(red: 176.0 / 255.0, green: 214.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
static let TableCellColor = UIColor(red: 120.0 / 255.0, green: 185.0 / 255.0, blue: 255.0 / 255.0, alpha: 1.0)
static let TableFooterColor = UIColor(red: 0.43, green: 0.45, blue: 0.45, alpha: 1.0)
}
}
|
fd51582cc960af64fbba13989ecbe2c0
| 54.193548 | 124 | 0.610754 | false | false | false | false |
matsuda/MuddlerKit
|
refs/heads/master
|
MuddlerKit/Reusable.swift
|
mit
|
1
|
//
// Reusable.swift
// MuddlerKit
//
// Created by Kosuke Matsuda on 2016/11/28.
// Copyright © 2016年 Kosuke Matsuda. All rights reserved.
//
import UIKit
// MARK: - Reusable
public protocol Reusable {
static var reusableIdentifier: String { get }
}
// MARK: - ReusableView
public protocol ReusableView: Reusable {}
extension ReusableView {
public static var reusableIdentifier: String {
return String(describing: self)
}
}
// MARK: - UITableView
extension UITableView {
public func registerNib<T: UITableViewCell>(_ type: T.Type) where T: ReusableView {
let identifier = T.reusableIdentifier
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: identifier, bundle: bundle)
register(nib, forCellReuseIdentifier: identifier)
}
public func registerClass<T: UITableViewCell>(_ type: T.Type) where T: ReusableView {
let identifier = T.reusableIdentifier
register(T.self, forCellReuseIdentifier: identifier)
}
public func dequeueReusableCell<T: UITableViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T where T: ReusableView {
let identifier = T.reusableIdentifier
guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell: \(T.self) with identifier: \(identifier).")
}
return cell
}
public func registerNib<T: UITableViewHeaderFooterView>(_ type: T.Type) where T: ReusableView {
let identifier = T.reusableIdentifier
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: identifier, bundle: bundle)
register(nib, forHeaderFooterViewReuseIdentifier: identifier)
}
public func registerClass<T: UITableViewHeaderFooterView>(_ type: T.Type) where T: ReusableView {
let identifier = T.reusableIdentifier
register(T.self, forHeaderFooterViewReuseIdentifier: identifier)
}
public func dequeueReusableHeaderFooterView<T: UITableViewHeaderFooterView>(_ type: T.Type) -> T where T: ReusableView {
let identifier = T.reusableIdentifier
guard let view = dequeueReusableHeaderFooterView(withIdentifier: identifier) as? T else {
fatalError("Could not dequeue HeaderFooterView: \(T.self) with identifier: \(identifier).")
}
return view
}
}
// MARK: - UICollectionView
extension UICollectionView {
public func registerNib<T: UICollectionViewCell>(_ type: T.Type) where T: ReusableView {
let identifier = T.reusableIdentifier
let bundle = Bundle(for: T.self)
let nib = UINib(nibName: identifier, bundle: bundle)
register(nib, forCellWithReuseIdentifier: identifier)
}
public func registerClass<T: UICollectionViewCell>(_ type: T.Type) where T: ReusableView {
let identifier = T.reusableIdentifier
register(T.self, forCellWithReuseIdentifier: identifier)
}
public func dequeueReusableCell<T: UICollectionViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T where T: ReusableView {
let identifier = T.reusableIdentifier
guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? T else {
fatalError("Could not dequeue cell: \(T.self) with identifier: \(identifier).")
}
return cell
}
}
// MARK: - UINib
extension UINib {
public class func instantiate<T: ReusableView>(_ type: T.Type) -> T {
let identifier = T.reusableIdentifier
let bundle: Bundle?
if let klass = T.self as? AnyClass {
bundle = Bundle(for: klass)
} else {
bundle = nil
}
let nib = UINib(nibName: identifier, bundle: bundle)
guard let view = nib.instantiate(withOwner: nil, options: nil).first as? T else {
fatalError("Could not load view: \(T.self) with identifier: \(identifier).")
}
return view
}
}
|
99a9727f33fcde42781d27dfbbd2d8c0
| 33.293103 | 131 | 0.670689 | false | false | false | false |
Jpadilla1/react-native-ios-charts
|
refs/heads/master
|
RNiOSCharts/chartDataHelpers.swift
|
mit
|
1
|
//
// chartDataHelpers.swift
// ChartsExplorer
//
// Created by Jose Padilla on 3/18/16.
// Copyright © 2016 Facebook. All rights reserved.
//
import Foundation
import Charts
import SwiftyJSON
var maximumDecimalPlaces: Int = 0;
var minimumDecimalPlaces: Int = 0;
func getLineData(_ labels: [String], json: JSON!) -> LineChartData {
if !json["dataSets"].exists() {
return LineChartData();
}
let dataSets = json["dataSets"].arrayObject;
var sets: [LineChartDataSet] = [];
for set in dataSets! {
let tmp = JSON(set);
if tmp["values"].exists() {
let values = tmp["values"].arrayValue.map({$0.doubleValue});
let label = tmp["label"].exists() ? tmp["label"].stringValue : "";
var dataEntries: [ChartDataEntry] = [];
for i in 0..<values.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i);
dataEntries.append(dataEntry);
}
let dataSet = LineChartDataSet(yVals: dataEntries, label: label);
if tmp["colors"].exists() {
let arrColors = tmp["colors"].arrayValue.map({$0.intValue});
dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)});
}
if tmp["drawCircles"].exists() {
dataSet.drawCirclesEnabled = tmp["drawCircles"].boolValue;
}
if tmp["lineWidth"].exists() {
dataSet.lineWidth = CGFloat(tmp["lineWidth"].floatValue);
}
if tmp["circleColors"].exists() {
let arrColors = tmp["circleColors"].arrayValue.map({$0.intValue});
dataSet.circleColors = arrColors.map({return RCTConvert.uiColor($0)});
}
if tmp["circleHoleColor"].exists() {
dataSet.circleHoleColor = RCTConvert.uiColor(tmp["circleHoleColor"].intValue);
}
if tmp["circleRadius"].exists() {
dataSet.circleRadius = CGFloat(tmp["circleRadius"].floatValue);
}
if tmp["cubicIntensity"].exists() {
dataSet.cubicIntensity = CGFloat(tmp["cubicIntensity"].floatValue);
}
if tmp["drawCircleHole"].exists() {
dataSet.drawCircleHoleEnabled = tmp["drawCircleHole"].boolValue;
}
if tmp["drawCubic"].exists() {
dataSet.drawCubicEnabled = tmp["drawCubic"].boolValue;
}
if tmp["drawFilled"].exists() {
dataSet.drawFilledEnabled = tmp["drawFilled"].boolValue;
}
if tmp["drawHorizontalHighlightIndicator"].exists() {
dataSet.drawHorizontalHighlightIndicatorEnabled = tmp["drawHorizontalHighlightIndicator"].boolValue;
}
if tmp["drawVerticalHighlightIndicator"].exists() {
dataSet.drawVerticalHighlightIndicatorEnabled = tmp["drawVerticalHighlightIndicator"].boolValue;
}
if tmp["drawValues"].exists() {
dataSet.drawValuesEnabled = tmp["drawValues"].boolValue;
}
if tmp["fillAlpha"].exists() {
dataSet.fillAlpha = CGFloat(tmp["fillAlpha"].floatValue);
}
if tmp["fillColor"].exists() {
dataSet.fillColor = RCTConvert.uiColor(tmp["fillColor"].intValue);
}
if tmp["highlightColor"].exists() {
dataSet.highlightColor = RCTConvert.uiColor(tmp["highlightColor"].intValue);
}
if tmp["highlightEnabled"].exists() {
dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue;
}
if tmp["highlightLineDashLengths"].exists() {
dataSet.highlightLineDashLengths = [CGFloat(tmp["highlightLineDashLengths"].floatValue)];
}
if tmp["highlightLineDashPhase"].exists() {
dataSet.highlightLineDashPhase = CGFloat(tmp["highlightLineDashPhase"].floatValue);
}
if tmp["highlightLineWidth"].exists() {
dataSet.highlightLineWidth = CGFloat(tmp["highlightLineWidth"].floatValue);
}
if tmp["lineDashLengths"].exists() {
dataSet.lineDashLengths = [CGFloat(tmp["lineDashLengths"].floatValue)];
}
if tmp["lineDashPhase"].exists() {
dataSet.lineDashPhase = CGFloat(tmp["lineDashPhase"].floatValue);
}
if tmp["lineWidth"].exists() {
dataSet.lineWidth = CGFloat(tmp["lineWidth"].floatValue);
}
if tmp["axisDependency"].exists() {
let value = tmp["axisDependency"].stringValue;
if value == "left" {
dataSet.axisDependency = .left;
} else if value == "right" {
dataSet.axisDependency = .right;
}
}
if tmp["valueTextFontName"].exists() {
dataSet.valueFont = UIFont(
name: tmp["valueTextFontName"].stringValue,
size: dataSet.valueFont.pointSize
)!;
}
if tmp["valueTextFontSize"].exists() {
dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue));
}
if tmp["valueTextColor"].exists() {
dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue);
}
if json["valueFormatter"].exists() {
if json["valueFormatter"]["minimumDecimalPlaces"].exists() {
minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["maximumDecimalPlaces"].exists() {
maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["type"].exists() {
switch(json["valueFormatter"]["type"]) {
case "regular":
dataSet.valueFormatter = NumberFormatter();
break;
case "abbreviated":
dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces);
break;
default:
dataSet.valueFormatter = NumberFormatter();
}
}
if json["valueFormatter"]["numberStyle"].exists() {
switch(json["valueFormatter"]["numberStyle"]) {
case "CurrencyAccountingStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyAccounting;
}
break;
case "CurrencyISOCodeStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyISOCode;
}
break;
case "CurrencyPluralStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyPlural;
}
break;
case "CurrencyStyle":
dataSet.valueFormatter?.numberStyle = .currency;
break;
case "DecimalStyle":
dataSet.valueFormatter?.numberStyle = .decimal;
break;
case "NoStyle":
dataSet.valueFormatter?.numberStyle = .none;
break;
case "OrdinalStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .ordinal;
}
break;
case "PercentStyle":
dataSet.valueFormatter?.numberStyle = .percent;
break;
case "ScientificStyle":
dataSet.valueFormatter?.numberStyle = .scientific;
break;
case "SpellOutStyle":
dataSet.valueFormatter?.numberStyle = .spellOut;
break;
default:
dataSet.valueFormatter?.numberStyle = .none;
}
}
dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces;
dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces;
}
sets.append(dataSet);
}
}
return LineChartData(xVals: labels, dataSets: sets);
}
func getBarData(_ labels: [String], json: JSON!) -> BarChartData {
if !json["dataSets"].exists() {
return BarChartData();
}
let dataSets = json["dataSets"].arrayObject;
var sets: [BarChartDataSet] = [];
for set in dataSets! {
let tmp = JSON(set);
if tmp["values"].exists() {
let values = tmp["values"].arrayValue.map({$0.doubleValue});
let label = tmp["label"].exists() ? tmp["label"].stringValue : "";
var dataEntries: [BarChartDataEntry] = [];
for i in 0..<values.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i);
dataEntries.append(dataEntry);
}
let dataSet = BarChartDataSet(yVals: dataEntries, label: label);
if tmp["barShadowColor"].exists() {
dataSet.barShadowColor = RCTConvert.uiColor(tmp["barShadowColor"].intValue);
}
if tmp["barSpace"].exists() {
dataSet.barSpace = CGFloat(tmp["barSpace"].floatValue);
}
if tmp["highlightAlpha"].exists() {
dataSet.highlightAlpha = CGFloat(tmp["highlightAlpha"].floatValue);
}
if tmp["highlightColor"].exists() {
dataSet.highlightColor = RCTConvert.uiColor(tmp["highlightColor"].intValue);
}
if tmp["highlightLineDashLengths"].exists() {
dataSet.highlightLineDashLengths = [CGFloat(tmp["highlightLineDashLengths"].floatValue)];
}
if tmp["highlightLineDashPhase"].exists() {
dataSet.highlightLineDashPhase = CGFloat(tmp["highlightLineDashPhase"].floatValue);
}
if tmp["highlightLineWidth"].exists() {
dataSet.highlightLineWidth = CGFloat(tmp["highlightLineWidth"].floatValue);
}
if tmp["stackLabels"].exists() {
dataSet.stackLabels = tmp["stackLabels"].arrayValue.map({$0.stringValue});
}
if tmp["colors"].exists() {
let arrColors = tmp["colors"].arrayValue.map({$0.intValue});
dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)});
}
if tmp["drawValues"].exists() {
dataSet.drawValuesEnabled = tmp["drawValues"].boolValue;
}
if tmp["highlightEnabled"].exists() {
dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue;
}
if tmp["valueTextFontName"].exists() {
dataSet.valueFont = UIFont(
name: tmp["valueTextFontName"].stringValue,
size: dataSet.valueFont.pointSize
)!;
}
if tmp["valueTextFontSize"].exists() {
dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue))
}
if tmp["valueTextColor"].exists() {
dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue);
}
if tmp["axisDependency"].exists() {
let value = tmp["axisDependency"].stringValue;
if value == "left" {
dataSet.axisDependency = .left;
} else if value == "right" {
dataSet.axisDependency = .right;
}
}
if json["valueFormatter"].exists() {
if json["valueFormatter"]["minimumDecimalPlaces"].exists() {
minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["maximumDecimalPlaces"].exists() {
maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["type"].exists() {
switch(json["valueFormatter"]["type"]) {
case "regular":
dataSet.valueFormatter = NumberFormatter();
break;
case "abbreviated":
dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces);
break;
default:
dataSet.valueFormatter = NumberFormatter();
}
}
if json["valueFormatter"]["numberStyle"].exists() {
switch(json["valueFormatter"]["numberStyle"]) {
case "CurrencyAccountingStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyAccounting;
}
break;
case "CurrencyISOCodeStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyISOCode;
}
break;
case "CurrencyPluralStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyPlural;
}
break;
case "CurrencyStyle":
dataSet.valueFormatter?.numberStyle = .currency;
break;
case "DecimalStyle":
dataSet.valueFormatter?.numberStyle = .decimal;
break;
case "NoStyle":
dataSet.valueFormatter?.numberStyle = .none;
break;
case "OrdinalStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .ordinal;
}
break;
case "PercentStyle":
dataSet.valueFormatter?.numberStyle = .percent;
break;
case "ScientificStyle":
dataSet.valueFormatter?.numberStyle = .scientific;
break;
case "SpellOutStyle":
dataSet.valueFormatter?.numberStyle = .spellOut;
break;
default:
dataSet.valueFormatter?.numberStyle = .none;
}
}
dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces;
dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces;
}
sets.append(dataSet);
}
}
return BarChartData(xVals: labels, dataSets: sets);
}
func getBubbleData(_ labels: [String], json: JSON!) -> BubbleChartData {
if !json["dataSets"].exists() {
return BubbleChartData();
}
let dataSets = json["dataSets"].arrayObject;
var sets: [BubbleChartDataSet] = [];
for set in dataSets! {
let tmp = JSON(set);
if tmp["values"].exists() {
let values = tmp["values"].arrayObject!;
let label = tmp["label"].exists() ? tmp["label"].stringValue : "";
var dataEntries: [BubbleChartDataEntry] = [];
for i in 0..<values.count {
let object = JSON(values[i]);
let dataEntry = BubbleChartDataEntry(
xIndex: i,
value: object["value"].doubleValue,
size: CGFloat(object["size"].floatValue)
);
dataEntries.append(dataEntry);
}
let dataSet = BubbleChartDataSet(yVals: dataEntries, label: label);
if tmp["colors"].exists() {
let arrColors = tmp["colors"].arrayValue.map({$0.intValue});
dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)});
}
if tmp["drawValues"].exists() {
dataSet.drawValuesEnabled = tmp["drawValues"].boolValue;
}
if tmp["highlightEnabled"].exists() {
dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue;
}
if tmp["highlightCircleWidth"].exists() {
dataSet.highlightCircleWidth = CGFloat(tmp["highlightCircleWidth"].floatValue);
}
if tmp["valueTextFontName"].exists() {
dataSet.valueFont = UIFont(
name: tmp["valueTextFontName"].stringValue,
size: dataSet.valueFont.pointSize
)!;
}
if tmp["axisDependency"].exists() {
let value = tmp["axisDependency"].stringValue;
if value == "left" {
dataSet.axisDependency = .left;
} else if value == "right" {
dataSet.axisDependency = .right;
}
}
if tmp["valueTextFontSize"].exists() {
dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue))
}
if tmp["valueTextColor"].exists() {
dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue);
}
if json["valueFormatter"].exists() {
if json["valueFormatter"]["minimumDecimalPlaces"].exists() {
minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["maximumDecimalPlaces"].exists() {
maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["type"].exists() {
switch(json["valueFormatter"]["type"]) {
case "regular":
dataSet.valueFormatter = NumberFormatter();
break;
case "abbreviated":
dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces);
break;
default:
dataSet.valueFormatter = NumberFormatter();
}
}
if json["valueFormatter"]["numberStyle"].exists() {
switch(json["valueFormatter"]["numberStyle"]) {
case "CurrencyAccountingStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyAccounting;
}
break;
case "CurrencyISOCodeStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyISOCode;
}
break;
case "CurrencyPluralStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyPlural;
}
break;
case "CurrencyStyle":
dataSet.valueFormatter?.numberStyle = .currency;
break;
case "DecimalStyle":
dataSet.valueFormatter?.numberStyle = .decimal;
break;
case "NoStyle":
dataSet.valueFormatter?.numberStyle = .none;
break;
case "OrdinalStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .ordinal;
}
break;
case "PercentStyle":
dataSet.valueFormatter?.numberStyle = .percent;
break;
case "ScientificStyle":
dataSet.valueFormatter?.numberStyle = .scientific;
break;
case "SpellOutStyle":
dataSet.valueFormatter?.numberStyle = .spellOut;
break;
default:
dataSet.valueFormatter?.numberStyle = .none;
}
}
dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces;
dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces;
}
sets.append(dataSet);
}
}
return BubbleChartData(xVals: labels, dataSets: sets);
}
func getScatterData(_ labels: [String], json: JSON!) -> ScatterChartData {
if !json["dataSets"].exists() {
return ScatterChartData();
}
let dataSets = json["dataSets"].arrayObject;
var sets: [ScatterChartDataSet] = [];
for set in dataSets! {
let tmp = JSON(set);
if tmp["values"].exists() {
let values = tmp["values"].arrayValue.map({$0.doubleValue});
let label = tmp["label"].exists() ? tmp["label"].stringValue : "";
var dataEntries: [ChartDataEntry] = [];
for i in 0..<values.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i);
dataEntries.append(dataEntry);
}
let dataSet = ScatterChartDataSet(yVals: dataEntries, label: label);
if tmp["colors"].exists() {
let arrColors = tmp["colors"].arrayValue.map({$0.intValue});
dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)});
}
if tmp["drawValues"].exists() {
dataSet.drawValuesEnabled = tmp["drawValues"].boolValue;
}
if tmp["highlightEnabled"].exists() {
dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue;
}
if tmp["scatterShapeSize"].exists() {
dataSet.scatterShapeSize = CGFloat(tmp["scatterShapeSize"].floatValue);
}
if tmp["scatterShapeHoleRadius"].exists() {
dataSet.scatterShapeHoleRadius = CGFloat(tmp["scatterShapeHoleRadius"].floatValue);
}
if tmp["scatterShapeHoleColor"].exists() {
dataSet.scatterShapeHoleColor = RCTConvert.uiColor(tmp["scatterShapeHoleColor"].intValue);
}
if tmp["scatterShape"].exists() {
switch(tmp["scatterShape"]) {
case "Square":
dataSet.scatterShape = .square;
break;
case "Circle":
dataSet.scatterShape = .circle;
break;
case "Triangle":
dataSet.scatterShape = .triangle;
break;
case "Cross":
dataSet.scatterShape = .cross;
break;
case "X":
dataSet.scatterShape = .x;
break;
default:
dataSet.scatterShape = .square;
break;
}
}
if tmp["valueTextFontName"].exists() {
dataSet.valueFont = UIFont(
name: tmp["valueTextFontName"].stringValue,
size: dataSet.valueFont.pointSize
)!;
}
if tmp["valueTextFontSize"].exists() {
dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue))
}
if tmp["valueTextColor"].exists() {
dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue);
}
if tmp["axisDependency"].exists() {
let value = tmp["axisDependency"].stringValue;
if value == "left" {
dataSet.axisDependency = .left;
} else if value == "right" {
dataSet.axisDependency = .right;
}
}
if json["valueFormatter"].exists() {
if json["valueFormatter"]["minimumDecimalPlaces"].exists() {
minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["maximumDecimalPlaces"].exists() {
maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["type"].exists() {
switch(json["valueFormatter"]["type"]) {
case "regular":
dataSet.valueFormatter = NumberFormatter();
break;
case "abbreviated":
dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces);
break;
default:
dataSet.valueFormatter = NumberFormatter();
}
}
if json["valueFormatter"]["numberStyle"].exists() {
switch(json["valueFormatter"]["numberStyle"]) {
case "CurrencyAccountingStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyAccounting;
}
break;
case "CurrencyISOCodeStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyISOCode;
}
break;
case "CurrencyPluralStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyPlural;
}
break;
case "CurrencyStyle":
dataSet.valueFormatter?.numberStyle = .currency;
break;
case "DecimalStyle":
dataSet.valueFormatter?.numberStyle = .decimal;
break;
case "NoStyle":
dataSet.valueFormatter?.numberStyle = .none;
break;
case "OrdinalStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .ordinal;
}
break;
case "PercentStyle":
dataSet.valueFormatter?.numberStyle = .percent;
break;
case "ScientificStyle":
dataSet.valueFormatter?.numberStyle = .scientific;
break;
case "SpellOutStyle":
dataSet.valueFormatter?.numberStyle = .spellOut;
break;
default:
dataSet.valueFormatter?.numberStyle = .none;
}
}
dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces;
dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces;
}
sets.append(dataSet);
}
}
return ScatterChartData(xVals: labels, dataSets: sets);
}
func getCandleStickData(_ labels: [String], json: JSON!) -> CandleChartData {
if !json["dataSets"].exists() {
return CandleChartData();
}
let dataSets = json["dataSets"].arrayObject;
var sets: [CandleChartDataSet] = [];
for set in dataSets! {
let tmp = JSON(set);
if tmp["values"].exists() {
let values = tmp["values"].arrayObject!;
let label = tmp["label"].exists() ? tmp["label"].stringValue : "";
var dataEntries: [CandleChartDataEntry] = [];
for i in 0..<values.count {
let object = JSON(values[i]);
let dataEntry = CandleChartDataEntry(
xIndex: i,
shadowH: object["shadowH"].doubleValue,
shadowL: object["shadowL"].doubleValue,
open: object["open"].doubleValue,
close: object["close"].doubleValue
);
dataEntries.append(dataEntry);
}
let dataSet = CandleChartDataSet(yVals: dataEntries, label: label);
if tmp["colors"].exists() {
let arrColors = tmp["colors"].arrayValue.map({$0.intValue});
dataSet.colors = arrColors.map({return RCTConvert.uiColor($0)});
}
if tmp["drawValues"].exists() {
dataSet.drawValuesEnabled = tmp["drawValues"].boolValue;
}
if tmp["highlightEnabled"].exists() {
dataSet.highlightEnabled = tmp["highlightEnabled"].boolValue;
}
if tmp["valueTextFontName"].exists() {
dataSet.valueFont = UIFont(
name: tmp["valueTextFontName"].stringValue,
size: dataSet.valueFont.pointSize
)!;
}
if tmp["valueTextFontSize"].exists() {
dataSet.valueFont = dataSet.valueFont.withSize(CGFloat(tmp["valueTextFontSize"].floatValue))
}
if tmp["valueTextColor"].exists() {
dataSet.valueTextColor = RCTConvert.uiColor(tmp["valueTextColor"].intValue);
}
if tmp["axisDependency"].exists() {
let value = tmp["axisDependency"].stringValue;
if value == "left" {
dataSet.axisDependency = .left;
} else if value == "right" {
dataSet.axisDependency = .right;
}
}
if tmp["barSpace"].exists() {
dataSet.barSpace = CGFloat(tmp["barSpace"].floatValue);
}
if tmp["showCandleBar"].exists() {
dataSet.showCandleBar = tmp["showCandleBar"].boolValue;
}
if tmp["shadowWidth"].exists() {
dataSet.shadowWidth = CGFloat(tmp["shadowWidth"].floatValue);
}
if tmp["shadowColor"].exists() {
dataSet.shadowColor = RCTConvert.uiColor(tmp["shadowColor"].intValue);
}
if tmp["shadowColorSameAsCandle"].exists() {
dataSet.shadowColorSameAsCandle = tmp["shadowColorSameAsCandle"].boolValue;
}
if tmp["neutralColor"].exists() {
dataSet.neutralColor = RCTConvert.uiColor(tmp["neutralColor"].intValue);
}
if tmp["increasingColor"].exists() {
dataSet.increasingColor = RCTConvert.uiColor(tmp["increasingColor"].intValue);
}
if tmp["decreasingColor"].exists() {
dataSet.decreasingColor = RCTConvert.uiColor(tmp["decreasingColor"].intValue);
}
if tmp["increasingFilled"].exists() {
dataSet.increasingFilled = tmp["increasingFilled"].boolValue;
}
if tmp["decreasingFilled"].exists() {
dataSet.decreasingFilled = tmp["decreasingFilled"].boolValue;
}
if json["valueFormatter"].exists() {
if json["valueFormatter"]["minimumDecimalPlaces"].exists() {
minimumDecimalPlaces = json["valueFormatter"]["minimumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["maximumDecimalPlaces"].exists() {
maximumDecimalPlaces = json["valueFormatter"]["maximumDecimalPlaces"].intValue;
}
if json["valueFormatter"]["type"].exists() {
switch(json["valueFormatter"]["type"]) {
case "regular":
dataSet.valueFormatter = NumberFormatter();
break;
case "abbreviated":
dataSet.valueFormatter = ABNumberFormatter(minimumDecimalPlaces: minimumDecimalPlaces, maximumDecimalPlaces: maximumDecimalPlaces);
break;
default:
dataSet.valueFormatter = NumberFormatter();
}
}
if json["valueFormatter"]["numberStyle"].exists() {
switch(json["valueFormatter"]["numberStyle"]) {
case "CurrencyAccountingStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyAccounting;
}
break;
case "CurrencyISOCodeStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyISOCode;
}
break;
case "CurrencyPluralStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .currencyPlural;
}
break;
case "CurrencyStyle":
dataSet.valueFormatter?.numberStyle = .currency;
break;
case "DecimalStyle":
dataSet.valueFormatter?.numberStyle = .decimal;
break;
case "NoStyle":
dataSet.valueFormatter?.numberStyle = .none;
break;
case "OrdinalStyle":
if #available(iOS 9.0, *) {
dataSet.valueFormatter?.numberStyle = .ordinal;
}
break;
case "PercentStyle":
dataSet.valueFormatter?.numberStyle = .percent;
break;
case "ScientificStyle":
dataSet.valueFormatter?.numberStyle = .scientific;
break;
case "SpellOutStyle":
dataSet.valueFormatter?.numberStyle = .spellOut;
break;
default:
dataSet.valueFormatter?.numberStyle = .none;
}
}
dataSet.valueFormatter?.minimumFractionDigits = minimumDecimalPlaces;
dataSet.valueFormatter?.maximumFractionDigits = maximumDecimalPlaces;
}
sets.append(dataSet);
}
}
return CandleChartData(xVals: labels, dataSets: sets);
}
|
8820c74dafd19231d804cbfa8eedb6c0
| 39.349277 | 155 | 0.491702 | false | false | false | false |
abelsanchezali/ViewBuilder
|
refs/heads/master
|
ViewBuilderDemo/ViewBuilderDemo/ViewControllers/OnboardingPhoneScreenView.swift
|
mit
|
1
|
//
// OnboardingPhoneScreenView.swift
// ViewBuilderDemo
//
// Created by Abel Sanchez on 10/9/16.
// Copyright © 2016 Abel Sanchez. All rights reserved.
//
import UIKit
import ViewBuilder
public class OnboardingPhoneScreenView: Panel {
weak var messageContainer: StackPanel!
weak var container: UIScrollView!
init() {
super.init(frame: CGRect.zero)
self.loadFromDocument(Constants.bundle.path(forResource: "OnboardingPhoneScreenView", ofType: "xml")!)
container = self.documentReferences!["container"] as! UIScrollView
messageContainer = self.documentReferences!["messageContainer"] as! StackPanel
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension OnboardingPhoneScreenView {
public func gotoIntialState() {
messageContainer.subviews.forEach() {
$0.isHidden = true
$0.alpha = 0
}
}
public func playAnimation() {
var index = 0
func showNextMessage() {
showMesageIndex(index) { (completed) in
if completed {
index += 1
AnimationHelper.delayedBlock(1.0, block: {
showNextMessage()
})
}
}
}
showNextMessage()
}
public func showMesageIndex(_ index: Int, comletion: ((Bool) -> Void)?) {
if index >= messageContainer.subviews.count {
comletion?(false)
return
}
let subview = messageContainer.subviews[index]
let delay = Double(subview.tag) / 1000.0
UIView.animate(withDuration: 0.75,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0.1,
options: [.curveEaseOut, .beginFromCurrentState],
animations: {
subview.isHidden = false
self.layoutIfNeeded()
self.container.scrollToBottom(false)
}, completion: nil)
subview.layer.removeAllAnimations()
subview.transform = CGAffineTransform(translationX: 0, y: 50)
UIView.animate(withDuration: 0.75,
delay: 0.25,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.1,
options: [.curveEaseOut, .beginFromCurrentState],
animations: {
subview.alpha = 1
subview.transform = CGAffineTransform.identity
}, completion: {(completed) in
if !completed {
comletion?(false)
} else {
AnimationHelper.delayedBlock(delay, block: {
comletion?(true)
})
}
})
}
}
|
871104746688618bbe6ddef9245c5c87
| 34.712644 | 110 | 0.509173 | false | false | false | false |
trill-lang/LLVMSwift
|
refs/heads/master
|
Sources/LLVM/FunctionType.swift
|
mit
|
1
|
#if SWIFT_PACKAGE
import cllvm
#endif
/// `FunctionType` represents a function's type signature. It consists of a
/// return type and a list of formal parameter types. The return type of a
/// function type is a `void` type or first class type — except for `LabelType`
/// and `MetadataType`.
public struct FunctionType: IRType {
/// The list of argument types.
public let parameterTypes: [IRType]
/// The return type of this function type.
public let returnType: IRType
/// Returns whether this function is variadic.
public let isVariadic: Bool
/// Creates a function type with the given argument types and return type.
///
/// - parameter argTypes: A list of the argument types of the function type.
/// - parameter returnType: The return type of the function type.
/// - parameter isVarArg: Indicates whether this function type is variadic.
/// Defaults to `false`.
/// - note: The context of this type is taken from it's `returnType`
@available(*, deprecated, message: "Use the more concise initializer instead", renamed: "FunctionType.init(_:_:variadic:)")
public init(argTypes: [IRType], returnType: IRType, isVarArg: Bool = false) {
self.parameterTypes = argTypes
self.returnType = returnType
self.isVariadic = isVarArg
}
/// Creates a function type with the given argument types and return type.
///
/// - parameter parameterTypes: A list of the argument types of the function
/// type.
/// - parameter returnType: The return type of the function type.
/// - parameter variadic: Indicates whether this function type is variadic.
/// Defaults to `false`.
/// - note: The context of this type is taken from it's `returnType`
public init(
_ parameterTypes: [IRType],
_ returnType: IRType,
variadic: Bool = false
) {
self.parameterTypes = parameterTypes
self.returnType = returnType
self.isVariadic = variadic
}
/// Retrieves the underlying LLVM type object.
public func asLLVM() -> LLVMTypeRef {
var argIRTypes = parameterTypes.map { $0.asLLVM() as Optional }
return argIRTypes.withUnsafeMutableBufferPointer { buf in
return LLVMFunctionType(returnType.asLLVM(),
buf.baseAddress,
UInt32(buf.count),
isVariadic.llvm)!
}
}
}
// MARK: Legacy Accessors
extension FunctionType {
/// The list of argument types.
@available(*, deprecated, message: "Use FunctionType.parameterTypes instead")
public var argTypes: [IRType] {
return self.parameterTypes
}
/// Returns whether this function is variadic.
@available(*, deprecated, message: "Use FunctionType.isVariadic instead")
public var isVarArg: Bool {
return self.isVariadic
}
}
extension FunctionType: Equatable {
public static func == (lhs: FunctionType, rhs: FunctionType) -> Bool {
return lhs.asLLVM() == rhs.asLLVM()
}
}
|
6258f90d686647f2f75e5519ed987377
| 35.5375 | 125 | 0.685255 | false | false | false | false |
adrfer/swift
|
refs/heads/master
|
test/SILGen/struct_resilience.swift
|
apache-2.0
|
1
|
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s
import resilient_struct
// Resilient structs are always address-only
// CHECK-LABEL: sil hidden @_TF17struct_resilience26functionWithResilientTypesFTV16resilient_struct4Size1fFS1_S1__S1_ : $@convention(thin) (@out Size, @in Size, @owned @callee_owned (@out Size, @in Size) -> ()) -> ()
// CHECK: bb0(%0 : $*Size, %1 : $*Size, %2 : $@callee_owned (@out Size, @in Size) -> ()):
func functionWithResilientTypes(s: Size, f: Size -> Size) -> Size {
// Stored properties of resilient structs from outside our resilience
// domain are accessed through accessors
// CHECK: copy_addr %1 to [initialization] [[OTHER_SIZE_BOX:%[0-9]*]] : $*Size
var s2 = s
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1wSi : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizes1wSi : $@convention(method) (Int, @inout Size) -> ()
// CHECK: apply [[FN]]([[RESULT]], [[OTHER_SIZE_BOX]])
s2.w = s.w
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: [[FN:%.*]] = function_ref @_TFV16resilient_struct4Sizeg1hSi : $@convention(method) (@in_guaranteed Size) -> Int
// CHECK: [[RESULT:%.*]] = apply [[FN]]([[SIZE_BOX]])
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*Size
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
// Fixed-layout structs may be trivial or loadable
// CHECK-LABEL: sil hidden @_TF17struct_resilience28functionWithFixedLayoutTypesFTV16resilient_struct5Point1fFS1_S1__S1_ : $@convention(thin) (Point, @owned @callee_owned (Point) -> Point) -> Point
// CHECK: bb0(%0 : $Point, %1 : $@callee_owned (Point) -> Point):
func functionWithFixedLayoutTypes(p: Point, f: Point -> Point) -> Point {
// Stored properties of fixed layout structs are accessed directly
var p2 = p
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.x
// CHECK: [[DEST:%.*]] = struct_element_addr [[POINT_BOX:%[0-9]*]] : $*Point, #Point.x
// CHECK: assign [[RESULT]] to [[DEST]] : $*Int
p2.x = p.x
// CHECK: [[RESULT:%.*]] = struct_extract %0 : $Point, #Point.y
_ = p.y
// CHECK: [[NEW_POINT:%.*]] = apply %1(%0)
// CHECK: return [[NEW_POINT]]
return f(p)
}
// Fixed-layout struct with resilient stored properties is still address-only
// CHECK-LABEL: sil hidden @_TF17struct_resilience39functionWithFixedLayoutOfResilientTypesFTV16resilient_struct9Rectangle1fFS1_S1__S1_ : $@convention(thin) (@out Rectangle, @in Rectangle, @owned @callee_owned (@out Rectangle, @in Rectangle) -> ()) -> ()
// CHECK: bb0(%0 : $*Rectangle, %1 : $*Rectangle, %2 : $@callee_owned (@out Rectangle, @in Rectangle) -> ()):
func functionWithFixedLayoutOfResilientTypes(r: Rectangle, f: Rectangle -> Rectangle) -> Rectangle {
return f(r)
}
// Make sure we generate getters and setters for stored properties of
// resilient structs
public struct MySize {
// Static computed property
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg10expirationSi : $@convention(thin) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes10expirationSi : $@convention(thin) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem10expirationSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize.Type, @thick MySize.Type.Type) -> ()>)
public static var expiration: Int {
get { return copyright + 70 }
set { copyright = newValue - 70 }
}
// Instance computed property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1dSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1dSi : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1dSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize, @thick MySize.Type) -> ()>)
public var d: Int {
get { return 0 }
set { }
}
// Instance stored property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1wSi : $@convention(method) (@in_guaranteed MySize) -> Int
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizes1wSi : $@convention(method) (Int, @inout MySize) -> ()
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizem1wSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout MySize) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize, @thick MySize.Type) -> ()>)
public var w: Int
// Read-only instance stored property
// CHECK-LABEL: sil @_TFV17struct_resilience6MySizeg1hSi : $@convention(method) (@in_guaranteed MySize) -> Int
public let h: Int
// Static stored property
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizeg9copyrightSi : $@convention(thin) (@thin MySize.Type) -> Int
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizes9copyrightSi : $@convention(thin) (Int, @thin MySize.Type) -> ()
// CHECK-LABEL: sil @_TZFV17struct_resilience6MySizem9copyrightSi : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @thin MySize.Type) -> (Builtin.RawPointer, Optional<@convention(thin) (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer, inout MySize.Type, @thick MySize.Type.Type) -> ()>)
public static var copyright: Int = 0
}
// CHECK-LABEL: sil @_TF17struct_resilience28functionWithMyResilientTypesFTVS_6MySize1fFS0_S0__S0_ : $@convention(thin) (@out MySize, @in MySize, @owned @callee_owned (@out MySize, @in MySize) -> ()) -> ()
public func functionWithMyResilientTypes(s: MySize, f: MySize -> MySize) -> MySize {
// Stored properties of resilient structs from inside our resilience
// domain are accessed directly
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%[0-9]*]] : $*MySize
var s2 = s
// CHECK: [[SRC_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.w
// CHECK: [[SRC:%.*]] = load [[SRC_ADDR]] : $*Int
// CHECK: [[DEST_ADDR:%.*]] = struct_element_addr [[SIZE_BOX]] : $*MySize, #MySize.w
// CHECK: assign [[SRC]] to [[DEST_ADDR]] : $*Int
s2.w = s.w
// CHECK: [[RESULT_ADDR:%.*]] = struct_element_addr %1 : $*MySize, #MySize.h
// CHECK: [[RESULT:%.*]] = load [[RESULT_ADDR]] : $*Int
_ = s.h
// CHECK: copy_addr %1 to [initialization] [[SIZE_BOX:%.*]] : $*MySize
// CHECK: apply %2(%0, [[SIZE_BOX]])
// CHECK: return
return f(s)
}
|
f2ef24ede1bcd796ec9c89fd3f609430
| 52.338346 | 319 | 0.661545 | false | false | false | false |
HusamAamer/Versioner
|
refs/heads/master
|
Example/Versioner/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Versioner
//
// Created by [email protected] on 08/05/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import Versioner
class ViewController: UIViewController {
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var subtitle: UILabel!
@IBOutlet weak var version_info_title: UILabel!
@IBOutlet weak var details: UILabel!
var ui_updated : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Get current version
let current_version = Versioner.currentVersion
// For example beauty
let launchesNumber = current_version.launchNumber
let formatter = NumberFormatter()
formatter.numberStyle = .ordinal
let styled_launchesNumber = formatter.string(from: NSNumber.init(value: launchesNumber))!
let welcoming_string = "This is your \(styled_launchesNumber) visit 😃"
////////////////////////////////////////////////////////////
// :: BEFORE NEXT CODE ::
// You should add Versioner.initiate() to
// didFinishLaunchingWithOptions in AppDelegate.swift
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// :: Usage #1 => at current version state do something cool
////////////////////////////////////////////////////////////
Versioner.currentVersion.isFreshInstall {
/*
🔸 App first launch ever
- App was not installed before this version
or - App was installed but this library was not included in previous versions
*/
updateUI(set: "Welcome 🙏🏻",
subtitle: welcoming_string,
details: current_version)
}.isUpdate { (prevVersion) in
/*
🔸 Update opened
- (App was installed before) and (this version has a number newer than previous one and launched for the first time)
*/
updateUI(set: "Updated successfully ✅",
subtitle: welcoming_string,
version_info: "Previous version info",
details: prevVersion)
}.isDowngrade { (prevVersion) in
// 🔸 Old version launched
updateUI(set: "🙁",
subtitle: "Please get me back to the newer version",
version_info: "Previous version info",
details: prevVersion)
}.isLaunch(number: 3) {
/*
🔸 Launch number X of this version (not all versions together),
X = any number you want */
updateUI(set: "Third Welcome is special ❤️",
subtitle: welcoming_string,
details: current_version)
}.isBuildUpdate { (prevVersion) in
/*
🔸 New build launched with same previous version number */
updateUI(set: "Welcome tester",
subtitle: "I'm the newest build",
version_info: "Previous version info",
details: prevVersion)
}.isBuildDowngrade(handler: { (prevVersion) in
/*
🔸 Old build launched with same previous version number */
updateUI(set: "YOU, Don't play with my build !!",
subtitle: welcoming_string,
version_info: "Previous version info",
details: prevVersion)
})
// If nothing of the above changed the UI
if !ui_updated {
updateUI(set: "Welcome back!",
subtitle: welcoming_string,
details: current_version)
}
////////////////////////////////////////////////////////////
// :: Usage #2 => Execute another specific code in future relase
////////////////////////////////////////////////////////////
if Versioner.currentVersion > AppVersion("3.0") {
// Do new code
// ex: call new backend
} else {
// Do old code
// ex: call old backend
}
////////////////////////////////////////////////////////////
// :: Usage #3 => Version number comparision operators
////////////////////////////////////////////////////////////
print(Versioner.currentVersion > AppVersion("3.0.0.1")) // true or false
print(AppVersion("3.0") < AppVersion("3.1")) // true
print(AppVersion("3.0") == AppVersion("3.0")) // true
}
/// Updates Example app Labels in Main.storyboard
///
private func updateUI (set title:String,
subtitle:String,
version_info:String = "Current version info ",
details:AppVersion) {
self.titleLbl.text = title
self.subtitle.text = subtitle
self.version_info_title.text = version_info
self.details.text = "Version : \(details.number) build \(details.build)\n"
self.details.text?.append("Launched \(details.launchNumber) time(s)\n")
self.details.text?.append("First launch : \(details.firstLaunchDate)\n")
self.details.text?.append("First installed os version : \(details.os_version)\n")
ui_updated = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
ff77a2f9001aafbdebf2216bd74759cb
| 35.103659 | 132 | 0.479649 | false | false | false | false |
sseitov/v-Chess-Swift
|
refs/heads/master
|
v-Chess/Extensions/UIFontExtension.swift
|
gpl-3.0
|
1
|
//
// UIFontExtension.swift
//
// Created by Сергей Сейтов on 22.05.17.
// Copyright © 2017 V-Channel. All rights reserved.
//
import UIKit
func printFontNames() {
for family:String in UIFont.familyNames {
print("\(family)")
for names:String in UIFont.fontNames(forFamilyName: family) {
print("== \(names)")
}
}
}
extension UIFont {
class func mainFont(_ size:CGFloat = 17) -> UIFont {
return UIFont(name: "HelveticaNeue", size: size)!
}
class func thinFont(_ size:CGFloat = 17) -> UIFont {
return UIFont(name: "HelveticaNeue-Thin", size: size)!
}
class func condensedFont(_ size:CGFloat = 17) -> UIFont {
return UIFont(name: "HelveticaNeue-CondensedBold", size: size)!
}
class func commentsFont() -> UIFont {
return mainFont(15)
}
}
|
0172d151ae177a23044a24b414264804
| 23.111111 | 71 | 0.599078 | false | false | false | false |
ddstone/4ddcmj
|
refs/heads/master
|
AmateurTimeRecoder/TimingViewController.swift
|
gpl-3.0
|
1
|
//
// TimingViewController.swift
// TimeRecorder
//
// Created by apple on 5/19/16.
// Copyright © 2016 ddstone. All rights reserved.
//
import UIKit
class TimingViewController: UIViewController, TurnOffTiming
{
var isTiming = false {
didSet {
updateUI()
}
}
var from: NSDate!
let imageView = UIImageView()
@IBOutlet weak var timingView: UIView!
@IBAction func longTap(sender: UILongPressGestureRecognizer) {
if sender.state == .Began {
if isTiming {
let title = "经过" + Utility.toCost(NSDate().timeIntervalSinceDate(from)) + ",CD好了么?"
let alert = UIAlertController(title: title, message: "", preferredStyle: .ActionSheet)
alert.addAction(UIAlertAction(title: "确定", style: .Default) { (action) in
self.performSegueWithIdentifier(Constant.TimeToProjectSegueIdentifier, sender: nil)
})
alert.addAction(UIAlertAction(title: "清零", style: .Destructive) { (action) in
self.isTiming = false
})
alert.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
} else {
from = NSDate()
isTiming = !isTiming
}
}
}
// MARK: - Respond to shake gesture
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
performSegueWithIdentifier(Constant.TimeToProjectSegueIdentifier, sender: event)
}
}
// MARK: - Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
timingView.addSubview(imageView)
timingView.backgroundColor = UIColor.blackColor()
// restore from db
if let isTiming = AppDelegate.database.read(Constant.DBIsTimingFile, key: Constant.DBIsTimingKey) as? Bool {
self.isTiming = isTiming
self.from = AppDelegate.database.read(Constant.DBFromFile, key: Constant.DBFromKey) as! NSDate
}
updateUI()
// Listen to backup when into background
NSNotificationCenter.defaultCenter().addObserverForName(
NotificationName.DidEnterBackground,
object: UIApplication.sharedApplication().delegate,
queue: NSOperationQueue.mainQueue()) { (notification) in
if self.isTiming {
self.storeData()
} else {
self.delData()
}
}
}
// MARK: - Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Constant.TimeToProjectSegueIdentifier {
switch sender {
case nil:
let ptvc = segue.destinationViewController.containerController as! ProjectsTableViewController
ptvc.timeIntervals = TimeInterval(from: from, to: NSDate())
ptvc.timingVC = self
case let event where event is UIEvent: break
default: break
}
}
}
// MARK: - Delegate
func turnOffTiming() {
isTiming = !isTiming
}
// MARK: - Internal functions
private func updateUI() {
let name = isTiming ? Constant.WadeSuspend : Constant().WadeOntheGo
imageView.image = UIImage(named: name)!
centerForImage()
}
private func centerForImage() {
let width = imageView.superview!.superview!.bounds.width
let height = width / imageView.image!.aspecRatio
let y = (imageView.superview!.superview!.bounds.height - height)/2
imageView.frame = CGRect(x: 0, y: y, width: width, height: height)
}
private func storeData() {
AppDelegate.database.insert(Constant.DBIsTimingFile, obj: self.isTiming, key: Constant.DBIsTimingKey)
AppDelegate.database.insert(Constant.DBFromFile, obj: self.from, key: Constant.DBFromKey)
}
private func delData() {
[Constant.DBIsTimingFile, Constant.DBFromFile].forEach {
AppDelegate.database.delFile($0)
}
}
// MARK: - Constains
struct Constant {
static let TimeToProjectSegueIdentifier = "TimeToProjectSegueIdentifier"
static let WadeSuspend = "Wade_suspend"
var WadeOntheGo = "Wade_onthego" + String(arc4random()%UInt32(6))
static let DBIsTimingFile = "DB_isTiming_file"
static let DBIsTimingKey = "DB isTiming Key"
static let DBFromFile = "DB_from_file"
static let DBFromKey = "DB from Key"
}
}
extension UIViewController {
var containerController: UIViewController {
if let navi = self as? UINavigationController {
return navi.visibleViewController!
} else {
return self
}
}
}
extension UIImage {
var aspecRatio: CGFloat {
return size.height != 0 ? size.width/size.height : 0
}
}
|
653ff597a3862420587db1c3a04d192c
| 32.966887 | 116 | 0.601677 | false | false | false | false |
sssbohdan/Design-Patterns-In-Swift
|
refs/heads/master
|
source/behavioral/iterator.swift
|
gpl-3.0
|
2
|
/*:
🍫 Iterator
-----------
The iterator pattern is used to provide a standard interface for traversing a collection of items in an aggregate object without the need to understand its underlying structure.
### Example:
*/
struct NovellasCollection<T> {
let novellas: [T]
}
extension NovellasCollection: SequenceType {
typealias Generator = AnyGenerator<T>
func generate() -> AnyGenerator<T> {
var i = 0
return AnyGenerator { i += 1; return i >= self.novellas.count ? nil : self.novellas[i] }
}
}
/*:
### Usage
*/
let greatNovellas = NovellasCollection(novellas:["Mist"])
for novella in greatNovellas {
print("I've read: \(novella)")
}
|
a67f812a8d7a68097878606f14f6ddd4
| 23.25 | 177 | 0.671576 | false | false | false | false |
ddaguro/clintonconcord
|
refs/heads/master
|
OIMApp/TasksCell.swift
|
mit
|
1
|
//
// TasksCell.swift
// OIMApp
//
// Created by Linh NGUYEN on 5/28/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import Foundation
import UIKit
class TasksCell : UITableViewCell {
@IBOutlet var typeImageView : UIImageView!
@IBOutlet var dateImageView : UIImageView!
@IBOutlet var nameLabel : UILabel!
@IBOutlet var postLabel : UILabel?
@IBOutlet var dateLabel : UILabel!
@IBOutlet var approveBtn: UIButton!
@IBOutlet var declineBtn: UIButton!
@IBOutlet var moreBtn: UIButton!
@IBOutlet var beneficiaryLabel: UILabel!
@IBOutlet var beneiciaryUserLabel: UILabel!
@IBOutlet var justificationLabel: UILabel!
override func awakeFromNib() {
nameLabel.font = UIFont(name: MegaTheme.fontName, size: 14)
nameLabel.textColor = MegaTheme.darkColor
postLabel?.font = UIFont(name: MegaTheme.fontName, size: 12)
postLabel?.textColor = MegaTheme.lightColor
dateImageView.image = UIImage(named: "clock")
dateImageView.alpha = 0.20
dateLabel.font = UIFont(name: MegaTheme.fontName, size: 10)
dateLabel.textColor = MegaTheme.lightColor
beneficiaryLabel.font = UIFont(name: MegaTheme.fontName, size: 12)
beneficiaryLabel.textColor = MegaTheme.darkColor
beneiciaryUserLabel.font = UIFont(name: MegaTheme.fontName, size: 12)
beneiciaryUserLabel.textColor = MegaTheme.lightColor
justificationLabel.font = UIFont(name: MegaTheme.fontName, size: 12)
justificationLabel.textColor = MegaTheme.lightColor
}
override func layoutSubviews() {
super.layoutSubviews()
if postLabel != nil {
let label = postLabel!
label.preferredMaxLayoutWidth = CGRectGetWidth(label.frame)
}
}
}
|
31a0c5f4fe4e8c831e4883f90577491e
| 30.163934 | 77 | 0.656842 | false | false | false | false |
wftllc/hahastream
|
refs/heads/master
|
Haha Stream/Features/Content List/ContentListViewController.swift
|
mit
|
1
|
import UIKit
import Kingfisher
import Moya
private let reuseIdentifier = "ContentListViewCell"
protocol ContentListView: AnyObject {
var interactor: ContentListInteractor? { get }
func updateView(contentList: ContentList, lastSelectedItem: ContentItem?)
func showLoading(animated: Bool)
func hideLoading(animated: Bool, completion: (()->Void)?)
func playURL(_ url: URL)
func showStreamChoiceAlert(game: Game, streams: [Stream])
var apiErrorClosure: (Any) -> Void { get }
var networkFailureClosure: (MoyaError) -> Void { get }
}
class ContentListViewController: HahaViewController, ContentListView, DateListDelegate, NFLDateListDelegate, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var inlinePlayerContainerView: UIView!
@IBOutlet weak var inlineVideoPlayerView: InlineVideoPlayerView!
@IBOutlet weak var noResultsLabel: UILabel!
var interactor: ContentListInteractor? { get {
return self.interactorStorage
}
}
var interactorStorage: ContentListInteractor?
var contentList: ContentList?
var preferredFocusIndexPath: IndexPath?
override var preferredFocusEnvironments: [UIFocusEnvironment] { get {
let def = super.preferredFocusEnvironments;
return self.collectionView.preferredFocusEnvironments + def
}}
//TODO - show something when no current results
override func viewDidLoad() {
super.viewDidLoad()
self.inlinePlayerContainerView.layer.masksToBounds = true
self.inlinePlayerContainerView.layer.cornerRadius = 8.0
self.inlinePlayerContainerView.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]
self.inlinePlayerContainerView.layer.shadowRadius = 12;
self.inlinePlayerContainerView.layer.shadowOpacity = 0.25;
self.inlinePlayerContainerView.layer.shadowOffset = CGSize(width:0, height:5);
// Uncomment the following line to preserve selection between presentations
self.restoresFocusAfterTransition = false
self.collectionView.remembersLastFocusedIndexPath = true
self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 90)
// self.clearsSelectionOnViewWillAppear = false
self.dateLabel.text = ""
interactor?.viewDidLoad();
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
interactor?.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated);
interactor?.viewWillDisappear(animated);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func playStream(stream: Stream, game: Game) {
interactor?.viewDidSelect(stream: stream, game: game)
}
override func showLoading(animated: Bool) {
self.activityIndicator.startAnimating()
UIView.animate(withDuration: animated ? 0.25 : 0) {
self.noResultsLabel.alpha = 0
self.collectionView.alpha = 0
}
}
override func hideLoading(animated: Bool, completion: (() -> Void)?) {
self.activityIndicator.stopAnimating()
let duration = animated ? 0.25 : 0
UIView.animate(withDuration: duration, animations: {
self.noResultsLabel.alpha = 1
self.collectionView.alpha = 1
}) { (_) in
completion?()
}
}
//MARK: - interactor callbacks
func updateView(contentList: ContentList, lastSelectedItem: ContentItem?) {
self.contentList = contentList
self.dateLabel.text = contentList.title
if let item = lastSelectedItem {
self.preferredFocusIndexPath = contentList.indexPath(forItem: item)
}
self.collectionView.reloadData()
self.noResultsLabel.isHidden = self.contentList?.sections.count != 0
}
//MARK: - DateListDelegate
func dateListDidSelect(date: Date) {
interactor?.viewDidSelect(date: date)
}
//MARK: - NFLDateListDelegate
func nflDateDidSelect(_ week: NFLWeek) {
interactor?.viewDidSelect(nflWeek: week)
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.contentList?.sections.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.contentList?.items(inSection: section).count ?? 0
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: ContentListHeader.ReuseIdentifier, for: indexPath) as! ContentListHeader
header.lineView.isHidden = indexPath.section == 0
return header
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ContentListViewCell;
guard let item = self.contentList?.item(atIndexPath: indexPath) else {
return cell
}
cell.update(withContentItem: item, inSection: contentList!.sections[indexPath.section])
return cell
}
func indexPathForPreferredFocusedView(in collectionView: UICollectionView) -> IndexPath? {
return self.preferredFocusIndexPath
}
// MARK: UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let item = self.contentList?.item(atIndexPath: indexPath) else {
return
}
interactor?.viewDidSelect(item: item)
}
}
class ContentListHeader: UICollectionReusableView {
public static let ReuseIdentifier = "ContentListHeader"
@IBOutlet weak var lineView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
self.lineView.layer.shadowRadius = 12;
self.lineView.layer.shadowOpacity = 0.25;
self.lineView.layer.shadowOffset = CGSize(width:0, height:5);
}
}
|
bac503ad7c8f5ac5a9bcdad54d8e2736
| 32.162921 | 170 | 0.772827 | false | false | false | false |
0xced/Carthage
|
refs/heads/master
|
Source/carthage/Checkout.swift
|
mit
|
1
|
//
// Checkout.swift
// Carthage
//
// Created by Alan Rogers on 11/10/2014.
// Copyright (c) 2014 Carthage. All rights reserved.
//
import CarthageKit
import Commandant
import Foundation
import LlamaKit
import ReactiveCocoa
public struct CheckoutCommand: CommandType {
public let verb = "checkout"
public let function = "Check out the project's dependencies"
public func run(mode: CommandMode) -> Result<()> {
return ColdSignal.fromResult(CheckoutOptions.evaluate(mode))
.map { self.checkoutWithOptions($0) }
.merge(identity)
.wait()
}
/// Checks out dependencies with the given options.
public func checkoutWithOptions(options: CheckoutOptions) -> ColdSignal<()> {
return options.loadProject()
.map { $0.checkoutResolvedDependencies() }
.merge(identity)
}
}
public struct CheckoutOptions: OptionsType {
public let directoryPath: String
public let useSSH: Bool
public let useSubmodules: Bool
public static func create(useSSH: Bool)(useSubmodules: Bool)(directoryPath: String) -> CheckoutOptions {
return self(directoryPath: directoryPath, useSSH: useSSH, useSubmodules: useSubmodules)
}
public static func evaluate(m: CommandMode) -> Result<CheckoutOptions> {
return create
<*> m <| Option(key: "use-ssh", defaultValue: false, usage: "use SSH for downloading GitHub repositories")
<*> m <| Option(key: "use-submodules", defaultValue: false, usage: "add dependencies as Git submodules")
<*> m <| Option(defaultValue: NSFileManager.defaultManager().currentDirectoryPath, usage: "the directory containing the Carthage project")
}
/// Attempts to load the project referenced by the options, and configure it
/// accordingly.
public func loadProject() -> ColdSignal<Project> {
if let directoryURL = NSURL.fileURLWithPath(self.directoryPath, isDirectory: true) {
return ColdSignal<Project>.lazy {
return .fromResult(Project.loadFromDirectory(directoryURL))
}
.map { project in
project.preferHTTPS = !self.useSSH
project.useSubmodules = self.useSubmodules
project.projectEvents.observe(ProjectEventSink())
return project
}
.mergeMap { (project: Project) -> ColdSignal<Project> in
return project
.migrateIfNecessary()
.on(next: carthage.println)
.then(.single(project))
}
} else {
return .error(CarthageError.InvalidArgument(description: "Invalid project path: \(directoryPath)").error)
}
}
}
/// Logs project events put into the sink.
private struct ProjectEventSink: SinkType {
mutating func put(event: ProjectEvent) {
switch event {
case let .Cloning(project):
carthage.println("*** Cloning \(project.name)")
case let .Fetching(project):
carthage.println("*** Fetching \(project.name)")
case let .CheckingOut(project, revision):
carthage.println("*** Checking out \(project.name) at \"\(revision)\"")
}
}
}
|
0cb2cc5e1953b4a5210c91ba7a1e3cf1
| 31.235955 | 141 | 0.721157 | false | false | false | false |
kaltura/playkit-ios
|
refs/heads/develop
|
Classes/Player/PlayerController.swift
|
agpl-3.0
|
1
|
// ===================================================================================================
// Copyright (C) 2017 Kaltura Inc.
//
// Licensed under the AGPLv3 license, unless a different license for a
// particular library is specified in the applicable library path.
//
// You may obtain a copy of the License at
// https://www.gnu.org/licenses/agpl-3.0.html
// ===================================================================================================
import Foundation
class PlayerController: NSObject, Player {
/************************************************************/
// MARK: - Properties
/************************************************************/
var onEventBlock: ((PKEvent) -> Void)?
fileprivate var currentPlayer: PlayerEngine = DefaultPlayerWrapper() {
// Initialize the currentPlayer to DefaultPlayerWrapper, which does nothing except printing warnings.
didSet {
// When set to a real player, enable the observer.
timeObserver.enabled = !(currentPlayer is DefaultPlayerWrapper)
}
}
var playerEngineWrapper: PlayerEngineWrapper?
/// Current selected media source
fileprivate var selectedSource: PKMediaSource?
/// Current handler for the selected source
fileprivate var assetHandler: AssetHandler?
/// Current media config that was set
private var mediaConfig: MediaConfig?
/// A semaphore to make sure prepare calling will wait till assetToPrepare it set.
private let prepareSemaphore = DispatchSemaphore(value: 0)
let sessionUUID = UUID()
var mediaSessionUUID: UUID?
// Every player that is created should own Reachability instance
let reachability = PKReachability()
var shouldRefresh: Bool = false
/* Time Observation */
lazy var timeObserver = TimeObserver(timeProvider: self)
var playheadObserverUUID: UUID?
struct PausePosition {
let date: Date = Date()
let savedPosition: TimeInterval
init(_ position: TimeInterval) {
self.savedPosition = position
}
}
var liveDVRPausedPosition: PausePosition?
/************************************************************/
// MARK: - Initialization
/************************************************************/
public override init() {
super.init()
self.currentPlayer.onEventBlock = { [weak self] event in
guard let self = self else { return }
PKLog.verbose("postEvent:: \(event)")
self.onEventBlock?(event)
}
self.playheadObserverUUID = self.timeObserver.addPeriodicObserver(interval: 0.1, observeOn: DispatchQueue.global()) { [weak self] (time) in
guard let self = self else { return }
self.onEventBlock?(PlayerEvent.PlayheadUpdate(currentTime: time))
}
self.onEventBlock = nil
}
deinit {
if let uuid = self.playheadObserverUUID {
self.timeObserver.removePeriodicObserver(uuid)
}
self.timeObserver.stopTimer()
self.timeObserver.removePeriodicObservers()
self.timeObserver.removeBoundaryObservers()
}
// ***************************** //
// MARK: - Player
// ***************************** //
public var mediaEntry: PKMediaEntry? {
return self.mediaConfig?.mediaEntry
}
let settings = PKPlayerSettings()
var mediaFormat = PKMediaSource.MediaFormat.unknown
public var sessionId: String {
return self.sessionUUID.uuidString + ":" + (self.mediaSessionUUID?.uuidString ?? "")
}
func addObserver(_ observer: AnyObject, event: PKEvent.Type, block: @escaping (PKEvent) -> Void) {
//Assert.shouldNeverHappen();
}
func addObserver(_ observer: AnyObject, events: [PKEvent.Type], block: @escaping (PKEvent) -> Void) {
//Assert.shouldNeverHappen();
}
func removeObserver(_ observer: AnyObject, event: PKEvent.Type) {
//Assert.shouldNeverHappen();
}
func removeObserver(_ observer: AnyObject, events: [PKEvent.Type]) {
//Assert.shouldNeverHappen();
}
func isLive() -> Bool {
let avPlayerItemAccessLogEventPlaybackTypeLive = "LIVE"
if let playbackType = currentPlayer.playbackType, playbackType == avPlayerItemAccessLogEventPlaybackTypeLive {
return true
}
if let entry = self.mediaEntry {
if entry.mediaType == MediaType.live || entry.mediaType == MediaType.dvrLive {
return true
}
}
return false
}
public func getController(type: PKController.Type) -> PKController? {
if type is PKVRController.Type && self.currentPlayer is VRPlayerEngine {
return PKVRController(player: self.currentPlayer)
}
return nil
}
public func updatePluginConfig(pluginName: String, config: Any) {
//Assert.shouldNeverHappen();
}
func updateTextTrackStyling() {
self.currentPlayer.updateTextTrackStyling(self.settings.textTrackStyling)
}
// ***************************** //
// MARK: - BasicPlayer
// ***************************** //
public var duration: TimeInterval {
return self.currentPlayer.duration
}
public var currentState: PlayerState {
return self.currentPlayer.currentState
}
public var isPlaying: Bool {
return self.currentPlayer.isPlaying
}
public weak var view: PlayerView? {
get { return self.currentPlayer.view }
set { self.currentPlayer.view = newValue }
}
public var currentTime: TimeInterval {
get {
let position = self.currentPlayer.currentPosition
let duration = self.duration
if position != TimeInterval.infinity && position > duration {
return duration
}
return position
}
set {
self.seek(to: newValue)
}
}
public var currentProgramTime: Date? {
return self.currentPlayer.currentProgramTime
}
public var currentAudioTrack: String? {
return self.currentPlayer.currentAudioTrack
}
public var currentTextTrack: String? {
return self.currentPlayer.currentTextTrack
}
public var rate: Float {
get {
return self.currentPlayer.rate
}
set {
self.currentPlayer.rate = newValue
}
}
public var volume: Float {
get {
return self.currentPlayer.volume
}
set {
self.currentPlayer.volume = newValue
}
}
public var loadedTimeRanges: [PKTimeRange]? {
return self.currentPlayer.loadedTimeRanges
}
public var bufferedTime: TimeInterval {
return self.currentPlayer.bufferedTime
}
private func shouldDVRLivePlayFromLiveEdge() -> Bool {
if let pausedPosition = liveDVRPausedPosition, currentTime == 0 {
let timePassed: TimeInterval = Date().timeIntervalSince(pausedPosition.date)
let shouldPlayFromLiveEdge = timePassed > pausedPosition.savedPosition
liveDVRPausedPosition = nil
return shouldPlayFromLiveEdge
}
return false
}
func play() {
guard let mediaEntry = self.mediaEntry else {
currentPlayer.play()
return
}
switch mediaEntry.mediaType {
case .live:
currentPlayer.playFromLiveEdge()
case .dvrLive:
if shouldDVRLivePlayFromLiveEdge() {
currentPlayer.playFromLiveEdge()
} else {
currentPlayer.play()
}
default:
currentPlayer.play()
}
}
func pause() {
// Save the paused position only if the player is playing, not every time the pause is called.
if mediaEntry?.mediaType == .dvrLive, currentPlayer.isPlaying {
liveDVRPausedPosition = PausePosition(currentTime)
}
self.currentPlayer.pause()
}
func resume() {
guard let mediaEntry = self.mediaEntry else {
currentPlayer.resume()
return
}
switch mediaEntry.mediaType {
case .live:
currentPlayer.playFromLiveEdge()
case .dvrLive:
if shouldDVRLivePlayFromLiveEdge() {
currentPlayer.playFromLiveEdge()
} else {
currentPlayer.resume()
}
default:
currentPlayer.resume()
}
}
func stop() {
self.currentPlayer.stop()
}
func replay() {
self.currentPlayer.replay()
}
func seek(to time: TimeInterval) {
self.currentPlayer.currentPosition = time
}
func seekToLiveEdge() {
self.currentPlayer.seekToLiveEdge()
}
public func selectTrack(trackId: String) {
self.currentPlayer.selectTrack(trackId: trackId)
}
func destroy() {
self.timeObserver.stopTimer()
self.timeObserver.removePeriodicObservers()
self.timeObserver.removeBoundaryObservers()
self.currentPlayer.stop()
self.currentPlayer.destroy()
self.removeAssetRefreshObservers()
}
func prepare(_ mediaConfig: MediaConfig) {
self.currentPlayer.prepare(mediaConfig)
if let source = self.selectedSource {
self.mediaFormat = source.mediaFormat
}
}
func startBuffering() {
currentPlayer.startBuffering()
}
// ****************************************** //
// MARK: - Private Functions
// ****************************************** //
/// Creates the wrapper if we haven't created it yet, otherwise uses the same instance we have.
/// - Returns: true if a new player was created and false if wrapper already exists.
private func createPlayerWrapper(_ mediaConfig: MediaConfig) -> Bool {
let isCreated: Bool
if (mediaConfig.mediaEntry.vrData != nil) {
if type(of: self.currentPlayer) is VRPlayerEngine.Type { // do not create new if current player is already vr player
isCreated = false
} else {
if let vrPlayerWrapper = NSClassFromString("PlayKitVR.VRPlayerWrapper") as? VRPlayerEngine.Type {
self.currentPlayer = vrPlayerWrapper.init()
isCreated = true
} else {
PKLog.error("VRPlayerWrapper does not exist, VR library is missing, make sure to add it via Podfile.")
// Create AVPlayer
if self.currentPlayer is AVPlayerWrapper { // do not create new if current player is already vr player
isCreated = false
} else {
self.currentPlayer = AVPlayerWrapper()
isCreated = true
}
}
}
} else {
if type(of: self.currentPlayer) is VRPlayerEngine.Type {
self.currentPlayer.destroy()
self.currentPlayer = AVPlayerWrapper()
isCreated = true
} else if self.currentPlayer is AVPlayerWrapper { // do not create new if current player is already vr player
isCreated = false
} else {
self.currentPlayer = AVPlayerWrapper()
isCreated = true
}
}
if let currentPlayer = self.currentPlayer as? AVPlayerWrapper {
currentPlayer.settings = self.settings
}
if let playerEW = playerEngineWrapper {
playerEW.playerEngine = currentPlayer
currentPlayer = playerEW
}
return isCreated
}
// ****************************************** //
// MARK: - Public Functions
// ****************************************** //
func setMedia(from mediaConfig: MediaConfig) {
self.mediaConfig = mediaConfig
// create new media session uuid
self.mediaSessionUUID = UUID()
// get the preferred media source and post source selected event
guard let (selectedSource, handler) = SourceSelector.selectSource(from: mediaConfig.mediaEntry) else {
PKLog.error("No playable source found for entry")
self.onEventBlock?(PlayerEvent.Error(error: PlayerError.missingMediaSource))
return
}
self.onEventBlock?(PlayerEvent.SourceSelected(mediaSource: selectedSource))
self.selectedSource = selectedSource
self.assetHandler = handler
// Update the selected source if there are external subtitles.
selectedSource.externalSubtitle = mediaConfig.mediaEntry.externalSubtitles
// update the media source request adapter with new media uuid if using kaltura request adapter
var pms = selectedSource
self.updateRequestAdapter(in: &pms)
// Take saved eventBlock from DefaultPlayerWrapper
// Must be called before `self.currentPlayer` reference is changed
let eventBlock = self.currentPlayer.onEventBlock
// Take saved view from DefaultPlayerWrapper
// Must be called before `self.currentPlayer` reference is changed
let playerView = self.currentPlayer.view
// if create player wrapper returns yes meaning a new wrapper was created, otherwise same wrapper as last time is used.
if self.createPlayerWrapper(mediaConfig) {
// After Setting PlayerWrapper set saved player's params
self.currentPlayer.onEventBlock = eventBlock
self.currentPlayer.view = playerView
}
// Update the mediaConfig
self.currentPlayer.mediaConfig = mediaConfig
// Reset the pause position
liveDVRPausedPosition = nil
self.currentPlayer.loadMedia(from: self.selectedSource, handler: handler)
}
}
/************************************************************/
// MARK: - Private
/************************************************************/
fileprivate extension PlayerController {
/// Updates the request adapter if one exists
func updateRequestAdapter(in mediaSource: inout PKMediaSource) {
// configure media sources content request adapter if request adapter exists
if let adapter = self.settings.contentRequestAdapter {
// update the request adapter with the updated session id
adapter.updateRequestAdapter(with: self)
// configure media source with the adapter
mediaSource.contentRequestAdapter = adapter
}
// Maybe update licenseRequestAdapter and fpsLicenseRequestDelegate in params
let drmAdapter = self.settings.licenseRequestAdapter
drmAdapter?.updateRequestAdapter(with: self)
let licenseProvider = self.settings.fairPlayLicenseProvider
if let drmData = mediaSource.drmData {
for d in drmData {
d.requestAdapter = drmAdapter
if let fps = d as? FairPlayDRMParams {
fps.licenseProvider = licenseProvider
}
}
}
}
}
/************************************************************/
// MARK: - Reachability & Application States Handling
/************************************************************/
extension PlayerController {
private func shouldRefreshAsset() {
guard let selectedSource = self.selectedSource,
let refreshableHandler = assetHandler as? RefreshableAssetHandler else { return }
refreshableHandler.shouldRefreshAsset(mediaSource: selectedSource) { [weak self] (shouldRefresh) in
guard let self = self else { return }
if shouldRefresh {
self.shouldRefresh = true
}
}
}
private func refreshAsset() {
guard let selectedSource = self.selectedSource,
let refreshableHandler = assetHandler as? RefreshableAssetHandler else { return }
self.currentPlayer.startPosition = self.currentPlayer.currentPosition
refreshableHandler.refreshAsset(mediaSource: selectedSource)
}
func addAssetRefreshObservers() {
self.addReachabilityObserver()
self.addAppStateChangeObserver()
self.shouldRefreshAsset()
}
func removeAssetRefreshObservers() {
self.removeReachabilityObserver()
self.removeAppStateChangeObserver()
}
// Reachability Handling
private func addReachabilityObserver() -> Void {
guard let reachability = self.reachability else { return }
reachability.startNotifier()
reachability.onUnreachable = { reachability in
PKLog.warning("network unreachable")
}
reachability.onReachable = { [weak self] reachability in
guard let self = self else { return }
if self.shouldRefresh {
self.handleRefreshAsset()
}
}
}
private func removeReachabilityObserver() -> Void {
self.reachability?.stopNotifier()
}
// Application States Handling
private func addAppStateChangeObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(PlayerController.applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
private func removeAppStateChangeObserver() {
NotificationCenter.default.removeObserver(self,
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
@objc private func applicationDidBecomeActive() {
self.handleRefreshAsset()
}
private func handleRefreshAsset() {
self.shouldRefresh = false
self.refreshAsset()
}
}
|
4fdad5044955f103e831581c77806a66
| 33.202206 | 147 | 0.569924 | false | false | false | false |
yangalex/TimeMatch
|
refs/heads/master
|
TimeMatch/TimeButton.swift
|
mit
|
2
|
//
// TimeButton.swift
// TimeMatch
//
// Created by Alexandre Yang on 7/15/15.
// Copyright (c) 2015 Alex Yang. All rights reserved.
//
import UIKit
class TimeButton: UIButton {
// Used only if handle
var matchingHandle: TimeButton?
// keep spacing constant
var spacing: CGFloat?
enum TimeState {
case Single, Handle, Path, Unselected
}
var timeState: TimeState = .Unselected {
didSet {
// fix positioning for when button was a path
if oldValue == .Path {
self.frame = CGRectMake(self.frame.origin.x + (spacing! - CGFloat(self.frame.size.height)), self.frame.origin.y, CGFloat(self.frame.size.height), CGFloat(self.frame.size.height))
self.layer.cornerRadius = 0.5 * self.frame.size.width
}
if timeState == .Single {
self.layer.borderColor = blueColor.CGColor
self.layer.cornerRadius = 0.5 * self.frame.size.width
self.backgroundColor = blueColor
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)
self.setBackgroundImage(nil, forState: .Selected)
} else if timeState == .Handle {
self.layer.borderColor = UIColor.clearColor().CGColor
} else if timeState == .Path {
let lightBlueColor = UIColor(red: 121/255, green: 219/255, blue: 243/255, alpha: 1.0)
self.layer.borderColor = blueColor.CGColor
self.layer.cornerRadius = 0
self.backgroundColor = blueColor
self.setBackgroundImage(nil, forState: .Selected)
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected)
self.selected = true
// change size of button
self.frame = CGRectMake(self.frame.origin.x - (spacing! - CGFloat(self.frame.size.height)), self.frame.origin.y, self.frame.width + (spacing! - CGFloat(self.frame.size.height))*2, self.frame.height)
} else if timeState == .Unselected {
self.layer.cornerRadius = 0.5 * self.frame.size.width
self.layer.borderColor = buttonColor.CGColor
self.backgroundColor = UIColor.whiteColor()
self.setTitleColor(buttonColor, forState: UIControlState.Normal)
self.setBackgroundImage(nil, forState: .Selected)
}
}
}
// Use for paths
var leftHandle: TimeButton?
var rightHandle: TimeButton?
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
|
b640f3940bcdf34b77b68d7c50707c39
| 37.12 | 214 | 0.594264 | false | false | false | false |
artursDerkintis/Starfly
|
refs/heads/master
|
Starfly/SFHistoryController.swift
|
mit
|
1
|
//
// SFHistoryController.swift
// Starfly
//
// Created by Arturs Derkintis on 12/10/15.
// Copyright © 2015 Starfly. All rights reserved.
//
import UIKit
class SFHistoryController: UIViewController {
var tableView : UITableView!
var historyProvider : SFHistoryProvider!
override func viewDidLoad() {
super.viewDidLoad()
historyProvider = SFHistoryProvider()
tableView = UITableView(frame: .zero)
historyProvider.tableView = tableView
tableView.registerClass(SFHistoryCell.self, forCellReuseIdentifier: historyCell)
tableView.registerClass(SFHistoryHeader.self, forHeaderFooterViewReuseIdentifier: historyHeader)
tableView.backgroundColor = .clearColor()
tableView.separatorColor = .clearColor()
addSubviewSafe(tableView)
tableView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(0)
make.bottom.equalTo(0)
make.width.equalTo(768)
make.centerX.equalTo(self.view.snp_centerX)
}
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
}
func load() {
historyProvider.loadData()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showDeleteActions(){
let actionController = UIAlertController(title: "What to delete?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let actionHour = UIAlertAction(title: "Last Hour", style: UIAlertActionStyle.Default) { (k) -> Void in
self.historyProvider.deleteLastHour()
}
let actionToday = UIAlertAction(title: "Today", style: UIAlertActionStyle.Default) { (k) -> Void in
self.historyProvider.deleteToday()
}
let actionThisWeek = UIAlertAction(title: "This Week", style: UIAlertActionStyle.Default) { (k) -> Void in
self.historyProvider.deleteThisWeek()
}
let actionAll = UIAlertAction(title: "Delete All", style: UIAlertActionStyle.Default) { (k) -> Void in
self.historyProvider.deleteAll()
}
let actionDeep = UIAlertAction(title: "Delete Deeply", style: UIAlertActionStyle.Default) { (k) -> Void in
self.historyProvider.deleteAllAndDeep()
}
let actionCancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { (k) -> Void in
}
for action in [actionHour, actionToday, actionThisWeek, actionAll, actionDeep, actionCancel]{
actionController.addAction(action)
}
presentViewController(actionController, animated: true, completion: nil)
}
}
|
68387aa0df1000144856e70066da42ff
| 34.410256 | 134 | 0.681028 | false | false | false | false |
atrick/swift
|
refs/heads/main
|
test/StringProcessing/Parse/regex_parse_error.swift
|
apache-2.0
|
1
|
// RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking
// REQUIRES: swift_in_compiler
_ = /(/ // expected-error@:7 {{expected ')'}}
_ = #/(/# // expected-error@:8 {{expected ')'}}
// FIXME: Should be 'group openings'
_ = /)/ // expected-error@:6 {{closing ')' does not balance any groups openings}}
_ = #/)/# // expected-error@:7 {{closing ')' does not balance any groups openings}}
_ = #/\\/''/ // expected-error@:5 {{unterminated regex literal}}
_ = #/\| // expected-error@:5 {{unterminated regex literal}}
_ = #// // expected-error@:5 {{unterminated regex literal}}
_ = #/xy // expected-error@:5 {{unterminated regex literal}}
_ = #/(?/# // expected-error@:7 {{expected group specifier}}
_ = #/(?'/# // expected-error@:10 {{expected group name}}
_ = #/(?'abc/# // expected-error@:13 {{expected '''}}
_ = #/(?'abc /# // expected-error@:13 {{expected '''}}
do {
_ = #/(?'a
// expected-error@-1:7 {{unterminated regex literal}}
// expected-error@-2:13 {{cannot parse regular expression: expected '''}}
}
_ = #/\(?'abc/#
do {
_ = /\
/
// expected-error@-2:7 {{unterminated regex literal}}
// expected-error@-3:9 {{expected escape sequence}}
} // expected-error@:1 {{expected expression after operator}}
do {
_ = #/\
/#
// expected-error@-2:7 {{unterminated regex literal}}
// expected-error@-3:10 {{expected escape sequence}}
// expected-error@-3:3 {{unterminated regex literal}}
// expected-warning@-4:3 {{regular expression literal is unused}}
}
func foo<T>(_ x: T, _ y: T) {}
foo(#/(?/#, #/abc/#) // expected-error@:7 {{expected group specifier}}
foo(#/(?C/#, #/abc/#) // expected-error@:10 {{expected ')'}}
foo(#/(?'/#, #/abc/#) // expected-error@:10 {{expected group name}}
|
702fa46453596dacf4f054de62dc9216
| 34.1 | 94 | 0.601709 | false | false | false | false |
biohazardlover/ROer
|
refs/heads/master
|
DataDownloader/MaterialDownloader.swift
|
mit
|
1
|
//
// MaterialDownloader.swift
// DataDownloader
//
// Created by Li Junlin on 9/1/16.
// Copyright © 2016 Li Junlin. All rights reserved.
//
import Cocoa
import SwiftyJSON
class MaterialDownloader: NSObject {
lazy var baseLocalURL: URL = {
let desktopURL = try! FileManager.default.url(for: .desktopDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
return desktopURL.appendingPathComponent("Material")
}()
let baseRemoteURL = URL(string: "http://nozomi.arege.jp/ro")!
lazy var body: JSON = {
let url = Bundle.main.url(forResource: "Body", withExtension: "json")!
let data = try! Data(contentsOf: url)
return JSON(data: data)
}()
lazy var item: JSON = {
let url = Bundle.main.url(forResource: "Item", withExtension: "json")!
let data = try! Data(contentsOf: url)
return JSON(data: data)
}()
lazy var other: JSON = {
let url = Bundle.main.url(forResource: "Other", withExtension: "json")!
let data = try! Data(contentsOf: url)
return JSON(data: data)
}()
lazy var session: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = Double.infinity
return URLSession(configuration: configuration)
}()
func download() {
downloadBody()
downloadItem()
downloadOther()
}
func downloadBody() {
downloadMaleBody()
downloadFemaleBody()
downloadHair()
}
func downloadMaleBody() {
let jobClasses = body["items"][0]["c"].arrayValue
for jobClass in jobClasses {
let jobs = jobClass["c"].arrayValue
for job in jobs {
let costumes = job["c"].arrayValue
if costumes.count == 0 {
let md = job["md"].intValue
downloadIfNeeded(remotePath: "body/\(md).txt", localPath: "Body/Body\(md).txt", completionHandler: { (data, _, _) in
guard let data = data else { return }
let json = JSON(data: data)
let i = json["value"]["i"].intValue
self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Body/Body\(i).png")
})
} else {
for costume in costumes {
let md = costume["md"].intValue
let ms = costume["ms"].intValue
downloadIfNeeded(remotePath: "body/\(md).txt", localPath: "Body/Body\(md).txt")
downloadIfNeeded(remotePath: "image/\(ms).png", localPath: "Body/Body\(ms).png")
}
}
}
}
}
func downloadFemaleBody() {
let jobClasses = body["items"][1]["c"].arrayValue
for jobClass in jobClasses {
let jobs = jobClass["c"].arrayValue
for job in jobs {
let costumes = job["c"].arrayValue
if costumes.count == 0 {
let fd = job["fd"].intValue
downloadIfNeeded(remotePath: "body/\(fd).txt", localPath: "Body/Body\(fd).txt", completionHandler: { (data, _, _) in
guard let data = data else { return }
let json = JSON(data: data)
let i = json["value"]["i"].intValue
self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Body/Body\(i).png")
})
} else {
for costume in costumes {
let fd = costume["fd"].intValue
let fs = costume["fs"].intValue
downloadIfNeeded(remotePath: "body/\(fd).txt", localPath: "Body/Body\(fd).txt")
downloadIfNeeded(remotePath: "image/\(fs).png", localPath: "Body/Body\(fs).png")
}
}
}
}
}
func downloadHair() {
let hairs = body["items"][2]["c"].arrayValue
for hair in hairs {
let colors = hair["c"].arrayValue
for color in colors {
let md = color["md"].intValue
let ms = color["ms"].intValue
let fd = color["fd"].intValue
let fs = color["fs"].intValue
downloadIfNeeded(remotePath: "body/\(md).txt", localPath: "Hair/Hair\(md).txt")
downloadIfNeeded(remotePath: "image/\(ms).png", localPath: "Hair/Hair\(ms).png")
downloadIfNeeded(remotePath: "body/\(fd).txt", localPath: "Hair/Hair\(fd).txt")
downloadIfNeeded(remotePath: "image/\(fs).png", localPath: "Hair/Hair\(fs).png")
}
}
}
func downloadItem() {
let types = item["items"].arrayValue
for type in types {
let items = type["c"].arrayValue
for item in items {
let m = item["m"].intValue
let f = item["f"].intValue
downloadIfNeeded(remotePath: "item/\(m).txt", localPath: "Item/Item\(m).txt", completionHandler: { (data, _, _) in
guard let data = data else { return }
let json = JSON(data: data)
let i = json["value"]["i"].intValue
if i != 0 {
self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Item/Item\(i).png")
}
})
downloadIfNeeded(remotePath: "item/\(f).txt", localPath: "Item/Item\(f).txt", completionHandler: { (data, _, _) in
guard let data = data else { return }
let json = JSON(data: data)
let i = json["value"]["i"].intValue
if i != 0 {
self.downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Item/Item\(i).png")
}
})
}
}
}
func downloadOther() {
let items = other.dictionaryValue
for (_, item) in items {
let i = item["i"].intValue
downloadIfNeeded(remotePath: "image/\(i).png", localPath: "Other/Other\(i).png")
}
}
func downloadIfNeeded(remotePath: String, localPath: String, completionHandler: ((Data?, URLResponse?, Error?) -> Void)? = nil) {
let remoteURL = baseRemoteURL.appendingPathComponent(remotePath)
let localURL = baseLocalURL.appendingPathComponent(localPath)
if FileManager.default.fileExists(atPath: localURL.path, isDirectory: nil) {
let data = try! Data(contentsOf: localURL)
print(localPath)
completionHandler?(data, nil, nil)
} else {
let task = session.dataTask(with: remoteURL, completionHandler: { (data, response, error) in
try! FileManager.default.createDirectory(at: localURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil)
try! data?.write(to: localURL, options: [])
print(remotePath)
completionHandler?(data, response, error)
})
task.resume()
}
}
}
|
741fde0adb436956028ac3df556e7f44
| 38.326531 | 150 | 0.49494 | false | false | false | false |
JohnSansoucie/MyProject2
|
refs/heads/master
|
BlueCapKit/Central/Service.swift
|
mit
|
1
|
//
// Service.swift
// BlueCap
//
// Created by Troy Stribling on 6/11/14.
// Copyright (c) 2014 gnos.us. All rights reserved.
//
import Foundation
import CoreBluetooth
public class Service : NSObject {
private let profile : ServiceProfile?
private var characteristicsDiscoveredPromise = Promise<[Characteristic]>()
internal let _peripheral : Peripheral
internal let cbService : CBService
internal var discoveredCharacteristics = Dictionary<CBUUID, Characteristic>()
public var name : String {
if let profile = self.profile {
return profile.name
} else {
return "Unknown"
}
}
public var uuid : CBUUID! {
return self.cbService.UUID
}
public var characteristics : [Characteristic] {
return self.discoveredCharacteristics.values.array
}
public var peripheral : Peripheral {
return self._peripheral
}
public func discoverAllCharacteristics() -> Future<[Characteristic]> {
Logger.debug("Service#discoverAllCharacteristics")
return self.discoverIfConnected(nil)
}
public func discoverCharacteristics(characteristics:[CBUUID]) -> Future<[Characteristic]> {
Logger.debug("Service#discoverCharacteristics")
return self.discoverIfConnected(characteristics)
}
private func discoverIfConnected(services:[CBUUID]!) -> Future<[Characteristic]> {
self.characteristicsDiscoveredPromise = Promise<[Characteristic]>()
if self.peripheral.state == .Connected {
self.peripheral.cbPeripheral.discoverCharacteristics(nil, forService:self.cbService)
} else {
self.characteristicsDiscoveredPromise.failure(BCError.peripheralDisconnected)
}
return self.characteristicsDiscoveredPromise.future
}
internal init(cbService:CBService, peripheral:Peripheral) {
self.cbService = cbService
self._peripheral = peripheral
self.profile = ProfileManager.sharedInstance.serviceProfiles[cbService.UUID]
}
internal func didDiscoverCharacteristics(error:NSError!) {
if let error = error {
self.characteristicsDiscoveredPromise.failure(error)
} else {
self.discoveredCharacteristics.removeAll()
if let cbCharacteristics = self.cbService.characteristics {
for cbCharacteristic : AnyObject in cbCharacteristics {
let bcCharacteristic = Characteristic(cbCharacteristic:cbCharacteristic as CBCharacteristic, service:self)
self.discoveredCharacteristics[bcCharacteristic.uuid] = bcCharacteristic
bcCharacteristic.didDiscover()
Logger.debug("Service#didDiscoverCharacteristics: uuid=\(bcCharacteristic.uuid.UUIDString), name=\(bcCharacteristic.name)")
}
self.characteristicsDiscoveredPromise.success(self.characteristics)
}
}
}
}
|
cfc465116105bdec8d13380ce34b20f7
| 35.892857 | 143 | 0.653002 | false | false | false | false |
giaunv/cookiecrunch-swift-spritekit-ios
|
refs/heads/master
|
cookiecrunch/GameScene.swift
|
mit
|
1
|
//
// GameScene.swift
// cookiecrunch
//
// Created by giaunv on 3/8/15.
// Copyright (c) 2015 366. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var level: Level!
let TileWidth: CGFloat = 32.0
let TileHeight: CGFloat = 36.0
let gameLayer = SKNode()
let cookiesLayer = SKNode()
let tilesLayer = SKNode()
var swipeFromColumn: Int?
var swipeFromRow: Int?
var swipeHandler: ((Swap) -> ())?
var selectionSprite = SKSpriteNode()
let swapSound = SKAction.playSoundFileNamed("Chomp.wav", waitForCompletion: false)
let invalidSwapSound = SKAction.playSoundFileNamed("Error.wav", waitForCompletion: false)
let matchSound = SKAction.playSoundFileNamed("Ka-Ching.wav", waitForCompletion: false)
let fallingCookieSound = SKAction.playSoundFileNamed("Scrape.wav", waitForCompletion: false)
let addCookieSound = SKAction.playSoundFileNamed("Drip.wav", waitForCompletion: false)
let cropLayer = SKCropNode()
let maskLayer = SKNode()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder) is not used in this app")
}
override init(size: CGSize){
super.init(size: size)
anchorPoint = CGPoint(x: 0.5, y: 0.5)
let background = SKSpriteNode(imageNamed: "Background")
addChild(background)
addChild(gameLayer)
gameLayer.hidden = true
let layerPosition = CGPoint(x: -TileWidth * CGFloat(NumColumns)/2, y: -TileHeight * CGFloat(NumRows)/2)
tilesLayer.position = layerPosition
gameLayer.addChild(tilesLayer)
gameLayer.addChild(cropLayer)
maskLayer.position = layerPosition
cropLayer.maskNode = maskLayer
cookiesLayer.position = layerPosition
cropLayer.addChild(cookiesLayer)
swipeFromColumn = nil
swipeFromRow = nil
SKLabelNode(fontNamed: "GillSans-BoldItalic")
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(cookiesLayer)
let (success, column, row) = convertPoint(location)
if success{
if let cookie = level.cookieAtColumn(column, row: row){
swipeFromColumn = column
swipeFromRow = row
showSelectionIndicatorForCookie(cookie)
}
}
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
if swipeFromColumn == nil {return}
let touch = touches.anyObject() as UITouch
let location = touch.locationInNode(cookiesLayer)
let (success, column, row) = convertPoint(location)
if success{
var horzDelta = 0, vertDelta = 0
if column < swipeFromColumn!{ // swipe left
horzDelta = -1
} else if column > swipeFromColumn!{ // swipe right
horzDelta = 1
} else if row < swipeFromRow!{ // swipe down
vertDelta = -1
} else if row > swipeFromRow!{ // swipe up
vertDelta = 1
}
if horzDelta != 0 || vertDelta != 0{
trySwapHorizontal(horzDelta, vertical: vertDelta)
hideSelectionIndicator()
swipeFromColumn = nil
}
}
}
func trySwapHorizontal(horzDelta: Int, vertical vertDelta: Int){
let toColumn = swipeFromColumn! + horzDelta
let toRow = swipeFromRow! + vertDelta
if toColumn < 0 || toColumn >= NumColumns {return}
if toRow < 0 || toRow >= NumRows {return}
if let toCookie = level.cookieAtColumn(toColumn, row: toRow){
if let fromCookie = level.cookieAtColumn(swipeFromColumn!, row: swipeFromRow!){
// println("*** swapping \(fromCookie) with \(toCookie)")
if let handler = swipeHandler{
let swap = Swap(cookieA: fromCookie, cookieB: toCookie)
handler(swap)
}
}
}
}
func animateSwap(swap: Swap, completion: () -> ()){
let spriteA = swap.cookieA.sprite!
let spriteB = swap.cookieB.sprite!
spriteA.zPosition = 100
spriteB.zPosition = 90
let Duration: NSTimeInterval = 0.3
let moveA = SKAction.moveTo(spriteB.position, duration: Duration)
moveA.timingMode = .EaseOut
spriteA.runAction(moveA, completion: completion)
let moveB = SKAction.moveTo(spriteA.position, duration: Duration)
moveB.timingMode = .EaseOut
spriteB.runAction(moveB)
runAction(swapSound)
}
func animateInvalidSwap(swap: Swap, completion: () -> ()){
let spriteA = swap.cookieA.sprite!
let spriteB = swap.cookieB.sprite!
spriteA.zPosition = 100
spriteB.zPosition = 90
let Duration: NSTimeInterval = 0.2
let moveA = SKAction.moveTo(spriteB.position, duration: Duration)
moveA.timingMode = .EaseOut
let moveB = SKAction.moveTo(spriteA.position, duration: Duration)
moveB.timingMode = .EaseOut
spriteA.runAction(SKAction.sequence([moveA, moveB]), completion: completion)
spriteB.runAction(SKAction.sequence([moveB, moveA]))
runAction(invalidSwapSound)
}
func animateMatchedCookies(chains: Set<Chain>, completion: () -> ()){
for chain in chains{
animateScoreForChain(chain)
for cookie in chain.cookies{
if let sprite = cookie.sprite{
if sprite.actionForKey("removing") == nil{
let scaleAction = SKAction.scaleTo(0.1, duration: 0.3)
scaleAction.timingMode = .EaseOut
sprite.runAction(SKAction.sequence([scaleAction, SKAction.removeFromParent()]), withKey: "removing")
}
}
}
}
runAction(matchSound)
runAction(SKAction.waitForDuration(0.3), completion: completion)
}
func animateFallingCookies(columns: [[Cookie]], completion: () -> ()){
var longestDuration: NSTimeInterval = 0
for array in columns{
for (idx, cookie) in enumerate(array){
let newPosition = pointForColumn(cookie.column, row: cookie.row)
let delay = 0.05 + 0.15*NSTimeInterval(idx)
let sprite = cookie.sprite!
let duration = NSTimeInterval(((sprite.position.y - newPosition.y)/TileHeight)*0.1)
longestDuration = max(longestDuration, duration+delay)
let moveAction = SKAction.moveTo(newPosition, duration: duration)
moveAction.timingMode = .EaseOut
sprite.runAction(SKAction.sequence([SKAction.waitForDuration(delay), SKAction.group([moveAction, fallingCookieSound])]))
}
}
runAction(SKAction.waitForDuration(longestDuration), completion: completion)
}
func animateNewCookies(columns: [[Cookie]], completion: () -> ()){
var longestDuration: NSTimeInterval = 0
for array in columns{
let startRow = array[0].row + 1
for (idx, cookie) in enumerate(array){
let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName)
sprite.position = pointForColumn(cookie.column, row: startRow)
cookiesLayer.addChild(sprite)
cookie.sprite = sprite
let delay = 0.1 + 0.2 * NSTimeInterval(array.count - idx - 1)
let duration = NSTimeInterval(startRow - cookie.row) * 0.1
longestDuration = max(longestDuration, duration + delay)
let newPostion = pointForColumn(cookie.column, row: cookie.row)
let moveAction = SKAction.moveTo(newPostion, duration: duration)
moveAction.timingMode = .EaseOut
sprite.alpha = 0
sprite.runAction(SKAction.sequence([SKAction.waitForDuration(delay), SKAction.group([SKAction.fadeInWithDuration(0.05), moveAction, addCookieSound])]))
}
}
runAction(SKAction.waitForDuration(longestDuration), completion: completion)
}
func animateScoreForChain(chain: Chain){
// Figure out what the midpoint of the chain is
let firstSprite = chain.firstCookie().sprite!
let lastSprite = chain.lastCookie().sprite!
let centerPosition = CGPoint(x:(firstSprite.position.x + lastSprite.position.x)/2, y:(firstSprite.position.y + lastSprite.position.y)/2 - 8)
// Add a label for the score that slowly floats up
let scoreLabel = SKLabelNode(fontNamed: "GillSans-BoldItalic")
scoreLabel.fontSize = 16
scoreLabel.text = NSString(format: "%ld", chain.score)
scoreLabel.position = centerPosition
scoreLabel.zPosition = 300
cookiesLayer.addChild(scoreLabel)
let moveAction = SKAction.moveBy(CGVector(dx: 0, dy: 0.3), duration: 0.7)
moveAction.timingMode = .EaseOut
scoreLabel.runAction(SKAction.sequence([moveAction, SKAction.removeFromParent()]))
}
func animateGameOver(completion: () -> ()){
let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3)
action.timingMode = .EaseIn
gameLayer.runAction(action, completion: completion)
}
func animateBeginGame(completion: () -> ()){
gameLayer.hidden = false
gameLayer.position = CGPoint(x: 0, y: size.height)
let action = SKAction.moveBy(CGVector(dx: 0, dy: -size.height), duration: 0.3)
action.timingMode = .EaseOut
gameLayer.runAction(action, completion)
}
override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
swipeFromColumn = nil
swipeFromRow = nil
}
override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) {
touchesEnded(touches, withEvent: event)
}
func pointForColumn(column: Int, row: Int) -> CGPoint{
return CGPoint(x: CGFloat(column) * TileWidth + TileWidth/2, y: CGFloat(row) * TileHeight + TileHeight/2)
}
func convertPoint(point: CGPoint) -> (success: Bool, column: Int, row: Int){
if point.x >= 0 && point.x < CGFloat(NumColumns) * TileWidth && point.y >= 0 && point.y < CGFloat(NumRows) * TileHeight{
return (true, Int(point.x/TileWidth), Int(point.y/TileHeight))
} else {
return (false, 0, 0) // invalid location
}
}
func addTiles(){
for row in 0..<NumRows{
for column in 0..<NumColumns{
if let tile = level.tileAtColumn(column, row: row){
let tileNode = SKSpriteNode(imageNamed: "MaskTile")
tileNode.position = pointForColumn(column, row: row)
maskLayer.addChild(tileNode)
}
}
}
for row in 0...NumRows {
for column in 0...NumColumns {
let topLeft = (column > 0) && (row < NumRows) && level.tileAtColumn(column - 1, row: row) != nil
let bottomLeft = (column > 0) && (row > 0) && level.tileAtColumn(column - 1, row: row - 1) != nil
let topRight = (column < NumColumns) && (row < NumRows) && level.tileAtColumn(column, row: row) != nil
let bottomRight = (column < NumColumns) && (row > 0) && level.tileAtColumn(column, row: row - 1) != nil
// The tiles are named from 0 to 15, according to the bitmask that is made by combining these four values
let value = Int(topLeft) | Int(topRight) << 1 | Int(bottomLeft) << 2 | Int(bottomRight) << 3
// Values 0 (no tiles), 6 and 9 (two opposite tiles) are not drawn.
if value != 0 && value != 6 && value != 9{
let name = String(format: "Tile_%ld", value)
let tileNode = SKSpriteNode(imageNamed: name)
var point = pointForColumn(column, row: row)
point.x -= TileWidth/2
point.y -= TileHeight/2
tileNode.position = point
tilesLayer.addChild(tileNode)
}
}
}
}
func addSpritesForCookies(cookies: Set<Cookie>){
for cookie in cookies{
let sprite = SKSpriteNode(imageNamed: cookie.cookieType.spriteName)
sprite.position = pointForColumn(cookie.column, row: cookie.row)
cookiesLayer.addChild(sprite)
cookie.sprite = sprite
// Give each cookie sprite a small, random delay. Then fade them in
sprite.alpha = 0
sprite.xScale = 0.5
sprite.yScale = 0.5
sprite.runAction(SKAction.sequence([SKAction.waitForDuration(0.25, withRange: 0.5), SKAction.group([SKAction.fadeInWithDuration(0.25), SKAction.scaleTo(1.0, duration: 0.25)])]))
}
}
func showSelectionIndicatorForCookie(cookie: Cookie){
if selectionSprite.parent != nil{
selectionSprite.removeFromParent()
}
if let sprite = cookie.sprite{
let texture = SKTexture(imageNamed: cookie.cookieType.highlightedSpriteName)
selectionSprite.size = texture.size()
selectionSprite.runAction(SKAction.setTexture(texture))
sprite.addChild(selectionSprite)
selectionSprite.alpha = 1.0
}
}
func hideSelectionIndicator(){
selectionSprite.runAction(SKAction.sequence([
SKAction.fadeOutWithDuration(0.3),
SKAction.removeFromParent()
]))
}
func removeAllCookieSprites(){
cookiesLayer.removeAllChildren()
}
}
|
0b310eeb55da32d67915f946a7508aef
| 38.265027 | 189 | 0.582324 | false | false | false | false |
zigdanis/Interactive-Transitioning
|
refs/heads/master
|
InteractiveTransitioning/ViewControllers/ThumbImageViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// InteractiveTransitioning
//
// Created by Danis Ziganshin on 15/07/16.
// Copyright © 2016 Zigdanis. All rights reserved.
//
import UIKit
class ThumbImageViewController: UIViewController {
@IBOutlet weak var thumbImageView: RoundedImageView!
let transitionController = TransitioningDelegate()
var startPoint: CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
setupGestureRecognizers()
startPoint = thumbImageView.center
view.backgroundColor = UIColor.groupTableViewBackground
}
func setupGestureRecognizers() {
let panGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture))
thumbImageView.addGestureRecognizer(panGesture)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
thumbImageView.addGestureRecognizer(tapGesture)
}
func handlePanGesture(gesture: UIGestureRecognizer) {
let location = gesture.location(in: view)
let xDist = location.x - startPoint.x
let yDist = location.y - startPoint.y
let distance = sqrt(xDist * xDist + yDist * yDist)
let newFrame = CGRect(x:0,y:0,width:150 + distance,height: 150 + distance)
thumbImageView.frame = newFrame
thumbImageView.center = startPoint
}
func handleTapGesture(gesture: UIGestureRecognizer) {
guard let secondVC = storyboard?.instantiateViewController(withIdentifier: "FullImageViewController") else {
return
}
let navController = UINavigationController(rootViewController: secondVC)
navController.modalPresentationStyle = .custom
navController.transitioningDelegate = transitionController
present(navController, animated: true)
}
}
|
47c167f87e7e0c32b901148ab283d830
| 35.137255 | 116 | 0.704829 | false | false | false | false |
luckymore0520/leetcode
|
refs/heads/master
|
First Missing Positive.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import UIKit
//Given an unsorted integer array, find the first missing positive integer.
//
//For example,
//Given [1,2,0] return 3,
//and [3,4,-1,1] return 2.
//
//Your algorithm should run in O(n) time and uses constant space.
//这题要求 O(n),而且对空间有要求
//遍历数组,把对应数字交换到对应的位置
class Solution {
func firstMissingPositive(_ nums: [Int]) -> Int {
if (nums.isEmpty) {
return 1
}
var nums = nums
var i = 0
while i < nums.count {
if (nums[i] != i+1 && nums[i] <= nums.count && nums[i] > 0 && nums[i] != nums[nums[i]-1]) {
(nums[i],nums[nums[i]-1]) = (nums[nums[i]-1], nums[i])
} else {
i += 1
}
}
for i in 0...nums.count-1 {
if nums[i] != i+1 {
return i+1
}
}
return nums.count + 1
}
}
let solution = Solution()
solution.firstMissingPositive([3,4,-1,1])
|
7d244bcdf196628fc418e6528ced30fa
| 22 | 103 | 0.503462 | false | false | false | false |
Aishwarya-Ramakrishnan/sparkios
|
refs/heads/master
|
Tests/TeamTests.swift
|
mit
|
1
|
// Copyright 2016 Cisco Systems Inc
//
// 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 Quick
import Nimble
@testable import SparkSDK
class TeamSpec: QuickSpec {
private func validate(team: Team) {
expect(team.id).notTo(beNil())
expect(team.name).notTo(beNil())
expect(team.created).notTo(beNil())
}
override func spec() {
beforeSuite {
print("Config.selfUser.token: \(Config.selfUser.token)")
Spark.initWith(accessToken: Config.selfUser.token!)
}
// MARK: - Create a team
describe("create a team") {
it("normal") {
do {
let teamName = "test team"
let team = try Spark.teams.create(name: teamName)
self.validate(team: team)
expect(team.name).to(equal(teamName))
} catch let error as NSError {
fail("Failed to create team, \(error.localizedFailureReason)")
}
}
}
it("with empty name") {
expect{try Spark.teams.create(name: "")}.to(throwError())
}
it("with special name") {
do {
let teamName = "@@@ &&&"
let team = try Spark.teams.create(name: teamName)
self.validate(team: team)
expect(team.name).to(equal(teamName))
} catch let error as NSError {
fail("Failed to create team, \(error.localizedFailureReason)")
}
}
// MARK: - List a team
describe("list a team") {
it("normal") {
do {
let team = try Spark.teams.create(name: "test team")
let teams = try Spark.teams.list()
expect(teams.isEmpty).to(beFalse())
expect(teams.contains(){$0 == team}).to(beTrue())
} catch let error as NSError {
fail("Failed to list team, \(error.localizedFailureReason)")
}
}
it("with max value") {
do {
let teams = try Spark.teams.list(max: 1)
expect(teams.count).to(beLessThanOrEqualTo(1))
} catch let error as NSError {
fail("Failed to list team, \(error.localizedFailureReason)")
}
}
it("with invalid max") {
expect{try Spark.teams.list(max: -1)}.to(throwError())
}
}
// MARK: - Get a team
describe("get a team") {
it("normal") {
do {
let teamName = "test team"
let team = try Spark.teams.create(name: teamName)
let teamFromGet = try Spark.teams.get(teamId: team.id!)
self.validate(team: teamFromGet)
expect(teamFromGet).to(equal(team))
} catch let error as NSError {
fail("Failed to get team, \(error.localizedFailureReason)")
}
}
it("with invalid id") {
expect{try Spark.teams.get(teamId: Config.InvalidId)}.to(throwError())
}
}
// MARK: - Update a team
describe("update a team") {
it("normal") {
do {
let teamName = "test team"
let team = try Spark.teams.create(name: teamName)
let newTeamName = "new test team"
let teamFromUpdate = try Spark.teams.update(teamId: team.id!, name: newTeamName)
self.validate(team: teamFromUpdate)
expect(teamFromUpdate.id).to(equal(team.id))
expect(teamFromUpdate.created).to(equal(team.created))
expect(teamFromUpdate.name).to(equal(newTeamName))
} catch let error as NSError {
fail("Failed to update team, \(error.localizedFailureReason)")
}
}
it("with empty name") {
do {
let team = try Spark.teams.create(name: "test team")
let teamFromUpdate = try Spark.teams.update(teamId: team.id!, name: "")
self.validate(team: teamFromUpdate)
expect(teamFromUpdate.id).to(equal(team.id))
expect(teamFromUpdate.created).to(equal(team.created))
expect(teamFromUpdate.name).to(equal(""))
} catch let error as NSError {
fail("Failed to update team, \(error.localizedFailureReason)")
}
}
it("with special name") {
do {
let team = try Spark.teams.create(name: "test team")
let teamName = "@@@ &&&"
let teamFromUpdate = try Spark.teams.update(teamId: team.id!, name: teamName)
self.validate(team: team)
expect(teamFromUpdate.name).to(equal(teamName))
} catch let error as NSError {
fail("Failed to create team, \(error.localizedFailureReason)")
}
}
it("with invalid id") {
expect{try Spark.teams.update(teamId: Config.InvalidId, name: Config.InvalidId)}.to(throwError())
}
}
// MARK: - Delete a team
describe("delete a team") {
it("normal") {
do {
let teamName = "test team"
let team = try Spark.teams.create(name: teamName)
expect{try Spark.teams.delete(teamId: team.id!)}.notTo(throwError())
} catch let error as NSError {
fail("Failed to delete team, \(error.localizedFailureReason)")
}
}
it("with invalid id") {
expect{try Spark.teams.delete(teamId: Config.InvalidId)}.to(throwError())
}
}
}
}
|
75f3b24ee3f0816e944ae47a547d8a70
| 37.57 | 113 | 0.487555 | false | false | false | false |
XQS6LB3A/LyricsX
|
refs/heads/master
|
LyricsX/Controller/KaraokeLyricsController.swift
|
gpl-3.0
|
2
|
//
// KaraokeLyricsController.swift
// LyricsX - https://github.com/ddddxxx/LyricsX
//
// 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 https://mozilla.org/MPL/2.0/.
//
import Cocoa
import CXShim
import GenericID
import LyricsCore
import MusicPlayer
import OpenCC
import SnapKit
import SwiftCF
import CoreGraphicsExt
class KaraokeLyricsWindowController: NSWindowController {
static private let windowFrame = NSWindow.FrameAutosaveName("KaraokeWindow")
private var lyricsView = KaraokeLyricsView(frame: .zero)
private var cancelBag = Set<AnyCancellable>()
init() {
let window = NSWindow(contentRect: .zero, styleMask: .borderless, backing: .buffered, defer: true)
window.backgroundColor = .clear
window.hasShadow = false
window.isOpaque = false
window.level = .floating
window.collectionBehavior = [.canJoinAllSpaces, .stationary]
window.setFrameUsingName(KaraokeLyricsWindowController.windowFrame, force: true)
super.init(window: window)
window.contentView?.addSubview(lyricsView)
addObserver()
makeConstraints()
updateWindowFrame(animate: false)
lyricsView.displayLrc("LyricsX")
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.lyricsView.displayLrc("")
AppController.shared.$currentLyrics
.signal()
.receive(on: DispatchQueue.lyricsDisplay.cx)
.invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self)
.store(in: &self.cancelBag)
AppController.shared.$currentLineIndex
.signal()
.receive(on: DispatchQueue.lyricsDisplay.cx)
.invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self)
.store(in: &self.cancelBag)
selectedPlayer.playbackStateWillChange
.signal()
.receive(on: DispatchQueue.lyricsDisplay.cx)
.invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self)
.store(in: &self.cancelBag)
defaults.publisher(for: [.preferBilingualLyrics, .desktopLyricsOneLineMode])
.prepend()
.invoke(KaraokeLyricsWindowController.handleLyricsDisplay, weaklyOn: self)
.store(in: &self.cancelBag)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addObserver() {
lyricsView.bind(\.textColor, withDefaultName: .desktopLyricsColor)
lyricsView.bind(\.progressColor, withDefaultName: .desktopLyricsProgressColor)
lyricsView.bind(\.shadowColor, withDefaultName: .desktopLyricsShadowColor)
lyricsView.bind(\.backgroundColor, withDefaultName: .desktopLyricsBackgroundColor)
lyricsView.bind(\.isVertical, withDefaultName: .desktopLyricsVerticalMode, options: [.nullPlaceholder: false])
lyricsView.bind(\.drawFurigana, withDefaultName: .desktopLyricsEnableFurigana)
let negateOption = [NSBindingOption.valueTransformerName: NSValueTransformerName.negateBooleanTransformerName]
window?.contentView?.bind(.hidden, withDefaultName: .desktopLyricsEnabled, options: negateOption)
observeDefaults(key: .disableLyricsWhenSreenShot, options: [.new, .initial]) { [unowned self] _, change in
self.window?.sharingType = change.newValue ? .none : .readOnly
}
observeDefaults(keys: [
.hideLyricsWhenMousePassingBy,
.desktopLyricsDraggable
], options: [.initial]) {
self.lyricsView.shouldHideWithMouse = defaults[.hideLyricsWhenMousePassingBy] && !defaults[.desktopLyricsDraggable]
}
observeDefaults(keys: [
.desktopLyricsFontName,
.desktopLyricsFontSize,
.desktopLyricsFontNameFallback
], options: [.initial]) { [unowned self] in
self.lyricsView.font = defaults.desktopLyricsFont
}
observeNotification(name: NSApplication.didChangeScreenParametersNotification, queue: .main) { [unowned self] _ in
self.updateWindowFrame(animate: true)
}
observeNotification(center: workspaceNC, name: NSWorkspace.activeSpaceDidChangeNotification, queue: .main) { [unowned self] _ in
self.updateWindowFrame(animate: true)
}
}
private func updateWindowFrame(toScreen: NSScreen? = nil, animate: Bool) {
let screen = toScreen ?? window?.screen ?? NSScreen.screens[0]
let fullScreen = screen.isFullScreen || defaults.bool(forKey: "DesktopLyricsIgnoreSafeArea")
let frame = fullScreen ? screen.frame : screen.visibleFrame
window?.setFrame(frame, display: false, animate: animate)
window?.saveFrame(usingName: KaraokeLyricsWindowController.windowFrame)
}
@objc private func handleLyricsDisplay() {
guard defaults[.desktopLyricsEnabled],
!defaults[.disableLyricsWhenPaused] || selectedPlayer.playbackState.isPlaying,
let lyrics = AppController.shared.currentLyrics,
let index = AppController.shared.currentLineIndex else {
DispatchQueue.main.async {
self.lyricsView.displayLrc("", secondLine: "")
}
return
}
let lrc = lyrics.lines[index]
let next = lyrics.lines[(index + 1)...].first { $0.enabled }
let languageCode = lyrics.metadata.translationLanguages.first
var firstLine = lrc.content
var secondLine: String
var secondLineIsTranslation = false
if defaults[.desktopLyricsOneLineMode] {
secondLine = ""
} else if defaults[.preferBilingualLyrics],
let translation = lrc.attachments[.translation(languageCode: languageCode)] {
secondLine = translation
secondLineIsTranslation = true
} else {
secondLine = next?.content ?? ""
}
if let converter = ChineseConverter.shared {
if lyrics.metadata.language?.hasPrefix("zh") == true {
firstLine = converter.convert(firstLine)
if !secondLineIsTranslation {
secondLine = converter.convert(secondLine)
}
}
if languageCode?.hasPrefix("zh") == true {
secondLine = converter.convert(secondLine)
}
}
DispatchQueue.main.async {
self.lyricsView.displayLrc(firstLine, secondLine: secondLine)
if let upperTextField = self.lyricsView.displayLine1,
let timetag = lrc.attachments.timetag {
let position = selectedPlayer.playbackTime
let timeDelay = AppController.shared.currentLyrics?.adjustedTimeDelay ?? 0
let progress = timetag.tags.map { ($0.time + lrc.position - timeDelay - position, $0.index) }
upperTextField.setProgressAnimation(color: self.lyricsView.progressColor, progress: progress)
if !selectedPlayer.playbackState.isPlaying {
upperTextField.pauseProgressAnimation()
}
}
}
}
private func makeConstraints() {
lyricsView.snp.remakeConstraints { make in
make.centerX.equalToSuperview().safeMultipliedBy(defaults[.desktopLyricsXPositionFactor] * 2).priority(.low)
make.centerY.equalToSuperview().safeMultipliedBy(defaults[.desktopLyricsYPositionFactor] * 2).priority(.low)
make.leading.greaterThanOrEqualToSuperview().priority(.keepWindowSize)
make.trailing.lessThanOrEqualToSuperview().priority(.keepWindowSize)
make.top.greaterThanOrEqualToSuperview().priority(.keepWindowSize)
make.bottom.lessThanOrEqualToSuperview().priority(.keepWindowSize)
}
}
// MARK: Dragging
private var vecToCenter: CGVector?
override func mouseDown(with event: NSEvent) {
let location = lyricsView.convert(event.locationInWindow, from: nil)
vecToCenter = CGVector(from: location, to: lyricsView.bounds.center)
}
override func mouseDragged(with event: NSEvent) {
guard defaults[.desktopLyricsDraggable],
let vecToCenter = vecToCenter,
let window = window else {
return
}
let bounds = window.frame
var center = event.locationInWindow + vecToCenter
let centerInScreen = window.convertToScreen(CGRect(origin: center, size: .zero)).origin
if let screen = NSScreen.screens.first(where: { $0.frame.contains(centerInScreen) }),
screen != window.screen {
updateWindowFrame(toScreen: screen, animate: false)
center = window.convertFromScreen(CGRect(origin: centerInScreen, size: .zero)).origin
return
}
var xFactor = (center.x / bounds.width).clamped(to: 0...1)
var yFactor = (1 - center.y / bounds.height).clamped(to: 0...1)
if abs(center.x - bounds.width / 2) < 8 {
xFactor = 0.5
}
if abs(center.y - bounds.height / 2) < 8 {
yFactor = 0.5
}
defaults[.desktopLyricsXPositionFactor] = xFactor
defaults[.desktopLyricsYPositionFactor] = yFactor
makeConstraints()
window.layoutIfNeeded()
}
}
private extension NSScreen {
var isFullScreen: Bool {
guard let windowInfoList = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as? [[String: Any]] else {
return false
}
return !windowInfoList.contains { info in
guard info[kCGWindowOwnerName as String] as? String == "Window Server",
info[kCGWindowName as String] as? String == "Menubar",
let boundsDict = info[kCGWindowBounds as String] as? NSDictionary as CFDictionary?,
let bounds = CGRect(dictionaryRepresentation: boundsDict) else {
return false
}
return frame.contains(bounds)
}
}
}
private extension ConstraintMakerEditable {
@discardableResult
func safeMultipliedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable {
var factor = amount.constraintMultiplierTargetValue
if factor.isZero {
factor = .leastNonzeroMagnitude
}
return multipliedBy(factor)
}
}
extension ConstraintPriority {
static let windowSizeStayPut = ConstraintPriority(NSLayoutConstraint.Priority.windowSizeStayPut.rawValue)
static let keepWindowSize = ConstraintPriority.windowSizeStayPut.advanced(by: -1)
}
|
81c868f82bbe1e6123a206430437cb7a
| 41.367816 | 136 | 0.640622 | false | false | false | false |
NordicSemiconductor/IOS-Pods-DFU-Library
|
refs/heads/master
|
iOSDFULibrary/Classes/Utilities/Data.swift
|
bsd-3-clause
|
1
|
/*
* Copyright (c) 2019, Nordic Semiconductor
* 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 nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
// Inspired by: https://stackoverflow.com/a/38024025/2115352
extension Data {
/// Converts the required number of bytes, starting from `offset`
/// to the value of return type.
///
/// - parameter offset: The offset from where the bytes are to be read.
/// - returns: The value of type of the return type.
func asValue<R>(offset: Int = 0) -> R {
let length = MemoryLayout<R>.size
#if swift(>=5.0)
return subdata(in: offset ..< offset + length).withUnsafeBytes { $0.load(as: R.self) }
#else
return subdata(in: offset ..< offset + length).withUnsafeBytes { $0.pointee }
#endif
}
}
// Source: http://stackoverflow.com/a/35201226/2115352
extension Data {
/// Returns the Data as hexadecimal string.
var hexString: String {
var array: [UInt8] = []
#if swift(>=5.0)
withUnsafeBytes { array.append(contentsOf: $0) }
#else
withUnsafeBytes { array.append(contentsOf: getByteArray($0)) }
#endif
return array.reduce("") { (result, byte) -> String in
result + String(format: "%02x", byte)
}
}
private func getByteArray(_ pointer: UnsafePointer<UInt8>) -> [UInt8] {
let buffer = UnsafeBufferPointer<UInt8>(start: pointer, count: count)
return [UInt8](buffer)
}
}
// Source: http://stackoverflow.com/a/42241894/2115352
public protocol DataConvertible {
static func + (lhs: Data, rhs: Self) -> Data
static func += (lhs: inout Data, rhs: Self)
}
extension DataConvertible {
public static func + (lhs: Data, rhs: Self) -> Data {
var value = rhs
let data = withUnsafePointer(to: &value) { (pointer) -> Data in
Data(buffer: UnsafeBufferPointer(start: pointer, count: 1))
}
return lhs + data
}
public static func += (lhs: inout Data, rhs: Self) {
lhs = lhs + rhs
}
}
extension UInt8 : DataConvertible { }
extension UInt16 : DataConvertible { }
extension UInt32 : DataConvertible { }
extension Int : DataConvertible { }
extension Float : DataConvertible { }
extension Double : DataConvertible { }
extension String : DataConvertible {
public static func + (lhs: Data, rhs: String) -> Data {
guard let data = rhs.data(using: .utf8) else { return lhs}
return lhs + data
}
}
extension Data : DataConvertible {
public static func + (lhs: Data, rhs: Data) -> Data {
var data = Data()
data.append(lhs)
data.append(rhs)
return data
}
}
|
1b076cbee5fa5e9646984ef7f77711f2
| 31.453846 | 94 | 0.662716 | false | false | false | false |
dangnguyenhuu/JSQMessagesSwift
|
refs/heads/master
|
Sources/Views/JSQMessagesToolbarContentView.swift
|
apache-2.0
|
1
|
//
// JSQMessagesToolbarContentView.swift
// JSQMessagesViewController
//
// Created by Sylvain FAY-CHATELARD on 20/08/2015.
// Copyright (c) 2015 Dviance. All rights reserved.
//
import UIKit
let kJSQMessagesToolbarContentViewHorizontalSpacingDefault: CGFloat = 8;
open class JSQMessagesToolbarContentView: UIView {
@IBOutlet fileprivate(set) open var textView: JSQMessagesComposerTextView!
@IBOutlet var leftBarButtonContainerView: UIView!
@IBOutlet var leftBarButtonContainerViewWidthConstraint: NSLayoutConstraint!
@IBOutlet var rightBarButtonContainerView: UIView!
@IBOutlet var rightBarButtonContainerViewWidthConstraint: NSLayoutConstraint!
@IBOutlet var leftHorizontalSpacingConstraint: NSLayoutConstraint!
@IBOutlet var rightHorizontalSpacingConstraint: NSLayoutConstraint!
open override var backgroundColor: UIColor? {
didSet {
self.leftBarButtonContainerView?.backgroundColor = backgroundColor
self.rightBarButtonContainerView?.backgroundColor = backgroundColor
}
}
open dynamic var leftBarButtonItem: UIButton? {
willSet {
self.leftBarButtonItem?.removeFromSuperview()
if let newValue = newValue {
if newValue.frame.equalTo(CGRect.zero) {
newValue.frame = self.leftBarButtonContainerView.bounds
}
self.leftBarButtonContainerView.isHidden = false
self.leftHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault
self.leftBarButtonItemWidth = newValue.frame.width
newValue.translatesAutoresizingMaskIntoConstraints = false
self.leftBarButtonContainerView.addSubview(newValue)
self.leftBarButtonContainerView.jsq_pinAllEdgesOfSubview(newValue)
self.setNeedsUpdateConstraints()
return
}
self.leftHorizontalSpacingConstraint.constant = 0
self.leftBarButtonItemWidth = 0
self.leftBarButtonContainerView.isHidden = true
}
}
var leftBarButtonItemWidth: CGFloat {
get {
return self.leftBarButtonContainerViewWidthConstraint.constant
}
set {
self.leftBarButtonContainerViewWidthConstraint.constant = newValue
self.setNeedsUpdateConstraints()
}
}
open dynamic var rightBarButtonItem: UIButton? {
willSet {
self.rightBarButtonItem?.removeFromSuperview()
if let newValue = newValue {
if newValue.frame.equalTo(CGRect.zero) {
newValue.frame = self.rightBarButtonContainerView.bounds
}
self.rightBarButtonContainerView.isHidden = false
self.rightHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault
self.rightBarButtonItemWidth = newValue.frame.width
newValue.translatesAutoresizingMaskIntoConstraints = false
self.rightBarButtonContainerView.addSubview(newValue)
self.rightBarButtonContainerView.jsq_pinAllEdgesOfSubview(newValue)
self.setNeedsUpdateConstraints()
return
}
self.rightHorizontalSpacingConstraint.constant = 0
self.rightBarButtonItemWidth = 0
self.rightBarButtonContainerView.isHidden = true
}
}
var rightBarButtonItemWidth: CGFloat {
get {
return self.rightBarButtonContainerViewWidthConstraint.constant
}
set {
self.rightBarButtonContainerViewWidthConstraint.constant = newValue
self.setNeedsUpdateConstraints()
}
}
open class func nib() -> UINib {
return UINib(nibName: JSQMessagesToolbarContentView.jsq_className, bundle: Bundle(for: JSQMessagesToolbarContentView.self))
}
// MARK: - Initialization
open override func awakeFromNib() {
super.awakeFromNib()
self.translatesAutoresizingMaskIntoConstraints = false
self.leftHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault
self.rightHorizontalSpacingConstraint.constant = kJSQMessagesToolbarContentViewHorizontalSpacingDefault
self.backgroundColor = UIColor.clear
}
// MARK: - UIView overrides
open override func setNeedsDisplay() {
super.setNeedsDisplay()
self.textView?.setNeedsDisplay()
}
}
|
46442fffc2539a613d91724fed7d8339
| 32.373333 | 131 | 0.629245 | false | false | false | false |
haskellswift/swift-package-manager
|
refs/heads/master
|
Sources/Basic/CollectionAlgorithms.swift
|
apache-2.0
|
2
|
/*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
extension BidirectionalCollection where Iterator.Element : Comparable {
/// Returns the index of the last occurrence of `element` or nil if none.
///
/// - Parameters:
/// - start: If provided, the `start` index limits the search to a suffix of the collection.
//
// FIXME: This probably shouldn't take the `from` parameter, the pattern in
// the standard library is to use slices for that.
public func rindex(of element: Iterator.Element, from start: Index? = nil) -> Index? {
let firstIdx = start ?? startIndex
var i = endIndex
while i > firstIdx {
self.formIndex(before: &i)
if self[i] == element {
return i
}
}
return nil
}
}
|
36b55969d8bc43512c35af7d8e4b8083
| 34.966667 | 98 | 0.650602 | false | false | false | false |
Instagram/IGListKit
|
refs/heads/main
|
Examples/Examples-iOS/IGListKitExamples/SectionControllers/DemoSectionController.swift
|
mit
|
1
|
/*
* Copyright (c) Meta Platforms, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import IGListKit
import UIKit
final class DemoItem: NSObject {
let name: String
let controllerClass: UIViewController.Type
let controllerIdentifier: String?
init(
name: String,
controllerClass: UIViewController.Type,
controllerIdentifier: String? = nil
) {
self.name = name
self.controllerClass = controllerClass
self.controllerIdentifier = controllerIdentifier
}
}
extension DemoItem: ListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return name as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? DemoItem else { return false }
return controllerClass == object.controllerClass && controllerIdentifier == object.controllerIdentifier
}
}
final class DemoSectionController: ListSectionController {
private var object: DemoItem?
override func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
let cell: LabelCell = collectionContext.dequeueReusableCell(for: self, at: index)
cell.text = object?.name
return cell
}
override func didUpdate(to object: Any) {
self.object = object as? DemoItem
}
override func didSelectItem(at index: Int) {
if let identifier = object?.controllerIdentifier {
let storyboard = UIStoryboard(name: "Demo", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: identifier)
controller.title = object?.name
viewController?.navigationController?.pushViewController(controller, animated: true)
} else if let controller = object?.controllerClass.init() {
controller.title = object?.name
viewController?.navigationController?.pushViewController(controller, animated: true)
}
}
}
|
aa043c22d46c378d4ccde4ea64010af8
| 30.09589 | 111 | 0.681057 | false | false | false | false |
toggl/superday
|
refs/heads/develop
|
teferi/Models/AnnotatedEvent.swift
|
bsd-3-clause
|
1
|
import Foundation
struct AnnotatedEvent
{
let startTime: Date
let endTime: Date
let type: MotionEventType
let location: Location
let subEvents: [MotionEvent]
var duration: TimeInterval
{
return endTime.timeIntervalSince(startTime)
}
}
let MAX_MERGING_GAP: TimeInterval = 60 * 15
let MAX_MERGING_DISTANCE: Double = 0.5
extension AnnotatedEvent
{
init (motionEvent: MotionEvent, location: Location)
{
self.startTime = motionEvent.start
self.endTime = motionEvent.end
self.type = motionEvent.type
self.location = location
self.subEvents = [motionEvent]
}
func merging(_ newEvent: AnnotatedEvent) -> AnnotatedEvent
{
return AnnotatedEvent(
startTime: self.startTime,
endTime: newEvent.endTime,
type: self.type,
location: self.location,
subEvents: self.subEvents + newEvent.subEvents
)
}
func with(endTime: Date) -> AnnotatedEvent
{
return AnnotatedEvent(
startTime: self.startTime,
endTime: endTime,
type: self.type,
location: self.location,
subEvents: self.subEvents
)
}
func canBeMergedWith(event: AnnotatedEvent) -> Bool
{
return (event.startTime.timeIntervalSince(self.endTime) < MAX_MERGING_GAP ||
self.startTime.timeIntervalSince(event.endTime) < MAX_MERGING_GAP) &&
event.type == self.type
// We should consider the possibility of taking the distance into account for most categories (not for movement)
}
}
extension AnnotatedEvent: CustomStringConvertible
{
var description: String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let timeInterval = endTime.timeIntervalSince(startTime)
let minutes = floor(timeInterval / 60)
let seconds = timeInterval - minutes * 60
return "\(dateFormatter.string(from: startTime)) - \(dateFormatter.string(from: endTime)) : \(type) \(Int(minutes))m \(Int(seconds))s"
}
}
|
46045f97b1abb48cb23bea7fbc8c394e
| 26.871795 | 142 | 0.627415 | false | false | false | false |
gu704823/DYTV
|
refs/heads/master
|
dytv/dytv/uicollectionbaseview.swift
|
mit
|
1
|
//
// uicollectionbaseview.swift
// dytv
//
// Created by jason on 2017/3/29.
// Copyright © 2017年 jason. All rights reserved.
//
import UIKit
class uicollectionbaseviewcell: UICollectionViewCell {
@IBOutlet weak var iconimageview: UIImageView!
@IBOutlet weak var nicknamelabel: UILabel!
@IBOutlet weak var onlinebtn: UIButton!
var anchor:anchormodel?{
didSet{
guard let anchor = anchor else{
return
}
//取出在线人数
var onlinepeople:String = ""
if anchor.online>10000{
onlinepeople = "\(anchor.online/10000)万人在线"
}else{
onlinepeople = "\(anchor.online)人在线"
}
onlinebtn.setTitle(onlinepeople, for: .normal)
nicknamelabel.text = anchor.nickname
let url = URL(string: anchor.vertical_src)
iconimageview.kf.setImage(with: url)
}
}
}
|
3c4d99cd258ba4342d1b1a466dca52f5
| 26.882353 | 59 | 0.581224 | false | false | false | false |
russellladd/Walker
|
refs/heads/master
|
Finished Project/Walker/MyWalksViewController.swift
|
gpl-2.0
|
1
|
//
// ViewController.swift
// Walker
//
// Created by Russell Ladd on 3/28/15.
// Copyright (c) 2015 GRL5. All rights reserved.
//
import UIKit
import CoreData
class MyWalksViewController: UIViewController, NSFetchedResultsControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, OnWalkViewControllerDelegate {
// MARK: Model
var context: NSManagedObjectContext!
private lazy var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "Walk")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.context, sectionNameKeyPath: nil, cacheName: nil)
controller.delegate = self
return controller
}()
func controllerDidChangeContent(controller: NSFetchedResultsController) {
collectionView.reloadData()
updateNoWalksLabelHidden()
}
// MARK: View
@IBOutlet private weak var collectionView: UICollectionView!
@IBOutlet private weak var noWalksLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
do {
try fetchedResultsController.performFetch()
} catch _ {
}
collectionView.reloadData()
updateNoWalksLabelHidden()
}
func updateNoWalksLabelHidden() {
noWalksLabel.hidden = fetchedResultsController.fetchedObjects!.count > 0
}
// MARK: Collection view data source
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return fetchedResultsController.fetchedObjects!.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Walk Cell", forIndexPath: indexPath) as! WalkCell
let walk = fetchedResultsController.objectAtIndexPath(indexPath) as! Walk
cell.numberOfStepsLabel.text = walk.numberOfSteps.description
cell.circleView.alpha = CGFloat(0.5 + 0.5 * walk.fractionToGoal())
return cell
}
// MARK: Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case "Start Walk":
let navigationController = segue.destinationViewController as! UINavigationController
let onWalkViewController = navigationController.viewControllers.first as! OnWalkViewController
onWalkViewController.context = context
onWalkViewController.delegate = self
default:
assertionFailure("Unknown segue identifier")
}
}
// MARK: Walk view controller delegate
func onWalkViewControllerDidCancel() {
dismissViewControllerAnimated(true, completion: nil)
}
func onWalkViewController(onWalkViewController: OnWalkViewController, didFinishWithWalk walk: Walk) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
65d93cb5b9b2f0a6e094451d4c0dfccf
| 31.417476 | 167 | 0.673255 | false | false | false | false |
qualaroo/QualarooSDKiOS
|
refs/heads/master
|
QualarooTests/UserResponseAdapterSpec.swift
|
mit
|
1
|
//
// UserResponseAdapterSpec.swift
// QualarooTests
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
import Quick
import Nimble
@testable import Qualaroo
class UserResponseAdapterSpec: QuickSpec {
override func spec() {
super.spec()
describe("UserResponseAdapter") {
let adapter = UserResponseAdapter()
let answerOneModel = AnswerResponse(id: 111,
alias: "answer_111_alias",
text: "Answer111")
let answerTwoModel = AnswerResponse(id: 222,
alias: "answer_222_alias",
text: "Answer222")
let answerThreeModel = AnswerResponse(id: 333,
alias: "answer_333_alias",
text: "Answer333")
let questionOneModel = QuestionResponse(id: 11,
alias: "question_11_alias",
answerList: [answerOneModel])
let questionTwoModel = QuestionResponse(id: 11,
alias: "question_22_alias",
answerList: [answerTwoModel, answerThreeModel])
let questionThreeModel = QuestionResponse(id: 33,
alias: nil,
answerList: [answerOneModel])
context("LeadGenResponse") {
it("creates UserResponse from leadGen response with one question") {
let leadGenModel = LeadGenResponse(id: 1,
alias: "leadGen_1_alias",
questionList: [questionOneModel])
let responseModel = NodeResponse.leadGen(leadGenModel)
let userResponse = adapter.toUserResponse(responseModel)!
expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias"))
expect(userResponse.getFilledElements()).to(equal(["question_11_alias"]))
expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111"))
}
it("creates UserResponse from leadGen response with two questions") {
let leadGenModel = LeadGenResponse(id: 1,
alias: "leadGen_1_alias",
questionList: [questionOneModel, questionTwoModel])
let responseModel = NodeResponse.leadGen(leadGenModel)
let userResponse = adapter.toUserResponse(responseModel)!
expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias"))
expect(userResponse.getFilledElements()).to(equal(["question_11_alias", "question_22_alias"]))
expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111"))
expect(userResponse.getElementText("question_22_alias")).to(equal("Answer222"))
}
it("skips questions with no alias") {
let leadGenModel = LeadGenResponse(id: 1,
alias: "leadGen_1_alias",
questionList: [questionOneModel, questionTwoModel, questionThreeModel])
let responseModel = NodeResponse.leadGen(leadGenModel)
let userResponse = adapter.toUserResponse(responseModel)!
expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias"))
expect(userResponse.getFilledElements()).to(equal(["question_11_alias", "question_22_alias"]))
expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111"))
expect(userResponse.getElementText("question_22_alias")).to(equal("Answer222"))
}
it("doesn't create UserResponse if there is empty alias") {
let leadGenModel = LeadGenResponse(id: 1,
alias: nil,
questionList: [questionOneModel])
let responseModel = NodeResponse.leadGen(leadGenModel)
let userResponse = adapter.toUserResponse(responseModel)
expect(userResponse).to(beNil())
}
}
context("QuestionResponse") {
it("creates UserResponse from question response with one answer") {
let responseModel = NodeResponse.question(questionOneModel)
let userResponse = adapter.toUserResponse(responseModel)!
expect(userResponse.getQuestionAlias()).to(equal("question_11_alias"))
expect(userResponse.getFilledElements()).to(equal(["answer_111_alias"]))
expect(userResponse.getElementText("answer_111_alias")).to(equal("Answer111"))
}
it("creates UserResponse from question response with two answers") {
let responseModel = NodeResponse.question(questionTwoModel)
let userResponse = adapter.toUserResponse(responseModel)!
expect(userResponse.getQuestionAlias()).to(equal("question_22_alias"))
expect(userResponse.getFilledElements()).to(equal(["answer_222_alias", "answer_333_alias"]))
expect(userResponse.getElementText("answer_222_alias")).to(equal("Answer222"))
expect(userResponse.getElementText("answer_333_alias")).to(equal("Answer333"))
}
it("skips answers with no alias") {
let answerModel = AnswerResponse(id: 444,
alias: nil,
text: "Answer444")
let questionModel = QuestionResponse(id: 44,
alias: "question_44_alias",
answerList: [answerTwoModel, answerThreeModel, answerModel])
let responseModel = NodeResponse.question(questionModel)
let userResponse = adapter.toUserResponse(responseModel)!
expect(userResponse.getQuestionAlias()).to(equal("question_44_alias"))
expect(userResponse.getFilledElements()).to(equal(["answer_222_alias", "answer_333_alias"]))
expect(userResponse.getElementText("answer_222_alias")).to(equal("Answer222"))
expect(userResponse.getElementText("answer_333_alias")).to(equal("Answer333"))
}
it("doesn't create UserResponse if there is empty alias") {
let responseModel = NodeResponse.question(questionThreeModel)
let userResponse = adapter.toUserResponse(responseModel)
expect(userResponse).to(beNil())
}
}
}
}
}
|
e2f75b9fb19a3884183a6594c0a9d8f9
| 54.983471 | 116 | 0.581636 | false | false | false | false |
bastiangardel/EasyPayClientSeller
|
refs/heads/master
|
TB_Client_Seller/TB_Client_Seller/ViewControllerCheckouts.swift
|
mit
|
1
|
//
// CheckoutsViewController.swift
// TB_Client_Seller
//
// Created by Bastian Gardel on 21.06.16.
//
// Copyright © 2016 Bastian Gardel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
import BButton
import MBProgressHUD
import SCLAlertView
// ** Class ViewControllerCheckouts **
//
// View Checkouts List Controller
//
// Author: Bastian Gardel
// Version: 1.0
class ViewControllerCheckouts: UIViewController,UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var logoutButton: BButton!
@IBOutlet weak var CheckoutsTable: UITableView!
var httpsSession = HTTPSSession.sharedInstance
var hud: MBProgressHUD?
var checkoutlist: Array<CheckoutDTO>?
var index: Int = 0
//View initialisation
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
logoutButton.color = UIColor.bb_dangerColorV2()
logoutButton.setStyle(BButtonStyle.BootstrapV2)
logoutButton.setType(BButtonType.Danger)
logoutButton.addAwesomeIcon(FAIcon.FASignOut, beforeTitle: false)
CheckoutsTable.delegate = self
CheckoutsTable.dataSource = self
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud?.labelText = "Checkouts List Loading in progress"
hud?.labelFont = UIFont(name: "HelveticaNeue", size: 30)!
httpsSession.getListCheckout(){
(success: Bool, errorDescription:String, listCheckoutDTO : Array<CheckoutDTO>) in
self.hud!.hide(true)
let appearance = SCLAlertView.SCLAppearance(
kTitleFont: UIFont(name: "HelveticaNeue", size: 30)!,
kTextFont: UIFont(name: "HelveticaNeue", size: 30)!,
kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 25)!,
kWindowWidth: 500.0,
kWindowHeight: 500.0,
kTitleHeight: 50,
showCloseButton: false
)
if(success)
{
self.checkoutlist = listCheckoutDTO
if(listCheckoutDTO.count == 0)
{
let alertView = SCLAlertView(appearance: appearance)
alertView.addButton("Logout"){
self.httpsSession.logout()
self.performSegueWithIdentifier("logoutSegue", sender: self)
}
alertView.showInfo("Checkouts List Info", subTitle: "Please, ask your administrator for a new checkout.")
}
self.CheckoutsTable.reloadData();
}
else
{
let alertView = SCLAlertView(appearance: appearance)
alertView.addButton("Logout"){
self.httpsSession.logout()
self.performSegueWithIdentifier("logoutSegue", sender: self)
}
alertView.showError("Checkouts List Loading Error", subTitle: errorDescription)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Prepare transfer value for next view
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "checkoutMenuSegue") {
let svc = segue.destinationViewController as! ViewControllerCheckoutMenu;
svc.toPass = self.checkoutlist![index];
}
}
// ***** tableView Delegate *****
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if checkoutlist != nil {
return (checkoutlist?.count)!
}
return 0;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("checkoutCell", forIndexPath: indexPath)
cell.textLabel?.text = (checkoutlist?[indexPath.row].name)! + " : " + (checkoutlist?[indexPath.row].uuid)!
cell.backgroundColor = UIColor(colorLiteralRed: 0.88, green: 0.93, blue: 0.91, alpha: 0.7)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
index = indexPath.row
self.performSegueWithIdentifier("checkoutMenuSegue", sender: self)
}
@IBAction func logoutAction(sender: AnyObject) {
httpsSession.logout()
self.performSegueWithIdentifier("logoutSegue", sender: self)
}
}
|
614896619c767ced02c33773fa1e644d
| 33.654321 | 120 | 0.65586 | false | false | false | false |
ryuichis/swift-lint
|
refs/heads/master
|
Sources/Lint/Reporter/HTMLReporter.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 Source
class HTMLReporter : Reporter {
func handle(issues: [Issue]) -> String {
if issues.isEmpty {
return ""
}
var issuesText = """
<hr />
<table>
<thead>
<tr>
<th>File</th>
<th>Location</th>
<th>Rule Identifier</th>
<th>Rule Category</th>
<th>Severity</th>
<th>Message</th>
</tr>
</thead>
<tbody>
"""
issuesText += issues.map({ $0.htmlString }).joined(separator: separator)
issuesText += "</tbody></table>"
return issuesText
}
func handle(numberOfTotalFiles: Int, issueSummary: IssueSummary) -> String {
let numberOfIssueFiles = issueSummary.numberOfFiles
var summaryHtml = """
<table>
<thead>
<tr>
<th>Total Files</th>
<th>Files with Issues</th>
"""
summaryHtml += Issue.Severity.allSeverities
.map({ "<th>\($0.rawValue.capitalized)</th>" }).joined(separator: "\n")
summaryHtml += """
</tr>
</thead>
<tbody>
<tr>
<td>\(numberOfTotalFiles)</td>
<td>\(numberOfIssueFiles)</td>
"""
summaryHtml += Issue.Severity.allSeverities.map({
let count = issueSummary.numberOfIssues(withSeverity: $0)
return "<th class=\"severity-\($0)\">\(count)</th>"
}).joined(separator: "\n")
summaryHtml += """
</tr>
</tbody>
</table>
"""
return summaryHtml
}
var header: String {
return """
<!DOCTYPE html>
<html>
<head>
<title>Yanagiba's swift-lint Report</title>
<style type='text/css'>
.severity-critical, .severity-major, .severity-minor, .severity-cosmetic {
font-weight: bold;
text-align: center;
color: #BF0A30;
}
.severity-critical { background-color: #FFC200; }
.severity-major { background-color: #FFD3A6; }
.severity-minor { background-color: #FFEEB5; }
.severity-cosmetic { background-color: #FFAAB5; }
table {
border: 2px solid gray;
border-collapse: collapse;
-moz-box-shadow: 3px 3px 4px #AAA;
-webkit-box-shadow: 3px 3px 4px #AAA;
box-shadow: 3px 3px 4px #AAA;
}
td, th {
border: 1px solid #D3D3D3;
padding: 4px 20px 4px 20px;
}
th {
text-shadow: 2px 2px 2px white;
border-bottom: 1px solid gray;
background-color: #E9F4FF;
}
</style>
</head>
<body>
<h1>Yanagiba's swift-lint report</h1>
<hr />
"""
}
var footer: String {
let versionInfo = "Yanagiba's \(SWIFT_LINT) v\(SWIFT_LINT_VERSION)"
return """
<hr />
<p>
\(Date().formatted)
|
Generated with <a href='http://yanagiba.org/swift-lint'>\(versionInfo)</a>.
</p>
</body>
</html>
"""
}
}
|
ff11a46d1b5ffcdcbcea8ea6474fa41e
| 24.708955 | 81 | 0.58926 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.