repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Stores/PluginStore+Persistence.swift | gpl-2.0 | 2 | import Foundation
extension PluginStoreState: Codable {
private enum CodingKeys: String, CodingKey {
case plugins
case featuredPluginSlugs
case directoryFeeds
case directoryEntries
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
plugins = try container.decode([JetpackSiteRef: SitePlugins].self, forKey: .plugins)
featuredPluginsSlugs = try container.decode([String].self, forKey: .featuredPluginSlugs)
directoryFeeds = try container.decode([String: PluginDirectoryPageMetadata].self, forKey: .directoryFeeds)
directoryEntries = try container.decode([String: PluginDirectoryEntryState].self, forKey: .directoryEntries)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(plugins, forKey: .plugins)
try container.encode(featuredPluginsSlugs, forKey: .featuredPluginSlugs)
try container.encode(directoryFeeds, forKey: .directoryFeeds)
try container.encode(directoryEntries, forKey: .directoryEntries)
}
}
| 412e9b7ee12c43f62e95ec494bc14344 | 36.903226 | 116 | 0.72 | false | false | false | false |
frootloops/swift | refs/heads/master | test/SILGen/types.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen -enable-sil-ownership %s | %FileCheck %s
class C {
var member: Int = 0
// Methods have method calling convention.
// CHECK-LABEL: sil hidden @_T05types1CC3fooySi1x_tF : $@convention(method) (Int, @guaranteed C) -> () {
func foo(x x: Int) {
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[THIS:%[0-9]+]] : @guaranteed $C):
member = x
// CHECK-NOT: copy_value
// CHECK: [[FN:%[0-9]+]] = class_method %1 : $C, #C.member!setter.1
// CHECK: apply [[FN]](%0, %1) : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK-NOT: destroy_value
}
// CHECK: } // end sil function '_T05types1CC3fooySi1x_tF'
}
struct S {
var member: Int
// CHECK-LABEL: sil hidden @{{.*}}1SV3foo{{.*}} : $@convention(method) (Int, @inout S) -> ()
mutating
func foo(x x: Int) {
var x = x
// CHECK: bb0([[X:%[0-9]+]] : @trivial $Int, [[THIS:%[0-9]+]] : @trivial $*S):
member = x
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int
// CHECK: [[X:%.*]] = load [trivial] [[READ]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[THIS]] : $*S
// CHECK: [[MEMBER:%[0-9]+]] = struct_element_addr [[WRITE]] : $*S, #S.member
// CHECK: assign [[X]] to [[MEMBER]] : $*Int
}
class SC {
// CHECK-LABEL: sil hidden @_T05types1SV2SCC3bar{{.*}}
func bar() {}
}
}
func f() {
class FC {
func zim() {}
}
}
func g(b b : Bool) {
if (b) {
class FC {
func zim() {}
}
} else {
class FC {
func zim() {}
}
}
}
struct ReferencedFromFunctionStruct {
let f: (ReferencedFromFunctionStruct) -> () = {x in ()}
let g: (ReferencedFromFunctionEnum) -> () = {x in ()}
}
enum ReferencedFromFunctionEnum {
case f((ReferencedFromFunctionEnum) -> ())
case g((ReferencedFromFunctionStruct) -> ())
}
// CHECK-LABEL: sil hidden @_T05types34referencedFromFunctionStructFieldsyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF{{.*}} : $@convention(thin) (@owned ReferencedFromFunctionStruct) -> (@owned @callee_guaranteed (@owned ReferencedFromFunctionStruct) -> (), @owned @callee_guaranteed (@owned ReferencedFromFunctionEnum) -> ()) {
// CHECK: bb0([[X:%.*]] : @owned $ReferencedFromFunctionStruct):
// CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]]
// CHECK: [[F:%.*]] = struct_extract [[BORROWED_X]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.f
// CHECK: [[COPIED_F:%.*]] = copy_value [[F]] : $@callee_guaranteed (@owned ReferencedFromFunctionStruct) -> ()
// CHECK: [[BORROWED_X_2:%.*]] = begin_borrow [[X]]
// CHECK: [[G:%.*]] = struct_extract [[BORROWED_X_2]] : $ReferencedFromFunctionStruct, #ReferencedFromFunctionStruct.g
// CHECK: [[COPIED_G:%.*]] = copy_value [[G]] : $@callee_guaranteed (@owned ReferencedFromFunctionEnum) -> ()
// CHECK: end_borrow [[BORROWED_X_2]] from [[X]]
// CHECK: end_borrow [[BORROWED_X]] from [[X]]
// CHECK: destroy_value [[X]]
// CHECK: [[RESULT:%.*]] = tuple ([[COPIED_F]] : {{.*}}, [[COPIED_G]] : {{.*}})
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '_T05types34referencedFromFunctionStructFieldsyAA010ReferencedcdE0Vc_yAA0gcD4EnumOctADF'
func referencedFromFunctionStructFields(_ x: ReferencedFromFunctionStruct)
-> ((ReferencedFromFunctionStruct) -> (), (ReferencedFromFunctionEnum) -> ()) {
return (x.f, x.g)
}
// CHECK-LABEL: sil hidden @_T05types32referencedFromFunctionEnumFieldsyAA010ReferencedcdE0OcSg_yAA0gcD6StructVcSgtADF
// CHECK: bb{{[0-9]+}}([[F:%.*]] : @owned $@callee_guaranteed (@owned ReferencedFromFunctionEnum) -> ()):
// CHECK: bb{{[0-9]+}}([[G:%.*]] : @owned $@callee_guaranteed (@owned ReferencedFromFunctionStruct) -> ()):
func referencedFromFunctionEnumFields(_ x: ReferencedFromFunctionEnum)
-> (
((ReferencedFromFunctionEnum) -> ())?,
((ReferencedFromFunctionStruct) -> ())?
) {
switch x {
case .f(let f):
return (f, nil)
case .g(let g):
return (nil, g)
}
}
// CHECK-LABEL: sil private @_T05types1fyyF2FCL_C3zimyyF
// CHECK-LABEL: sil private @_T05types1gySb1b_tF2FCL_C3zimyyF
// CHECK-LABEL: sil private @_T05types1gySb1b_tF2FCL0_C3zimyyF
| 4f47360dc7bb2ba58a194148ce0993af | 38.477064 | 325 | 0.613525 | false | false | false | false |
Ferrari-lee/firefox-ios | refs/heads/autocomplete-highlight | Client/Frontend/Browser/BrowserScrollController.swift | mpl-2.0 | 26 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
private let ToolbarBaseAnimationDuration: CGFloat = 0.2
class BrowserScrollingController: NSObject {
enum ScrollDirection {
case Up
case Down
}
enum ToolbarState {
case Collapsed
case Visible
case Animating
}
weak var browser: Browser? {
willSet {
self.scrollView?.delegate = nil
self.scrollView?.removeGestureRecognizer(panGesture)
}
didSet {
self.scrollView?.addGestureRecognizer(panGesture)
scrollView?.delegate = self
}
}
weak var header: UIView?
weak var footer: UIView?
weak var urlBar: URLBarView?
weak var snackBars: UIView?
var footerBottomConstraint: Constraint?
// TODO: Since SnapKit hasn't added support yet (Swift 2.0/iOS 9) for handling layoutGuides,
// this constraint uses the system abstraction instead of SnapKit's Constraint class
var headerTopConstraint: NSLayoutConstraint?
var toolbarsShowing: Bool { return headerTopOffset == 0 }
private var headerTopOffset: CGFloat = 0 {
didSet {
headerTopConstraint?.constant = headerTopOffset
header?.superview?.setNeedsLayout()
}
}
private var footerBottomOffset: CGFloat = 0 {
didSet {
footerBottomConstraint?.updateOffset(footerBottomOffset)
footer?.superview?.setNeedsLayout()
}
}
private lazy var panGesture: UIPanGestureRecognizer = {
let panGesture = UIPanGestureRecognizer(target: self, action: "handlePan:")
panGesture.maximumNumberOfTouches = 1
panGesture.delegate = self
return panGesture
}()
private var scrollView: UIScrollView? { return browser?.webView?.scrollView }
private var contentOffset: CGPoint { return scrollView?.contentOffset ?? CGPointZero }
private var contentSize: CGSize { return scrollView?.contentSize ?? CGSizeZero }
private var scrollViewHeight: CGFloat { return scrollView?.frame.height ?? 0 }
private var headerFrame: CGRect { return header?.frame ?? CGRectZero }
private var footerFrame: CGRect { return footer?.frame ?? CGRectZero }
private var snackBarsFrame: CGRect { return snackBars?.frame ?? CGRectZero }
private var lastContentOffset: CGFloat = 0
private var scrollDirection: ScrollDirection = .Down
private var toolbarState: ToolbarState = .Visible
override init() {
super.init()
}
func showToolbars(animated animated: Bool, completion: ((finished: Bool) -> Void)? = nil) {
toolbarState = .Visible
let durationRatio = abs(headerTopOffset / headerFrame.height)
let actualDuration = NSTimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated: animated,
duration: actualDuration,
headerOffset: 0,
footerOffset: 0,
alpha: 1,
completion: completion)
}
func hideToolbars(animated animated: Bool, completion: ((finished: Bool) -> Void)? = nil) {
toolbarState = .Collapsed
let durationRatio = abs((headerFrame.height + headerTopOffset) / headerFrame.height)
let actualDuration = NSTimeInterval(ToolbarBaseAnimationDuration * durationRatio)
self.animateToolbarsWithOffsets(
animated: animated,
duration: actualDuration,
headerOffset: -headerFrame.height,
footerOffset: footerFrame.height - snackBarsFrame.height,
alpha: 0,
completion: completion)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "contentSize" {
if !checkScrollHeightIsLargeEnoughForScrolling() && !toolbarsShowing {
showToolbars(animated: true, completion: nil)
}
}
}
}
private extension BrowserScrollingController {
func browserIsLoading() -> Bool {
return browser?.loading ?? true
}
@objc func handlePan(gesture: UIPanGestureRecognizer) {
if browserIsLoading() {
return
}
if let containerView = scrollView?.superview {
let translation = gesture.translationInView(containerView)
let delta = lastContentOffset - translation.y
if delta > 0 {
scrollDirection = .Down
} else if delta < 0 {
scrollDirection = .Up
}
lastContentOffset = translation.y
if checkRubberbandingForDelta(delta) && checkScrollHeightIsLargeEnoughForScrolling() {
if toolbarState != .Collapsed || contentOffset.y <= 0 {
scrollWithDelta(delta)
}
if headerTopOffset == -headerFrame.height {
toolbarState = .Collapsed
} else if headerTopOffset == 0 {
toolbarState = .Visible
} else {
toolbarState = .Animating
}
}
if gesture.state == .Ended || gesture.state == .Cancelled {
lastContentOffset = 0
}
}
}
func checkRubberbandingForDelta(delta: CGFloat) -> Bool {
return !((delta < 0 && contentOffset.y + scrollViewHeight > contentSize.height &&
scrollViewHeight < contentSize.height) ||
contentOffset.y < delta)
}
func scrollWithDelta(delta: CGFloat) {
if scrollViewHeight >= contentSize.height {
return
}
var updatedOffset = headerTopOffset - delta
headerTopOffset = clamp(updatedOffset, min: -headerFrame.height, max: 0)
if isHeaderDisplayedForGivenOffset(updatedOffset) {
scrollView?.contentOffset = CGPoint(x: contentOffset.x, y: contentOffset.y - delta)
}
updatedOffset = footerBottomOffset + delta
footerBottomOffset = clamp(updatedOffset, min: 0, max: footerFrame.height - snackBarsFrame.height)
let alpha = 1 - abs(headerTopOffset / headerFrame.height)
urlBar?.updateAlphaForSubviews(alpha)
}
func isHeaderDisplayedForGivenOffset(offset: CGFloat) -> Bool {
return offset > -headerFrame.height && offset < 0
}
func clamp(y: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
if y >= max {
return max
} else if y <= min {
return min
}
return y
}
func animateToolbarsWithOffsets(animated animated: Bool, duration: NSTimeInterval, headerOffset: CGFloat,
footerOffset: CGFloat, alpha: CGFloat, completion: ((finished: Bool) -> Void)?) {
let animation: () -> Void = {
self.headerTopOffset = headerOffset
self.footerBottomOffset = footerOffset
self.urlBar?.updateAlphaForSubviews(alpha)
self.header?.superview?.layoutIfNeeded()
}
if animated {
UIView.animateWithDuration(duration, animations: animation, completion: completion)
} else {
animation()
completion?(finished: true)
}
}
func checkScrollHeightIsLargeEnoughForScrolling() -> Bool {
return (UIScreen.mainScreen().bounds.size.height + 2 * UIConstants.ToolbarHeight) < scrollView?.contentSize.height
}
}
extension BrowserScrollingController: UIGestureRecognizerDelegate {
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension BrowserScrollingController: UIScrollViewDelegate {
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if browserIsLoading() {
return
}
if (decelerate || (toolbarState == .Animating && !decelerate)) && checkScrollHeightIsLargeEnoughForScrolling() {
if scrollDirection == .Up {
showToolbars(animated: true)
} else if scrollDirection == .Down {
hideToolbars(animated: true)
}
}
}
func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
showToolbars(animated: true)
return true
}
}
| 1c9fa14b75a2139f87e138175ca0ad6c | 34.463115 | 157 | 0.633538 | false | false | false | false |
One-self/ZhihuDaily | refs/heads/master | ZhihuDaily/ZhihuDaily/Classes/View/ZDStoryViewController.swift | mit | 1 | //
// ZDStoryViewController.swift
// ZhihuDaily
//
// Created by Oneselfly on 2017/5/15.
// Copyright © 2017年 Oneself. All rights reserved.
//
import WebKit
private let toolbarHeight: CGFloat = 45
enum ZDStoryLoadDataMethod {
case dropDown
case pull
case normal
}
class ZDStoryViewController: UIViewController {
lazy var detailStoryViewModel = ZDDetailStoryViewModel()
fileprivate lazy var storyToolbar = ZDStoryToolbar.storyToolbar()
fileprivate lazy var webView = WKWebView()
fileprivate lazy var headImageView = ZDDetailStoryHeadImageView.headImageView()
fileprivate lazy var dropDownRefreshControl = YLRefreshControl()
private var loadDataMethod: ZDStoryLoadDataMethod = .normal
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
setupUI()
loadDetailStory()
}
@objc fileprivate func dropDownReloadData() {
loadDataMethod = .dropDown
loadDetailStory()
}
private func loadDetailStory() {
detailStoryViewModel.loadDetailStory(loadDataMethod: loadDataMethod) {
if $0 == true {
self.detailStoryViewModel.isFirstStory ? print("是第一个") : print("不是第一个")
self.webView.loadHTMLString(self.detailStoryViewModel.HTMLString ?? "", baseURL: Bundle.main.bundleURL)
self.headImageView.detailStory = self.detailStoryViewModel.detailStory
}
self.dropDownRefreshControl.endRefreshing()
self.loadDataMethod = .normal
}
}
}
// MARK: - UI
extension ZDStoryViewController {
fileprivate func setupUI() {
view.addSubview(storyToolbar)
storyToolbar.snp.makeConstraints {
$0.left.bottom.right.equalToSuperview()
$0.height.equalTo(toolbarHeight)
}
storyToolbar.returnButtonClosure = { [weak self] in
self?.navigationController?.popViewController(animated: true)
}
view.addSubview(webView)
webView.snp.makeConstraints {
$0.top.left.right.equalToSuperview()
$0.bottom.equalTo(storyToolbar.snp.top)
}
let webContentView = webView.scrollView.subviews[0]
webContentView.addSubview(headImageView)
headImageView.snp.makeConstraints {
$0.bottom.equalTo(webContentView.snp.top).offset(200)
$0.left.equalTo(webContentView)
// 貌似无效,宽度变得很窄
// $0.right.equalTo(webContentView)
// 无奈之举...
$0.width.equalTo(UIScreen.main.bounds.width)
$0.top.equalTo(webView)
}
webView.scrollView.delegate = self
webView.scrollView.addSubview(dropDownRefreshControl)
dropDownRefreshControl.addTarget(self, action: #selector(dropDownReloadData), for: .valueChanged)
}
}
extension ZDStoryViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if -scrollView.contentOffset.y > 90 {
scrollView.setContentOffset(CGPoint(x: 0, y: -90), animated: false)
}
}
}
| c3fcce6656b2bf69d861d359dcb0c815 | 28.5 | 119 | 0.626211 | false | false | false | false |
Miciah/origin | refs/heads/master | cluster-api/vendor/github.com/googleapis/gnostic/plugins/gnostic-swift-sample/Sources/gnostic-swift-sample/main.swift | apache-2.0 | 21 | // Copyright 2017 Google Inc. 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 Gnostic
func printDocument(document:Openapi_V2_Document,
name:String) -> String {
var code = CodePrinter()
code.print("READING \(name)\n")
code.print("Swagger: \(document.swagger)\n")
code.print("Host: \(document.host)\n")
code.print("BasePath: \(document.basePath)\n")
if document.hasInfo {
code.print("Info:\n")
code.indent()
if document.info.title != "" {
code.print("Title: \(document.info.title)\n")
}
if document.info.description_p != "" {
code.print("Description: \(document.info.description_p)\n")
}
if document.info.version != "" {
code.print("Version: \(document.info.version)\n")
}
code.outdent()
}
code.print("Paths:\n")
code.indent()
for pair in document.paths.path {
let v = pair.value
if v.hasGet {
code.print("GET \(pair.name)\n")
}
if v.hasPost {
code.print("POST \(pair.name)\n")
}
}
code.outdent()
return code.content
}
func main() throws {
var response = Gnostic_Plugin_V1_Response()
let rawRequest = try Stdin.readall()
let request = try Gnostic_Plugin_V1_Request(serializedData: rawRequest)
if request.hasOpenapi2 {
let document = request.openapi2
let report = printDocument(document:document, name:request.sourceName)
if let reportData = report.data(using:.utf8) {
var file = Gnostic_Plugin_V1_File()
file.name = "report.txt"
file.data = reportData
response.files.append(file)
}
}
let serializedResponse = try response.serializedData()
Stdout.write(bytes: serializedResponse)
}
try main()
| ba03cf77b13db5e384551401d5de87ff | 30.027778 | 75 | 0.672784 | false | false | false | false |
caronae/caronae-ios | refs/heads/master | Caronae/Ride/RideViewController+rideActions.swift | gpl-3.0 | 1 | import SVProgressHUD
import Sheriff
extension RideViewController {
func userIsRider() -> Bool {
let userID = UserService.instance.user!.id
guard ride.riders.contains(where: { $0.id == userID }) else {
return false
}
return true
}
func userIsDriver() -> Bool {
return UserService.instance.user!.id == ride.driver.id
}
@objc func updateChatButtonBadge() {
guard let unreadNotifications = try? NotificationService.instance.getNotifications(of: [.chat])
.filter({ $0.rideID == self.ride.id }) else { return }
let badge = GIBadgeView()
let button = UIButton()
button.setTitle("Chat ", for: .normal)
button.setTitleColor(navigationController?.navigationBar.tintColor, for: .normal)
button.addTarget(self, action: #selector(openChatWindow), for: .touchUpInside)
button.titleLabel?.addSubview(badge)
badge.badgeValue = unreadNotifications.count
let barButton = UIBarButtonItem(customView: button)
navigationItem.rightBarButtonItem = barButton
}
func deleteRoutine() {
let routineID = self.ride.routineID.value!
NSLog("Requesting to delete routine with id %ld", routineID)
cancelButton.isEnabled = false
SVProgressHUD.show()
RideService.instance.deleteRoutine(withID: routineID, success: {
SVProgressHUD.dismiss()
NSLog("User left all rides from routine.")
lastAllRidesUpdate = Date.distantPast
_ = self.navigationController?.popViewController(animated: true)
}, error: { error in
SVProgressHUD.dismiss()
self.cancelButton.isEnabled = true
NSLog("Error deleting routine (%@)", error.localizedDescription)
CaronaeAlertController.presentOkAlert(withTitle: "Algo deu errado.",
message: String(format: "Não foi possível cancelar sua rotina. (%@)", error.localizedDescription))
})
}
func clearNotifications() {
NotificationService.instance.clearNotifications(forRideID: ride.id, of: [.rideJoinRequestAccepted])
}
func clearNotificationOfJoinRequest(from senderID: Int) {
NotificationService.instance.clearNotifications(forRideID: ride.id, of: [.rideJoinRequest], from: senderID)
}
func loadRealmRide() {
if let realmRide = RideService.instance.getRideFromRealm(withID: self.ride.id) {
NSLog("Ride loaded from realm database")
self.ride = realmRide
}
}
}
| 7d9a4ef2678cc031eb5bd38d3a7f419e | 36.430556 | 148 | 0.623748 | false | false | false | false |
google/JacquardSDKiOS | refs/heads/main | JacquardSDK/Classes/Internal/TagAPIDetails/ModuleCommands.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.
/// Command request to retrieve all the modules available in the device.
struct ListModulesCommand: CommandRequest {
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .base
request.opcode = .listModules
return request
}
func parseResponse(outerProto: Any) -> Result<[Module], Error> {
guard let outerProto = outerProto as? Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
guard outerProto.hasGoogle_Jacquard_Protocol_ListModuleResponse_listModules else {
return .failure(JacquardCommandError.malformedResponse)
}
let moduleDiscriptors =
outerProto.Google_Jacquard_Protocol_ListModuleResponse_listModules.modules
let modules = moduleDiscriptors.map { Module(moduleDescriptor: $0) }
return .success(modules)
}
}
/// Command request to activate a module in the device.
struct ActivateModuleCommand: CommandRequest {
let module: Module
init(module: Module) {
self.module = module
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .base
request.opcode = .loadModule
var loadModuleRequest = Google_Jacquard_Protocol_LoadModuleRequest()
loadModuleRequest.module = module.getModuleDescriptorRequest()
request.Google_Jacquard_Protocol_LoadModuleRequest_loadModule = loadModuleRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard outerProto is Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
return .success(())
}
}
struct ActivateModuleNotificationSubscription: NotificationSubscription {
/// Initialize a subscription request.
public init() {}
func extract(from outerProto: Any) -> Google_Jacquard_Protocol_LoadModuleNotification? {
guard let notification = outerProto as? Google_Jacquard_Protocol_Notification else {
jqLogger.assert(
"calling extract() with anything other than Google_Jacquard_Protocol_Notification is an error"
)
return nil
}
// Silently ignore other notifications.
guard
notification.hasGoogle_Jacquard_Protocol_LoadModuleNotification_loadModuleNotif
else {
return nil
}
let innerProto =
notification.Google_Jacquard_Protocol_LoadModuleNotification_loadModuleNotif
return innerProto
}
}
/// Command request to de-activate a module in the device.
struct DeactivateModuleCommand: CommandRequest {
let module: Module
init(module: Module) {
self.module = module
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .base
request.opcode = .unloadModule
var unloadModuleRequest = Google_Jacquard_Protocol_UnloadModuleRequest()
unloadModuleRequest.module = module.getModuleDescriptorRequest()
request.Google_Jacquard_Protocol_UnloadModuleRequest_unloadModule = unloadModuleRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard outerProto is Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
return .success(())
}
}
/// Command request to delete a module in the device.
struct DeleteModuleCommand: CommandRequest {
let module: Module
init(module: Module) {
self.module = module
}
var request: V2ProtocolCommandRequestIDInjectable {
var request = Google_Jacquard_Protocol_Request()
request.domain = .base
request.opcode = .deleteModule
var deleteModuleRequest = Google_Jacquard_Protocol_DeleteModuleRequest()
deleteModuleRequest.module = module.getModuleDescriptorRequest()
request.Google_Jacquard_Protocol_DeleteModuleRequest_deleteModule = deleteModuleRequest
return request
}
func parseResponse(outerProto: Any) -> Result<Void, Error> {
guard outerProto is Google_Jacquard_Protocol_Response else {
jqLogger.assert(
"calling parseResponse() with anything other than Google_Jacquard_Protocol_Response is an error"
)
return .failure(CommandResponseStatus.errorAppUnknown)
}
return .success(())
}
}
| ba9031ea7cd41312572c80f01c5d38e1 | 31.048193 | 104 | 0.739474 | false | false | false | false |
SBGMobile/Charts | refs/heads/master | ChartsDemo/Pods/Charts/Source/Charts/Highlight/BarHighlighter.swift | apache-2.0 | 7 | //
// BarHighlighter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(BarChartHighlighter)
open class BarHighlighter: ChartHighlighter
{
open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight?
{
let high = super.getHighlight(x: x, y: y)
if high == nil
{
return nil
}
if let barData = (self.chart as? BarChartDataProvider)?.barData
{
let pos = getValsForTouch(x: x, y: y)
if
let set = barData.getDataSetByIndex(high!.dataSetIndex) as? IBarChartDataSet,
set.isStacked
{
return getStackedHighlight(high: high!,
set: set,
xValue: Double(pos.x),
yValue: Double(pos.y))
}
return high
}
return nil
}
internal override func getDistance(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) -> CGFloat
{
return abs(x1 - x2)
}
internal override var data: ChartData?
{
return (chart as? BarChartDataProvider)?.barData
}
/// This method creates the Highlight object that also indicates which value of a stacked BarEntry has been selected.
/// - parameter high: the Highlight to work with looking for stacked values
/// - parameter set:
/// - parameter xIndex:
/// - parameter yValue:
/// - returns:
open func getStackedHighlight(high: Highlight,
set: IBarChartDataSet,
xValue: Double,
yValue: Double) -> Highlight?
{
guard
let chart = self.chart as? BarLineScatterCandleBubbleChartDataProvider,
let entry = set.entryForXValue(xValue, closestToY: yValue) as? BarChartDataEntry
else { return nil }
// Not stacked
if entry.yValues == nil
{
return high
}
if let ranges = entry.ranges,
ranges.count > 0
{
let stackIndex = getClosestStackIndex(ranges: ranges, value: yValue)
let pixel = chart
.getTransformer(forAxis: set.axisDependency)
.pixelForValues(x: high.x, y: ranges[stackIndex].to)
return Highlight(x: entry.x,
y: entry.y,
xPx: pixel.x,
yPx: pixel.y,
dataSetIndex: high.dataSetIndex,
stackIndex: stackIndex,
axis: high.axis)
}
return nil
}
/// - returns: The index of the closest value inside the values array / ranges (stacked barchart) to the value given as a parameter.
/// - parameter entry:
/// - parameter value:
/// - returns:
open func getClosestStackIndex(ranges: [Range]?, value: Double) -> Int
{
if ranges == nil
{
return 0
}
var stackIndex = 0
for range in ranges!
{
if range.contains(value)
{
return stackIndex
}
else
{
stackIndex += 1
}
}
let length = max(ranges!.count - 1, 0)
return (value > ranges![length].to) ? length : 0
}
}
| 48d81104bdaf00890bbdd2b620152ae1 | 28.773438 | 136 | 0.489898 | false | false | false | false |
ello/ello-ios | refs/heads/master | Sources/Controllers/Onboarding/OnboardingCreatorTypeViewController.swift | mit | 1 | ////
/// OnboardingCreatorTypeViewController.swift
//
import PromiseKit
class OnboardingCreatorTypeViewController: BaseElloViewController {
private var _mockScreen: OnboardingCreatorTypeScreenProtocol?
var screen: OnboardingCreatorTypeScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
var categories: [Category]?
var creatorType: Profile.CreatorType {
get { return _creatorType }
set {
_creatorType = newValue
if isViewLoaded {
screen.updateCreatorType(type: newValue)
}
}
}
private var _creatorType: Profile.CreatorType = .none
var onboardingViewController: OnboardingViewController?
var onboardingData: OnboardingData!
weak var delegate: DynamicSettingsDelegate?
override var navigationBarsVisible: Bool? { return true }
override func loadView() {
let screen = OnboardingCreatorTypeScreen()
screen.delegate = self
screen.showIntroText = false
view = screen
}
override func viewDidLoad() {
super.viewDidLoad()
let isOnboarding = onboardingViewController != nil
if isOnboarding {
screen.topInset = 0
screen.navigationBar.isHidden = true
}
else {
screen.topInset = ElloNavigationBar.Size.height
updatesBottomBar = false
screen.navigationBar.title = InterfaceString.Settings.CreatorType
screen.navigationBar.leftItems = [.back]
postNotification(StatusBarNotifications.statusBarVisibility, value: true)
}
CategoryService().loadCreatorCategories()
.done { categories in
self.categories = categories
self.screen.creatorCategories = categories.map { $0.name }
self.screen.updateCreatorType(type: self.creatorType)
}
.ignoreErrors()
}
override func backButtonTapped() {
super.backButtonTapped()
saveCreatorType()
.done { user in
self.delegate?.dynamicSettingsUserChanged(user)
}
.catch { error in
let alertController = AlertViewController(
confirmation: InterfaceString.GenericError
)
self.appViewController?.present(alertController, animated: true, completion: nil)
}
}
override func updateNavBars(animated: Bool) {
super.updateNavBars(animated: animated)
if bottomBarController?.bottomBarVisible == true {
screen.bottomInset = ElloTabBar.Size.height
}
else {
screen.bottomInset = 0
}
}
}
extension OnboardingCreatorTypeViewController: OnboardingCreatorTypeDelegate {
func creatorTypeChanged(type: OnboardingCreatorTypeScreen.CreatorType) {
switch type {
case .none:
_creatorType = .none
case .fan:
_creatorType = .fan
case let .artist(selections):
if let categories = categories {
let selectedCategories = selections.map { categories[$0] }
_creatorType = .artist(selectedCategories)
}
else {
_creatorType = .none
}
}
onboardingViewController?.canGoNext = _creatorType.isValid
}
}
extension OnboardingCreatorTypeViewController: OnboardingStepController {
@discardableResult
func saveCreatorType() -> Promise<User> {
let ids: [String]
if case let .artist(selectedCategories) = creatorType {
ids = selectedCategories.map { $0.id }
}
else {
ids = []
}
return ProfileService().updateUserProfile([.creatorTypeCategoryIds: ids])
}
func onboardingStepBegin() {
onboardingViewController?.hasAbortButton = false
onboardingViewController?.canGoNext = false
let onboardingVersion = currentUser?.onboardingVersion ?? 0
let showAllOnboarding = onboardingVersion < Onboarding.minCreatorTypeVersion
if showAllOnboarding {
onboardingViewController?.prompt = InterfaceString.Onboard.CreateAccount
}
else {
onboardingViewController?.prompt = InterfaceString.Submit
}
screen.showIntroText = !showAllOnboarding
}
func onboardingWillProceed(
abort: Bool,
proceedClosure: @escaping (_ success: OnboardingViewController.OnboardingProceed) -> Void
) {
guard creatorType.isValid else {
proceedClosure(.error)
return
}
saveCreatorType()
.done { _ in
Tracker.shared.onboardingCreatorTypeSelected(self.creatorType)
self.onboardingData.creatorType = self.creatorType
proceedClosure(.continue)
}
.catch { _ in
let alertController = AlertViewController(
confirmation: InterfaceString.GenericError
)
self.appViewController?.present(alertController, animated: true, completion: nil)
proceedClosure(.error)
}
}
}
| aac5e09f53f741200cb937521992125d | 30.372781 | 97 | 0.611845 | false | false | false | false |
mumbler/PReVo-iOS | refs/heads/trunk | PoshReVo/Chefaj Paghoj/InformojTableViewController.swift | mit | 1 | //
// InformoTableViewController.swift.swift
// PoshReVo
//
// Created by Robin Hill on 8/8/19.
// Copyright © 2019 Robin Hill. All rights reserved.
//
import UIKit
final class InformojTableViewController: BazStilaTableViewController, Chefpagho {
private enum Sekcio{
case ReVo, PoshReVo
public static func deNumero(_ numero: Int) -> Sekcio {
switch numero {
case 0:
return .ReVo
case 1:
return .PoshReVo
default:
fatalError("Sekcio ne validas")
}
}
public func chelKvanto() -> Int {
switch self {
case .ReVo:
return 3
case .PoshReVo:
return 1
}
}
public func titolo(numero: Int) -> String {
var titoloj = [String]()
switch self {
case .ReVo:
titoloj = [
NSLocalizedString("informoj revo titolo", comment: ""),
NSLocalizedString("informoj vortaraj-mallongigoj titolo", comment: ""),
NSLocalizedString("informoj fakaj-mallongigoj titolo", comment: "")
]
case .PoshReVo:
titoloj = [NSLocalizedString("informoj poshrevo titolo", comment: "")]
}
return titoloj[numero]
}
public func teksto(numero: Int) -> String {
var tekstoj = [String]()
switch self {
case .ReVo:
tekstoj = [
NSLocalizedString("informoj revo teksto", comment: ""),
Bundle.main.localizedString(forKey: "informoj vortaraj-mallongigoj teksto", value: nil, table: "Generataj"),
Bundle.main.localizedString(forKey: "informoj fakaj-mallongigoj teksto", value: nil, table: "Generataj")
]
case .PoshReVo:
let versioTeksto = String(format: NSLocalizedString("informoj versio", comment: ""), arguments: [ (Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String) ?? "" ])
tekstoj = [
String(format: NSLocalizedString("informoj poshrevo teksto", comment: ""), versioTeksto)
]
}
return tekstoj[numero]
}
public func destino(numero: Int) -> InformojPaghoViewController {
let pagho = InformojPaghoViewController(titolo: titolo(numero: numero), teksto: teksto(numero: numero))
return pagho
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
efektivigiStilon()
}
}
// MARK: - UITableViewDelegate & UITableViewDatasource
extension InformojTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sekcio = Sekcio.deNumero(section)
return sekcio.chelKvanto()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let chelo = tableView.dequeueReusableCell(withIdentifier: "chelo") ?? UITableViewCell()
let sekcio = Sekcio.deNumero(indexPath.section)
chelo.textLabel?.text = sekcio.titolo(numero: indexPath.row)
chelo.backgroundColor = UzantDatumaro.stilo.bazKoloro
chelo.textLabel?.textColor = UzantDatumaro.stilo.tekstKoloro
return chelo
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let sekcio = Sekcio.deNumero(indexPath.section)
let destino = sekcio.destino(numero: indexPath.row)
navigationController?.pushViewController(destino, animated: true)
}
// MARK: Chefpagho
func aranghiNavigaciilo() {
parent?.title = NSLocalizedString("informoj titolo", comment: "")
parent?.navigationItem.rightBarButtonItem = nil
}
}
| 6d5a25165b0b35050a2bcc962dad06d4 | 32.820313 | 193 | 0.568723 | false | false | false | false |
onmyway133/Github.swift | refs/heads/master | Carthage/Checkouts/Tailor/Sources/Shared/Extensions/Dictionary+Tailor.swift | mit | 1 | import Sugar
// MARK: - Basic
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it returns nil
*/
func property<T>(name: String) -> T? {
guard let key = name as? Key,
value = self[key] as? T
else { return nil }
return value
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it throws
*/
func propertyOrThrow<T>(name: String) throws -> T {
guard let result: T = property(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
/**
- Parameter name: The name of the property that you want to map
- Parameter transformer: A transformation closure
- Returns: A generic type if casting succeeds, otherwise it returns nil
*/
func transform<T, U>(name: String, transformer: ((value: U) -> T?)) -> T? {
guard let key = name as? Key,
value = self[key] as? U
else { return nil }
return transformer(value: value)
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object directory, otherwise it returns nil
*/
func directory<T : Mappable>(name: String) -> [String : T]? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
var directory = [String : T]()
for (key, value) in dictionary {
guard let value = value as? JSONDictionary else { continue }
directory[key] = T(value)
}
return directory
}
/**
- Parameter name: The name of the key
- Returns: A child dictionary for that key, otherwise it returns nil
*/
func dictionary(name: String) -> JSONDictionary? {
guard let key = name as? Key,
value = self[key] as? JSONDictionary
else { return nil }
return value
}
/**
- Parameter name: The name of the key
- Returns: A child dictionary for that key, otherwise it throws
*/
func dictionaryOrThrow(name: String) throws -> JSONDictionary {
guard let result = dictionary(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as JSONDictionary") }
return result
}
/**
- Parameter name: The name of the key
- Returns: A child array for that key, otherwise it returns nil
*/
func array(name: String) -> JSONArray? {
guard let key = name as? Key,
value = self[key] as? JSONArray
else { return nil }
return value
}
/**
- Parameter name: The name of the key
- Returns: A child array for that key, otherwise it throws
*/
func arrayOrThrow(name: String) throws -> JSONArray {
guard let result = array(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as JSONArray") }
return result
}
/**
- Parameter name: The name of the key
- Returns: An enum if casting succeeds, otherwise it returns nil
*/
func `enum`<T: RawRepresentable>(name: String) -> T? {
guard let key = name as? Key,
value = self[key] as? T.RawValue
else { return nil }
return T(rawValue: value)
}
/**
- Parameter name: The name of the key
- Returns: An enum if casting succeeds, otherwise it throws
*/
func enumOrThrow<T: RawRepresentable>(name: String) throws -> T {
guard let result: T = `enum`(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as enum") }
return result
}
}
// MARK: - Relation
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object, otherwise it returns nil
*/
func relation<T : Mappable>(name: String) -> T? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
return T(dictionary)
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it throws
*/
func relationOrThrow<T : Mappable>(name: String) throws -> T {
guard let result: T = relation(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object, otherwise it returns nil
*/
func relation<T : SafeMappable>(name: String) -> T? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
let result: T?
do {
result = try T(dictionary)
} catch {
result = nil
}
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A generic type if casting succeeds, otherwise it throws
*/
func relationOrThrow<T : SafeMappable>(name: String) throws -> T {
guard let result: T = relation(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
}
// MARK: - Relations
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it returns nil
*/
func relations<T : Mappable>(name: String) -> [T]? {
guard let key = name as? Key,
array = self[key] as? JSONArray
else { return nil }
return array.map { T($0) }
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it throws
*/
func relationsOrThrow<T : Mappable>(name: String) throws -> [T] {
guard let result: [T] = relations(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it returns nil
*/
func relations<T : SafeMappable>(name: String) -> [T]? {
guard let key = name as? Key,
array = self[key] as? JSONArray
else { return nil }
var result = [T]()
do {
result = try array.map { try T($0) }
} catch {}
return result
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, otherwise it throws
*/
func relationsOrThrow<T : SafeMappable>(name: String) throws -> [T] {
guard let result: [T] = relations(name)
else { throw MappableError.TypeError(message: "Tried to get value for \(name) as \(T.self)") }
return result
}
}
// MARK: - Relation Hierarchically
public extension Dictionary {
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object, considering hierarchy, otherwise it returns nil
*/
func relationHierarchically<T where T: Mappable, T: HierarchyType>(name: String) -> T? {
guard let key = name as? Key,
dictionary = self[key] as? JSONDictionary
else { return nil }
return T.cluster(dictionary) as? T
}
/**
- Parameter name: The name of the property that you want to map
- Returns: A mappable object array, considering hierarchy, otherwise it returns nil
*/
func relationsHierarchically<T where T: Mappable, T: HierarchyType>(name: String) -> [T]? {
guard let key = name as? Key,
array = self[key] as? JSONArray
else { return nil }
return array.flatMap { T.cluster($0) as? T }
}
}
| 2a1504e46c430725a7e6e1a891934284 | 26.752727 | 105 | 0.641116 | false | false | false | false |
lakesoft/LKUserDefaultOption | refs/heads/master | Pod/Classes/LKUserDefaultOptionSwitch.swift | mit | 1 | //
// LKUserDefaultOptionBool.swift
// Pods
//
// Created by Hiroshi Hashiguchi on 2015/10/11.
//
//
public class LKUserDefaultOptionSwitch:LKUserDefaultOption {
public var optionValue:Bool = false
// MARK: - LKUserDefaultOptionModel
public override func save() {
saveUserDefaults(optionValue)
}
public override func restore() {
if let value = restoreUserDefaults() as? Bool {
optionValue = value
}
}
public override func setValue(value:AnyObject) {
if let value = value as? Bool {
optionValue = value
}
}
public override func value() -> AnyObject? {
return optionValue
}
public override func setDefaultValue(defaultValue: AnyObject) {
if let defaultValue = defaultValue as? Bool {
optionValue = defaultValue
}
}
}
| c8c65a899ca276fb9f9b9ea1d6224c8c | 22.289474 | 67 | 0.613559 | false | false | false | false |
mohonish/MCPushUpPopupTransition | refs/heads/master | Pod/Classes/BlurDismissAnimationController.swift | mit | 1 | //
// BlurDismissAnimationController.swift
// Pods
//
// Created by Mohonish Chakraborty on 29/03/16.
//
//
import Foundation
import UIKit
public class BlurDismissAnimationController: NSObject, UIViewControllerAnimatedTransitioning {
let duration: NSTimeInterval!
let alphaValue: CGFloat!
public init(duration: NSTimeInterval, alphaValue: CGFloat) {
self.duration = duration
self.alphaValue = alphaValue
}
// MARK: - UIViewControllerAnimatedTransitioning
public func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return self.duration
}
public func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
let toViewController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
let finalFrameForVC = transitionContext.finalFrameForViewController(toViewController!)
toViewController!.view.frame = finalFrameForVC
let bounds = UIScreen.mainScreen().bounds
let fromFinalFrame = CGRectOffset(fromViewController!.view.frame, 0, bounds.size.height)
UIView.animateWithDuration(transitionDuration(transitionContext), animations: {
toViewController!.view.viewWithTag(151)!.alpha = 0
fromViewController!.view.frame = fromFinalFrame
}, completion: { (finished) in
toViewController!.view.viewWithTag(151)?.removeFromSuperview()
transitionContext.completeTransition(true)
})
}
} | ed3c8529d1190355fb37fb61141421b7 | 34.06 | 113 | 0.707192 | false | false | false | false |
certainly/Caculator | refs/heads/master | Smashtag/Twitter/Twitter/Request.swift | mit | 3 | //
// TwitterRequest.swift
// Twitter
//
// Created by CS193p Instructor.
// Copyright (c) 2015-17 Stanford University. All rights reserved.
//
import Foundation
import Accounts
import Social
import CoreLocation
// Simple Twitter query class
// Create an instance of it using one of the initializers
// Set the requestType and parameters (if not using a convenience init that sets those)
// Call fetch (or fetchTweets if fetching Tweets)
// The handler passed in will be called when the information comes back from Twitter
// Once a successful fetch has happened,
// a follow-on TwitterRequest to get more Tweets (newer or older) can be created
// using the requestFor{Newer,Older} methods
private var twitterAccount: ACAccount?
public class Request: NSObject
{
public let requestType: String
public let parameters: [String:String]
public var searchTerm: String? {
return parameters[TwitterKey.query]?.components(separatedBy: "-").first?.trimmingCharacters(in: CharacterSet.whitespaces)
}
public enum SearchResultType: Int {
case mixed
case recent
case popular
}
// designated initializer
public init(_ requestType: String, _ parameters: Dictionary<String, String> = [:]) {
self.requestType = requestType
self.parameters = parameters
}
// convenience initializer for creating a TwitterRequest that is a search for Tweets
public convenience init(search: String, count: Int = 0) { // , resultType resultType: SearchResultType = .Mixed, region region: CLCircularRegion? = nil) {
var parameters = [TwitterKey.query : search]
if count > 0 {
parameters[TwitterKey.count] = "\(count)"
}
// switch resultType {
// case .Recent: parameters[TwitterKey.ResultType] = TwitterKey.ResultTypeRecent
// case .Popular: parameters[TwitterKey.ResultType] = TwitterKey.ResultTypePopular
// default: break
// }
// if let geocode = region {
// parameters[TwitterKey.Geocode] = "\(geocode.center.latitude),\(geocode.center.longitude),\(geocode.radius/1000.0)km"
// }
self.init(TwitterKey.searchForTweets, parameters)
}
// convenience "fetch" for when self is a request that returns Tweet(s)
// handler is not necessarily invoked on the main queue
public func fetchTweets(_ handler: @escaping ([Tweet]) -> Void) {
fetch { results in
var tweets = [Tweet]()
var tweetArray: NSArray?
if let dictionary = results as? NSDictionary {
if let tweets = dictionary[TwitterKey.tweets] as? NSArray {
tweetArray = tweets
} else if let tweet = Tweet(data: dictionary) {
tweets = [tweet]
}
} else if let array = results as? NSArray {
tweetArray = array
}
if tweetArray != nil {
for tweetData in tweetArray! {
if let tweet = Tweet(data: tweetData as? NSDictionary) {
tweets.append(tweet)
}
}
}
handler(tweets)
}
}
public typealias PropertyList = Any
// send the request specified by our requestType and parameters off to Twitter
// calls the handler (not necessarily on the main queue)
// with the JSON results converted to a Property List
public func fetch(_ handler: @escaping (PropertyList?) -> Void) {
performTwitterRequest(.GET, handler: handler)
}
// generates a request for older Tweets than were returned by self
// only makes sense if self has completed a fetch already
// only makes sense for requests for Tweets
public var older: Request? {
if min_id == nil {
if parameters[TwitterKey.maxID] != nil {
return self
}
} else {
return modifiedRequest(parametersToChange: [TwitterKey.maxID : min_id!])
}
return nil
}
// generates a request for newer Tweets than were returned by self
// only makes sense if self has completed a fetch already
// only makes sense for requests for Tweets
public var newer: Request? {
if max_id == nil {
if parameters[TwitterKey.sinceID] != nil {
return self
}
} else {
return modifiedRequest(parametersToChange: [TwitterKey.sinceID : max_id!], clearCount: true)
}
return nil
}
// MARK: - Internal Implementation
// creates an appropriate SLRequest using the specified SLRequestMethod
// then calls the other version of this method that takes an SLRequest
// handler is not necessarily called on the main queue
func performTwitterRequest(_ method: SLRequestMethod, handler: @escaping (PropertyList?) -> Void) {
let jsonExtension = (self.requestType.range(of: Constants.JSONExtension) == nil) ? Constants.JSONExtension : ""
let url = URL(string: "\(Constants.twitterURLPrefix)\(self.requestType)\(jsonExtension)")
if let request = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: method, url: url, parameters: parameters) {
performTwitterSLRequest(request, handler: handler)
}
}
// sends the request to Twitter
// unpackages the JSON response into a Property List
// and calls handler (not necessarily on the main queue)
func performTwitterSLRequest(_ request: SLRequest, handler: @escaping (PropertyList?) -> Void) {
if let account = twitterAccount {
request.account = account
request.perform { (jsonResponse, httpResponse, _) in
var propertyListResponse: PropertyList?
if jsonResponse != nil {
propertyListResponse = try? JSONSerialization.jsonObject(with: jsonResponse!, options: .mutableLeaves)
if propertyListResponse == nil {
let error = "Couldn't parse JSON response."
self.log(error)
propertyListResponse = error
}
} else {
let error = "No response from Twitter."
self.log(error)
propertyListResponse = error
}
self.synchronize {
self.captureFollowonRequestInfo(propertyListResponse)
}
handler(propertyListResponse)
}
} else {
let accountStore = ACAccountStore()
let twitterAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: twitterAccountType, options: nil) { (granted, _) in
if granted {
if let account = accountStore.accounts(with: twitterAccountType)?.last as? ACAccount {
twitterAccount = account
self.performTwitterSLRequest(request, handler: handler)
} else {
let error = "Couldn't discover Twitter account type."
self.log(error)
handler(error)
}
} else {
let error = "Access to Twitter was not granted."
self.log(error)
handler(error)
}
}
}
}
private var min_id: String? = nil
private var max_id: String? = nil
// modifies parameters in an existing request to create a new one
private func modifiedRequest(parametersToChange: Dictionary<String,String>, clearCount: Bool = false) -> Request {
var newParameters = parameters
for (key, value) in parametersToChange {
newParameters[key] = value
}
if clearCount { newParameters[TwitterKey.count] = nil }
return Request(requestType, newParameters)
}
// captures the min_id and max_id information
// to support requestForNewer and requestForOlder
private func captureFollowonRequestInfo(_ propertyListResponse: PropertyList?) {
if let responseDictionary = propertyListResponse as? NSDictionary {
self.max_id = responseDictionary.value(forKeyPath: TwitterKey.SearchMetadata.maxID) as? String
if let next_results = responseDictionary.value(forKeyPath: TwitterKey.SearchMetadata.nextResults) as? String {
for queryTerm in next_results.components(separatedBy: TwitterKey.SearchMetadata.separator) {
if queryTerm.hasPrefix("?\(TwitterKey.maxID)=") {
let next_id = queryTerm.components(separatedBy: "=")
if next_id.count == 2 {
self.min_id = next_id[1]
}
}
}
}
}
}
// debug println with identifying prefix
private func log(_ whatToLog: Any) {
debugPrint("TwitterRequest: \(whatToLog)")
}
// synchronizes access to self across multiple threads
private func synchronize(_ closure: () -> Void) {
objc_sync_enter(self)
closure()
objc_sync_exit(self)
}
// constants
private struct Constants {
static let JSONExtension = ".json"
static let twitterURLPrefix = "https://api.twitter.com/1.1/"
}
// keys in Twitter responses/queries
struct TwitterKey {
static let count = "count"
static let query = "q"
static let tweets = "statuses"
static let resultType = "result_type"
static let resultTypeRecent = "recent"
static let resultTypePopular = "popular"
static let geocode = "geocode"
static let searchForTweets = "search/tweets"
static let maxID = "max_id"
static let sinceID = "since_id"
struct SearchMetadata {
static let maxID = "search_metadata.max_id_str"
static let nextResults = "search_metadata.next_results"
static let separator = "&"
}
}
}
| 30be1fb5c8546c58de88a5781833e82c | 38.169811 | 158 | 0.59711 | false | false | false | false |
BlueCocoa/Maria | refs/heads/master | Maria/TaskListViewController.swift | gpl-3.0 | 1 | //
// TaskListViewController.swift
// Maria
//
// Created by ShinCurry on 16/5/10.
// Copyright © 2016年 ShinCurry. All rights reserved.
//
import Cocoa
import Aria2RPC
import SwiftyJSON
class TaskListViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
let nib = NSNib(nibNamed: "TaskCellView", bundle: Bundle.main)
taskListTableView.register(nib!, forIdentifier: "TaskCell")
taskListTableView.rowHeight = 64
taskListTableView.selectionHighlightStyle = .none
aria2Config()
alertConnectButton.attributedTitle = NSAttributedString(string: NSLocalizedString("aria2.status.disconnected.tryNow", comment: ""), attributes: [NSForegroundColorAttributeName: NSColor(calibratedRed: 0.000, green: 0.502, blue: 0.753, alpha: 1.00), NSFontAttributeName: NSFont.systemFont(ofSize: 14)])
}
override func viewWillAppear() {
runTimer()
}
override func viewWillDisappear() {
closeTimer()
}
var timer: Timer!
var timeToConnectAria = 4
var countdownTimeToConnectAria = 4
let maria = Maria.shared
var currentStatus: ConnectionStatus = .disconnected
typealias NumberOfTask = (active: Int,waiting: Int,stopped: Int)
var numberOfTask: NumberOfTask = (0, 0, 0)
typealias TaskData = (active: [Aria2Task], waiting: [Aria2Task], stopped: [Aria2Task])
var taskData: [Aria2Task] = []
var newTaskData: TaskData = ([], [], [])
let selectedColor = NSColor(calibratedRed: 211.0/255.0, green: 231.0/255.0, blue: 250.0/255.0, alpha: 1.0).cgColor
@IBOutlet weak var alertLabel: NSTextField!
@IBOutlet weak var alertConnectButton: NSButton!
@IBOutlet weak var taskListTableView: NSTableView!
@IBOutlet weak var globalSpeedLabel: NSTextField!
@IBOutlet weak var globalTaskNumberLabel: NSTextField!
override func keyDown(with theEvent: NSEvent) {
// esc key pressed
if theEvent.keyCode == 53 {
taskListTableView.deselectRow(taskListTableView.selectedRow)
}
}
@IBAction func connectToAria(_ sender: NSButton) {
maria.rpc?.connect()
}
}
extension TaskListViewController {
func updateListStatus() {
// if let core = maria.core {
// print("---core---")
// if let tasks = core.getActiveDownload() {
// print(tasks)
// } else {
// print("nil")
// }
// }
switch maria.rpc!.status {
case .disconnected:
countdownTimeToConnectAria -= 1
if countdownTimeToConnectAria == 0 {
maria.rpc?.connect()
timeToConnectAria *= 2
countdownTimeToConnectAria = timeToConnectAria
} else {
let localized = NSLocalizedString("aria2.status.disconnected", comment: "")
alertLabel.stringValue = String(format: localized, countdownTimeToConnectAria)
}
case .connected:
timeToConnectAria = 4
countdownTimeToConnectAria = 4
maria.rpc?.tellActive()
maria.rpc?.tellWaiting()
maria.rpc?.tellStopped()
maria.rpc?.getGlobalStatus()
maria.rpc?.onGlobalStatus = { status in
let activeNumber = status.numberOfActiveTask!
let totalNumber = status.numberOfActiveTask! + status.numberOfWaitingTask!
self.globalTaskNumberLabel.stringValue = "\(activeNumber) of \(totalNumber) download(s)"
self.globalSpeedLabel.stringValue = "⬇︎ " + status.speed!.downloadString + " ⬆︎ " + status.speed!.uploadString
}
default:
break
}
}
func aria2Config() {
maria.rpc?.onActives = {
guard let tasks = $0 else {
return
}
self.newTaskData.active = tasks
}
maria.rpc?.onWaitings = {
guard let tasks = $0 else {
return
}
self.newTaskData.waiting = tasks
}
maria.rpc?.onStoppeds = {
guard let tasks = $0 else {
return
}
self.newTaskData.stopped = tasks.filter({ return !($0.title!.range(of: "[METADATA]") != nil && $0.status! == "complete") })
self.updateListView()
}
maria.rpc?.onStatusChanged = {
if self.maria.rpc?.status == .connecting || self.maria.rpc?.status == .disconnected {
self.taskData = []
self.numberOfTask = (0, 0, 0)
self.taskListTableView.reloadData()
}
switch self.maria.rpc!.status {
case .connecting:
self.alertLabel.isHidden = false
self.alertLabel.stringValue = NSLocalizedString("aria2.status.connecting", comment: "")
self.alertConnectButton.isHidden = true
case .connected:
self.alertLabel.isHidden = true
self.alertLabel.isHidden = true
case .unauthorized:
self.alertLabel.isHidden = false
self.alertLabel.stringValue = NSLocalizedString("aria2.status.unauthorized", comment: "")
self.alertConnectButton.isHidden = true
case .disconnected:
self.alertLabel.isHidden = false
self.alertConnectButton.isHidden = false
}
}
}
}
// MARK: - Timer Config
extension TaskListViewController {
fileprivate func runTimer() {
updateListStatus()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateListStatus), userInfo: nil, repeats: true)
}
fileprivate func closeTimer() {
timer.invalidate()
timer = nil
}
}
// MARK: - TableView Config
extension TaskListViewController: NSTableViewDelegate, NSTableViewDataSource {
func updateListView() {
let flag = (numberOfTask.active != newTaskData.active.count) ||
(numberOfTask.waiting != newTaskData.waiting.count) ||
(numberOfTask.stopped != newTaskData.stopped.count)
numberOfTask.active = newTaskData.active.count
numberOfTask.waiting = newTaskData.waiting.count
numberOfTask.stopped = newTaskData.stopped.count
taskData = newTaskData.active + newTaskData.waiting + newTaskData.stopped
if flag {
taskListTableView.reloadData()
if let controller = self.view.window?.windowController as? MainWindowController {
controller.taskCleanButton.isEnabled = (numberOfTask.stopped != 0)
}
} else {
for index in 0..<taskData.count {
if let cell = taskListTableView.view(atColumn: 0, row: index, makeIfNecessary: true) as?TaskCellView {
cell.update(taskData[index])
}
}
}
// NSApplication.shared().dockTile.badgeLabel = (numberOfTask.active == 0 ? nil : "\(numberOfTask.active)")
}
func updateTasksStatus(_ status: String) {
for index in 0..<taskData.count {
if let cell = taskListTableView.view(atColumn: 0, row: index, makeIfNecessary: true) as? TaskCellView {
cell.status = status
}
}
}
func numberOfRows(in tableView: NSTableView) -> Int {
return taskData.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let cell = tableView.make(withIdentifier: "TaskCell", owner: self) as? TaskCellView else {
fatalError("Unexpected cell type at \(row)")
}
cell.update(taskData[row])
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
if let controller = self.view.window?.windowController as? MainWindowController {
controller.taskRemoveButton.isEnabled = (taskListTableView.selectedRowIndexes.count > 0)
}
for row in 0..<taskListTableView.numberOfRows {
let cell = taskListTableView.view(atColumn: 0, row: row, makeIfNecessary: true) as! TaskCellView
cell.wantsLayer = true
if taskListTableView.selectedRowIndexes.contains(row) {
cell.layer?.backgroundColor = selectedColor
} else {
cell.layer?.backgroundColor = NSColor.clear.cgColor
}
}
}
}
| c1a7e3ee5f40f948a892ade2ed825526 | 35.881356 | 308 | 0.594899 | false | false | false | false |
sunlijian/sinaBlog_repository | refs/heads/master | sinaBlog_sunlijian/sinaBlog_sunlijian/Classes/Module/Compose/View/IWComposePhotoView.swift | apache-2.0 | 1 |
//
// IWComposePhotoView.swift
// sinaBlog_sunlijian
//
// Created by sunlijian on 15/10/22.
// Copyright © 2015年 myCompany. All rights reserved.
//
import UIKit
class IWComposePhotoView: UIImageView {
override init(image: UIImage?) {
super.init(image: image)
//添加按钮
addSubview(deleteButton)
//设置可以用户交互
userInteractionEnabled = true
}
//懒加载
private lazy var deleteButton: UIButton = {
let button = UIButton()
//设置图片
button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
//设置大小
button.sizeToFit()
//添加点击事件
button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
//button 的点击事件
@objc private func deleteButtonClick(){
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.alpha = 0
}) { (finished) -> Void in
self.removeFromSuperview()
}
}
//设置按钮的位置
override func layoutSubviews() {
super.layoutSubviews()
deleteButton.x = width - deleteButton.width
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 9a146a371e59c716d83f29442ba47ce0 | 22.928571 | 108 | 0.595522 | false | false | false | false |
eric1202/LZJ_Coin | refs/heads/master | DinDinShopDemo/Pods/XCGLogger/Sources/XCGLogger/Destinations/TestDestination.swift | mit | 3 | //
// TestDestination.swift
// XCGLogger: https://github.com/DaveWoodCom/XCGLogger
//
// Created by Dave Wood on 2016-08-26.
// Copyright © 2016 Dave Wood, Cerebral Gardens.
// Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt
//
import Dispatch
// MARK: - TestDestination
/// A destination for testing, preload it with the expected logs, send your logs, then check for success
open class TestDestination: BaseQueuedDestination {
// MARK: - Properties
/// Array of all expected log messages
open var expectedLogMessages: [String] = []
/// Array of received, unexpected log messages
open var unexpectedLogMessages: [String] = []
/// Number of log messages still expected
open var remainingNumberOfExpectedLogMessages: Int {
get {
return expectedLogMessages.count
}
}
/// Number of unexpected log messages
open var numberOfUnexpectedLogMessages: Int {
get {
return unexpectedLogMessages.count
}
}
/// Add the messages you expect to be logged
///
/// - Parameters:
/// - expectedLogMessage: The log message, formated as you expect it to be received.
///
/// - Returns: Nothing
///
open func add(expectedLogMessage message: String) {
sync {
expectedLogMessages.append(message)
}
}
/// Execute a closure on the logQueue if it exists, otherwise just execute on the current thread
///
/// - Parameters:
/// - closure: The closure to execute.
///
/// - Returns: Nothing
///
fileprivate func sync(closure: () -> ()) {
if let logQueue = logQueue {
logQueue.sync {
closure()
}
}
else {
closure()
}
}
/// Reset our expections etc for additional tests
///
/// - Parameters: Nothing
///
/// - Returns: Nothing
///
open func reset() {
haveLoggedAppDetails = false
expectedLogMessages = []
unexpectedLogMessages = []
}
// MARK: - Overridden Methods
/// Removes line from expected log messages if there's a match, otherwise adds to unexpected log messages.
///
/// - Parameters:
/// - logDetails: The log details.
/// - message: Formatted/processed message ready for output.
///
/// - Returns: Nothing
///
open override func output(logDetails: LogDetails, message: String) {
sync {
var logDetails = logDetails
var message = message
// Apply filters, if any indicate we should drop the message, we abort before doing the actual logging
if self.shouldExclude(logDetails: &logDetails, message: &message) {
return
}
applyFormatters(logDetails: &logDetails, message: &message)
let index = expectedLogMessages.index(of: message)
if let index = index {
expectedLogMessages.remove(at: index)
}
else {
unexpectedLogMessages.append(message)
}
}
}
}
| 4fe5794c08a9ddb093e8b1d1672c7f9c | 28.330275 | 114 | 0.587426 | false | false | false | false |
ps12138/dribbbleAPI | refs/heads/master | Model/User.swift | mit | 1 | //
// User.swift
// DribbbleModuleFramework
//
// Created by PSL on 12/7/16.
// Copyright © 2016 PSL. All rights reserved.
//
import Foundation
open class User {
open let id: Int
open let name: String?
open let userName: String?
open let html_url: String?
open let avatar_url: String?
open let bio: String?
open let location: String
open let linkDict: Dictionary<String, String>?
open var linkArray: [(title: String, urlString: String)]?
open let buckets_count: Int
open let comments_received_count: Int
open let followers_count: Int
open let followings_count: Int
open let likes_count: Int
open let likes_received_count: Int
open let projects_count: Int
open let rebounds_received_count: Int
open let shots_count: Int
open let teams_count: Int
init?(dict: Dictionary<String, AnyObject>?) {
guard let id = dict?[UserKey.id] as? Int,
let userName = dict?[UserKey.username] as? String,
let buckets_count = dict?[UserKey.buckets_count] as? Int,
let comments_received_count = dict?[UserKey.comments_received_count] as? Int,
let followers_count = dict?[UserKey.followers_count] as? Int,
let followings_count = dict?[UserKey.followings_count] as? Int,
let likes_count = dict?[UserKey.likes_count] as? Int,
let likes_received_count = dict?[UserKey.likes_received_count] as? Int,
let projects_count = dict?[UserKey.projects_count] as? Int,
let rebounds_received_count = dict?[UserKey.rebounds_received_count] as? Int,
let shots_count = dict?[UserKey.shots_count] as? Int,
let teams_count = dict?[UserKey.teams_count] as? Int
else {
return nil
}
self.id = id
self.name = dict?[UserKey.name] as? String
self.userName = userName
self.html_url = dict?[UserKey.html_url] as? String
self.avatar_url = dict?[UserKey.avatar_url] as? String
self.bio = dict?[UserKey.bio] as? String
self.location = (dict?[UserKey.location] as? String) ?? "unknown"
self.linkDict = dict?[UserKey.links] as? Dictionary<String, String>
self.buckets_count = buckets_count
self.comments_received_count = comments_received_count
self.followers_count = followers_count
self.followings_count = followings_count
self.likes_count = likes_count
self.likes_received_count = likes_received_count
self.projects_count = projects_count
self.rebounds_received_count = rebounds_received_count
self.shots_count = shots_count
self.teams_count = teams_count
}
open var links: [(title: String, urlString: String)]? {
if let validLinks = linkArray {
return validLinks
} else {
return convertFrom(dict: linkDict)
}
}
private func convertFrom(dict: Dictionary<String, String>?) -> [(title: String, urlString: String)]? {
guard let validDict = dict else {
return nil
}
var result = [(title: String, urlString: String)]()
for (key, value) in validDict {
result.append((title: key, urlString: value))
}
return result
}
}
| 1d4e2dd3e5f0eeaf4a7b996da0cbdb29 | 34.252632 | 106 | 0.617796 | false | false | false | false |
ioscreator/ioscreator | refs/heads/master | IOSPopoverTutorial/IOSPopoverTutorial/ViewController.swift | mit | 1 | //
// ViewController.swift
// IOSPopoverTutorial
//
// Created by Arthur Knopper on 03/05/2019.
// Copyright © 2019 Arthur Knopper. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBAction func displayPopover(_ sender: UIBarButtonItem) {
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "PopoverViewController")
vc.modalPresentationStyle = .popover
let popover: UIPopoverPresentationController = vc.popoverPresentationController!
popover.barButtonItem = sender
present(vc, animated: true, completion:nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
| 24d7a06e1c7be5c04bc3fa5f4c0c02dd | 28.321429 | 94 | 0.700365 | false | false | false | false |
qingtianbuyu/Mono | refs/heads/master | Moon/Classes/Main/Model/MNMode.swift | mit | 1 | //
// MNMode.swift
// Moon
//
// Created by YKing on 16/6/4.
// Copyright © 2016年 YKing. All rights reserved.
//
import UIKit
class MNMode: MNBanner {
var group: MNGroup?
var campaign: MNRefCampaign?
override init(dict: [String: AnyObject]) {
super.init(dict: dict)
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forKey key: String) {
if key == "group" {
group = MNGroup(dict: (value as! [String: AnyObject]))
return
}
if key == "campaign" {
campaign = MNRefCampaign(dict: (value as! [String: AnyObject]))
return
}
super.setValue(value, forKey: key)
}
}
| caed450d53f32ad6e9beb0c2186c98ce | 17.527778 | 69 | 0.596702 | false | false | false | false |
damicreabox/Git2Swift | refs/heads/master | Sources/Git2Swift/repository/Repository+Lookup.swift | apache-2.0 | 1 | //
// Repository+Lookup.swift
// Git2Swift
//
// Created by Dami on 31/07/2016.
//
//
import Foundation
import CLibgit2
/// Git reference lookup
///
/// - parameter repository: Libgit2 repository pointer
/// - parameter name: Reference name
///
/// - throws: GitError
///
/// - returns: Libgit2 reference pointer
internal func gitReferenceLookup(repository: UnsafeMutablePointer<OpaquePointer?>,
name: String) throws -> UnsafeMutablePointer<OpaquePointer?> {
// Find reference pointer
let reference = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
// Lookup reference
let error = git_reference_lookup(reference, repository.pointee, name)
if (error != 0) {
reference.deinitialize()
reference.deallocate(capacity: 1)
// 0 on success, GIT_ENOTFOUND, GIT_EINVALIDSPEC or an error code.
switch (error) {
case GIT_ENOTFOUND.rawValue :
throw GitError.notFound(ref: name)
case GIT_EINVALIDSPEC.rawValue:
throw GitError.invalidSpec(spec: name)
default:
throw gitUnknownError("Unable to lookup reference \(name)", code: error)
}
}
return reference
}
// MARK: - Repository extension for lookup
extension Repository {
/// Lookup reference
///
/// - parameter name: Refrence name
///
/// - throws: GitError
///
/// - returns: Refernce
public func referenceLookup(name: String) throws -> Reference {
return try Reference(repository: self, name: name, pointer: try gitReferenceLookup(repository: pointer, name: name))
}
/// Lookup a tree
///
/// - parameter tree_id: Tree OID
///
/// - throws: GitError
///
/// - returns: Tree
public func treeLookup(oid tree_id: OID) throws -> Tree {
// Create tree
let tree : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
var oid = tree_id.oid
let error = git_tree_lookup(tree, pointer.pointee, &oid)
if (error != 0) {
tree.deinitialize()
tree.deallocate(capacity: 1)
throw gitUnknownError("Unable to lookup tree", code: error)
}
return Tree(repository: self, tree: tree)
}
/// Lookup a commit
///
/// - parameter commit_id: OID
///
/// - throws: GitError
///
/// - returns: Commit
public func commitLookup(oid commit_id: OID) throws -> Commit {
// Create tree
let commit : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
var oid = commit_id.oid
let error = git_commit_lookup(commit, pointer.pointee, &oid)
if (error != 0) {
commit.deinitialize()
commit.deallocate(capacity: 1)
throw gitUnknownError("Unable to lookup commit", code: error)
}
return Commit(repository: self, pointer: commit, oid: OID(withGitOid: oid))
}
/// Lookup a blob
///
/// - parameter blob_id: OID
///
/// - throws: GitError
///
/// - returns: Blob
public func blobLookup(oid blob_id: OID) throws -> Blob {
// Create tree
let blob : UnsafeMutablePointer<OpaquePointer?> = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
var oid = blob_id.oid
let error = git_blob_lookup(blob, pointer.pointee, &oid)
if error != 0 {
blob.deinitialize()
blob.deallocate(capacity: 1)
throw gitUnknownError("Unable to lookup blob", code: error)
}
return Blob(blob: blob)
}
}
| 083d2a6ca83c2abe3a442d14cbde91b6 | 27.333333 | 124 | 0.585098 | false | false | false | false |
carlynorama/learningSwift | refs/heads/main | Playgrounds/SimpleInfoChecking_iOS10.playground/Contents.swift | unlicense | 1 | //Array, Dictionary Scratch Pad, Swift Xcode 8 Beta 6
//2016. 08
//carlynorama, license: CC0
//https://www.udemy.com/complete-ios-10-developer-course/
//https://developer.apple.com/reference/swift/dictionary
//https://www.hackingwithswift.com/new-syntax-swift-2-error-handling-try-catch
import UIKit
let stringVar:String? = nil
stringVar ?? "a default string" // if string var is not nill return stringVar, else return default
enum UserProfileError: Error {
case UserNotFound
case BadPass
case NietherSupplied
case OneNotSupplied
}
//SCOPE!!! These must be outside do to be used also by the catches.
let enteredUser = "GeorgeJettson"
let enteredPassword = "partparty"
func checkUser(user: String, withPassword password: String) throws -> String {
guard !password.isEmpty && !user.isEmpty else { throw UserProfileError.NietherSupplied }
guard !password.isEmpty || !user.isEmpty else { throw UserProfileError.OneNotSupplied }
var userVerified = Bool()
var passwordVerified = Bool()
if user == "GeorgeJettson" { userVerified = true; } else { userVerified = false }
//if password == "partyparty" { passwordVerified = true } else { passwordVerified = false }
//a >= 0 ? doThis(): doThat()
password == "partyparty" ? (passwordVerified = true) : (passwordVerified = false)
guard userVerified else { throw UserProfileError.UserNotFound }
guard passwordVerified else { throw UserProfileError.BadPass }
//let welcomeMessage =
return "Welcome \(enteredUser). Please enjoy the show."}
do {
defer { print("Shutting the door.") }
let verificationMessage = try checkUser(user: enteredUser, withPassword: enteredPassword)
print(verificationMessage)
//other stuff
} catch UserProfileError.UserNotFound {
print("I don't recognize you.")
} catch UserProfileError.BadPass {
let message = String(format: "I'm sorry %@ that password was not correct", enteredUser)
print(message)
} catch UserProfileError.NietherSupplied {
print("I'm sorry I didn't hear anything")
} catch UserProfileError.OneNotSupplied {
print("I'm sorry, could you make sure you entered BOTH a username and password?")
} catch {
print("Something went wrong!")
}
| ffdaaf49c3cdebfebfeedc41b247d9a6 | 33.212121 | 99 | 0.713906 | false | false | false | false |
mzrimsek/school | refs/heads/master | CS49995/mzrimsek/KaleidoNav/KaleidoNav/ConfigViewController.swift | mit | 1 | //
// ConfigViewController.swift
// KaleidoTab
//
// Created by Mike Zrimsek on 4/11/17.
// Copyright © 2017 Mike Zrimsek. All rights reserved.
//
import UIKit
class ConfigViewController: UIViewController {
@IBOutlet var speedLabel: UILabel!
@IBOutlet var rectangleCountLabel: UILabel!
@IBOutlet var minDimensionLabel: UILabel!
@IBOutlet var minDimensionStepper: UIStepper!
@IBOutlet var maxDimensionLabel: UILabel!
@IBOutlet var maxDimensionStepper: UIStepper!
var kaleidoViewContoller : KaleidoViewController?
override func viewDidLoad() {
super.viewDidLoad()
kaleidoViewContoller = navigationController?.viewControllers[0] as? KaleidoViewController
}
override var prefersStatusBarHidden: Bool {
return true
}
@IBAction func updateSpeed(_ sender: UISlider) {
let displayValue = (sender.value*100).rounded()/100
let newDelay = TimeInterval(1-sender.value)
let kaleidoView = kaleidoViewContoller?.view as! KaleidoView
speedLabel.text = "(" + String(displayValue) + ")"
kaleidoView.delay = newDelay
if !(kaleidoViewContoller?.isPaused)! {
kaleidoView.stopDrawing()
kaleidoView.startDrawing()
}
}
@IBAction func updateRectangleCount(_ sender: UISlider) {
let newCount = Int(sender.value)*4
let kaleidoView = kaleidoViewContoller?.view as! KaleidoView
rectangleCountLabel.text = "(" + String(newCount) + ")"
kaleidoView.viewCount = newCount
kaleidoView.removeSubviews()
}
@IBAction func updateMinDimension(_ sender: UIStepper) {
let newMin = CGFloat(sender.value)
let kaleidoView = kaleidoViewContoller?.view as! KaleidoView
minDimensionLabel.text = "(" + String(Int(newMin)) + ")"
maxDimensionStepper.minimumValue = Double(newMin)
kaleidoView.rectMinDimension = newMin
}
@IBAction func updateMaxDimension(_ sender: UIStepper) {
let newMax = CGFloat(sender.value)
let kaleidoView = kaleidoViewContoller?.view as! KaleidoView
maxDimensionLabel.text = "(" + String(Int(newMax)) + ")"
minDimensionStepper.maximumValue = Double(newMax)
kaleidoView.rectMaxDimension = newMax
}
}
| c3af76e1e0f33adbe37e5ef92108ec60 | 30.92 | 97 | 0.648705 | false | false | false | false |
mac-cain13/R.swift | refs/heads/master | Sources/RswiftCore/Util/SwiftIdentifier.swift | mit | 2 | //
// SwiftIdentifier.swift
// R.swift
//
// Created by Mathijs Kadijk on 11-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
private let numberPrefixRegex = try! NSRegularExpression(pattern: "^[0-9]+")
private let upperCasedPrefixRegex = try! NSRegularExpression(pattern: "^([A-Z]+)(?=[^a-z]{1})")
/*
Disallowed characters: whitespace, mathematical symbols, arrows, private-use and invalid Unicode points, line- and boxdrawing characters
Special rules: Can't begin with a number
*/
struct SwiftIdentifier : CustomStringConvertible, Hashable {
let description: String
init(name: String, lowercaseStartingCharacters: Bool = true) {
// Remove all blacklisted characters from the name and uppercase the character after a blacklisted character
var nameComponents = name.components(separatedBy: blacklistedCharacters)
let firstComponent = nameComponents.remove(at: 0)
let cleanedSwiftName = nameComponents.reduce(firstComponent) { $0 + $1.uppercaseFirstCharacter }
// Remove numbers at the start of the name
let sanitizedSwiftName = numberPrefixRegex.stringByReplacingMatches(in: cleanedSwiftName, options: [], range: cleanedSwiftName.fullRange, withTemplate: "")
// Lowercase the start of the name
let capitalizedSwiftName = lowercaseStartingCharacters ? SwiftIdentifier.lowercasePrefix(sanitizedSwiftName) : sanitizedSwiftName
// Escape the name if it is a keyword
if SwiftKeywords.contains(capitalizedSwiftName) {
description = "`\(capitalizedSwiftName)`"
} else {
description = capitalizedSwiftName
}
}
init(rawValue: String) {
description = rawValue
}
private static func lowercasePrefix(_ name: String) -> String {
let prefixRange = upperCasedPrefixRegex.rangeOfFirstMatch(in: name, options: [], range: name.fullRange)
if prefixRange.location == NSNotFound {
return name.lowercaseFirstCharacter
} else {
let lowercasedPrefix = (name as NSString).substring(with: prefixRange).lowercased()
return (name as NSString).replacingCharacters(in: prefixRange, with: lowercasedPrefix)
}
}
static func +(lhs: SwiftIdentifier, rhs: SwiftIdentifier) -> SwiftIdentifier {
return SwiftIdentifier(rawValue: "\(lhs.description).\(rhs.description)")
}
}
extension SwiftIdentifier : ExpressibleByStringLiteral {
typealias StringLiteralType = String
typealias UnicodeScalarLiteralType = String
typealias ExtendedGraphemeClusterLiteralType = String
init(stringLiteral value: StringLiteralType) {
description = value
if self != SwiftIdentifier(name: value, lowercaseStartingCharacters: false) {
assertionFailure("'\(value)' not a correct SwiftIdentifier")
}
}
init(unicodeScalarLiteral value: StringLiteralType) {
description = value
}
init(extendedGraphemeClusterLiteral value: StringLiteralType) {
description = value
}
}
struct SwiftNameGroups<T> {
let uniques: [T]
let duplicates: [(SwiftIdentifier, [String])] // Identifiers that result in duplicate Swift names
let empties: [String] // Identifiers (wrapped in quotes) that result in empty swift names
func printWarningsForDuplicatesAndEmpties(source: String, container: String? = nil, result: String) {
let sourceSingular = [source, container].compactMap { $0 }.joined(separator: " ")
let sourcePlural = ["\(source)s", container].compactMap { $0 }.joined(separator: " ")
let resultSingular = result
let resultPlural = "\(result)s"
for (sanitizedName, dups) in duplicates {
warn("Skipping \(dups.count) \(sourcePlural) because symbol '\(sanitizedName)' would be generated for all of these \(resultPlural): \(dups.joined(separator: ", "))")
}
if let empty = empties.first , empties.count == 1 {
warn("Skipping 1 \(sourceSingular) because no swift identifier can be generated for \(resultSingular): \(empty)")
}
else if empties.count > 1 {
warn("Skipping \(empties.count) \(sourcePlural) because no swift identifier can be generated for all of these \(resultPlural): \(empties.joined(separator: ", "))")
}
}
}
extension Sequence {
func grouped(bySwiftIdentifier identifierSelector: @escaping (Iterator.Element) -> String) -> SwiftNameGroups<Iterator.Element> {
var groupedBy = grouped { SwiftIdentifier(name: identifierSelector($0)) }
let empty = SwiftIdentifier(name: "")
let empties = groupedBy[empty]?.map { "'\(identifierSelector($0))'" }.sorted()
groupedBy[empty] = nil
let uniques = Array(groupedBy.values.filter { $0.count == 1 }.joined())
.sorted { identifierSelector($0) < identifierSelector($1) }
let duplicates = groupedBy
.filter { $0.1.count > 1 }
.map { ($0.0, $0.1.map(identifierSelector).sorted()) }
.sorted { $0.0.description < $1.0.description }
return SwiftNameGroups(uniques: uniques, duplicates: duplicates, empties: empties ?? [])
}
}
private let blacklistedCharacters: CharacterSet = {
let blacklist = NSMutableCharacterSet(charactersIn: "")
blacklist.formUnion(with: CharacterSet.whitespacesAndNewlines)
blacklist.formUnion(with: CharacterSet.punctuationCharacters)
blacklist.formUnion(with: CharacterSet.symbols)
blacklist.formUnion(with: CharacterSet.illegalCharacters)
blacklist.formUnion(with: CharacterSet.controlCharacters)
blacklist.removeCharacters(in: "_")
// Emoji ranges, roughly based on http://www.unicode.org/Public/emoji/1.0//emoji-data.txt
[
0x2600...0x27BF,
0x1F300...0x1F6FF,
0x1F900...0x1F9FF,
0x1F1E6...0x1F1FF,
].forEach {
let range = NSRange(location: $0.lowerBound, length: $0.upperBound - $0.lowerBound)
blacklist.removeCharacters(in: range)
}
return blacklist as CharacterSet
}()
// Based on https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID413
private let SwiftKeywords = [
// Keywords used in declarations
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate", "func", "import", "init", "inout", "internal", "let", "open", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var",
// Keywords used in statements
"break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while",
// Keywords used in expressions and types
"as", "Any", "catch", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw", "throws", "true", "try",
// Keywords that begin with a number sign (#)
"#available", "#colorLiteral", "#column", "#else", "#elseif", "#endif", "#error", "#file", "#fileLiteral", "#function", "#if", "#imageLiteral", "#line", "#selector", "#sourceLocation", "#warning",
// Keywords from Swift 2 that are still reserved
"__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__",
]
| 88cd884d4bfca349ec7a8830c1dc1e2f | 39.745562 | 234 | 0.705054 | false | false | false | false |
sun409377708/swiftDemo | refs/heads/master | SinaSwiftPractice/SinaSwiftPractice/Classes/Tools/Extension/UIImage+Extension.swift | mit | 1 | //
// UIImage+Extension.swift
// SinaSwiftPractice
//
// Created by maoge on 16/11/14.
// Copyright © 2016年 maoge. All rights reserved.
//
import UIKit
extension UIImage {
//UIImage分类, 中心线切图片
class func jq_resizeableImageName(imageName: String) -> UIImage {
guard let image = UIImage(named: imageName) else {
return UIImage()
}
let w = image.size.width * 0.5
let h = image.size.height * 0.5
let edge = UIEdgeInsetsMake(h, w, h, w)
return image.resizableImage(withCapInsets: edge, resizingMode: .tile)
}
//返回缩放后的降帧视图
func jq_scaleToWidth(width: CGFloat) -> UIImage {
if self.size.width < width {
return self
}
let height = width / self.size.width * self.size.height;
let rect = CGRect(x: 0, y: 0, width: width, height: height)
UIGraphicsBeginImageContext(rect.size)
self.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
//返回缩放后的降帧视图并控制宽高
func jq_scaleToWidth(width: CGFloat, height: CGFloat) -> UIImage {
let size = self.jq_scaleOriginalImageWidth(imageWidth: width, imageHeight: height)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContext(rect.size)
self.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
//返回缩放后原视图
func jq_scaleOriginalImageWidth(imageWidth: CGFloat, imageHeight: CGFloat) -> CGSize {
let imageSize = self.size
//判断宽度
var width: CGFloat
if imageSize.width > imageWidth {
width = imageWidth
}else {
width = imageSize.width
}
//判断高度
var height = imageSize.height * width / imageSize.width
if height > imageHeight {
height = imageHeight
width = height * imageSize.width / imageSize.height
}
return CGSize(width: width, height: height)
}
//屏幕截图
class func snapShotCurrent() -> UIImage {
//截取当前屏幕
let window = (UIApplication.shared.keyWindow)!
// 1. 开启位图
UIGraphicsBeginImageContextWithOptions(window.bounds.size, false, UIScreen.main.scale)
//绘制
window.drawHierarchy(in: window.bounds, afterScreenUpdates: false)
//提取
let image = UIGraphicsGetImageFromCurrentImageContext()
//关闭
UIGraphicsEndImageContext()
return image!
}
}
| aca3d6aef5c552df9bcebb0e9b92b9fc | 24.5 | 94 | 0.5559 | false | false | false | false |
Lordxen/MagistralSwift | refs/heads/master | Carthage/Checkouts/SwiftyJSON/Tests/BaseTests.swift | apache-2.0 | 7 | // BaseTests.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import SwiftyJSON
class BaseTests: XCTestCase {
var testData: NSData!
override func setUp() {
super.setUp()
if let file = NSBundle(forClass:BaseTests.self).pathForResource("Tests", ofType: "json") {
self.testData = NSData(contentsOfFile: file)
} else {
XCTFail("Can't find the test JSON file")
}
}
override func tearDown() {
super.tearDown()
}
func testInit() {
let json0 = JSON(data:self.testData)
XCTAssertEqual(json0.array!.count, 3)
XCTAssertEqual(JSON("123").description, "123")
XCTAssertEqual(JSON(["1":"2"])["1"].string!, "2")
let dictionary = NSMutableDictionary()
dictionary.setObject(NSNumber(double: 1.0), forKey: "number" as NSString)
dictionary.setObject(NSNull(), forKey: "null" as NSString)
_ = JSON(dictionary)
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(self.testData, options: [])
let json2 = JSON(object)
XCTAssertEqual(json0, json2)
} catch _ {
}
}
func testCompare() {
XCTAssertNotEqual(JSON("32.1234567890"), JSON(32.1234567890))
XCTAssertNotEqual(JSON("9876543210987654321"),JSON(NSNumber(unsignedLongLong:9876543210987654321)))
XCTAssertNotEqual(JSON("9876543210987654321.12345678901234567890"), JSON(9876543210987654321.12345678901234567890))
XCTAssertEqual(JSON("😊"), JSON("😊"))
XCTAssertNotEqual(JSON("😱"), JSON("😁"))
XCTAssertEqual(JSON([123,321,456]), JSON([123,321,456]))
XCTAssertNotEqual(JSON([123,321,456]), JSON(123456789))
XCTAssertNotEqual(JSON([123,321,456]), JSON("string"))
XCTAssertNotEqual(JSON(["1":123,"2":321,"3":456]), JSON("string"))
XCTAssertEqual(JSON(["1":123,"2":321,"3":456]), JSON(["2":321,"1":123,"3":456]))
XCTAssertEqual(JSON(NSNull()),JSON(NSNull()))
XCTAssertNotEqual(JSON(NSNull()), JSON(123))
}
func testJSONDoesProduceValidWithCorrectKeyPath() {
let json = JSON(data:self.testData)
let tweets = json
let tweets_array = json.array
let tweets_1 = json[1]
_ = tweets_1[1]
let tweets_1_user_name = tweets_1["user"]["name"]
let tweets_1_user_name_string = tweets_1["user"]["name"].string
XCTAssertNotEqual(tweets.type, Type.Null)
XCTAssert(tweets_array != nil)
XCTAssertNotEqual(tweets_1.type, Type.Null)
XCTAssertEqual(tweets_1_user_name, JSON("Raffi Krikorian"))
XCTAssertEqual(tweets_1_user_name_string!, "Raffi Krikorian")
let tweets_1_coordinates = tweets_1["coordinates"]
let tweets_1_coordinates_coordinates = tweets_1_coordinates["coordinates"]
let tweets_1_coordinates_coordinates_point_0_double = tweets_1_coordinates_coordinates[0].double
let tweets_1_coordinates_coordinates_point_1_float = tweets_1_coordinates_coordinates[1].float
let new_tweets_1_coordinates_coordinates = JSON([-122.25831,37.871609] as NSArray)
XCTAssertEqual(tweets_1_coordinates_coordinates, new_tweets_1_coordinates_coordinates)
XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_double!, -122.25831)
XCTAssertTrue(tweets_1_coordinates_coordinates_point_1_float! == 37.871609)
let tweets_1_coordinates_coordinates_point_0_string = tweets_1_coordinates_coordinates[0].stringValue
let tweets_1_coordinates_coordinates_point_1_string = tweets_1_coordinates_coordinates[1].stringValue
XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_string, "-122.25831")
XCTAssertEqual(tweets_1_coordinates_coordinates_point_1_string, "37.871609")
let tweets_1_coordinates_coordinates_point_0 = tweets_1_coordinates_coordinates[0]
let tweets_1_coordinates_coordinates_point_1 = tweets_1_coordinates_coordinates[1]
XCTAssertEqual(tweets_1_coordinates_coordinates_point_0, JSON(-122.25831))
XCTAssertEqual(tweets_1_coordinates_coordinates_point_1, JSON(37.871609))
let created_at = json[0]["created_at"].string
let id_str = json[0]["id_str"].string
let favorited = json[0]["favorited"].bool
let id = json[0]["id"].int64
let in_reply_to_user_id_str = json[0]["in_reply_to_user_id_str"]
XCTAssertEqual(created_at!, "Tue Aug 28 21:16:23 +0000 2012")
XCTAssertEqual(id_str!,"240558470661799936")
XCTAssertFalse(favorited!)
XCTAssertEqual(id!,240558470661799936)
XCTAssertEqual(in_reply_to_user_id_str.type, Type.Null)
let user = json[0]["user"]
let user_name = user["name"].string
let user_profile_image_url = user["profile_image_url"].URL
XCTAssert(user_name == "OAuth Dancer")
XCTAssert(user_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg"))
let user_dictionary = json[0]["user"].dictionary
let user_dictionary_name = user_dictionary?["name"]?.string
let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.URL
XCTAssert(user_dictionary_name == "OAuth Dancer")
XCTAssert(user_dictionary_name_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg"))
}
func testSequenceType() {
let json = JSON(data:self.testData)
XCTAssertEqual(json.count, 3)
for (_, aJson) in json {
XCTAssertEqual(aJson, json[0])
break
}
let index = 0
let keys = (json[1].dictionaryObject! as NSDictionary).allKeys as! [String]
for (aKey, aJson) in json[1] {
XCTAssertEqual(aKey, keys[index])
XCTAssertEqual(aJson, json[1][keys[index]])
break
}
}
func testJSONNumberCompare() {
XCTAssertEqual(JSON(12376352.123321), JSON(12376352.123321))
XCTAssertGreaterThan(JSON(20.211), JSON(20.112))
XCTAssertGreaterThanOrEqual(JSON(30.211), JSON(20.112))
XCTAssertGreaterThanOrEqual(JSON(65232), JSON(65232))
XCTAssertLessThan(JSON(-82320.211), JSON(20.112))
XCTAssertLessThanOrEqual(JSON(-320.211), JSON(123.1))
XCTAssertLessThanOrEqual(JSON(-8763), JSON(-8763))
XCTAssertEqual(JSON(12376352.123321), JSON(12376352.123321))
XCTAssertGreaterThan(JSON(20.211), JSON(20.112))
XCTAssertGreaterThanOrEqual(JSON(30.211), JSON(20.112))
XCTAssertGreaterThanOrEqual(JSON(65232), JSON(65232))
XCTAssertLessThan(JSON(-82320.211), JSON(20.112))
XCTAssertLessThanOrEqual(JSON(-320.211), JSON(123.1))
XCTAssertLessThanOrEqual(JSON(-8763), JSON(-8763))
}
func testNumberConvertToString(){
XCTAssertEqual(JSON(true).stringValue, "true")
XCTAssertEqual(JSON(999.9823).stringValue, "999.9823")
XCTAssertEqual(JSON(true).number!.stringValue, "1")
XCTAssertEqual(JSON(false).number!.stringValue, "0")
XCTAssertEqual(JSON("hello").numberValue.stringValue, "0")
XCTAssertEqual(JSON(NSNull()).numberValue.stringValue, "0")
XCTAssertEqual(JSON(["a","b","c","d"]).numberValue.stringValue, "0")
XCTAssertEqual(JSON(["a":"b","c":"d"]).numberValue.stringValue, "0")
}
func testNumberPrint(){
XCTAssertEqual(JSON(false).description,"false")
XCTAssertEqual(JSON(true).description,"true")
XCTAssertEqual(JSON(1).description,"1")
XCTAssertEqual(JSON(22).description,"22")
#if (arch(x86_64) || arch(arm64))
XCTAssertEqual(JSON(9.22337203685478E18).description,"9.22337203685478e+18")
#elseif (arch(i386) || arch(arm))
XCTAssertEqual(JSON(2147483647).description,"2147483647")
#endif
XCTAssertEqual(JSON(-1).description,"-1")
XCTAssertEqual(JSON(-934834834).description,"-934834834")
XCTAssertEqual(JSON(-2147483648).description,"-2147483648")
XCTAssertEqual(JSON(1.5555).description,"1.5555")
XCTAssertEqual(JSON(-9.123456789).description,"-9.123456789")
XCTAssertEqual(JSON(-0.00000000000000001).description,"-1e-17")
XCTAssertEqual(JSON(-999999999999999999999999.000000000000000000000001).description,"-1e+24")
XCTAssertEqual(JSON(-9999999991999999999999999.88888883433343439438493483483943948341).stringValue,"-9.999999991999999e+24")
XCTAssertEqual(JSON(Int(Int.max)).description,"\(Int.max)")
XCTAssertEqual(JSON(NSNumber(long: Int.min)).description,"\(Int.min)")
XCTAssertEqual(JSON(NSNumber(unsignedLong: UInt.max)).description,"\(UInt.max)")
XCTAssertEqual(JSON(NSNumber(unsignedLongLong: UInt64.max)).description,"\(UInt64.max)")
XCTAssertEqual(JSON(NSNumber(longLong: Int64.max)).description,"\(Int64.max)")
XCTAssertEqual(JSON(NSNumber(unsignedLongLong: UInt64.max)).description,"\(UInt64.max)")
XCTAssertEqual(JSON(Double.infinity).description,"inf")
XCTAssertEqual(JSON(-Double.infinity).description,"-inf")
XCTAssertEqual(JSON(Double.NaN).description,"nan")
XCTAssertEqual(JSON(1.0/0.0).description,"inf")
XCTAssertEqual(JSON(-1.0/0.0).description,"-inf")
XCTAssertEqual(JSON(0.0/0.0).description,"nan")
}
func testNullJSON() {
XCTAssertEqual(JSON(NSNull()).debugDescription,"null")
let json:JSON = nil
XCTAssertEqual(json.debugDescription,"null")
XCTAssertNil(json.error)
let json1:JSON = JSON(NSNull())
if json1 != nil {
XCTFail("json1 should be nil")
}
}
func testExistance() {
let dictionary = ["number":1111]
let json = JSON(dictionary)
XCTAssertFalse(json["unspecifiedValue"].exists())
XCTAssertTrue(json["number"].exists())
}
func testErrorHandle() {
let json = JSON(data:self.testData)
if let _ = json["wrong-type"].string {
XCTFail("Should not run into here")
} else {
XCTAssertEqual(json["wrong-type"].error!.code, SwiftyJSON.ErrorWrongType)
}
if let _ = json[0]["not-exist"].string {
XCTFail("Should not run into here")
} else {
XCTAssertEqual(json[0]["not-exist"].error!.code, SwiftyJSON.ErrorNotExist)
}
let wrongJSON = JSON(NSObject())
if let error = wrongJSON.error {
XCTAssertEqual(error.code, SwiftyJSON.ErrorUnsupportedType)
}
}
func testReturnObject() {
let json = JSON(data:self.testData)
XCTAssertNotNil(json.object)
}
func testNumberCompare(){
XCTAssertEqual(NSNumber(double: 888332), NSNumber(int:888332))
XCTAssertNotEqual(NSNumber(double: 888332.1), NSNumber(int:888332))
XCTAssertLessThan(NSNumber(int: 888332).doubleValue, NSNumber(double:888332.1).doubleValue)
XCTAssertGreaterThan(NSNumber(double: 888332.1).doubleValue, NSNumber(int:888332).doubleValue)
XCTAssertFalse(NSNumber(double: 1) == NSNumber(bool:true))
XCTAssertFalse(NSNumber(int: 0) == NSNumber(bool:false))
XCTAssertEqual(NSNumber(bool: false), NSNumber(bool:false))
XCTAssertEqual(NSNumber(bool: true), NSNumber(bool:true))
}
} | b12ceb93a0a832ef786222a7248bf18b | 45.347985 | 146 | 0.657208 | false | true | false | false |
byu-oit/ios-byuSuite | refs/heads/dev | byuSuite/Apps/Galleries/controller/GalleriesViewController.swift | apache-2.0 | 1 | //
// GalleriesViewController.swift
// byuSuite
//
// Created by Alex Boswell on 2/9/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
import UIKit
private let SEGUE_ID = "showAlbums"
class GalleriesViewController: ByuTableDataViewController {
//MARK: View controller life cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(nibName: String(describing: GalleriesTableViewCell.self))
loadGalleries()
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == SEGUE_ID, let gallery = sender as? Gallery, let vc = segue.destination as? GalleriesAlbumsViewController {
vc.title = gallery.name
vc.galleryId = gallery.id
}
}
//MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(for: indexPath) as? GalleriesTableViewCell else {
return UITableViewCell()
}
if let gallery: Gallery = tableData.object(forIndexPath: indexPath) {
cell.galleryImage = gallery.image
}
return cell
}
private func loadGalleries() {
GalleriesClient.getGalleries { (galleries, error) in
self.spinner?.stopAnimating()
if let galleries = galleries {
self.tableData = TableData(rows: galleries.map { gallery in
Row(action: {
self.performSegue(withIdentifier: SEGUE_ID, sender: gallery)
}, enabled: true, height: 140, object: gallery) })
self.tableView.reloadData()
} else {
super.displayAlert(error: error)
}
}
}
}
| a5f965640a7b17506841073da00e3a59 | 28.309091 | 131 | 0.727047 | false | false | false | false |
FUKUZAWA-Tadashi/FHCCommander | refs/heads/master | fhcc/FHCHTTPAccess.swift | mit | 1 | //
// FHCHTTPAccess.swift
// fhcc
//
// Created by 福澤 正 on 2014/07/10.
// Copyright (c) 2014年 Fukuzawa Technology. All rights reserved.
//
import Foundation
class FHCAccess : NSObject, NSURLSessionTaskDelegate {
class func getURLSessionOfNoCache () -> NSURLSessionConfiguration {
var conf = NSURLSessionConfiguration.defaultSessionConfiguration()
conf.URLCache = nil
return conf
}
class var sessionConf : NSURLSessionConfiguration {
struct _Static { static let conf = FHCAccess.getURLSessionOfNoCache() }
return _Static.conf
}
var session: NSURLSession!
override init () {
super.init()
session = NSURLSession(configuration: FHCAccess.sessionConf, delegate: self, delegateQueue:nil)
}
func getPage(url: NSURL, callback: (String, NSHTTPURLResponse) -> Void, errorHandler: ((NSError)->Void)? = nil) {
get(url, { (data1:String, response1:NSURLResponse) -> Void in
if response1.URL?.path == "/auth" {
self.auth(url, html:data1) {
(data2:String, response2:NSURLResponse!) -> Void in
let path2 = response2?.URL?.path
if path2 == nil || path2 == "/auth" {
fhcLog("\(url.scheme!)://\(url.host!) ログイン失敗")
} else {
fhcLog("\(url.scheme!)://\(url.host!) ログイン成功")
callback(data2, response2 as NSHTTPURLResponse)
}
}
} else {
callback(data1, response1 as NSHTTPURLResponse)
}
}, errorHandler)
}
func postPage(url: NSURL, postStr: String, callback: (String, NSHTTPURLResponse) -> Void, errorHandler: ((NSError)->Void)? = nil) {
post(url, postStr: postStr, { (data1:String, response1:NSURLResponse) -> Void in
if response1.URL?.path == "/auth" {
self.auth(url, html:data1, { (data2:String, response2:NSURLResponse!) -> Void in
let path2 = response2?.URL?.path
if path2 == nil || path2 == "/auth" {
fhcLog("\(url.scheme!)://\(url.host!) ログイン失敗")
} else {
fhcLog("\(url.scheme!)://\(url.host!) ログイン成功")
callback(data2, response2 as NSHTTPURLResponse)
}
}, errorHandler)
} else {
callback(data1, response1 as NSHTTPURLResponse)
}
}, errorHandler)
}
func auth(url: NSURL, html: String, callback:(String,NSURLResponse!)->Void, errorHandler: ((NSError)->Void)? = nil) {
let m_form = regexpMatch(html, pattern: "<form([^>]*)>(.*?)</form>")
if m_form.count < 1 {
fhcLog("auth form mismatch")
callback("", nil)
return
}
let m_action = regexpMatch(m_form[0][1], pattern: "action=\"(.*?)\"")
let action = m_action[0][1]
let m_method = regexpMatch(m_form[0][1], pattern: "method=\"(.*?)\"")
let method = m_method[0][1].lowercaseString
let m_input = regexpMatch(m_form[0][2], pattern: "<input(.*?)>")
var inputDict = [String:String]() // [name : value]
for inp in m_input {
let attribs = inp[0]
let m_type = regexpMatch(attribs, pattern: "type=\"(.*?)\"")
if m_type.count > 0 {
let type = m_type[0][1].lowercaseString
if type != "submit" {
let m_name = regexpMatch(attribs, pattern: "name=\"(.*?)\"")
if m_name.count > 0 {
let name = m_name[0][1]
let m_value = regexpMatch(attribs, pattern: "value=\"(.*?)\"")
let value = m_value.count > 0 ? m_value[0][1] : ""
inputDict[name] = value
}
}
}
}
let idOpt: String? = FHCState.singleton.state.mailAddr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
inputDict["id"] = idOpt
let pwOpt: String? = FHCState.singleton.state.password.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
inputDict["password"] = pwOpt?.stringByReplacingOccurrencesOfString("&", withString: "%26")
let actionUrlStr = "\(url.scheme!)://\(url.host!)\(action)"
let actionUrl = NSURL.URLWithString(actionUrlStr)
if actionUrl == nil {
fhcLog("bad url: \(actionUrlStr)")
callback("", nil)
return
}
// NSURL(scheme:host:path:) はpath中の#をエスケープしてしまう
var pairs = [String]()
for (name,value) in inputDict {
pairs.append(name + "=" + value)
}
let content = "&".join(pairs)
switch method.lowercaseString {
case "get":
get(actionUrl, callback: callback, errorHandler: errorHandler)
case "post":
post(actionUrl, postStr: content, callback: callback, errorHandler: errorHandler)
default:
fhcLog("unknown method '\(method)' on auth page")
callback("", nil)
}
}
// callFHCAPI("elec/action", params: ["elec":"家電名", "action":"操作名"]) { ... }
// callFHCAPI("sensor/get") { ... }
// can use under local connection
func callFHCAPI (apiPath: String, params: [String:String], callback: ((JSON!)->Void)? = nil, errorHandler: ((NSError)->Void)? = nil) {
var dic = params
dic["webapi_apikey"] = FHCState.singleton.state.fhcSecret
let queryStr = makeQueryString(dic)
let path = "/api/\(apiPath)?\(queryStr)"
let url = NSURL(scheme: "http", host: FHCState.singleton.state.fhcAddress, path: path)
getPage(url, { (data:String, response:NSHTTPURLResponse) -> Void in
if !isResponseJSON(response) {
NSLog(response.description)
fhcLog("API呼び出し失敗")
if errorHandler != nil {
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable, userInfo: ["FHCC":"API call failed"])
errorHandler!(error)
} else {
callback?(nil)
}
return
}
let json = JSON.parse(data)
if json["result"].asString != "ok" {
let errCode = json["code"].asString!
let errMess = json["message"].asString!
fhcLog("APIエラー:\(errCode) \(errMess)")
if errorHandler != nil {
let info: [NSObject : AnyObject] = [
"FHCC_JSON_ERRORCODE" : errCode,
"FHCC_JSON_ERRMESSAGE" : errMess
]
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse, userInfo: info)
errorHandler!(error)
}
}
callback?(json)
}, errorHandler)
}
func callFHCAPI (apiPath: String, callback: ((JSON!)->Void)? = nil, errorHandler: ((NSError)->Void)? = nil) {
callFHCAPI(apiPath, params: [:], callback: callback, errorHandler: errorHandler)
}
// ["key":"value", "key2":"value2"] --> "key=value&key2=value2"
func makeQueryString (params: [String:String]) -> String {
if params.count < 1 { return "" }
var pairs: [String] = []
for (key,value) in params {
pairs.append("\(key)=\(value)")
}
return "&".join(pairs)
}
// can use under local connection
func callVoiceCommand (command: String, callback: ((JSON!)->Void)? = nil, errorHandler: ((NSError)->Void)? = nil) {
callFHCAPI("recong/firebystring", params: ["str":command], callback: callback, errorHandler: errorHandler)
}
// callFHCRemoconButton("http", host: "192.168.99.999", type1: "テレビ", type2: "入力切替")
// can use under local or internet connection
func callFHCRemoconButton (scheme: String, host: String, type1: String, type2: String, errorHandler: ((NSError)->Void)? = nil) {
if type1 == State.VOICE_COMMAND {
callVoiceCommand(type2, { (json: JSON!) -> Void in
if json["result"].asString == "ok" {
fhcLog("音声コマンド実行")
}
}, errorHandler)
}
let remoconPageUrl = NSURL(scheme: scheme, host: host, path: "/")
getPage(remoconPageUrl, {
(data_r:String, response_r:NSHTTPURLResponse) -> Void in
if response_r.URL?.path != "/remocon" {
fhcLog("リモコンページへのアクセス失敗")
return
}
let refererURL = response_r.URL?.absoluteString
self.session.configuration.HTTPAdditionalHeaders = [:]
if refererURL != nil {
self.session.configuration.HTTPAdditionalHeaders!["Referer"] = refererURL!
}
self.session.configuration.HTTPAdditionalHeaders!["Content-Type"] = "application/x-www-form-urlencoded"
let queryStr = self.makeQueryString(["type1":type1, "type2":type2])
let path = "/remocon/fire/bytype"
let url = NSURL(scheme: scheme, host: host, path: path)
self.postPage(url, postStr: queryStr, {
(data:String, response:NSHTTPURLResponse) -> Void in
if response.URL?.path != path {
NSLog("remocon button URL goes --> \(response.URL?.path)")
let err = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: ["FHCC_REMOCON_PATH":(response.URL?.path ?? "nil")])
errorHandler?(err)
return
}
if !isResponseJSON(response) {
NSLog(response.description)
NSLog(data)
fhcLog("リモコン操作失敗")
if errorHandler != nil {
let info: [NSObject:AnyObject] = [
"FHCC" : "remocon control failed",
"FHCC_RESPONSE" : response.description,
"FHCC_DATA" : data
]
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable, userInfo: info)
errorHandler!(error)
}
return
}
let json = JSON.parse(data)
if json["result"].asString != "ok" {
let errCode = json["code"].asString!
let errMess = json["message"].asString!
fhcLog("APIエラー:\(errCode) \(errMess)")
if errorHandler != nil {
let info: [NSObject : AnyObject] = [
"FHCC_JSON_ERRORCODE" : errCode,
"FHCC_JSON_ERRMESSAGE" : errMess
]
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse, userInfo: info)
errorHandler!(error)
}
} else {
fhcLog("リモコン操作実行")
}
}, errorHandler)
}, errorHandler)
}
/**
** low level access funcs
**/
func get (url: NSURL, callback:(String,NSURLResponse)->Void, errorHandler:((NSError)->Void)? = nil) {
var task = session.dataTaskWithURL(url) {
(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
if errorHandler != nil {
errorHandler!(error)
} else {
fhcLog("error on get \(url): \(error)")
}
} else {
let str: String = NSString(data:data, encoding:NSUTF8StringEncoding)
callback(str, response)
}
}
task.resume()
}
func post (url: NSURL, postStr: String, callback:(String,NSURLResponse)->Void, errorHandler:((NSError)->Void)? = nil) {
var request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postStr.dataUsingEncoding(NSUTF8StringEncoding)
var task = session.dataTaskWithRequest(request) {
(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
if errorHandler != nil {
errorHandler!(error)
} else {
fhcLog("error on post \(url): \(error)")
}
} else {
let str: String = NSString(data:data, encoding:NSUTF8StringEncoding)
callback(str, response)
}
}
task.resume()
}
/**
** protocol NSURLSessionTaskDelegate
**/
func URLSession(session: NSURLSession!, task: NSURLSessionTask, didCompleteWithError error: NSError!) {
NSLog("task:didCompleteWithError: \(error)")
}
func URLSession(session: NSURLSession!,
task: NSURLSessionTask!,
didReceiveChallenge challenge: NSURLAuthenticationChallenge!,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
NSLog("task:didReceiveChallenge")
}
func URLSession(session: NSURLSession!,
task: NSURLSessionTask!,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) {
//NSLog("task:didSendBodyData bytesSent=\(bytesSent) totalBytesSent=\(totalBytesSent) totalBytesExpectedToSend=\(totalBytesExpectedToSend)")
}
func URLSession(session: NSURLSession!,
task: NSURLSessionTask!,
needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
NSLog("task:needNewBodyStream")
}
func URLSession(session: NSURLSession!,
task: NSURLSessionTask!,
willPerformHTTPRedirection response: NSHTTPURLResponse!,
newRequest request: NSURLRequest!,
completionHandler: ((NSURLRequest!) -> Void)!) {
//NSLog("task:willPerformHTTPRedirection")
// assert: 300 <= response.statusCode <= 307
//let statusStr = NSHTTPURLResponse.localizedStringForStatusCode(response.statusCode)
//let headerStr = "\(response.allHeaderFields)"
//NSLog("\(response.statusCode) \(statusStr)")
//NSLog(headerStr)
//NSLog(request.HTTPMethod)
completionHandler?(request)
}
/**
** protocol NSURLSessionDelegate
**/
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
NSLog("didBecomeInvalidWithError: \(error)")
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
// NSLog("didReceiveChallenge: \(challenge)")
if challenge.previousFailureCount > 1 { return }
let credential = NSURLCredential(
user: FHCState.singleton.state.mailAddr,
password: FHCState.singleton.state.password,
persistence: .ForSession)
completionHandler(.UseCredential, credential)
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
NSLog("URLSessionDidFinishEventsForBackgroundURLSession")
}
}
| 67c6d770adcf74514df5981d64dbddbb | 40.946809 | 152 | 0.541402 | false | false | false | false |
alfishe/mooshimeter-osx | refs/heads/master | mooshimeter-osx/Device/DeviceProtocol.swift | mit | 1 | //
// Created by Dev on 8/28/16.
// Copyright (c) 2016 alfishe. All rights reserved.
//
import Foundation
protocol DeviceProtocol
{
func getPCBVersion() -> UInt8
func setName(_ name: String)
func getName() -> String
func getDiagnostics() -> String
func getAdminTree() -> Void
}
extension Device
{
//MARK: -
//MARK: - System methods
// Mooshimeter firmware has 20 secs timeout for inactive connection
// Sending any command each 10 secs will keep connection alive
func keepalive()
{
_ = self.getTime()
}
func getAdminTree() -> Void
{
print("Getting AdminTree...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Tree))
self.writeValueAsync(bytes: dataBytes)
}
func sendCRC32(crc: UInt32) -> Void
{
print(String(format: "Sending CRC: 0x%x ...", crc))
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getWriteCommandCode(type: DeviceCommandType.CRC32))
dataBytes.append(contentsOf: crc.byteArray())
self.writeValueAsync(bytes: dataBytes)
}
// TODO: Doesn't work
func getDiagnostic() -> Void
{
print("Getting Diagnostic...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Diagnostic))
self.writeValueAsync(bytes: dataBytes)
}
func getPCBVersion() -> Void
{
print("Getting PCB_VERSION...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.PCBVersion))
self.writeValueAsync(bytes: dataBytes)
}
func getName() -> Void
{
print("Getting Name...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Name))
self.writeValueAsync(bytes: dataBytes)
}
//MARK: -
//MARK: Time methods
func getTime()
{
print("Getting Time_UTC...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.TimeUTC))
self.writeValueAsync(bytes: dataBytes)
}
func setTime(_ time: Double)
{
}
func getTimeMs()
{
print("Getting Time_UTCms...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.TimeUTCms))
self.writeValueAsync(bytes: dataBytes)
}
func setTimeMs(_ time: UInt16)
{
}
//MARK: -
//MARK: Sampling methods
func getSamplingRate()
{
print("Getting Sampling Rate...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.SamplingRate))
self.writeValueAsync(bytes: dataBytes)
}
func setSamplingRate(_ samplerate: SamplingRateType)
{
print("Setting Sampling Rate...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getWriteCommandCode(type: DeviceCommandType.SamplingRate))
dataBytes.append(contentsOf: DeviceCommand.getCommandPayload(commandType: DeviceCommandType.SamplingRate, value: samplerate as AnyObject))
self.writeValueAsync(bytes: dataBytes)
}
func getSamplingDepth()
{
print("Getting Sampling Depth...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.SamplingDepth))
self.writeValueAsync(bytes: dataBytes)
}
func setSamplingDepth(_ depth: SamplingDepthType)
{
print("Setting Sampling Depth...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getWriteCommandCode(type: DeviceCommandType.SamplingDepth))
dataBytes.append(contentsOf: DeviceCommand.getCommandPayload(commandType: DeviceCommandType.SamplingDepth, value: depth as AnyObject))
self.writeValueAsync(bytes: dataBytes)
}
func getSamplingTrigger()
{
print("Getting Sampling Trigger...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.SamplingTrigger))
self.writeValueAsync(bytes: dataBytes)
}
func setSamplingTrigger(_ trigger: SamplingTriggerType)
{
print("Setting Sampling Trigger...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getWriteCommandCode(type: DeviceCommandType.SamplingTrigger))
dataBytes.append(contentsOf: DeviceCommand.getCommandPayload(commandType: DeviceCommandType.SamplingTrigger, value: trigger as AnyObject))
self.writeValueAsync(bytes: dataBytes)
}
//MARK: -
//MARK: Channel1 methods
func getChannel1Mapping()
{
print("Getting Channel1 Mapping...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Channel1Mapping))
self.writeValueAsync(bytes: dataBytes)
}
func setChannel1Mapping(_ mapping: Channel1MappingType)
{
print("Setting Channel1 Mapping...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getWriteCommandCode(type: DeviceCommandType.Channel1Mapping))
dataBytes.append(contentsOf: DeviceCommand.getCommandPayload(commandType: DeviceCommandType.Channel1Mapping, value: mapping as AnyObject))
self.writeValueAsync(bytes: dataBytes)
}
func getChannel1Value()
{
//print("Getting Channel1 Value...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Channel1Value))
self.writeValueAsync(bytes: dataBytes)
}
func getChannel1Buffer()
{
print("Getting Channel1 Buffer...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Channel1Buf))
self.writeValueAsync(bytes: dataBytes)
}
//MARK: -
//MARK: Channel2 methods
func getChannel2Mapping()
{
print("Getting Channel2 Mapping...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Channel2Mapping))
self.writeValueAsync(bytes: dataBytes)
}
func setChannel2Mapping(_ mapping: Channel1MappingType)
{
print("Setting Channel2 Mapping...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getWriteCommandCode(type: DeviceCommandType.Channel2Mapping))
dataBytes.append(contentsOf: DeviceCommand.getCommandPayload(commandType: DeviceCommandType.Channel2Mapping, value: mapping as AnyObject))
self.writeValueAsync(bytes: dataBytes)
}
func getChannel2Value()
{
//print("Getting Channel2 Value...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Channel2Value))
self.writeValueAsync(bytes: dataBytes)
}
func getChannel2Buffer()
{
print("Getting Channel2 Buffer...")
var dataBytes: [UInt8] = [UInt8]()
dataBytes.append(self.getNextSendPacketNum())
dataBytes.append(DeviceCommand.getReadCommandCode(type: DeviceCommandType.Channel2Buf))
self.writeValueAsync(bytes: dataBytes)
}
}
| 6f44335d0c87f367e3c97a65e56f3484 | 27.640138 | 142 | 0.704845 | false | false | false | false |
zapdroid/RXWeather | refs/heads/master | Pods/RxSwift/RxSwift/Subjects/AsyncSubject.swift | mit | 1 | //
// AsyncSubject.swift
// RxSwift
//
// Created by Victor Galán on 07/01/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// An AsyncSubject emits the last value (and only the last value) emitted by the source Observable,
/// and only after that source Observable completes.
///
/// (If the source Observable does not emit any values, the AsyncSubject also completes without emitting any values.)
public final class AsyncSubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, SynchronizedUnsubscribeType {
public typealias SubjectObserverType = AsyncSubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock(); defer { _lock.unlock() }
return _observers.count > 0
}
let _lock = RecursiveLock()
// state
private var _observers = Observers()
private var _isStopped = false
private var _stoppedEvent = nil as Event<Element>? {
didSet {
_isStopped = _stoppedEvent != nil
}
}
private var _lastElement: Element?
/// Creates a subject.
public override init() {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
super.init()
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_ event: Event<E>) {
let (observers, event) = _synchronized_on(event)
switch event {
case .next:
dispatch(observers, event)
dispatch(observers, .completed)
case .completed:
dispatch(observers, event)
case .error:
dispatch(observers, event)
}
}
func _synchronized_on(_ event: Event<E>) -> (Observers, Event<E>) {
_lock.lock(); defer { _lock.unlock() }
if _isStopped {
return (Observers(), .completed)
}
switch event {
case let .next(element):
_lastElement = element
return (Observers(), .completed)
case .error:
_stoppedEvent = event
let observers = _observers
_observers.removeAll()
return (observers, event)
case .completed:
let observers = _observers
_observers.removeAll()
if let lastElement = _lastElement {
_stoppedEvent = .next(lastElement)
return (observers, .next(lastElement))
} else {
_stoppedEvent = event
return (observers, .completed)
}
}
}
/// Subscribes an observer to the subject.
///
/// - parameter observer: Observer to subscribe to the subject.
/// - returns: Disposable object that can be used to unsubscribe the observer from the subject.
public override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock(); defer { _lock.unlock() }
return _synchronized_subscribe(observer)
}
func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
if let stoppedEvent = _stoppedEvent {
switch stoppedEvent {
case .next:
observer.on(stoppedEvent)
observer.on(.completed)
case .completed:
observer.on(stoppedEvent)
case .error:
observer.on(stoppedEvent)
}
return Disposables.create()
}
let key = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
_ = _observers.removeKey(disposeKey)
}
/// Returns observer interface for subject.
public func asObserver() -> AsyncSubject<Element> {
return self
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
| 94ed64e151364ad09aab1e8a9c22e207 | 28.717241 | 117 | 0.589696 | false | false | false | false |
tschmidt64/Shuttle | refs/heads/master | Shuttle/StackViewController.swift | mit | 1 | //
// StackViewController.swift
// Pods
//
// Created by Taylor Schmidt on 5/1/16.
//
//
import Foundation
import UIKit
import MapKit
class StackViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var mapTableStack: UIStackView!
@IBOutlet weak var toolbar: UIView!
@IBOutlet weak var stopsSegmentedControl: UISegmentedControl!
@IBOutlet weak var dividerHeightConstraintHigh: NSLayoutConstraint!
@IBOutlet weak var dividerHeightConstraintLow: NSLayoutConstraint!
@IBOutlet weak var dividerHigh: UIView!
@IBOutlet weak var dividerLow: UIView!
@IBOutlet weak var refreshButton: UIBarButtonItem!
var activitySpinnerView: UIActivityIndicatorView?
@IBAction func refreshButtonPress(_ sender: AnyObject) {
getDataFromBuses()
}
var userLocButton: MKUserTrackingBarButtonItem!
var showListButton: UIBarButtonItem!
var tableHidden = false
var containsSegmentControl = true
/* Timer Fields */
var startTime = TimeInterval() // start stopwatch timer
var route: Route = Route(routeNum: 0, nameShort: "", nameLong: "")
var stopAnnotation: MKAnnotation?
var curStops: [Stop] = []
var selectedStop: Stop?
var locationManager = CLLocationManager()
var userLocation: CLLocationCoordinate2D!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Route \(route.routeNum)"
dividerHeightConstraintHigh.constant = 1/UIScreen.main.scale//enforces it to be a true 1 pixel line
dividerHeightConstraintLow.constant = 1/UIScreen.main.scale//enforces it to be a true 1 pixel line
// Get's coordinates for stops and buses
setupTableView()
setupMap()
setupLocationManager()
generateCoordinates()
sortAndSetStops()
selectedStop = curStops.first
initBusAnnotations()
addRoutePolyline()
setupToolbar()
DispatchQueue.main.async {
self.tableView.reloadData()
}
StopsSegmentedControlChoose(self)
}
// Hide the navController toolbar when leaving
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.isToolbarHidden = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkLocationAuthorizationStatus()
}
func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
mapView.showsUserLocation = true
} else {
locationManager.requestWhenInUseAuthorization()
}
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var view: MKAnnotationView
if(annotation is StopAnnotation) {
let ann = annotation as! StopAnnotation
view = MKAnnotationView(annotation: ann, reuseIdentifier: "stop")
//view.pinTintColor = MKPinAnnotationView.greenPinColor()
let image = UIImage(named: ann.img)
view.image = image
} else if (annotation is BusAnnotation) {
let ann = annotation as! BusAnnotation
view = MKAnnotationView(annotation: ann, reuseIdentifier: "bus")
//view.pinTintColor = MKPinAnnotationView.redPinColor()
// ROTATE IMAGE
// READ EXTENSION DOWN BELOW, GOT FROM:
// http://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift
//TODO I think all the buses look like they are moving backward, so might need to adjust the orientation modifier (+10) more
let image = UIImage(named: ann.img)
view.image = image
} else {
return nil
}
view.canShowCallout = true
return view
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay is MKPolyline {
let polyRenderer = MKPolylineRenderer(overlay: overlay)
// polyRenderer.strokeColor = UIColor(red: 0.5703125, green: 0.83203125, blue: 0.63671875, alpha: 0.8)
polyRenderer.strokeColor = UIColor(red: 49/255, green: 131/255, blue: 255/255, alpha: 1)
polyRenderer.lineWidth = 4
return polyRenderer
} else {
let polyRenderer = MKPolygonRenderer(overlay: overlay)
return polyRenderer
}
}
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views {
if view.annotation is StopAnnotation {
view.superview?.bringSubview(toFront: view)
} else {
view.superview?.sendSubview(toBack: view)
}
}
}
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
if let ann = (mapView.annotations.filter { $0 is StopAnnotation }.first as! StopAnnotation?) {
if let view = mapView.view(for: ann) {
view.superview?.bringSubview(toFront: view)
}
}
}
func initBusAnnotations() {
DispatchQueue.main.async(execute: {
guard let stop = self.selectedStop else {
print("ERROR: initBusAnnotations selectedStop was nil")
return
}
let lat = stop.location.latitude
let lon = stop.location.longitude
let stopName = stop.name
let coord: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: lon)
self.stopAnnotation = StopAnnotation(coordinate: coord, title: "Stop at " + stopName, subtitle: "", img: "Bus-Stop.png")
guard let annotation = self.stopAnnotation else {
print("ERROR: annotation = nil")
return
}
self.mapView.removeAnnotations(self.mapView.annotations)
self.mapView.addAnnotation(annotation as! StopAnnotation)
let distances = self.route.busDistancesFromStop(stop)
for (_, bus) in self.route.busesOnRoute {
if(self.containsNextStop(bus.nextStopId)) {
//TODO not sure if orientaiton passing is cool here
var distanceMiles: Double? = nil
if let distanceMeters = distances[bus.busId] {
distanceMiles = distanceMeters * 0.000621371
}
let annotation: BusAnnotation
if distanceMiles != nil {
annotation = BusAnnotation(coordinate: bus.location,
title: "\(String(format: "%.2f", distanceMiles!)) miles to stop",
subtitle: "",
img: "Bus-Circle.png",
orientation: 0,
busId: bus.busId)
} else {
annotation = BusAnnotation(coordinate: bus.location,
title: "Bus \(self.route.routeNum)",
subtitle: "Distance Unkown",
img: "Bus-Circle.png",
orientation: 0,
busId: bus.busId)
}
//print("bus latitude: \(bus.location.latitude), bus longitude: \(bus.location.longitude)")
print("ADDING ANNOTATION")
self.mapView.addAnnotation(annotation)
}
}
self.centerMapOnLocation(CLLocation(latitude: lat, longitude: lon), animated: true) //consider centering on stop instead
})
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// scroll to top
updateMapView()
self.tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .none, animated: true)
// Update selected stop for newly selected tableViewCell
selectedStop = self.curStops[(indexPath as NSIndexPath).row]
updateStopAnnotation()
// Update the bus locations
// getDataFromBuses()
updateBusAnnotations()
}
func updateStopAnnotation() {
if stopAnnotation != nil { mapView.removeAnnotations(mapView.annotations.filter {$0 is StopAnnotation}) }
DispatchQueue.main.async {
guard let stop = self.selectedStop else {
print("ERROR: updateStopAnnotation selectedStop was nil")
return
}
let lat = stop.location.latitude
let lon = stop.location.longitude
let stopName = stop.name
let coord: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat, longitude: lon)
self.stopAnnotation = StopAnnotation(coordinate: coord, title: "Stop at " + stopName, subtitle: "", img: "Bus-Stop.png")
guard let annotation = self.stopAnnotation else {
print("ERROR: annotation = nil")
return
}
self.mapView.addAnnotation(annotation as! StopAnnotation)
}
}
func updateMapView() {
guard let stop = selectedStop else {
print("ERROR: stop was nil")
return
}
addRoutePolyline()
let location = CLLocation(latitude: stop.location.latitude, longitude: stop.location.longitude)
centerMapOnLocation(location, animated: true)
}
func containsNextStop(_ nextStopId: String) -> Bool {
if(nextStopId == "") {
print("ERROR: No next stop id")
return true;
}
for stop in curStops {
if(nextStopId == stop.stopId) {
print("Found next stop")
return true;
}
}
print("Next stop not in stops")
return false;
}
@IBAction func StopsSegmentedControlChoose(_ sender: AnyObject) {
if stopsSegmentedControl.selectedSegmentIndex == 1 {
print("selected 1")
route.generateStopCoords(1)
route.generateRouteCoords(1)
} else {
print("selected 0")
route.generateStopCoords(0)
route.generateRouteCoords(0)
}
initBusAnnotations()
// Sort newly assigned stops
sortAndSetStops()
// Select first stop on new segment
selectedStop = curStops.first
let indexPath = IndexPath(row: 0, section: 0)
tableView.selectRow(at: indexPath, animated: true, scrollPosition: .bottom)
tableView(tableView, didSelectRowAt: indexPath)
DispatchQueue.main.async {
self.tableView.reloadData();
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let loc = manager.location {
userLocation = loc.coordinate
} else {
print("ERROR: Failed to update user location")
}
}
func updateBusAnnotations() {
guard let stop = self.selectedStop else {
print("ERROR: selectedStop is nil")
return
}
let selectedAnn = mapView.selectedAnnotations
for ann in selectedAnn { mapView.deselectAnnotation(ann, animated: true) }
let distances = self.route.busDistancesFromStop(stop)
var annArr: [BusAnnotation] = []
for annotation in ((self.mapView.annotations.filter() { $0 is BusAnnotation }) as! [BusAnnotation]) {
let id = annotation.busId
if let bus = self.route.busesOnRoute[id] {
var distanceMiles: Double? = nil
if let distanceMeters = distances[id] {
distanceMiles = distanceMeters * 0.000621371
annotation.title = "\(String(format: "%.2f", distanceMiles!)) miles to stop"
} else {
annotation.title = "Distance unknown"
}
if annotation.coordinate.latitude != bus.location.latitude
|| annotation.coordinate.longitude != bus.location.longitude {
annotation.coordinate = bus.location
annArr.append(annotation)
}
} else {
print("ERROR: no bus found for id = \(id)")
}
}
self.mapView.addAnnotations(annArr)
}
func getDataFromBuses() {
self.updateStopwatch()
self.startTime = Date.timeIntervalSinceReferenceDate
DispatchQueue.global(qos: .default).async {
self.route.refreshBuses {
print("=== BUSES UPDATED ===")
self.updateBusAnnotations()
}
}
}
func centerMapOnLocation(_ location: CLLocation, animated: Bool) {
// This zooms over the user and the stop as an alternative.
// It doesn't seem to always show the stop though; sometimes it is covered up
// so I commented it out and am now just using the whole route
// var coords: [CLLocationCoordinate2D]
// if let stopAn = stopAnnotation, userLoc = userLocation {
// coords = [userLoc, stopAn.coordinate]
// } else {
// print("HERE BITCH")
// coords = route.routeCoords
// }
// Get bus coords
let buses = Array(route.busesOnRoute.values)
let busCoords = buses.map { $0.location }
var coords = busCoords + route.routeCoords
let polyline = MKPolyline(coordinates: &coords, count: coords.count)
let routeRegion = polyline.boundingMapRect
mapView.setVisibleMapRect(routeRegion, edgePadding: UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0), animated: animated)
}
func sortAndSetStops() {
// Sort stops by distance from user
if self.route.stops.isEmpty {
print("======== Self.route.stops is empty =========")
}
self.curStops = self.route.stops.sorted {
if let uCoord = self.locationManager.location?.coordinate {
let uLoc = CLLocation(latitude: uCoord.latitude, longitude: uCoord.longitude)
let stop0 = CLLocation(latitude: $0.location.latitude, longitude: $0.location.longitude)
let stop1 = CLLocation(latitude: $1.location.latitude, longitude: $1.location.longitude)
return stop0.distance(from: uLoc) < stop1.distance(from: uLoc)
} else {
print("RETURNING FALSE")
return false
}
}
}
func generateCoordinates() {
if(route.routeNum == 640 || route.routeNum == 642 ) {
containsSegmentControl = false
toolbar.isHidden = true
dividerLow.isHidden = true
dividerHigh.isHidden = true
print("BEFORE")
print(route.stops)
route.generateStopCoords(0)
route.generateRouteCoords(0)
print(route.stops)
print("AFTER")
//do this because these routes only have on direction, so need to be set on 0
// StopsSegmentedControl.hidden = true
// self.navBar.removeFromSuperview()
// self.tableView.contentInset = UIEdgeInsets(top: -44.0, left: 0.0, bottom: 0.0, right: 0.0)
}
}
func setupTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
tableView.backgroundView = blurEffectView
tableView.separatorEffect = UIVibrancyEffect(blurEffect: blurEffect)
}
func setupMap() {
mapView.delegate = self
}
func setupLocationManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func setupToolbar() {
userLocButton = MKUserTrackingBarButtonItem(mapView: mapView)
userLocButton.customView?.tintColor = UIColor(red: 112/255, green: 183/255, blue: 132/255, alpha: 1)
if tableHidden {
showListButton = UIBarButtonItem(title: "Show Stops", style: .plain, target: self, action: Selector.buttonTapped)
} else {
showListButton = UIBarButtonItem(title: "Hide Stops", style: .plain, target: self, action: Selector.buttonTapped)
}
showListButton.tintColor = UIColor(red: 112/255, green: 183/255, blue: 132/255, alpha: 1)
navigationController?.isToolbarHidden = false
let flexL = UIBarButtonItem(barButtonSystemItem: .flexibleSpace , target: self, action: nil)
let flexR = UIBarButtonItem(barButtonSystemItem: .flexibleSpace , target: self, action: nil)
toolbarItems = [userLocButton, flexL, showListButton, flexR]
}
func showListTapped(_ sender: UIBarButtonItem) {
self.tableHidden = !self.tableHidden
UIView.animate(withDuration: 0.2, animations: {
self.tableView.isHidden = self.tableHidden
self.toolbar.isHidden = self.containsSegmentControl ? self.tableHidden : true
self.dividerHigh.isHidden = self.containsSegmentControl ? self.tableHidden : true
self.dividerLow.isHidden = self.containsSegmentControl ? self.tableHidden : true
// self.view.layoutIfNeeded()
})
setupToolbar()
print("Button Pressed")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StackCell", for: indexPath)
let curStopCoord = curStops[(indexPath as NSIndexPath).row].location
let curStopLoc = CLLocation(latitude: curStopCoord.latitude, longitude: curStopCoord.longitude)
let userLoc: CLLocation?
if let userCoord = self.locationManager.location?.coordinate {
userLoc = CLLocation(latitude: userCoord.latitude, longitude: userCoord.longitude)
let distanceMeters = curStopLoc.distance(from: userLoc!)
let distanceMiles = distanceMeters * 0.000621371
cell.detailTextLabel!.text = String(format: "%.2f", distanceMiles) + " mi"
} else {
cell.detailTextLabel!.text = ""
}
let name:String = curStops[(indexPath as NSIndexPath).row].name
cell.textLabel!.text = name
return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.curStops.count
}
func addRoutePolyline() {
print("ADDING POLY")
print(route.routeCoords.count)
let polyline = MKPolyline(coordinates: &route.routeCoords, count: route.routeCoords.count)
mapView.removeOverlays(mapView.overlays)
mapView.add(polyline)
}
func updateStopwatch() {
let currentTime = Date.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
// print(elapsedTime)
//calculate the minutes in elapsed time.
let minutes = UInt32(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt32(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
/*
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
print(strMinutes)
print(strSeconds)
*/
}
}
private extension Selector {
static let buttonTapped = #selector(StackViewController.showListTapped(_:))
}
| cd3177e1e5d686540d9e5e17947ab281 | 38.738462 | 136 | 0.599835 | false | false | false | false |
HarveyHu/BLEHelper | refs/heads/master | BLEHelperExample/BLEHelperExample/MasterViewController.swift | mit | 1 | //
// MasterViewController.swift
// BLEHelperExample
//
// Created by HarveyHu on 3/21/16.
// Copyright © 2016 HarveyHu. All rights reserved.
//
import UIKit
import BLEHelper
import CoreBluetooth
class MasterViewController: UITableViewController {
let bleHelper = BLECentralHelper()
var detailViewController: DetailViewController? = nil
var devices = [CBPeripheral]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(MasterViewController.scan(_:)))
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
bleHelper.scan(1.0, serviceUUID: nil) {[weak self] (devices) -> (Void) in
for device in devices {
print("deviceUUID: \(device.identifier.UUIDString)")
self?.devices = devices
self?.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func scan(sender: AnyObject) {
// scan for 1 second
bleHelper.scan(1.0, serviceUUID: nil) {[weak self] (devices) -> (Void) in
for device in devices {
print("deviceUUID: \(device.identifier.UUIDString)")
self?.devices = devices
self?.tableView.reloadData()
}
}
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = devices[indexPath.row]
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return devices.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = devices[indexPath.row]
cell.textLabel?.text = object.name
cell.detailTextLabel?.text = object.identifier.UUIDString
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
devices.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| e3cbd682d64f64d3e05aa43a853143fe | 36.935185 | 157 | 0.668782 | false | false | false | false |
agilewalker/SwiftyChardet | refs/heads/master | SwiftyChardet/enums.swift | lgpl-2.1 | 1 | /// The different states a universal detector can be in.
enum InputState: Int {
case pure_ascii = 0
case esc_ascii = 1
case high_byte = 2
}
struct LanguageFilter: OptionSet {
let rawValue: Int
static let chinese_simplified = LanguageFilter(rawValue: 1 << 0)
static let chinese_traditional = LanguageFilter(rawValue: 1 << 1)
static let japanese = LanguageFilter(rawValue: 1 << 2)
static let korean = LanguageFilter(rawValue: 1 << 3)
static let non_cjk = LanguageFilter(rawValue: 1 << 4)
static let chinese: LanguageFilter = [chinese_simplified, chinese_traditional]
static let cjk: LanguageFilter = [chinese, japanese, korean]
static let all: LanguageFilter = [cjk, non_cjk]
}
/// The different states a prober can be in.
enum ProbingState: Int {
/*
This enum represents
*/
case detecting = 0
case found_it = 1
case not_me = 2
}
/// The different states a state machine can be in.
enum MachineState: Int {
case start = 0
case error = 1
case its_me = 2
case _3 = 3
case _4 = 4
case _5 = 5
case _6 = 6
case _7 = 7
case _8 = 8
case _9 = 9
case _10 = 10
case _11 = 11
case _12 = 12
}
| 5f81a9560de557dafb7604181ebac20a | 25.8 | 82 | 0.636816 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/swift-sdk/Source/PersonalityInsightsV3/PersonalityInsights.swift | mit | 1 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
The IBM Watson Personality Insights service enables applications to derive insights from social media, enterprise data,
or other digital communications. The service uses linguistic analytics to infer individuals' intrinsic personality
characteristics, including Big Five, Needs, and Values, from digital communications such as email, text messages,
tweets, and forum posts.
The service can automatically infer, from potentially noisy social media, portraits of individuals that reflect their
personality characteristics. The service can infer consumption preferences based on the results of its analysis and,
for JSON content that is timestamped, can report temporal behavior.
* For information about the meaning of the models that the service uses to describe personality characteristics, see
[Personality models](https://console.bluemix.net/docs/services/personality-insights/models.html).
* For information about the meaning of the consumption preferences, see [Consumption
preferences](https://console.bluemix.net/docs/services/personality-insights/preferences.html).
**Note:** Request logging is disabled for the Personality Insights service. The service neither logs nor retains data
from requests and responses, regardless of whether the `X-Watson-Learning-Opt-Out` request header is set.
*/
public class PersonalityInsights {
/// The base URL to use when contacting the service.
public var serviceURL = "https://gateway.watsonplatform.net/personality-insights/api"
/// The default HTTP headers for all requests to the service.
public var defaultHeaders = [String: String]()
private let credentials: Credentials
private let domain = "com.ibm.watson.developer-cloud.PersonalityInsightsV3"
private let version: String
/**
Create a `PersonalityInsights` object.
- parameter username: The username used to authenticate with the service.
- parameter password: The password used to authenticate with the service.
- parameter version: The release date of the version of the API to use. Specify the date
in "YYYY-MM-DD" format.
*/
public init(username: String, password: String, version: String) {
self.credentials = .basicAuthentication(username: username, password: password)
self.version = version
}
/**
If the response or data represents an error returned by the Personality Insights service,
then return NSError with information about the error that occured. Otherwise, return nil.
- parameter response: the URL response returned from the service.
- parameter data: Raw data returned from the service that may represent an error.
*/
private func responseToError(response: HTTPURLResponse?, data: Data?) -> NSError? {
// First check http status code in response
if let response = response {
if (200..<300).contains(response.statusCode) {
return nil
}
}
// ensure data is not nil
guard let data = data else {
if let code = response?.statusCode {
return NSError(domain: domain, code: code, userInfo: nil)
}
return nil // RestKit will generate error for this case
}
let code = response?.statusCode ?? 400
do {
let json = try JSONWrapper(data: data)
let message = try json.getString(at: "error")
let help = try? json.getString(at: "help")
let userInfo = [NSLocalizedDescriptionKey: message, NSLocalizedFailureReasonErrorKey: help ?? ""]
return NSError(domain: domain, code: code, userInfo: userInfo)
} catch {
return NSError(domain: domain, code: code, userInfo: nil)
}
}
/**
Get profile.
Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input
content, but it requires much less text to produce an accurate profile; for more information, see [Providing
sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient). The
service analyzes text in Arabic, English, Japanese, Korean, or Spanish and returns its results in a variety of
languages. You can provide plain text, HTML, or JSON input by specifying the **Content-Type** parameter; the
default is `text/plain`. Request a JSON or comma-separated values (CSV) response by specifying the **Accept**
parameter; CSV output includes a fixed number of columns and optional headers. Per the JSON specification, the
default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default
encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content
type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text;
for example: `Content-Type: text/plain;charset=utf-8`. For detailed information about calling the service and the
responses it can generate, see [Requesting a
profile](https://console.bluemix.net/docs/services/personality-insights/input.html), [Understanding a JSON
profile](https://console.bluemix.net/docs/services/personality-insights/output.html), and [Understanding a CSV
profile](https://console.bluemix.net/docs/services/personality-insights/output-csv.html).
- parameter content: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see
[Providing sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient).
For JSON input, provide an object of type `Content`.
- parameter contentLanguage: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants
are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the
**Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or
`text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is
`application/json`, **Content-Language** overrides a language specified with the `language` parameter of a
`ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base
the language on the specification of the content items. You can specify any combination of languages for
**Content-Language** and **Accept-Language**.
- parameter acceptLanguage: The desired language of the response. For two-character arguments, regional variants are treated as their parent
language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input
and response content.
- parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw
scores are not compared with a sample population. By default, only normalized percentiles are returned.
- parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are
returned.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func profile(
content: Content,
contentLanguage: String? = nil,
acceptLanguage: String? = nil,
rawScores: Bool? = nil,
consumptionPreferences: Bool? = nil,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Profile) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(content) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "application/json"
if let contentLanguage = contentLanguage {
headerParameters["Content-Language"] = contentLanguage
}
if let acceptLanguage = acceptLanguage {
headerParameters["Accept-Language"] = acceptLanguage
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let rawScores = rawScores {
let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)")
queryParameters.append(queryParameter)
}
if let consumptionPreferences = consumptionPreferences {
let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/profile",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Profile>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get profile.
Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input
content, but it requires much less text to produce an accurate profile; for more information, see [Providing
sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient). The
service analyzes text in Arabic, English, Japanese, Korean, or Spanish and returns its results in a variety of
languages. You can provide plain text, HTML, or JSON input by specifying the **Content-Type** parameter; the
default is `text/plain`. Request a JSON or comma-separated values (CSV) response by specifying the **Accept**
parameter; CSV output includes a fixed number of columns and optional headers. Per the JSON specification, the
default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default
encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content
type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text;
for example: `Content-Type: text/plain;charset=utf-8`. For detailed information about calling the service and the
responses it can generate, see [Requesting a
profile](https://console.bluemix.net/docs/services/personality-insights/input.html), [Understanding a JSON
profile](https://console.bluemix.net/docs/services/personality-insights/output.html), and [Understanding a CSV
profile](https://console.bluemix.net/docs/services/personality-insights/output-csv.html).
- parameter text: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see
[Providing sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient).
For JSON input, provide an object of type `Content`.
- parameter contentLanguage: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants
are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the
**Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or
`text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is
`application/json`, **Content-Language** overrides a language specified with the `language` parameter of a
`ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base
the language on the specification of the content items. You can specify any combination of languages for
**Content-Language** and **Accept-Language**.
- parameter acceptLanguage: The desired language of the response. For two-character arguments, regional variants are treated as their parent
language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input
and response content.
- parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw
scores are not compared with a sample population. By default, only normalized percentiles are returned.
- parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are
returned.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func profile(
text: String,
contentLanguage: String? = nil,
acceptLanguage: String? = nil,
rawScores: Bool? = nil,
consumptionPreferences: Bool? = nil,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Profile) -> Void)
{
// construct body
guard let body = text.data(using: .utf8) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "text/plain"
if let contentLanguage = contentLanguage {
headerParameters["Content-Language"] = contentLanguage
}
if let acceptLanguage = acceptLanguage {
headerParameters["Accept-Language"] = acceptLanguage
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let rawScores = rawScores {
let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)")
queryParameters.append(queryParameter)
}
if let consumptionPreferences = consumptionPreferences {
let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/profile",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Profile>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get profile.
Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input
content, but it requires much less text to produce an accurate profile; for more information, see [Providing
sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient). The
service analyzes text in Arabic, English, Japanese, Korean, or Spanish and returns its results in a variety of
languages. You can provide plain text, HTML, or JSON input by specifying the **Content-Type** parameter; the
default is `text/plain`. Request a JSON or comma-separated values (CSV) response by specifying the **Accept**
parameter; CSV output includes a fixed number of columns and optional headers. Per the JSON specification, the
default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default
encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content
type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text;
for example: `Content-Type: text/plain;charset=utf-8`. For detailed information about calling the service and the
responses it can generate, see [Requesting a
profile](https://console.bluemix.net/docs/services/personality-insights/input.html), [Understanding a JSON
profile](https://console.bluemix.net/docs/services/personality-insights/output.html), and [Understanding a CSV
profile](https://console.bluemix.net/docs/services/personality-insights/output-csv.html).
- parameter html: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see
[Providing sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient).
For JSON input, provide an object of type `Content`.
- parameter contentLanguage: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants
are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the
**Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or
`text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is
`application/json`, **Content-Language** overrides a language specified with the `language` parameter of a
`ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base
the language on the specification of the content items. You can specify any combination of languages for
**Content-Language** and **Accept-Language**.
- parameter acceptLanguage: The desired language of the response. For two-character arguments, regional variants are treated as their parent
language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input
and response content.
- parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw
scores are not compared with a sample population. By default, only normalized percentiles are returned.
- parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are
returned.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func profile(
html: String,
contentLanguage: String? = nil,
acceptLanguage: String? = nil,
rawScores: Bool? = nil,
consumptionPreferences: Bool? = nil,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (Profile) -> Void)
{
// construct body
guard let body = html.data(using: .utf8) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "application/json"
headerParameters["Content-Type"] = "text/html"
if let contentLanguage = contentLanguage {
headerParameters["Content-Language"] = contentLanguage
}
if let acceptLanguage = acceptLanguage {
headerParameters["Accept-Language"] = acceptLanguage
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let rawScores = rawScores {
let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)")
queryParameters.append(queryParameter)
}
if let consumptionPreferences = consumptionPreferences {
let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/profile",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseObject(responseToError: responseToError) {
(response: RestResponse<Profile>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get profile. as csv
Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input
content, but it requires much less text to produce an accurate profile; for more information, see [Providing
sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient). The
service analyzes text in Arabic, English, Japanese, Korean, or Spanish and returns its results in a variety of
languages. You can provide plain text, HTML, or JSON input by specifying the **Content-Type** parameter; the
default is `text/plain`. Request a JSON or comma-separated values (CSV) response by specifying the **Accept**
parameter; CSV output includes a fixed number of columns and optional headers. Per the JSON specification, the
default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default
encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content
type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text;
for example: `Content-Type: text/plain;charset=utf-8`. For detailed information about calling the service and the
responses it can generate, see [Requesting a
profile](https://console.bluemix.net/docs/services/personality-insights/input.html), [Understanding a JSON
profile](https://console.bluemix.net/docs/services/personality-insights/output.html), and [Understanding a CSV
profile](https://console.bluemix.net/docs/services/personality-insights/output-csv.html).
- parameter content: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see
[Providing sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient).
For JSON input, provide an object of type `Content`.
- parameter contentLanguage: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants
are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the
**Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or
`text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is
`application/json`, **Content-Language** overrides a language specified with the `language` parameter of a
`ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base
the language on the specification of the content items. You can specify any combination of languages for
**Content-Language** and **Accept-Language**.
- parameter acceptLanguage: The desired language of the response. For two-character arguments, regional variants are treated as their parent
language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input
and response content.
- parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw
scores are not compared with a sample population. By default, only normalized percentiles are returned.
- parameter csvHeaders: Indicates whether column labels are returned with a CSV response. By default, no column labels are returned.
Applies only when the **Accept** parameter is set to `text/csv`.
- parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are
returned.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func profileAsCsv(
content: Content,
contentLanguage: String? = nil,
acceptLanguage: String? = nil,
rawScores: Bool? = nil,
csvHeaders: Bool? = nil,
consumptionPreferences: Bool? = nil,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (String) -> Void)
{
// construct body
guard let body = try? JSONEncoder().encode(content) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "text/csv"
headerParameters["Content-Type"] = "application/json"
if let contentLanguage = contentLanguage {
headerParameters["Content-Language"] = contentLanguage
}
if let acceptLanguage = acceptLanguage {
headerParameters["Accept-Language"] = acceptLanguage
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let rawScores = rawScores {
let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)")
queryParameters.append(queryParameter)
}
if let csvHeaders = csvHeaders {
let queryParameter = URLQueryItem(name: "csv_headers", value: "\(csvHeaders)")
queryParameters.append(queryParameter)
}
if let consumptionPreferences = consumptionPreferences {
let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/profile",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseString(responseToError: responseToError) {
(response: RestResponse<String>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get profile. as csv
Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input
content, but it requires much less text to produce an accurate profile; for more information, see [Providing
sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient). The
service analyzes text in Arabic, English, Japanese, Korean, or Spanish and returns its results in a variety of
languages. You can provide plain text, HTML, or JSON input by specifying the **Content-Type** parameter; the
default is `text/plain`. Request a JSON or comma-separated values (CSV) response by specifying the **Accept**
parameter; CSV output includes a fixed number of columns and optional headers. Per the JSON specification, the
default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default
encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content
type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text;
for example: `Content-Type: text/plain;charset=utf-8`. For detailed information about calling the service and the
responses it can generate, see [Requesting a
profile](https://console.bluemix.net/docs/services/personality-insights/input.html), [Understanding a JSON
profile](https://console.bluemix.net/docs/services/personality-insights/output.html), and [Understanding a CSV
profile](https://console.bluemix.net/docs/services/personality-insights/output-csv.html).
- parameter text: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see
[Providing sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient).
For JSON input, provide an object of type `Content`.
- parameter contentLanguage: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants
are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the
**Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or
`text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is
`application/json`, **Content-Language** overrides a language specified with the `language` parameter of a
`ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base
the language on the specification of the content items. You can specify any combination of languages for
**Content-Language** and **Accept-Language**.
- parameter acceptLanguage: The desired language of the response. For two-character arguments, regional variants are treated as their parent
language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input
and response content.
- parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw
scores are not compared with a sample population. By default, only normalized percentiles are returned.
- parameter csvHeaders: Indicates whether column labels are returned with a CSV response. By default, no column labels are returned.
Applies only when the **Accept** parameter is set to `text/csv`.
- parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are
returned.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func profileAsCsv(
text: String,
contentLanguage: String? = nil,
acceptLanguage: String? = nil,
rawScores: Bool? = nil,
csvHeaders: Bool? = nil,
consumptionPreferences: Bool? = nil,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (String) -> Void)
{
// construct body
guard let body = text.data(using: .utf8) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "text/csv"
headerParameters["Content-Type"] = "text/plain"
if let contentLanguage = contentLanguage {
headerParameters["Content-Language"] = contentLanguage
}
if let acceptLanguage = acceptLanguage {
headerParameters["Accept-Language"] = acceptLanguage
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let rawScores = rawScores {
let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)")
queryParameters.append(queryParameter)
}
if let csvHeaders = csvHeaders {
let queryParameter = URLQueryItem(name: "csv_headers", value: "\(csvHeaders)")
queryParameters.append(queryParameter)
}
if let consumptionPreferences = consumptionPreferences {
let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/profile",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseString(responseToError: responseToError) {
(response: RestResponse<String>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
/**
Get profile. as csv
Generates a personality profile for the author of the input text. The service accepts a maximum of 20 MB of input
content, but it requires much less text to produce an accurate profile; for more information, see [Providing
sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient). The
service analyzes text in Arabic, English, Japanese, Korean, or Spanish and returns its results in a variety of
languages. You can provide plain text, HTML, or JSON input by specifying the **Content-Type** parameter; the
default is `text/plain`. Request a JSON or comma-separated values (CSV) response by specifying the **Accept**
parameter; CSV output includes a fixed number of columns and optional headers. Per the JSON specification, the
default character encoding for JSON content is effectively always UTF-8; per the HTTP specification, the default
encoding for plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When specifying a content
type of plain text or HTML, include the `charset` parameter to indicate the character encoding of the input text;
for example: `Content-Type: text/plain;charset=utf-8`. For detailed information about calling the service and the
responses it can generate, see [Requesting a
profile](https://console.bluemix.net/docs/services/personality-insights/input.html), [Understanding a JSON
profile](https://console.bluemix.net/docs/services/personality-insights/output.html), and [Understanding a CSV
profile](https://console.bluemix.net/docs/services/personality-insights/output-csv.html).
- parameter html: A maximum of 20 MB of content to analyze, though the service requires much less text; for more information, see
[Providing sufficient input](https://console.bluemix.net/docs/services/personality-insights/input.html#sufficient).
For JSON input, provide an object of type `Content`.
- parameter contentLanguage: The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants
are treated as their parent language; for example, `en-US` is interpreted as `en`. The effect of the
**Content-Language** parameter depends on the **Content-Type** parameter. When **Content-Type** is `text/plain` or
`text/html`, **Content-Language** is the only way to specify the language. When **Content-Type** is
`application/json`, **Content-Language** overrides a language specified with the `language` parameter of a
`ContentItem` object, and content items that specify a different language are ignored; omit this parameter to base
the language on the specification of the content items. You can specify any combination of languages for
**Content-Language** and **Accept-Language**.
- parameter acceptLanguage: The desired language of the response. For two-character arguments, regional variants are treated as their parent
language; for example, `en-US` is interpreted as `en`. You can specify any combination of languages for the input
and response content.
- parameter rawScores: Indicates whether a raw score in addition to a normalized percentile is returned for each characteristic; raw
scores are not compared with a sample population. By default, only normalized percentiles are returned.
- parameter csvHeaders: Indicates whether column labels are returned with a CSV response. By default, no column labels are returned.
Applies only when the **Accept** parameter is set to `text/csv`.
- parameter consumptionPreferences: Indicates whether consumption preferences are returned with the results. By default, no consumption preferences are
returned.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed if an error occurs.
- parameter success: A function executed with the successful result.
*/
public func profileAsCsv(
html: String,
contentLanguage: String? = nil,
acceptLanguage: String? = nil,
rawScores: Bool? = nil,
csvHeaders: Bool? = nil,
consumptionPreferences: Bool? = nil,
headers: [String: String]? = nil,
failure: ((Error) -> Void)? = nil,
success: @escaping (String) -> Void)
{
// construct body
guard let body = html.data(using: .utf8) else {
failure?(RestError.serializationError)
return
}
// construct header parameters
var headerParameters = defaultHeaders
if let headers = headers {
headerParameters.merge(headers) { (_, new) in new }
}
headerParameters["Accept"] = "text/csv"
headerParameters["Content-Type"] = "text/html"
if let contentLanguage = contentLanguage {
headerParameters["Content-Language"] = contentLanguage
}
if let acceptLanguage = acceptLanguage {
headerParameters["Accept-Language"] = acceptLanguage
}
// construct query parameters
var queryParameters = [URLQueryItem]()
queryParameters.append(URLQueryItem(name: "version", value: version))
if let rawScores = rawScores {
let queryParameter = URLQueryItem(name: "raw_scores", value: "\(rawScores)")
queryParameters.append(queryParameter)
}
if let csvHeaders = csvHeaders {
let queryParameter = URLQueryItem(name: "csv_headers", value: "\(csvHeaders)")
queryParameters.append(queryParameter)
}
if let consumptionPreferences = consumptionPreferences {
let queryParameter = URLQueryItem(name: "consumption_preferences", value: "\(consumptionPreferences)")
queryParameters.append(queryParameter)
}
// construct REST request
let request = RestRequest(
method: "POST",
url: serviceURL + "/v3/profile",
credentials: credentials,
headerParameters: headerParameters,
queryItems: queryParameters,
messageBody: body
)
// execute REST request
request.responseString(responseToError: responseToError) {
(response: RestResponse<String>) in
switch response.result {
case .success(let retval): success(retval)
case .failure(let error): failure?(error)
}
}
}
}
| f105ee25d8d23d2b96b3f451b979b4cf | 56.786104 | 156 | 0.695414 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | refs/heads/master | PopcornTime/UI/iOS/Buttons/CircularButton.swift | gpl-3.0 | 1 |
import UIKit
class CircularButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width/2
layer.masksToBounds = true
}
private var classContext = 0
override func awakeFromNib() {
super.awakeFromNib()
imageView?.isHidden = true
imageView?.addObserver(self, forKeyPath: "image", options: .new, context: &classContext)
backgroundColor = tintColor
}
override var intrinsicContentSize: CGSize {
guard let imageView = imageView else { return super.intrinsicContentSize }
let size = imageView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
let common = Swift.max(size.width, size.height)
let padding: CGFloat = 10
return CGSize(width: common + padding, height: common + padding)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let keyPath = keyPath, keyPath == "image", context == &classContext {
if let layer = imageView?.image?.scaled(to: intrinsicContentSize).layerMask {
layer.frame = bounds
self.layer.mask = layer
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
override func tintColorDidChange() {
super.tintColorDidChange()
invalidateAppearance()
}
override var isHighlighted: Bool {
didSet {
invalidateAppearance()
}
}
func invalidateAppearance() {
let isDimmed = tintAdjustmentMode == .dimmed
let color: UIColor = isDimmed ? tintColor : isHighlighted ? tintColor.withAlphaComponent(0.3) : tintColor
UIView.animate(withDuration: 0.25, delay: 0.0, options: [.allowUserInteraction, .curveEaseInOut], animations: { [unowned self] in
self.backgroundColor = color
})
}
deinit {
do { try imageView?.remove(self, for: "image", in: &classContext) } catch {}
}
}
| ae68dc978fc03854e59444197b08e72c | 32.738462 | 151 | 0.623347 | false | false | false | false |
jjatie/Charts | refs/heads/master | Source/Charts/Charts/ChartViewBase.swift | apache-2.0 | 1 | //
// ChartViewBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
// Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880
import CoreGraphics
import Foundation
#if !os(OSX)
import UIKit
#endif
public protocol ChartViewDelegate: AnyObject {
/// Called when a value has been selected inside the chart.
///
/// - Parameters:
/// - entry: The selected Entry.
/// - highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc.
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight)
/// Called when a user stops panning between values on the chart
func chartViewDidEndPanning(_ chartView: ChartViewBase)
// Called when nothing has been selected or an "un-select" has been made.
func chartValueNothingSelected(_ chartView: ChartViewBase)
// Callbacks when the chart is scaled / zoomed via pinch zoom gesture.
func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat)
// Callbacks when the chart is moved / translated via drag gesture.
func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat)
// Callbacks when Animator stops animating
func chartView(_ chartView: ChartViewBase, animatorDidStop animator: Animator)
}
open class ChartViewBase: NSUIView {
// MARK: - Properties
/// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values.
internal lazy var defaultValueFormatter: ValueFormatter = DefaultValueFormatter(decimals: 0)
/// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied
open var data: ChartData? {
didSet {
offsetsCalculated = false
guard let data = data else { return }
// calculate how many digits are needed
setupDefaultFormatter(min: data.yRange.min, max: data.yRange.max)
for set in data where set.valueFormatter is DefaultValueFormatter {
set.valueFormatter = defaultValueFormatter
}
// let the chart know there is new data
notifyDataSetChanged()
}
}
/// If set to true, chart continues to scroll after touch up
public var isDragDecelerationEnabled = true
/// The object representing the labels on the x-axis
public internal(set) lazy var xAxis = XAxis()
/// The `Description` object of the chart.
public lazy var chartDescription = Description()
/// The legend object containing all data associated with the legend
open internal(set) lazy var legend = Legend()
/// delegate to receive chart events
open weak var delegate: ChartViewDelegate?
/// text that is displayed when the chart is empty
open var noDataText = "No chart data available."
/// Font to be used for the no data text.
open var noDataFont = NSUIFont.systemFont(ofSize: 12)
/// color of the no data text
open var noDataTextColor: NSUIColor = .labelOrBlack
/// alignment of the no data text
open var noDataTextAlignment: TextAlignment = .left
/// The renderer object responsible for rendering / drawing the Legend.
open lazy var legendRenderer = LegendRenderer(viewPortHandler: viewPortHandler, legend: legend)
/// object responsible for rendering the data
open var renderer: DataRenderer?
open var highlighter: Highlighter?
/// The ViewPortHandler of the chart that is responsible for the
/// content area of the chart and its offsets and dimensions.
open internal(set) lazy var viewPortHandler = ViewPortHandler(width: bounds.size.width, height: bounds.size.height)
/// The animator responsible for animating chart values.
lazy var chartAnimator: Animator = {
let animator = Animator()
animator.delegate = self
return animator
}()
/// flag that indicates if offsets calculation has already been done or not
private var offsetsCalculated = false
/// The array of currently highlighted values. This might an empty if nothing is highlighted.
open internal(set) var highlighted = [Highlight]()
/// `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
open var drawMarkers = true
/// - Returns: `true` if drawing the marker is enabled when tapping on values
/// (use the `marker` property to specify a marker)
open var isDrawMarkersEnabled: Bool { return drawMarkers }
/// The marker that is displayed when a value is clicked on the chart
open var marker: Marker?
/// An extra offset to be appended to the viewport's top
open var extraTopOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's right
open var extraRightOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's bottom
open var extraBottomOffset: CGFloat = 0.0
/// An extra offset to be appended to the viewport's left
open var extraLeftOffset: CGFloat = 0.0
open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) {
extraLeftOffset = left
extraTopOffset = top
extraRightOffset = right
extraBottomOffset = bottom
}
// MARK: - Initializers
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
deinit {
removeObserver(self, forKeyPath: "bounds")
removeObserver(self, forKeyPath: "frame")
}
internal func initialize() {
#if os(iOS)
backgroundColor = .clear
#endif
addObserver(self, forKeyPath: "bounds", options: .new, context: nil)
addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
// MARK: - ChartViewBase
/// Lets the chart know its underlying data has changed and should perform all necessary recalculations.
/// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour.
open func notifyDataSetChanged() {
fatalError("notifyDataSetChanged() cannot be called on ChartViewBase")
}
/// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position
internal func calculateOffsets() {
fatalError("calculateOffsets() cannot be called on ChartViewBase")
}
/// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter
internal func setupDefaultFormatter(min: Double, max: Double) {
// check if a custom formatter is set or not
var reference = 0.0
if let data = data, data.entryCount >= 2 {
reference = abs(max - min)
} else {
reference = Swift.max(abs(min), abs(max))
}
if let formatter = defaultValueFormatter as? DefaultValueFormatter {
// setup the formatter with a new number of digits
let digits = reference.decimalPlaces
formatter.decimals = digits
}
}
override open func draw(_: CGRect) {
guard let context = NSUIGraphicsGetCurrentContext() else { return }
if data === nil, !noDataText.isEmpty {
context.saveGState()
defer { context.restoreGState() }
let paragraphStyle = MutableParagraphStyle.default.mutableCopy() as! MutableParagraphStyle
paragraphStyle.minimumLineHeight = noDataFont.lineHeight
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = noDataTextAlignment
context.drawMultilineText(noDataText,
at: CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0),
constrainedTo: bounds.size,
anchor: CGPoint(x: 0.5, y: 0.5),
angleRadians: 0.0,
attributes: [.font: noDataFont,
.foregroundColor: noDataTextColor,
.paragraphStyle: paragraphStyle])
return
}
if !offsetsCalculated {
calculateOffsets()
offsetsCalculated = true
}
}
/// Draws the description text in the bottom right corner of the chart (per default)
internal func drawDescription(in context: CGContext) {
let description = chartDescription
// check if description should be drawn
guard
description.isEnabled,
let descriptionText = description.text,
!descriptionText.isEmpty
else { return }
let position = description.position ?? CGPoint(x: bounds.width - viewPortHandler.offsetRight - description.xOffset,
y: bounds.height - viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight)
let attrs: [NSAttributedString.Key: Any] = [
.font: description.font,
.foregroundColor: description.textColor,
]
context.drawText(descriptionText,
at: position,
align: description.textAlign,
attributes: attrs)
}
// MARK: - Accessibility
override open func accessibilityChildren() -> [Any]? {
return renderer?.accessibleChartElements
}
// MARK: - Highlighting
/// Set this to false to prevent values from being highlighted by tap gesture.
/// Values can still be highlighted via drag or programmatically.
/// **default**: true
public var isHighLightPerTapEnabled: Bool = true
/// Checks if the highlight array is null, has a length of zero or if the first object is null.
///
/// - Returns: `true` if there are values to highlight, `false` ifthere are no values to highlight.
public final var valuesToHighlight: Bool {
!highlighted.isEmpty
}
/// Highlights the values at the given indices in the given DataSets. Provide
/// null or an empty array to undo all highlighting.
/// This should be used to programmatically highlight values.
/// This method *will not* call the delegate.
public final func highlightValues(_ highs: [Highlight]?) {
// set the indices to highlight
highlighted = highs ?? []
lastHighlighted = highlighted.first
// redraw the chart
setNeedsDisplay()
}
/// Highlights the value at the given x-value and y-value in the given DataSet.
/// Provide -1 as the dataSetIndex to undo all highlighting.
///
/// - Parameters:
/// - x: The x-value to highlight
/// - y: The y-value to highlight. Supply `NaN` for "any"
/// - dataSetIndex: The dataset index to search in
/// - dataIndex: The data index to search in (only used in CombinedChartView currently)
/// - callDelegate: Should the delegate be called for this change
public final func highlightValue(x: Double, y: Double = .nan, dataSetIndex: Int, dataIndex: Int = -1, callDelegate: Bool = true)
{
guard let data = data else {
Swift.print("Value not highlighted because data is nil")
return
}
if data.indices.contains(dataSetIndex) {
highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex, dataIndex: dataIndex), callDelegate: callDelegate)
} else {
highlightValue(nil, callDelegate: callDelegate)
}
}
/// Highlights the value selected by touch gesture.
public final func highlightValue(_ highlight: Highlight?, callDelegate: Bool = false) {
var high = highlight
guard
let h = high,
let entry = data?.entry(for: h)
else {
high = nil
highlighted.removeAll(keepingCapacity: false)
if callDelegate {
delegate?.chartValueNothingSelected(self)
}
return
}
// set the indices to highlight
highlighted = [h]
if callDelegate {
// notify the listener
delegate?.chartValueSelected(self, entry: entry, highlight: h)
}
// redraw the chart
setNeedsDisplay()
}
/// - Returns: The Highlight object (contains x-index and DataSet index) of the
/// selected value at the given touch point inside the Line-, Scatter-, or
/// CandleStick-Chart.
open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? {
guard data != nil else {
Swift.print("Can't select by touch. No data set.")
return nil
}
return highlighter?.getHighlight(x: pt.x, y: pt.y)
}
/// The last value that was highlighted via touch.
open var lastHighlighted: Highlight?
// MARK: - Markers
/// draws all MarkerViews on the highlighted positions
func drawMarkers(context: CGContext) {
// if there is no marker view or drawing marker is disabled
guard let marker = marker,
isDrawMarkersEnabled,
valuesToHighlight
else { return }
for highlight in highlighted {
guard let set = data?[highlight.dataSetIndex],
let e = data?.entry(for: highlight),
let entryIndex = set.firstIndex(of: e),
entryIndex <= Int(Double(set.count) * chartAnimator.phaseX)
else { continue }
let pos = getMarkerPosition(highlight: highlight)
// check bounds
guard viewPortHandler.isInBounds(x: pos.x, y: pos.y) else { continue }
// callbacks to update the content
marker.refreshContent(entry: e, highlight: highlight)
// draw the marker
marker.draw(context: context, point: pos)
}
}
/// - Returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet.
public func getMarkerPosition(highlight: Highlight) -> CGPoint {
CGPoint(x: highlight.drawX, y: highlight.drawY)
}
// MARK: - Animation
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingX: an easing function for the animation on the x axis
/// - easingY: an easing function for the animation on the y axis
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingOptionX: the easing function for the animation on the x axis
/// - easingOptionY: the easing function for the animation on the y axis
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easing: an easing function for the animation
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - yAxisDuration: duration for animating the y axis
/// - easingOption: the easing function for the animation
public final func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine)
{
chartAnimator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - easing: an easing function for the animation
public final func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
chartAnimator.animate(xAxisDuration: xAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the x-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - xAxisDuration: duration for animating the x axis
/// - easingOption: the easing function for the animation
public final func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine) {
chartAnimator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
/// - easing: an easing function for the animation
public final func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) {
chartAnimator.animate(yAxisDuration: yAxisDuration, easing: easing)
}
/// Animates the drawing / rendering of the chart the y-axis with the specified animation time.
/// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart.
///
/// - Parameters:
/// - yAxisDuration: duration for animating the y axis
/// - easingOption: the easing function for the animation
public final func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption = .easeInOutSine) {
chartAnimator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption)
}
// MARK: - Accessors
/// The center of the chart taking offsets under consideration. (returns the center of the content rectangle)
public final var centerOffsets: CGPoint {
viewPortHandler.contentCenter
}
/// The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn).
public final var contentRect: CGRect {
viewPortHandler.contentRect
}
private var _viewportJobs = [ViewPortJob]()
override open func observeValue(forKeyPath keyPath: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer?)
{
if keyPath == "bounds" || keyPath == "frame" {
let bounds = self.bounds
if bounds.size.width != viewPortHandler.chartWidth ||
bounds.size.height != viewPortHandler.chartHeight
{
viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height)
// This may cause the chart view to mutate properties affecting the view port -- lets do this
// before we try to run any pending jobs on the view port itself
notifyDataSetChanged()
// Finish any pending viewport changes
while !_viewportJobs.isEmpty {
let job = _viewportJobs.remove(at: 0)
job.doJob()
}
}
}
}
public final func addViewportJob(_ job: ViewPortJob) {
if viewPortHandler.hasChartDimens {
job.doJob()
} else {
_viewportJobs.append(job)
}
}
public final func removeViewportJob(_ job: ViewPortJob) {
if let index = _viewportJobs.firstIndex(where: { $0 === job }) {
_viewportJobs.remove(at: index)
}
}
/// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately.
/// 1 is an invalid value, and will be converted to 0.999 automatically.
public final var dragDecelerationFrictionCoef: CGFloat {
get { _dragDecelerationFrictionCoef }
set { _dragDecelerationFrictionCoef = newValue.clamped(to: 0...0.999) }
}
private var _dragDecelerationFrictionCoef: CGFloat = 0.9
/// The maximum distance in screen pixels away from an entry causing it to highlight.
/// **default**: 500.0
public final var maxHighlightDistance: CGFloat = 500.0
}
// MARK: - AnimatorDelegate
extension ChartViewBase: AnimatorDelegate {
public final func animatorUpdated(_: Animator) {
setNeedsDisplay()
}
public final func animatorStopped(_ chartAnimator: Animator) {
delegate?.chartView(self, animatorDidStop: chartAnimator)
}
}
| e5f1a4111ba57adbda8d0f6127a335e0 | 39.734875 | 183 | 0.655353 | false | false | false | false |
devpunk/cartesian | refs/heads/master | GaussSquad/Extensions/ExtensionNSLayoutConstraint.swift | mit | 3 | import UIKit
extension NSLayoutConstraint
{
@discardableResult class func topToTop(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.top,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func topToBottom(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.top,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.bottom,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func bottomToBottom(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.bottom,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func bottomToTop(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.bottom,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.top,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func leftToLeft(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.left,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func leftToRight(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.left,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.right,
multiplier:multiplier,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func rightToRight(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.right,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.right,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func rightToLeft(
view:UIView,
toView:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.right,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.left,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func width(
view:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
@discardableResult class func height(
view:UIView,
constant:CGFloat = 0,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:1,
constant:constant)
constraint.isActive = true
return constraint
}
class func size(
view:UIView,
constant:CGFloat,
multiplier:CGFloat = 1)
{
NSLayoutConstraint.width(
view:view,
constant:constant,
multiplier:multiplier)
NSLayoutConstraint.height(
view:view,
constant:constant,
multiplier:multiplier)
}
@discardableResult class func width(
view:UIView,
toView:UIView,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.width,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.width,
multiplier:1,
constant:0)
constraint.isActive = true
return constraint
}
@discardableResult class func height(
view:UIView,
toView:UIView,
multiplier:CGFloat = 1) -> NSLayoutConstraint
{
let constraint:NSLayoutConstraint = NSLayoutConstraint(
item:view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:toView,
attribute:NSLayoutAttribute.height,
multiplier:1,
constant:0)
constraint.isActive = true
return constraint
}
class func equals(view:UIView, toView:UIView, margin:CGFloat = 0)
{
NSLayoutConstraint.topToTop(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.bottomToBottom(
view:view,
toView:toView,
constant:-margin)
NSLayoutConstraint.leftToLeft(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.rightToRight(
view:view,
toView:toView,
constant:-margin)
}
class func equalsHorizontal(view:UIView, toView:UIView, margin:CGFloat = 0)
{
NSLayoutConstraint.leftToLeft(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.rightToRight(
view:view,
toView:toView,
constant:-margin)
}
class func equalsVertical(view:UIView, toView:UIView, margin:CGFloat = 0)
{
NSLayoutConstraint.topToTop(
view:view,
toView:toView,
constant:margin)
NSLayoutConstraint.bottomToBottom(
view:view,
toView:toView,
constant:-margin)
}
}
| ef4092e50d3009206daeb25ca7e7ba68 | 28.321678 | 79 | 0.580968 | false | false | false | false |
GenericDataSource/GenericDataSource | refs/heads/master | Sources/DataSourceSelector.swift | mit | 1 | //
// DataSourceSelector.swift
// GenericDataSource
//
// Created by Mohamed Ebrahim Mohamed Afifi on 3/30/17.
// Copyright © 2017 mohamede1945. All rights reserved.
//
import UIKit
/// Represents the data source selectors that can be optional.
/// Each case corresponds to a selector in the DataSource.
@objc public enum DataSourceSelector: Int {
/// Represents the size selector.
case size
/*case shouldHighlight
case didHighlight
case didUnhighlight
case shouldSelect
case didSelect
case shouldDeselect
case didDeselect
case supplementaryViewOfKind
case sizeForSupplementaryViewOfKind
case willDisplaySupplementaryView
case didEndDisplayingSupplementaryView
case canMove
case move
case willDisplayCell
case didEndDisplayingCell*/
/// Represents the can edit selector.
case canEdit
/// Represents the commit editing selector.
case commitEditingStyle
/// Represents the editing style selector.
case editingStyle
/// Represents the title for delete confirmation button selector.
case titleForDeleteConfirmationButton
/// Represents the edit actions selector.
case editActions
/// Represents the should indent while editing selector.
case shouldIndentWhileEditing
/// Represents the will begin selector.
case willBeginEditing
/// Represents the did end editing selector.
case didEndEditing
/// Represents the should show menu for item selector.
case shouldShowMenuForItemAt
/// Represents the can perform action selector.
case canPerformAction
/// Represents the perform action selector.
case performAction
/// Represents the can focus item at index selector.
case canFocusItemAt
/// Represents the should update focus in selector.
case shouldUpdateFocusIn
/// Represents the did update focus in selector.
case didUpdateFocusIn
/// Represents the index path for preferred focused in view selector.
case indexPathForPreferredFocusedView
}
extension DataSourceSelector {
/// Whether or not the selector requires all data sources to respond to it.
/// Current implementation only `.size` requires all selectors and may change in the future.
/// It's always recommended if you want to implement a selector in your `BasicDataSource` subclass.
/// To do it in all classes that will be children of a `CompositeDataSource` or `SegmentedDataSource`.
public var mustAllRespondsToIt: Bool {
switch self {
case .size: return true
case .canEdit: return false
case .commitEditingStyle: return false
case .editingStyle: return false
case .titleForDeleteConfirmationButton: return false
case .editActions: return false
case .shouldIndentWhileEditing: return false
case .willBeginEditing: return false
case .didEndEditing: return false
case .shouldShowMenuForItemAt: return false
case .canPerformAction: return false
case .performAction: return false
case .canFocusItemAt: return false
case .shouldUpdateFocusIn: return false
case .didUpdateFocusIn: return false
case .indexPathForPreferredFocusedView: return false
}
}
}
let dataSourceSelectorToSelectorMapping: [DataSourceSelector: [Selector]] = {
var mapping: [DataSourceSelector: [Selector]] =
[.size: [
#selector(UITableViewDelegate.tableView(_:heightForRowAt:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:layout:sizeForItemAt:)),
#selector(DataSource.ds_collectionView(_:sizeForItemAt:))
],
.canEdit: [
#selector(UITableViewDataSource.tableView(_:canEditRowAt:)),
#selector(DataSource.ds_collectionView(_:canEditItemAt:))
],
.commitEditingStyle: [
#selector(UITableViewDataSource.tableView(_:commit:forRowAt:)),
#selector(DataSource.ds_collectionView(_:commit:forItemAt:))
],
.editingStyle: [
#selector(UITableViewDelegate.tableView(_:editingStyleForRowAt:)),
#selector(DataSource.ds_collectionView(_:editingStyleForItemAt:))
],
.titleForDeleteConfirmationButton: [
#selector(UITableViewDelegate.tableView(_:titleForDeleteConfirmationButtonForRowAt:)),
#selector(DataSource.ds_collectionView(_:titleForDeleteConfirmationButtonForItemAt:))
],
.editActions: [
#selector(UITableViewDelegate.tableView(_:editActionsForRowAt:)),
#selector(DataSource.ds_collectionView(_:editActionsForItemAt:))
],
.shouldIndentWhileEditing: [
#selector(UITableViewDelegate.tableView(_:shouldIndentWhileEditingRowAt:)),
#selector(DataSource.ds_collectionView(_:shouldIndentWhileEditingItemAt:))
],
.willBeginEditing: [
#selector(UITableViewDelegate.tableView(_:willBeginEditingRowAt:)),
#selector(DataSource.ds_collectionView(_:willBeginEditingItemAt:))
],
.didEndEditing: [
#selector(UITableViewDelegate.tableView(_:didEndEditingRowAt:)),
#selector(DataSource.ds_collectionView(_:didEndEditingItemAt:))
],
.shouldShowMenuForItemAt: [
#selector(UITableViewDelegate.tableView(_:shouldShowMenuForRowAt:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:shouldShowMenuForItemAt:)),
#selector(DataSource.ds_collectionView(_:shouldShowMenuForItemAt:))
],
.canPerformAction: [
#selector(UITableViewDelegate.tableView(_:canPerformAction:forRowAt:withSender:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:canPerformAction:forItemAt:withSender:)),
#selector(DataSource.ds_collectionView(_:canPerformAction:forItemAt:withSender:))
],
.performAction: [
#selector(UITableViewDelegate.tableView(_:performAction:forRowAt:withSender:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:performAction:forItemAt:withSender:)),
#selector(DataSource.ds_collectionView(_:performAction:forItemAt:withSender:))
]]
if #available(iOS 9.0, *) {
mapping[.canFocusItemAt] = [
#selector(UITableViewDelegate.tableView(_:canFocusRowAt:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:canFocusItemAt:)),
#selector(DataSource.ds_collectionView(_:canFocusItemAt:))
]
mapping[.shouldUpdateFocusIn] = [
#selector(UITableViewDelegate.tableView(_:shouldUpdateFocusIn:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:shouldUpdateFocusIn:)),
#selector(DataSource.ds_collectionView(_:shouldUpdateFocusIn:))
]
mapping[.didUpdateFocusIn] = [
#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:)),
#selector(UICollectionViewDelegateFlowLayout.collectionView(_:didUpdateFocusIn:with:)),
#selector(DataSource.ds_collectionView(_:didUpdateFocusIn:with:))
]
mapping[.indexPathForPreferredFocusedView] = [
#selector(UITableViewDelegate.indexPathForPreferredFocusedView(in:)),
#selector(UICollectionViewDelegateFlowLayout.indexPathForPreferredFocusedView(in:)),
#selector(DataSource.ds_indexPathForPreferredFocusedView(in:))
]
}
return mapping
}()
let selectorToDataSourceSelectorMapping: [Selector: DataSourceSelector] = {
var mapping: [Selector: DataSourceSelector] = [:]
for (key, value) in dataSourceSelectorToSelectorMapping {
for item in value {
precondition(mapping[item] == nil, "Use of selector \(item) multiple times")
mapping[item] = key
}
}
return mapping
}()
| 919095fe6ba721173e1f25f6b71ac9dd | 39.629442 | 115 | 0.687531 | false | false | false | false |
avito-tech/Marshroute | refs/heads/master | Marshroute/Sources/Transitions/TransitionAnimations/Modal/Presentation/ModalPresentationAnimationContext.swift | mit | 1 | import UIKit
/// Описание параметров анимаций прямого модального перехода на UIViewController
public struct ModalPresentationAnimationContext {
/// контроллер, на который нужно осуществить прямой модальный переход
public let targetViewController: UIViewController
/// контроллер, с которого нужно осуществить прямой модальный переход
public let sourceViewController: UIViewController
public init(
targetViewController: UIViewController,
sourceViewController: UIViewController)
{
self.targetViewController = targetViewController
self.sourceViewController = sourceViewController
}
public init?(
modalPresentationAnimationLaunchingContext: ModalPresentationAnimationLaunchingContext)
{
guard let targetViewController = modalPresentationAnimationLaunchingContext.targetViewController
else { return nil }
guard let sourceViewController = modalPresentationAnimationLaunchingContext.sourceViewController
else { return nil }
self.targetViewController = targetViewController
self.sourceViewController = sourceViewController
}
}
| bc5b8b05bbccddb11979e865bf6454a6 | 37.354839 | 104 | 0.746005 | false | false | false | false |
jathu/UIImageColors | refs/heads/master | UIImageColorsExample/ViewController.swift | mit | 1 | //
// ViewController.swift
// UIImageColorsExample
//
// Created by Jathu Satkunarajah on 2017-11-30 - Toronto
// Copyright © 2017 Jathu Satkunarajah. All rights reserved.
//
import UIKit
import UIImageColors
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
let albums: [Album] = [
Album(albumImage: #imageLiteral(resourceName: "Calvin Klein - Kaws"), albumName: "Calvin Klein", artistName: "Kaws", year: 1999),
Album(albumImage: #imageLiteral(resourceName: "Cafe Terrace at Night - Vincent Van Gogh"), albumName: "Cafe Terrace at Night", artistName: "Vincent Van Gogh", year: 1888),
Album(albumImage: #imageLiteral(resourceName: "Woman I - Willem de Kooning"), albumName: "Woman I", artistName: "Willem de Kooning", year: 1952),
Album(albumImage: #imageLiteral(resourceName: "Skull - Jean-Michel Basquiat"), albumName: "Skull", artistName: "Jean-Michel Basquiat", year: 1981),
Album(albumImage: #imageLiteral(resourceName: "Les Demoiselles d'Avignon - Picasso"), albumName: "Les Demoiselles d'Avignon", artistName: "Pablo Picasso", year: 1907),
Album(albumImage: #imageLiteral(resourceName: "Le Reve - Pablo Picasso"), albumName: "Le Rêve", artistName: "Pablo Picasso", year: 1932),
Album(albumImage: #imageLiteral(resourceName: "Mona Lisa - Leonardo da Vinci"), albumName: "Mona Lisa", artistName: "Leonardo da Vinci", year: 1503),
Album(albumImage: #imageLiteral(resourceName: "No. 210:No. 211 - Mark Rothko"), albumName: "No. 210/211 Orange", artistName: "Mark Rothko", year: 1960),
Album(albumImage: #imageLiteral(resourceName: "Blue Nude II - Henri Matisse"), albumName: "Blue Nude II", artistName: "Henri Matisse", year: 1952),
Album(albumImage: #imageLiteral(resourceName: "Nighthawks - Edward Hopper"), albumName: "Nighthawks", artistName: "Edward Hopper", year: 1942),
Album(albumImage: #imageLiteral(resourceName: "Number 1A - Jackson Pollock"), albumName: "Number 1A", artistName: "Jackson Pollock", year: 1948),
Album(albumImage: #imageLiteral(resourceName: "Self-portrait Spring 1887 - Vincent Van Gogh"), albumName: "Self-Portrait", artistName: "Vincent Van Gogh", year: 1887),
]
private let cellID = "cellID"
private let cellSizeFactor: CGFloat = 0.8
private lazy var cellSize: CGSize = {
let w = self.view.frame.width
return CGSize(width: w*self.cellSizeFactor, height: w)
}()
private lazy var cellSpacing: CGFloat = {
return self.view.frame.width*((1-self.cellSizeFactor)/4)
}()
private lazy var collectionView: UICollectionView = {
let l = UICollectionViewFlowLayout()
l.scrollDirection = .horizontal
l.minimumInteritemSpacing = 0
l.minimumLineSpacing = self.cellSpacing
let c = UICollectionView(frame: .zero, collectionViewLayout: l)
c.translatesAutoresizingMaskIntoConstraints = false
c.isScrollEnabled = true
c.isPagingEnabled = false
c.showsHorizontalScrollIndicator = false
c.showsVerticalScrollIndicator = false
c.backgroundColor = .clear
c.register(AlbumViewCell.self, forCellWithReuseIdentifier: self.cellID)
c.dataSource = self
c.delegate = self
return c
}()
private let mainLabel: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.textAlignment = .left
l.numberOfLines = 2
l.font = UIFont.systemFont(ofSize: 25, weight: UIFont.Weight.regular)
return l
}()
private let secondaryLabel: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.textAlignment = .left
l.numberOfLines = 1
l.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.regular)
return l
}()
private let detailLabel: UILabel = {
let l = UILabel()
l.translatesAutoresizingMaskIntoConstraints = false
l.textAlignment = .left
l.numberOfLines = 1
l.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.regular)
return l
}()
private var selectedIndex: IndexPath?
private var timer: Timer?
private let playButton: UIButton = {
let b = UIButton()
b.translatesAutoresizingMaskIntoConstraints = false
b.setImage(#imageLiteral(resourceName: "play").withRenderingMode(.alwaysTemplate), for: .normal)
b.tintColor = .white
return b
}()
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
// Add subviews
self.view.addSubview(self.collectionView)
self.view.addSubview(self.mainLabel)
self.view.addSubview(self.secondaryLabel)
self.view.addSubview(self.detailLabel)
self.view.addSubview(self.playButton)
// Constraints
NSLayoutConstraint.activate([
self.collectionView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
self.collectionView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.6),
self.collectionView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.collectionView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
self.mainLabel.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: self.cellSizeFactor),
self.mainLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.mainLabel.bottomAnchor.constraint(equalTo: self.collectionView.topAnchor),
self.secondaryLabel.widthAnchor.constraint(equalTo: self.mainLabel.widthAnchor),
self.secondaryLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.secondaryLabel.topAnchor.constraint(equalTo: self.collectionView.bottomAnchor),
self.detailLabel.widthAnchor.constraint(equalTo: self.mainLabel.widthAnchor),
self.detailLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
self.detailLabel.topAnchor.constraint(equalTo: self.secondaryLabel.bottomAnchor),
self.playButton.widthAnchor.constraint(equalToConstant: 24),
self.playButton.heightAnchor.constraint(equalToConstant: 24),
self.playButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -12),
self.playButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -12),
])
// Set up play button
self.playButton.addTarget(self, action: #selector(setupPlayTimer), for: .touchUpInside)
// Update view
self.selectedIndex = IndexPath(item: 0, section: 0)
self.updateView(with: self.albums[0])
}
@objc func setupPlayTimer() {
if self.timer == nil {
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(startPlaying), userInfo: nil, repeats: true)
self.playButton.isHidden = true
}
}
@objc func startPlaying() {
if let index = self.selectedIndex {
self.selectedIndex = IndexPath(item: (index.item+1)%self.albums.count, section: 0)
self.goTo(indexPath: self.selectedIndex)
}
}
func goTo(indexPath: IndexPath?) {
if let index = indexPath {
self.collectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true)
self.updateView(with: self.albums[index.item])
}
}
// Mark: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.albums.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellID, for: indexPath) as! AlbumViewCell
cell.imageView.image = self.albums[indexPath.item].albumImage
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return self.cellSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: self.cellSpacing*2, bottom: 0, right: self.cellSpacing*2)
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
if let _ = self.timer {
self.timer?.invalidate()
self.timer = nil
self.playButton.isHidden = false
}
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let rect = CGRect(origin: self.collectionView.contentOffset, size: self.collectionView.bounds.size)
let mid = CGPoint(x: rect.midX, y: rect.midY)
DispatchQueue.main.async {
var smallestDiff = CGFloat.greatestFiniteMagnitude
for index in self.collectionView.indexPathsForVisibleItems {
if let cell = self.collectionView.cellForItem(at: index) {
let diff = abs((cell.frame.origin.x+(cell.frame.width/2))-mid.x)
if diff < smallestDiff {
smallestDiff = diff
self.selectedIndex = index
}
}
}
self.goTo(indexPath: self.selectedIndex)
}
}
private func updateView(with album: Album) {
album.albumImage?.getColors(quality: .high) { colors in
guard let colors = colors else { return }
UIView.animate(withDuration: 0.15, animations: {
self.view.backgroundColor = colors.background
self.mainLabel.text = album.albumName
self.mainLabel.textColor = colors.primary
self.secondaryLabel.text = album.artistName
self.secondaryLabel.textColor = colors.secondary
self.detailLabel.text = "\(album.year)"
self.detailLabel.textColor = colors.detail
self.playButton.tintColor = colors.detail
})
}
}
}
| 5ad2988670c24eb0e72ac460f383d2c6 | 45.615385 | 179 | 0.657957 | false | false | false | false |
tensorflow/swift-apis | refs/heads/main | Tests/TensorFlowTests/LossTests.swift | apache-2.0 | 1 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
@testable import TensorFlow
final class LossTests: XCTestCase {
func testL1Loss() {
let predicted = Tensor<Float>([1, 2, 3, 4])
let expected = Tensor<Float>([0.1, 0.2, 0.3, 0.4])
let loss = l1Loss(predicted: predicted, expected: expected)
let expectedLoss: Float = 9.0
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testL2Loss() {
let predicted = Tensor<Float>([1, 2, 3, 4])
let expected = Tensor<Float>([0.5, 1.5, 2.5, 3.5])
let loss = l2Loss(predicted: predicted, expected: expected)
let expectedLoss: Float = 1.0
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testMeanSquaredErrorLoss() {
let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
let loss = meanSquaredError(predicted: predicted, expected: expected)
let expectedLoss: Float = 23.325
assertEqual(loss, Tensor(expectedLoss), accuracy: 2e-6)
}
func testMeanSquaredLogarithmicError() {
let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
let loss = meanSquaredLogarithmicError(predicted: predicted, expected: expected)
let expectedLoss: Float = 2.1312442
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testMeanAbsoluteError() {
let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
let loss = meanAbsoluteError(predicted: predicted, expected: expected)
let expectedLoss: Float = 4.25
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testMeanAbsolutePercentageError() {
let predicted = Tensor<Float>([1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8])
let loss = meanAbsolutePercentageError(predicted: predicted, expected: expected)
let expectedLoss: Float = 900.0
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testMeanSquaredErrorGrad() {
let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
let expectedGradientsBeforeMean = Tensor<Float>(
shape: [2, 4],
scalars: [1.8, 3.6, 5.4, 7.2, 9.2, 11.4, 13.6, 15.8])
// As the loss is mean loss, we should scale the golden gradient numbers.
let expectedGradients = expectedGradientsBeforeMean / Float(predicted.scalars.count)
let gradients = gradient(
at: predicted,
in: { meanSquaredError(predicted: $0, expected: expected) })
assertEqual(gradients, expectedGradients, accuracy: 1e-6)
}
func testHingeLoss() {
let predicted = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
let loss = hingeLoss(predicted: predicted, expected: expected)
let expectedLoss: Float = 0.225
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testSquaredHingeLoss() {
let predicted = Tensor<Float>([1, 2, 3, 4, 5, 6, 7, 8])
let expected = Tensor<Float>([0.5, 1, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0])
let loss = squaredHingeLoss(predicted: predicted, expected: expected)
let expectedLoss: Float = 0.00390625
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testCategoricalHingeLoss() {
let predicted = Tensor<Float>([3, 4, 5])
let expected = Tensor<Float>([0.3, 0.4, 0.3])
let loss = categoricalHingeLoss(predicted: predicted, expected: expected)
let expectedLoss: Float = 0.5
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testLogCoshLoss() {
let predicted = Tensor<Float>([0.2, 0.3, 0.4])
let expected = Tensor<Float>([1.0, 4.0, 3.0])
let loss = logCoshLoss(predicted: predicted, expected: expected)
let expectedLoss: Float = 1.7368573
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testPoissonLoss() {
let predicted = Tensor<Float>([0.1, 0.2, 0.3])
let expected = Tensor<Float>([1, 2, 3])
let loss = poissonLoss(predicted: predicted, expected: expected)
let expectedLoss: Float = 3.2444599
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testKullbackLeiblerDivergence() {
let predicted = Tensor<Float>([0.2, 0.3, 0.4])
let expected = Tensor<Float>([1.0, 4.0, 3.0])
let loss = kullbackLeiblerDivergence(predicted: predicted, expected: expected)
let expectedLoss: Float = 18.015217
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testSoftmaxCrossEntropyWithProbabilitiesLoss() {
let logits = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let labels = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
let loss = softmaxCrossEntropy(logits: logits, probabilities: labels)
// Loss for two rows are 1.44019 and 2.44019 respectively.
let expectedLoss: Float = (1.44019 + 2.44019) / 2.0
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testSoftmaxCrossEntropyWithProbabilitiesGrad() {
let logits = Tensor<Float>(shape: [2, 4], scalars: [1, 2, 3, 4, 5, 6, 7, 8])
let labels = Tensor<Float>(
shape: [2, 4],
scalars: [0.1, 0.2, 0.3, 0.4, 0.4, 0.3, 0.2, 0.1])
// For the logits and labels above, the gradients below are the golden values. To calcuate
// them by hand, you can do
//
// D Loss / D logits_i = p_i - labels_i
//
// where p_i is softmax(logits_i).
let expectedGradientsBeforeMean = Tensor<Float>(
shape: [2, 4],
scalars: [
-0.067941, -0.112856, -0.063117, 0.243914,
-0.367941, -0.212856, 0.036883, 0.543914,
])
// As the loss is mean loss, we should scale the golden gradient numbers.
let expectedGradients = expectedGradientsBeforeMean / Float(logits.shape[0])
let gradients = gradient(
at: logits,
in: { softmaxCrossEntropy(logits: $0, probabilities: labels) })
assertEqual(gradients, expectedGradients, accuracy: 1e-6)
}
func testSigmoidCrossEntropyLoss() {
let logits = Tensor<Float>(
shape: [2, 4],
scalars: [-100, -2, -2, 0, 2, 2, 2, 100])
let labels = Tensor<Float>(
shape: [2, 4],
scalars: [0, 0, 1, 0, 0, 1, 0.5, 1])
let loss = sigmoidCrossEntropy(logits: logits, labels: labels)
let expectedLoss: Float = 0.7909734
assertEqual(loss, Tensor(expectedLoss), accuracy: 1e-6)
}
func testSigmoidCrossEntropyGradient() {
let logits = Tensor<Float>(shape: [2, 4], scalars: [-100, -2, -2, 0, 0, 2, 2, 100])
let labels = Tensor<Float>(shape: [2, 4], scalars: [0, 0, 1, 0, 1, 1, 0.5, 1])
let computedGradient = gradient(
at: logits,
in: { sigmoidCrossEntropy(logits: $0, labels: labels) })
// The expected value of the gradient was computed using Python TensorFlow 1.14 with
// the following code:
// ```
// with tf.GradientTape() as t:
// t.watch([logits])
// y = tf.losses.sigmoid_cross_entropy(labels, logits, reduction="weighted_mean")
// print(t.gradient(y, [logits]))
// ```
let expectedGradient = Tensor<Float>([
[0.0, 0.01490036, -0.11009964, 0.0625],
[-0.0625, -0.01490036, 0.04759964, 0.0],
])
assertEqual(computedGradient, expectedGradient, accuracy: 1e-6)
}
func testHuberLoss() {
let predictions = Tensor<Float>([[0.9, 0.2, 0.2], [0.8, 0.4, 0.6]])
let labels = Tensor<Float>([[1, 0, 1], [1, 0, 0]])
do {
// Test adapted from:
// https://github.com/tensorflow/tensorflow/blob/148f07323f97ef54998f28cd95c195064ce2c426/tensorflow/python/keras/losses_test.py#L1554
let loss = huberLoss(predicted: predictions, expected: predictions, delta: 1)
assertEqual(loss, Tensor(0), accuracy: 1e-6)
}
do {
// Test adapted from:
// https://github.com/tensorflow/tensorflow/blob/148f07323f97ef54998f28cd95c195064ce2c426/tensorflow/python/keras/losses_test.py#L1560
// The expected loss was computed using Python TensorFlow 2.0.0-beta1:
// ```
// import tensorflow as tf # 2.0.0-beta1
// predictions = tf.constant([[0.9, 0.2, 0.2], [0.8, 0.4, 0.6]])
// labels = tf.constant([[1.0, 0.0, 1.0], [1.0, 0.0, 0.0]])
// loss = tf.losses.Huber(delta=1.0, reduction=tf.losses.Reduction.SUM)
// print(loss(labels, predictions))
// # tf.Tensor(0.62500006, shape=(), dtype=float32)
// ```
let loss = huberLoss(predicted: predictions, expected: labels, delta: Float(1))
assertEqual(loss, Tensor(0.62500006), accuracy: 1e-6)
}
}
static var allTests = [
("testL1Loss", testL1Loss),
("testL2Loss", testL2Loss),
("testMeanSquaredErrorLoss", testMeanSquaredErrorLoss),
("testMeanSquaredErrorGrad", testMeanSquaredErrorGrad),
("testMeanSquaredLogarithmicError", testMeanSquaredLogarithmicError),
("testMeanAbsoluteError", testMeanAbsoluteError),
("testMeanAbsolutePercentageError", testMeanAbsolutePercentageError),
("testHingeLoss", testHingeLoss),
("testKullbackLeiblerDivergence", testKullbackLeiblerDivergence),
("testCategoricalHingeLoss", testCategoricalHingeLoss),
("testSquaredHingeLoss", testSquaredHingeLoss),
("testPoissonLoss", testPoissonLoss),
("testLogCoshLoss", testLogCoshLoss),
(
"testSoftmaxCrossEntropyWithProbabilitiesLoss",
testSoftmaxCrossEntropyWithProbabilitiesLoss
),
(
"testSoftmaxCrossEntropyWithProbabilitiesGrad",
testSoftmaxCrossEntropyWithProbabilitiesGrad
),
("testSigmoidCrossEntropyLoss", testSigmoidCrossEntropyLoss),
("testSigmoidCrossEntropyGradient", testSigmoidCrossEntropyGradient),
("testHuberLoss", testHuberLoss),
]
}
| 29eec3ad918ed63156f24c0294b361c3 | 37.99639 | 140 | 0.651453 | false | true | false | false |
Isahkaren/ND-OnTheMap | refs/heads/master | OnTheMap/Controllers/MapViewController.swift | mit | 1 | //
// MapViewController.swift
// OnTheMap
//
// Created by Isabela Karen de Oliveira Gomes on 14/01/16.
// Copyright © 2017 Isabela Karen de Oliveira Gomes. All rights reserved.
//
import UIKit
import MapKit
class MapViewController: UIViewController {
// MARK: - Properties
@IBOutlet var mapMain: MKMapView!
var locationMananger = CLLocationManager()
fileprivate let pinReuseId = "pinStudentLocation"
fileprivate let segueLocation = "sgLocation"
// MARK: - Life Circle
override func viewDidLoad() {
super.viewDidLoad()
mapMain.delegate = self
locations()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locations()
}
//MARK: - Actions
@IBAction func btnRefresh_Clicked(_ sender: UIBarButtonItem) {
locations()
}
@IBAction func btnLogout_Clicked(_ sender: UIBarButtonItem) {
logout()
}
@IBAction func btnAddPin_Clicked(_ sender: UIBarButtonItem) {
self.performSegue(withIdentifier: self.segueLocation, sender: nil)
}
//MARK: - Services
func logout() {
UdacityServices.logout(onSuccess: { (serviceResponse) in
DispatchQueue.main.async {
Login.shared.clearLoggedUserData()
self.tabBarController?.dismiss(animated: true, completion: nil)
}
}, onFailure: { (serviceResponse) in
self.displayError(title: "Sorry!", message: "Logout went wrong")
}, onCompletion: {
})
}
func locations() {
UdacityServices.locationStudents(onSuccess: { (serviceResponse) in
guard let locationsDict = JsonUtils.deserialize(data: serviceResponse.data!) else {
return
}
print(locationsDict)
ShareLocations.share.locations = StudentLocation.mapLocations(dictionary: locationsDict)
self.setupPins(locations: ShareLocations.share.locations)
}, onFailure: { (serviceResponse) in
self.displayError(title: "Sorry", message: "An error occurred")
}, onCompletion: {
})
}
func setupPins(locations: [StudentLocation]) {
var annotations = [MKPointAnnotation]()
for location in locations {
guard let firstName = location.firstName else {
continue
}
guard let lat = location.latitude else {
continue
}
guard let long = location.longitude else {
continue
}
guard let lastName = location.lastName else {
continue
}
guard let mediaURL = location.mediaURL else {
continue
}
let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
annotation.title = "\(firstName) \(lastName)"
annotation.subtitle = mediaURL
annotations.append(annotation)
}
DispatchQueue.main.async {
self.mapMain.addAnnotations(annotations)
}
}
func displayError(title: String, message: String) {
let alert = UIAlertController(title: title, message:message , preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.destructive) { (action) in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(okAction)
DispatchQueue.main.async {
self.present(alert, animated: true, completion: nil)
}
}
}
// MARK: - Map
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: pinReuseId) as? MKPinAnnotationView
if pinView == nil {
pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: pinReuseId)
pinView!.canShowCallout = true
pinView!.pinTintColor = .red
pinView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
}
else {
pinView!.annotation = annotation
}
if (pinView?.annotation?.title!!.contains("Isabela"))! {
print("hey")
}
return pinView
}
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
if control == view.rightCalloutAccessoryView {
let app = UIApplication.shared
if let toOpen = view.annotation?.subtitle, let urlString = toOpen, let url = URL(string: urlString), app.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
self.displayError(title: "Error", message: "An error occurred!")
}
}
}
}
| aa2f744ee7b538a2c3e7e3c78c9b28da | 28.967391 | 134 | 0.565107 | false | false | false | false |
sjtu-meow/iOS | refs/heads/master | Meow/HomeViewController.swift | apache-2.0 | 1 | //
// HomeViewController.swift
// Meow
//
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import UIKit
import RxSwift
import Rswift
class HomeViewController: UITableViewController {
let bannerViewIdentifier = "bannerViewCell"
let disposeBag = DisposeBag()
var banners = [Banner]()
var currentPage = 0
var moments = [Moment]()
let searchBar = NoCancelButtonSearchBar()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.tableFooterView = UIView(frame: CGRect.zero)
loadData()
searchBar.delegate = self
self.navigationItem.titleView = searchBar
//let vc = R.storyboard.main.searchViewController()
//present(vc!, animated: true, completion: nil)
//self.navigationController?.pushViewController(vc!, animated: true)
//let vc = R.storyboard.articlePage.articleDetailViewController()
// let vc = R.storyboard.loginSignupPage.loginViewController()
//present(vc!, animated: true, completion: nil)
// let vc = R.storyboard.articlePage.articleDetailViewController()
// let vc = R.storyboard.loginSignupPage.loginViewController()
// present(vc!, animated: true, completion: nil)
//logger.log("hello world")
tableView.estimatedRowHeight = 80
tableView.rowHeight = UITableViewAutomaticDimension
tableView.register(R.nib.bannerViewCell)
tableView.register(R.nib.momentHomePageTableViewCell)
tableView.register(R.nib.answerHomePageTableViewCell)
tableView.register(R.nib.questionHomePageTableViewCell)
tableView.register(R.nib.articleHomePageTableViewCell)
}
func loadData() {
MeowAPIProvider.shared.request(.banners)
.mapTo(arrayOf: Banner.self)
.subscribe(onNext: {
[weak self] (banners) in
self?.banners = banners
})
.addDisposableTo(disposeBag)
loadMore()
MeowAPIProvider.shared.request(.moments) // FIXME: need to support other item types
.mapTo(arrayOf: Moment.self)
.subscribe(onNext: {
[weak self]
(items) in
self?.moments = items
self?.tableView.reloadData()
})
.addDisposableTo(disposeBag)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1 /* banners */ + 1 /* items */
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 /* banners: one cell */ {
return 1
}
/* item sections: one cell for each item */
return self.moments.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
/* banners */
if indexPath.section == 0 {
let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.bannerViewCell)!
view.configure(banners: self.banners)
view.onTapBanner = {
[weak self] banner in
self?.onTapBanner(banner!)
}
return view
}
/* items */
let item = self.moments[indexPath.row ]
// FIXME: check whether it is a comment cell
switch(item.type!) {
case .moment:
let view = R.nib.momentHomePageTableViewCell.firstView(owner: nil)!
// let view = tableView.dequeueReusableCell(withIdentifier: R.nib.momentHomePageTableViewCell)!
view.configure(model: item as! Moment)
view.delegate = self
return view
case .answer:
let view = tableView.dequeueReusableCell(withIdentifier: R.nib.answerHomePageTableViewCell.identifier)!
(view as! AnswerHomePageTableViewCell).configure(model: item as! AnswerSummary)
return view
case .article:
let view = tableView.dequeueReusableCell(withIdentifier: R.nib.articleHomePageTableViewCell.identifier)!
(view as! ArticleHomePageTableViewCell).configure(model: item as! ArticleSummary)
return view
case .question:
let view = tableView.dequeueReusableCell(withIdentifier: R.nib.questionHomePageTableViewCell.identifier)!
(view as! QuestionHomePageTableViewCell).configure(model: item as! Question)
return view
}
}
override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
guard section == 1 else { return }
loadMore()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let moment = moments[indexPath.row]
MomentDetailViewController.show(moment, from: self)
}
func loadMore() {
MeowAPIProvider.shared.request(.moments) // FIXME: need to support other item types
.mapTo(arrayOf: Moment.self)
.subscribe(onNext: {
[weak self] (items) in
self?.moments = items // FIXME
self?.tableView.reloadData()
self?.currentPage += 1
})
.addDisposableTo(disposeBag)
}
override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let moment = moments[indexPath.row]
MomentDetailViewController.show(moment, from: self)
}
@IBAction func showPostTypePicker(_ sender: Any) {
PostTypeViewController.show(from: self)
}
func onTapBanner(_ banner: Banner) {
let type = banner.itemType!
switch type {
case .moment:
MeowAPIProvider.shared.request(.moment(id: banner.itemId)).mapTo(type: Moment.self).subscribe(onNext: {
[weak self] moment in
if let self_ = self {
MomentDetailViewController.show(moment, from: self_)
}
}).addDisposableTo(disposeBag)
case .article:
MeowAPIProvider.shared.request(.article(id: banner.itemId)).mapTo(type: Article.self).subscribe (onNext: {
[weak self] article in
if let self_ = self {
ArticleDetailViewController.show(article, from: self_)
}
}).addDisposableTo(disposeBag)
case .answer:
MeowAPIProvider.shared.request(.answer(id: banner.itemId)).mapTo(type: Answer.self).subscribe (onNext: {
[weak self] answer in
if let self_ = self {
ArticleDetailViewController.show(answer, from: self_)
}
}).addDisposableTo(disposeBag)
case .question:
let vc = R.storyboard.questionAnswerPage.questionDetailViewController()!
vc.configure(questionId: banner.itemId)
navigationController?.pushViewController(vc, animated: true)
default: break
}
}
}
extension HomeViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
DispatchQueue.main.async {
let vc = R.storyboard.main.searchViewController()
self.navigationController?.pushViewController(vc!, animated: true)
}
return false
}
}
extension HomeViewController: MomentCellDelegate {
func didTapAvatar(profile: Profile) {
if let userId = UserManager.shared.currentUser?.userId, userId == profile.userId {
MeViewController.show(from: navigationController!)
} else {
UserProfileViewController.show(profile, from: self)
}
}
func didToggleLike(id: Int, isLiked: Bool) -> Bool {
var liked = isLiked
let request = isLiked ? MeowAPI.unlikeMoment(id: id) : MeowAPI.likeMoment(id: id)
MeowAPIProvider.shared.request(request)
.subscribe(onNext: {
_ in
liked = !isLiked
})
.addDisposableTo(disposeBag)
return liked
}
func didPostComment(moment: Moment, content: String, from cell: MomentHomePageTableViewCell) {
MeowAPIProvider.shared.request(.postComment(item: moment, content: content))
.subscribe(onNext:{
[weak self]
_ in
cell.clearComment()
cell.model!.commentCount! += 1
cell.updateCommentCountLabel()
self?.loadData()
})
}
}
| 93a2d3fb33a7a09d337da25f1082f48c | 34.294821 | 118 | 0.596568 | false | false | false | false |
phatblat/SwiftHub | refs/heads/master | SwiftHubTests/SwiftHubSpec.swift | mit | 1 | //
// SwiftHubSpec.swift
// SwiftHub
//
// Created by Ben Chatelain on 8/8/15.
// Copyright © 2015 phatblat. All rights reserved.
//
import Quick
class SwiftHubSpec: QuickSpec {
var semaphore: dispatch_semaphore_t?
/// Starts an async test.
func startAsync() {
guard let semaphore = dispatch_semaphore_create(0)
else { fatalError("Failed to create semaphore") }
self.semaphore = semaphore
}
/// Stops an async test.
func stopAsync() {
semaphore = nil
}
/// Signals the semaphore.
func signal() {
guard let semaphore = self.semaphore
else { fatalError("Can't signal with a nil semaphore") }
dispatch_semaphore_signal(semaphore)
}
/// Halts execution of the current queue, waiting for either the semaphore
/// to be signaled or the given timeout (default 10s).
/// - seconds: The number of seconds to wait for the async operation before
/// failing the test.
func waitForSignalOrTimeout(seconds: Int = 10) {
guard let semaphore = self.semaphore
else { fatalError("Can't wait on a nil semaphore") }
let timeout = dispatch_time(DISPATCH_TIME_NOW, Int64(UInt64(seconds) * NSEC_PER_SEC))
dispatch_semaphore_wait(semaphore, timeout)
}
}
| 1c20d4e0b2de8ea8bd13c72febb2d3fa | 26.020833 | 93 | 0.645335 | false | true | false | false |
frootloops/swift | refs/heads/master | test/IRGen/subclass.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// CHECK: %swift.refcounted = type {
// CHECK: [[TYPE:%swift.type]] = type
// CHECK: [[OBJC_CLASS:%objc_class]] = type {
// CHECK: [[OPAQUE:%swift.opaque]] = type
// CHECK: [[A:%T8subclass1AC]] = type <{ [[REF:%swift.refcounted]], %TSi, %TSi }>
// CHECK: [[INT:%TSi]] = type <{ i64 }>
// CHECK: [[B:%T8subclass1BC]] = type <{ [[REF]], [[INT]], [[INT]], [[INT]] }>
// CHECK: @_DATA__TtC8subclass1A = private constant {{.*\* } }}{
// CHECK: @_T08subclass1ACMf = internal global [[A_METADATA:<{.*i64 }>]] <{
// CHECK: void ([[A]]*)* @_T08subclass1ACfD,
// CHECK: i8** @_T0BoWV,
// CHECK: i64 ptrtoint ([[OBJC_CLASS]]* @_T08subclass1ACMm to i64),
// CHECK: [[OBJC_CLASS]]* @"OBJC_CLASS_$_SwiftObject",
// CHECK: [[OPAQUE]]* @_objc_empty_cache,
// CHECK: [[OPAQUE]]* null,
// CHECK: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1A to i64), i64 1),
// CHECK: i64 ([[A]]*)* @_T08subclass1AC1fSiyF,
// CHECK: [[A]]* ([[TYPE]]*)* @_T08subclass1AC1gACyFZ
// CHECK: }>
// CHECK: @_DATA__TtC8subclass1B = private constant {{.*\* } }}{
// CHECK: @_T08subclass1BCMf = internal global <{ {{.*}} }> <{
// CHECK: void ([[B]]*)* @_T08subclass1BCfD,
// CHECK: i8** @_T0BoWV,
// CHECK: i64 ptrtoint ([[OBJC_CLASS]]* @_T08subclass1BCMm to i64),
// CHECK: [[TYPE]]* {{.*}} @_T08subclass1ACMf,
// CHECK: [[OPAQUE]]* @_objc_empty_cache,
// CHECK: [[OPAQUE]]* null,
// CHECK: i64 add (i64 ptrtoint ({ {{.*}} }* @_DATA__TtC8subclass1B to i64), i64 1),
// CHECK: i64 ([[B]]*)* @_T08subclass1BC1fSiyF,
// CHECK: [[A]]* ([[TYPE]]*)* @_T08subclass1AC1gACyFZ
// CHECK: }>
// CHECK: @objc_classes = internal global [2 x i8*] [i8* {{.*}} @_T08subclass1ACN {{.*}}, i8* {{.*}} @_T08subclass1BCN {{.*}}], section "__DATA,__objc_classlist,regular,no_dead_strip", align 8
class A {
var x = 0
var y = 0
func f() -> Int { return x }
class func g() -> A { return A() }
init() { }
}
class B : A {
var z : Int = 10
override func f() -> Int { return z }
}
class G<T> : A {
}
// Ensure that downcasts to generic types instantiate generic metadata instead
// of trying to reference global metadata. <rdar://problem/14265663>
// CHECK: define hidden swiftcc %T8subclass1GCySiG* @_T08subclass9a_to_gintAA1GCySiGAA1AC1a_tF(%T8subclass1AC*) {{.*}} {
func a_to_gint(a: A) -> G<Int> {
// CHECK: call %swift.type* @_T08subclass1GCySiGMa()
// CHECK: call i8* @swift_dynamicCastClassUnconditional
return a as! G<Int>
}
// CHECK: }
| 6e228959a62771d662b99407829fdd38 | 38.636364 | 192 | 0.595566 | false | false | false | false |
Mrwerdo/QuickShare | refs/heads/master | EncodingTests/EncodingTests.swift | mit | 1 | //
// EncodingTests.swift
// QuickShare
//
// Copyright (c) 2016 Andrew Thompson
//
// 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
@testable import Core
class EncodingTests : XCTestCase {
func testBasicUsage() {
let ctlmsg = ControlMessage(type: .Repeat,
signatureHash: 0xFF00,
packetID: 21)
var buff = [UInt8](count: Int(ctlmsg.length), repeatedValue: 1)
ctlmsg.fill(&buff, offset: 0)
let expectedBuff: [UInt8] = [
7, // Type
0, 0, 0, 0, // upper 4 bytes of signature hash
0, 0, 255, 0, // lower 4 bytes of signature hash
0, 0, 0, 0, // upper 4 bytes of packetID
0 ,0, 0, 21, // lower 4 bytes of packetID
0, 19, // lower 4 bytes of length
]
XCTAssertEqual(expectedBuff, buff)
}
func testUser() {
let user = User(username: "Bob Phillohop",
macAddress: nil,
ipAddress: 0xC0A80004, // 192.168.0.4
time: 0)
let ctlmsg = ControlMessage(type: .Repeat,
signatureHash: 0xFF00,
packetID: 30)
let computedBuff = ctlmsg.pack(user)
let expectedBuff: [UInt8] = [
7, // Type
0,0,0,0, 0,0,255,0, // Signature Hash
0,0,0,0, 0,0,0,30, // Packet ID
0,51, // Length
0,0,0,0, 0,0, // MAC Address (which is nil)
192,168,0,4, // IP Address
0,255, // Byte ordering
0,32, // User length
0, // Info = (is controlling and transfering)
0,0,0,0, // User Time
66,111,98,32, 80,104,105,108,108,111,104,111,112 // username
]
XCTAssertEqual(expectedBuff, computedBuff)
}
func testUser2() {
let user = User(username: "Bob Phillohop",
macAddress: 0xa82066522efb0000,
ipAddress: 0xC0A80004, // 192.168.0.4
time: 0)
let ctlmsg = ControlMessage(type: .Repeat,
signatureHash: 0xFF00,
packetID: 30)
let computedBuff = ctlmsg.pack(user)
let expectedBuff: [UInt8] = [
7, // Type
0,0,0,0, 0,0,255,0, // Signature Hash
0,0,0,0, 0,0,0,30, // Packet ID
0,51, // Length
0xa8,0x20,0x66,0x52, 0x2e,0xfb, // Mac Address
192,168,0,4, // IP Address
0,255, // Byte ordering
0,32, // User length
0, // Info = (is controlling and transfering)
0,0,0,0, // User Time
66,111,98,32, 80,104,105,108,108,111,104,111,112 // username
]
XCTAssertEqual(expectedBuff, computedBuff)
[7, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 51, 168, 32, 102, 82, 46, 251, 192, 168, 0, 4, 0, 255, 0, 32, 0, 0, 0, 0, 0, 66, 111, 98, 32, 80, 104, 105, 108, 108, 111, 104, 111, 112]
[7, 0, 0, 0, 0, 0, 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 30, 0, 51, 102, 82, 46, 251, 0, 0, 192, 168, 0, 4, 0, 255, 0, 32, 0, 0, 0, 0, 0, 66, 111, 98, 32, 80, 104, 105, 108, 108, 111, 104, 111, 112]
}
func testSignature() {
let user = User(username: "logzzz1",
macAddress: 0xAB0FFF0022550000,
ipAddress: 0xC0A80008,
time: 0)
user.isTransfering = true
user.isController = true
let signature = Signature(hash: 0xFEDCBA9876543210,
user: user)
let message = ControlMessage(type: .SyncMessage,
signatureHash: signature.hash,
packetID: 1_000_000_000)
let computedBuff = message.pack(signature)
let expectedBuff: [UInt8] = [
4, // message.type
0xfe,0xdc,0xba,0x98, 0x76,0x54,0x32,0x10, // signatuer.hash
0,0,0,0, 0x3b, 0x9a, 0xca, 0x00, // message.packetID
0, 53, // Computed length
0xfe,0xdc,0xba,0x98, 0x76,0x54,0x32,0x10, // signature.hash
0xab,0x0f,0xff,0x00, 0x22,0x55, // user.macAddress
192,168,0,8, // user.ipAddress
0,255, // user.byteOrdering
0,26, // user.length
3, // user.info
0,0,0,0, // user.time
108,111,103,122, 122,122,49, // user.username
]
XCTAssertEqual(expectedBuff, computedBuff)
}
func testFileMetadata() {
let metadata = FileMetadata(filename: "Video1.mov",
filesize: 4096,
checksumP1: 0x12345678,
checksumP2: 0,
numberOfPackets: 8,
sizeOfPackets: 512,
fileID: 0x56473829,
originPath: nil)
let message = ControlMessage(type: .Packet,
signatureHash: 0xFEED,
packetID: 17)
let computedBuff = message.pack(metadata)
let expectedBuff: [UInt8] = [
5, // message.type
0,0,0,0, 0,0,0xFE,0xED, // signature.hash
0,0,0,0, 0,0,0,17, // message.packetID
0,69, // Computed Length
0,0,0,0, 0,0,16,0, // metadata.filesize
0,0,0,0, 0x12,0x34,0x56,0x78, // metadata.checksumP1
0,0,0,0, 0,0,0,0, // metadata.checksumP2
0,0,0,0, 0,0,0,8, // metadata.numberOfPackets
2,0, // metadata.sizeOfPackets
0,50, // metadata.length
0x56,0x47,0x38,0x29, // metadata.fid
86,105,100,101, 111,49,46,109, 111,118 // metadata.filename
]
XCTAssertEqual(expectedBuff, computedBuff)
}
func testTransferMessage1() {
let metadata = FileMetadata(filename: "illegal_torrent1.sometype",
filesize: 0xabcdefabcdef0000, //123454326789,
checksumP1: 0xF0F0F0F,
checksumP2: 0,
numberOfPackets: 0x55e6f7d5e6f780,
sizeOfPackets: 512,
fileID: 0xFFFFFFFF,
originPath: nil)
let transferMessage = TransferMessage(metadata: metadata,
fileID: metadata.fileID,
type: .Request)
let message = ControlMessage(type: .TransferMessage,
signatureHash: 0x87,
packetID: 101)
let computedBuff = message.pack(transferMessage)
let expectedBuff: [UInt8] = [
2, // message.type
0,0,0,0, 0,0,0,135, // Signature hash
0,0,0,0, 0,0,0,101, // message.packet
0, 89, // Computed Length
1, // transferMessage.type
0xff,0xff,0xff,0xff, // transferMessage.fileID
0xab,0xcd,0xef,0xab, 0xcd,0xef,0,0, // metadata.filesize
0,0,0,0, 0xf, 0xf, 0xf, 0xf, // metadata.checksumP1
0,0,0,0, 0,0,0,0, // metadata.checksumP2
0,0x55,0xe6,0xf7, 0xd5,0xe6,0xf7,0x80, // metadata.numberOfPackets
2,0, // metadata.sizeOfPackets
0,65, // metadata.length
0xff,0xff,0xff,0xff, // metadata.fid
105,108,108,101, 103,97,108,95, // metadata.filename
116,111,114,114, 101,110,116,49,
46,115,111,109, 101,116,121,112,
101
]
XCTAssertEqual(expectedBuff, computedBuff)
}
func testTransferMessage2() {
let transferMessage = TransferMessage(metadata: nil,
fileID: 0xFFFFFFFF,
type: .NotEnoughSpace)
let message = ControlMessage(type: .TransferMessage,
signatureHash: 0x87,
packetID: 101)
let computedBuff = message.pack(transferMessage)
let expectedBuff: [UInt8] = [
2, // message.type
0,0,0,0, 0,0,0,135, // Signature hash
0,0,0,0, 0,0,0,101, // message.packet
0, 24, // Computed Length
4, // transferMessage.type
0xff,0xff,0xff,0xff, // transferMessage.fileID
]
XCTAssertEqual(expectedBuff, computedBuff)
}
func testSyncMessage() {
let user = User(username: "Andrew",
macAddress: nil,
ipAddress: nil,
time: 0)
let signature = Signature(hash: 0x1234, user: user)
let syncMessage = SyncMessage(type: .Sync,
signature: signature)
let message = ControlMessage(type: .SyncMessage,
signatureHash: 0x1234,
packetID: 4)
let computedBuff = message.pack(syncMessage)
let expectedBuff: [UInt8] = [
4, // message.type
0,0,0,0, 0,0,0x12,0x34, // signature.hash
0,0,0,0, 0,0,0,4, // message.packet
0, 53, // computed length
1, // syncmessage.type
0,0,0,0, 0,0,0x12,0x34, // signature.hash
0,0,0,0, 0,0, // user.mackaddress
0,0,0,0, // user.ipaddress
0,0xff, // user.byteordering
0,25, // user.length
0, // user.info
0,0,0,0, // user.time
65, 110, 100, 114, 101, 119 // user.username
]
XCTAssertEqual(expectedBuff, computedBuff)
}
func testSyncMessage2() {
let user = User(username: "Bob The Dragron Slayer",
macAddress: nil,
ipAddress: nil,
time: 0xF0F0F0F0)
user.isController = true
let signature = Signature(hash: 0, user: user)
let syncMessage = SyncMessage(type: .Sync,
signature: signature)
let message = ControlMessage(type: .SyncMessage,
signatureHash: 0x1234,
packetID: 4)
let computedBuff = message.pack(syncMessage)
let expectedBuff: [UInt8] = [
4, // message.type
0,0,0,0, 0,0,0x12,0x34, // signature.hash
0,0,0,0, 0,0,0,4, // message.packet
0, 69, // computed length
1, // syncmessage.type
0,0,0,0, 0,0,0,0, // signature.hash
0,0,0,0, 0,0, // user.macaddress
0,0,0,0, // user.ipaddress
0, 255, // user.byteordering
0, 41, // user.length
1, // user.info
0xF0,0xF0,0xF0,0xF0, // user.time
66, 111, 98, 32, 84, 104, 101, 32, 68, 114, 97, 103, 114, 111, 110, 32, 83, 108, 97, 121, 101, 114,
]
XCTAssertEqual(expectedBuff, computedBuff)
}
}
| ac420863ae20181fdd6fe79b97f9516b | 47.605863 | 203 | 0.415226 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Sync/CleartextPayloadJSON.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
import SwiftyJSON
open class BasePayloadJSON {
let json: JSON
required public init(_ jsonString: String) {
self.json = JSON(parseJSON: jsonString)
}
public init(_ json: JSON) {
self.json = json
}
// Override me.
public func isValid() -> Bool {
return self.json.type != .unknown &&
self.json.error == nil
}
subscript(key: String) -> JSON { return json[key] }
}
/**
* http://docs.services.mozilla.com/sync/objectformats.html
* "In addition to these custom collection object structures, the
* Encrypted DataObject adds fields like id and deleted."
*/
open class CleartextPayloadJSON: BasePayloadJSON {
required public override init(_ json: JSON) {
super.init(json)
}
required public init(_ jsonString: String) {
super.init(jsonString)
}
// Override me.
override open func isValid() -> Bool {
return super.isValid() && self["id"].isString()
}
open var id: String {
return self["id"].string!
}
open var deleted: Bool {
let d = self["deleted"]
if let bool = d.bool {
return bool
} else {
return false
}
}
// Override me.
// Doesn't check id. Should it?
open func equalPayloads (_ obj: CleartextPayloadJSON) -> Bool {
return self.deleted == obj.deleted
}
}
| d9b7b6f7a672b7151a2b218e4bbb7f50 | 24.061538 | 70 | 0.61019 | false | false | false | false |
narner/AudioKit | refs/heads/master | AudioKit/Common/MIDI/Sequencer/AKDuration.swift | mit | 1 | //
// AKDuration.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
public typealias BPM = Double
/// Container for the notion of time in sequencing
public struct AKDuration: CustomStringConvertible, Comparable {
let secondsPerMinute = 60
/// Duration in beats
public var beats: Double
/// Samples per second
public var sampleRate: Double = 44_100
/// Tempo in BPM (beats per minute)
public var tempo: BPM = 60.0
/// While samples is the most accurate, they blow up too fast, so using beat as standard
public var samples: Int {
get {
let doubleSamples = beats / tempo * secondsPerMinute * sampleRate
if doubleSamples <= Double(Int.max) {
return Int(doubleSamples)
} else {
AKLog("Warning: Samples exceeds the maximum number.")
return .max
}
}
set {
beats = (newValue / sampleRate) / secondsPerMinute * tempo
}
}
/// Regular time measurement
public var seconds: Double {
return Double(samples) / sampleRate
}
/// Useful for math using tempo in BPM (beats per minute)
public var minutes: Double {
return seconds / 60.0
}
/// Music time stamp for the duration in beats
public var musicTimeStamp: MusicTimeStamp {
return MusicTimeStamp(beats)
}
/// Pretty printout
public var description: String {
return "\(samples) samples at \(sampleRate) = \(beats) Beats at \(tempo) BPM = \(seconds)s"
}
/// Initialize with samples
///
/// - Parameters:
/// - samples: Number of samples
/// - sampleRate: Sample rate in samples per second
///
public init(samples: Int, sampleRate: Double = 44_100, tempo: BPM = 60) {
self.beats = tempo * (samples / sampleRate) / secondsPerMinute
self.sampleRate = sampleRate
self.tempo = tempo
}
/// Initialize from a beat perspective
///
/// - Parameters:
/// - beats: Duration in beats
/// - tempo: AKDurations per minute
///
public init(beats: Double, tempo: BPM = 60) {
self.beats = beats
self.tempo = tempo
}
/// Initialize from a normal time perspective
///
/// - Parameters:
/// - seconds: Duration in seconds
/// - sampleRate: Samples per second (Default: 44100)
///
public init(seconds: Double, sampleRate: Double = 44_100, tempo: BPM = 60) {
self.sampleRate = sampleRate
self.tempo = tempo
self.beats = tempo * (seconds / secondsPerMinute)
}
/// Add to a duration
///
/// - parameter lhs: Starting duration
/// - parameter rhs: Amount to add
///
public static func += (lhs: inout AKDuration, rhs: AKDuration) {
lhs.beats += rhs.beats
}
/// Subtract from a duration
///
/// - parameter lhs: Starting duration
/// - parameter rhs: Amount to subtract
///
public static func -= (lhs: inout AKDuration, rhs: AKDuration) {
lhs.beats -= rhs.beats
}
/// Duration equality
///
/// - parameter lhs: One duration
/// - parameter rhs: Another duration
///
public static func ==(lhs: AKDuration, rhs: AKDuration) -> Bool {
return lhs.beats == rhs.beats
}
/// Duration less than
///
/// - parameter lhs: One duration
/// - parameter rhs: Another duration
///
public static func < (lhs: AKDuration, rhs: AKDuration) -> Bool {
return lhs.beats < rhs.beats
}
/// Adding durations
///
/// - parameter lhs: One duration
/// - parameter rhs: Another duration
///
public static func + (lhs: AKDuration, rhs: AKDuration) -> AKDuration {
var newDuration = lhs
newDuration.beats += rhs.beats
return newDuration
}
/// Subtracting durations
///
/// - parameter lhs: One duration
/// - parameter rhs: Another duration
///
public static func - (lhs: AKDuration, rhs: AKDuration) -> AKDuration {
var newDuration = lhs
newDuration.beats -= rhs.beats
return newDuration
}
/// Modulus of the duration's beats
///
/// - parameter lhs: One duration
/// - parameter rhs: Another duration
///
public static func % (lhs: AKDuration, rhs: AKDuration) -> AKDuration {
var copy = lhs
copy.beats = lhs.beats.truncatingRemainder(dividingBy: rhs.beats)
return copy
}
}
/// Upper bound of a duration, in beats
///
/// - parameter duration: AKDuration
///
public func ceil(_ duration: AKDuration) -> AKDuration {
var copy = duration
copy.beats = ceil(copy.beats)
return copy
}
| bb26080888950c1245f0ee5d06a1beb6 | 26.924855 | 99 | 0.59408 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/17733-swift-sourcemanager-getmessage.swift | mit | 11 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
let a = {
deinit {
{
class A {
class A {
let a = [ {
{
func b {
{
let a = {
let a {
class A {
enum b {
extension NSData {
class A {
class d {
class A {
let a = [ {
case
let {
{
var d {
{
let a = {
p( [ {
{
class A {
var d {
case
{
( {
case
let {
{
{
}
class A {
enum A {
func b {
class
for {
class B {
class
case ,
| f738cdc3a86470b5fd774ff24b1eca6e | 8.918367 | 87 | 0.604938 | false | false | false | false |
auermi/noted | refs/heads/master | Noted/EditViewController.swift | mit | 1 | //
// EditViewController.swift
// Noted
//
// Created by Michael Andrew Auer on 1/23/16.
// Copyright © 2016 Usonia LLC. All rights reserved.
//
import UIKit
class EditViewController: UIViewController {
@IBOutlet weak var noteTextField: UITextView!
@IBOutlet weak var noteTitleField: UITextField!
var selectedValue: Note!
let dataInterface = DataInterface()
var user: [User] = []
override func viewDidLoad() {
super.viewDidLoad()
// Get rid of that blank space at the top of the text view
self.automaticallyAdjustsScrollViewInsets = false
if (selectedValue != nil) {
// Set the value of the text field to the note that we clicked on in the table view
noteTitleField.text = selectedValue?.noteTitle
noteTextField.text = selectedValue?.note
self.navigationController?.topViewController!.title = "Edit Note"
} else {
self.navigationController?.topViewController!.title = "New Note"
}
// Hide the back button
self.navigationItem.setHidesBackButton(true, animated: false)
user = dataInterface.get("User") as! [User]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "save") {
// If we have a note object update it, if not create a new one
if (selectedValue == nil) {
dataInterface.create("Note", properties: [
"note": noteTextField.text! as NSObject,
"noteTitle": noteTitleField.text! as NSObject,
"dateUpdated": DateTime().setDate() as NSObject,
"userID": (user.first?.id)! as NSObject
])
} else {
selectedValue?.note = noteTextField.text!
selectedValue?.noteTitle = noteTitleField.text!
selectedValue?.dateUpdated = DateTime().setDate()
dataInterface.update(selectedValue)
}
}
}
}
| 79c0f899e0a94c57590e79c9df4d15df | 34.83871 | 95 | 0.59991 | false | false | false | false |
mas-cli/mas | refs/heads/main | Sources/MasKit/AppStore/SSPurchase.swift | mit | 1 | //
// SSPurchase.swift
// mas-cli
//
// Created by Andrew Naylor on 25/08/2015.
// Copyright (c) 2015 Andrew Naylor. All rights reserved.
//
import CommerceKit
import StoreFoundation
typealias SSPurchaseCompletion =
(_ purchase: SSPurchase?, _ completed: Bool, _ error: Error?, _ response: SSPurchaseResponse?) -> Void
extension SSPurchase {
convenience init(adamId: UInt64, account: ISStoreAccount?, purchase: Bool = false) {
self.init()
var parameters: [String: Any] = [
"productType": "C",
"price": 0,
"salableAdamId": adamId,
"pg": "default",
"appExtVrsId": 0,
]
if purchase {
parameters["macappinstalledconfirmed"] = 1
parameters["pricingParameters"] = "STDQ"
} else {
// is redownload, use existing functionality
parameters["pricingParameters"] = "STDRDL"
}
buyParameters =
parameters.map { key, value in
"\(key)=\(value)"
}
.joined(separator: "&")
itemIdentifier = adamId
if let account = account {
accountIdentifier = account.dsID
appleID = account.identifier
}
// Not sure if this is needed, but lets use it here.
if purchase {
isRedownload = false
}
let downloadMetadata = SSDownloadMetadata()
downloadMetadata.kind = "software"
downloadMetadata.itemIdentifier = adamId
self.downloadMetadata = downloadMetadata
}
func perform(_ completion: @escaping SSPurchaseCompletion) {
CKPurchaseController.shared().perform(self, withOptions: 0, completionHandler: completion)
}
}
| 4a5cede181639483641c43631ca226d0 | 26.4375 | 106 | 0.58656 | false | false | false | false |
3DprintFIT/octoprint-ios-client | refs/heads/dev | OctoPhoneTests/Networking/Model Mapping/PrinterProfileTests.swift | mit | 1 | //
// PrinterProfileTests.swift
// OctoPhone
//
// Created by Josef Dolezal on 02/04/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import Nimble
import Quick
@testable import OctoPhone
class PrinterProfileTests: QuickSpec {
override func spec() {
describe("Printer profile") {
describe("converts from JSON") {
context("valid JSON") {
var data: [String: Any]!
beforeEach {
data = ["id": "_default", "model": "RepRap Printer", "name": "Default"]
}
afterEach {
data = nil
}
it("converts") {
expect() { try PrinterProfile.fromJSON(json: data) }.toNot(throwError())
if let subject = try? PrinterProfile.fromJSON(json: data) {
expect(subject.ID) == "_default"
expect(subject.name) == "Default"
expect(subject.model) == "RepRap Printer"
}
}
}
context("invalid JSON") {
var data: [String: Any]!
beforeEach {
data = [:]
}
afterEach {
data = nil
}
it("throws an error") {
expect() { try PrinterProfile.fromJSON(json: data) }.to(throwError())
}
}
}
describe("converts to JSON") {
let profile = PrinterProfile(ID: "Identifier", model: "Model", name: "Name")
it("creates valid JSON") {
let json = profile.asJSON()
expect((json["id"] as! String)) == "Identifier"
expect((json["name"] as! String)) == "Name"
expect((json["model"] as! String)) == "Model"
}
it("converts all required properties to json") {
expect(profile.asJSON().count) == 3
}
}
}
}
}
| b91896ac134930dca60c872d9482952c | 30.027397 | 96 | 0.407506 | false | false | false | false |
mengxiangyue/MShare_Salon | refs/heads/master | 第一期:iOS专场/JS与Swift的交互/WebviewIFrameTest/WebviewIFrameTest/ViewController.swift | mit | 1 | //
// ViewController.swift
// WebviewIFrameTest
//
// Created by xiangyue on 16/3/22.
// Copyright © 2016年 xiangyue. All rights reserved.
//
import UIKit
import JavaScriptCore
class ViewController: UIViewController {
lazy var webView = UIWebView()
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = self.view.frame
webView.delegate = self
self.view.addSubview(webView)
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("test", ofType: "html")!)
let request = NSURLRequest(URL: url);
self.webView.loadRequest(request)
let button = UIButton(frame: CGRect(x: 300, y: 60, width: 60, height: 40))
button.setTitle("后退", forState: .Normal)
button.backgroundColor = UIColor.redColor()
self.view.addSubview(button)
button.addTarget(self, action: #selector(goBack), forControlEvents: .TouchUpInside)
let reloadButton = UIButton(frame: CGRect(x: 300, y: 120, width: 60, height: 40))
reloadButton.setTitle("刷新", forState: .Normal)
reloadButton.backgroundColor = UIColor.redColor()
self.view.addSubview(reloadButton)
reloadButton.addTarget(self, action: #selector(refresh), forControlEvents: .TouchUpInside)
let callJSButton = UIButton(frame: CGRect(x: 300, y: 180, width: 60, height: 40))
callJSButton.setTitle("Call JS", forState: .Normal)
callJSButton.backgroundColor = UIColor.redColor()
self.view.addSubview(callJSButton)
callJSButton.addTarget(self, action: #selector(callJS), forControlEvents: .TouchUpInside)
}
func goBack() {
self.webView.goBack()
}
func refresh() {
self.webView.reload()
}
func callJS() {
self.webView.stringByEvaluatingJavaScriptFromString("alert('执行js函数')")
// let context = JSContext()
let context = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as! JSContext
context.evaluateScript("var x = 2; var y = 3;")
let result = context.evaluateScript("x + y")
print("调用context获取的返回值:\(result)")
context.evaluateScript("alert('通过context调用的函数')")
}
}
extension ViewController : UIWebViewDelegate {
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
print("\(#file) \(#function)")
return true
}
func webViewDidStartLoad(webView: UIWebView) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {}
struct Static {
static var onceToken : dispatch_once_t = 0
}
dispatch_once(&Static.onceToken) {}
let jsContext = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as! JSContext
jsContext.setObject(JSBridegeObject(), forKeyedSubscript: "mxy")
jsContext.exceptionHandler = {(context: JSContext!, exceptionValue: JSValue!) -> Void in
print("异常了:\(exceptionValue)")
}
self.webView.stringByEvaluatingJavaScriptFromString("alert('webViewDidStartLoad-mxy')")
print("\(#file) \(#function)")
}
func webViewDidFinishLoad(webView: UIWebView) {
print("\(#file) \(#function)")
let jsContext = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as! JSContext
jsContext.evaluateScript("$('#label').text('这是OC文字')")
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
print("\(#file) \(#function)")
}
func share() {
print("\(#file) \(#function)")
}
}
// 必须使用@objc 标注出来 必须继承自JSExport协议
@objc protocol JavaScriptObjectiveCDelegate: JSExport {
func share()
func printLog(log: String)
func getId() -> String
}
@objc class JSBridegeObject : NSObject, JavaScriptObjectiveCDelegate {
func share() {
print("这是JS->OC方法的调用")
}
func printLog(log: String) {
print(log)
}
func getId() -> String {
return "id:mengxiangyue"
}
}
| dac67e35efb99793f9b1fb753b52dc12 | 32.865079 | 137 | 0.640262 | false | false | false | false |
AaronMT/firefox-ios | refs/heads/main | Storage/ReadingList.swift | mpl-2.0 | 9 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
func ReadingListNow() -> Timestamp {
return Timestamp(Date.timeIntervalSinceReferenceDate * 1000.0)
}
let ReadingListDefaultUnread: Bool = true
let ReadingListDefaultArchived: Bool = false
let ReadingListDefaultFavorite: Bool = false
public protocol ReadingList {
func getAvailableRecords() -> Deferred<Maybe<[ReadingListItem]>>
@discardableResult func deleteRecord(_ record: ReadingListItem) -> Success
func deleteAllRecords() -> Success
@discardableResult func createRecordWithURL(_ url: String, title: String, addedBy: String) -> Deferred<Maybe<ReadingListItem>>
func getRecordWithURL(_ url: String) -> Deferred<Maybe<ReadingListItem>>
@discardableResult func updateRecord(_ record: ReadingListItem, unread: Bool) -> Deferred<Maybe<ReadingListItem>>
}
public struct ReadingListItem: Equatable {
public let id: Int
public let lastModified: Timestamp
public let url: String
public let title: String
public let addedBy: String
public let unread: Bool
public let archived: Bool
public let favorite: Bool
/// Initializer for when a record is loaded from a database row
public init(id: Int, lastModified: Timestamp, url: String, title: String, addedBy: String, unread: Bool = true, archived: Bool = false, favorite: Bool = false) {
self.id = id
self.lastModified = lastModified
self.url = url
self.title = title
self.addedBy = addedBy
self.unread = unread
self.archived = archived
self.favorite = favorite
}
}
public func ==(lhs: ReadingListItem, rhs: ReadingListItem) -> Bool {
return lhs.id == rhs.id
&& lhs.lastModified == rhs.lastModified
&& lhs.url == rhs.url
&& lhs.title == rhs.title
&& lhs.addedBy == rhs.addedBy
&& lhs.unread == rhs.unread
&& lhs.archived == rhs.archived
&& lhs.favorite == rhs.favorite
}
| ec41088fc0b67c4a5040b51a7272fc16 | 36.12069 | 165 | 0.6902 | false | false | false | false |
skheenat/Pong_Game | refs/heads/master | PongGame/GameViewController.swift | apache-2.0 | 1 | //
// GameViewController.swift
// PongGame
//
// Created by Sandun Heenatigala on 9/4/17.
// Copyright © 2017 Sandun Heenatigala. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit any size of screens in the ios device lineup
//.fill is used here as reference the given link would help
//http://stackoverflow.com/questions/33968046/sprite-kit-scene-editor-gamescene-sks-scene-width-and-height
scene.scaleMode = .fill
// Present the scene
scene.score = [0,0]
scene.viewController = self
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = false
view.showsNodeCount = false
}
}
//function for game over - due to global variables can take
public func gameOver(gameScene : GameScene, winner : SKNode)
{
//message local variable for showing information
var message = ""
//Rapid fire mode
if(_MODE == Mode.RapidFire)
{
message = "Score: " + String(_SCORE) + " points"
}
//If single player or multiplayer mode
else
{
if(_MODE == Mode.SinglePlayer)
{
if(winner == gameScene.paddle1)
{
message = "Winner!!"
}
else
{
message = "You Lose!!"
}
}
else
{
if(winner == gameScene.paddle1)
{
message = "Player 1 Wins"
}
else
{
message = "Player 2 Wins"
}
}
}
//Showing message
// Message for rapid fire modee
if(_MODE == Mode.RapidFire)
{
let alert = UIAlertController(title: "Game Over", message: message, preferredStyle: .alert)
//Adding text field for capturing name
alert.addTextField { (textField) in
textField.text = "Enter Name"
}
//Adding action when button gets pressed
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
// Creating and adding score
let textField = (alert?.textFields![0])! as UITextField
let value = textField.text!
//Getting the name value from the scores
let score = Score();
score.setScore(score: _SCORE, name: value)
score.Save()
self.performSegue(withIdentifier: "toScore", sender: nil);
}))
// 4. Present the alert.
self.present(alert, animated: true, completion: nil)
}
else
{
//presenting alert
let alert = UIAlertController(title: "Game Over", message: message, preferredStyle: UIAlertControllerStyle.alert)
// User resumes game
alert.addAction(UIAlertAction(title: "Continue", style: .default, handler: { (action: UIAlertAction!) in
self.performSegue(withIdentifier: "leaveGame", sender: nil);
}))
alert.addAction(UIAlertAction(title: "Restart", style: .default, handler: { (action: UIAlertAction!) in
gameScene.removeFromParent()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit any size of screens in the ios device lineup
//.fill is used here as reference the given link would help
//http://stackoverflow.com/questions/33968046/sprite-kit-scene-editor-gamescene-sks-scene-width-and-height
scene.scaleMode = .fill
// Present the scene
scene.score = [0,0]
scene.viewController = self
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}))
present(alert, animated: true, completion: nil)
}
}
// function called when game is paused
public func gamePaused(gameScene : GameScene)
{
//presenting alert
let alert = UIAlertController(title: "Paused", message: "", preferredStyle: UIAlertControllerStyle.alert)
// User resumes game
alert.addAction(UIAlertAction(title: "Resume", style: .default, handler: { (action: UIAlertAction!) in
gameScene.isPaused = false
}))
alert.addAction(UIAlertAction(title: "Restart", style: .default, handler: { (action: UIAlertAction!) in
gameScene.removeFromParent()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = GameScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit any size of screens in the ios device lineup
//.fill is used here as reference the given link would help
//http://stackoverflow.com/questions/33968046/sprite-kit-scene-editor-gamescene-sks-scene-width-and-height
scene.scaleMode = .fill
// Present the scene
scene.score = [0,0]
scene.viewController = self
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = false
view.showsNodeCount = false
}
}))
// user exiting game
alert.addAction(UIAlertAction(title: "Exit", style: .cancel, handler: { (action: UIAlertAction!) in
self.performSegue(withIdentifier: "leaveGame", sender: nil);
}))
present(alert, animated: true, completion: nil) }
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| 102fc846d16216f494cee4823e758fba | 34.320574 | 126 | 0.517881 | false | false | false | false |
dasdom/Poster | refs/heads/master | Poster/Networking/WebLoginViewController.swift | mit | 1 | //
// WebLoginViewController.swift
// Poster
//
// Created by dasdom on 12.04.15.
// Copyright (c) 2015 Dominik Hauser. All rights reserved.
//
import Cocoa
import WebKit
import KeychainAccess
import ADN
let kAccountNameArrayKey = "kAccountNameArrayKey"
let kActiveAccountNameKey = "kActiveAccountNameKey"
class WebLoginViewController: NSViewController, WKNavigationDelegate {
// @IBOutlet weak var webView: WebView!
var webView: WKWebView!
var progressIndicator: NSProgressIndicator!
override func viewDidLoad() {
super.viewDidLoad()
var urlString = "https://account.app.net/oauth/authenticate?client_id=\(kClientId)&response_type=token&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=write_post stream"
let request = NSMutableURLRequest(URL: NSURL(string: urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)!)
// request.HTTPShouldHandleCookies = false
// let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
// if let allCookies = storage.cookies {
// for cookie in allCookies as! [NSHTTPCookie] {
// println("cookie domain: \(cookie.domain)")
// if cookie.domain == "account.app.net" {
// storage.deleteCookie(cookie)
// }
// }
// }
webView = WKWebView(frame: NSRect.zeroRect)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.navigationDelegate = self
view.addSubview(webView)
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[webView(450)]|", options: nil, metrics: nil, views: ["webView": webView]))
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView(450)]|", options: nil, metrics: nil, views: ["webView": webView]))
progressIndicator = NSProgressIndicator()
progressIndicator.displayedWhenStopped = false
progressIndicator.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(progressIndicator)
NSLayoutConstraint(item: progressIndicator, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .CenterX, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint(item: progressIndicator, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .CenterY, multiplier: 1.0, constant: 0.0).active = true
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("[progressIndicator(50)]", options: nil, metrics: nil, views: ["progressIndicator": progressIndicator]))
NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[progressIndicator(50)]", options: nil, metrics: nil, views: ["progressIndicator": progressIndicator]))
webView.loadRequest(request)
progressIndicator.startAnimation(self)
println("viewDidLoad")
}
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
progressIndicator.startAnimation(self)
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
progressIndicator.stopAnimation(self)
if let title = webView.title {
let length = title.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
if length > 30 {
let accessToken = title
webView.loadHTMLString("Fetching username", baseURL: nil)
let apiCommunicator = ADNAPICommunicator()
apiCommunicator.loggedInUserWithAccessToken(accessToken) { user in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let user = user
println("username: \(user.username)")
let accountKey = "AccessToken_\(user.username)"
KeychainAccess.setPassword(accessToken, account: accountKey)
let userDefaults = NSUserDefaults(suiteName: kSuiteName)
var array = userDefaults?.arrayForKey(kAccountNameArrayKey)
if array == nil {
array = [String]()
}
array!.append(user.username)
userDefaults?.setObject(array!, forKey: kAccountNameArrayKey)
userDefaults?.setObject(user.username, forKey: kActiveAccountNameKey)
userDefaults?.synchronize()
// println("userdefaults \(userDefaults?.dictionaryRepresentation())")
NSNotificationCenter.defaultCenter().postNotificationName(DidLoginOrLogoutNotification, object: self, userInfo: nil)
// NSApplication.sharedApplication().stopModal()
if let window = NSApplication.sharedApplication().keyWindow {
print(window)
window.close()
}
});
}
}
}
}
}
| 5d51cb9a0d3e17a920d6d01138c9e004 | 40.29661 | 196 | 0.677817 | false | false | false | false |
Mobilette/AniMee | refs/heads/develop | AniMee/Classes/Modules/Anime/List/Day/User Interface/Cell/AnimeListDayCell.swift | mit | 1 | //
// AnimeListDayCell.swift
// AniMee
//
// Created by Benaly Issouf M'sa on 09/02/16.
// Copyright © 2016 Mobilette. All rights reserved.
//
import UIKit
class AnimeListDayCell: UICollectionViewCell {
var name: String = "" {
didSet {
self.animeTitle.text = name
}
}
var season: String = "" {
didSet {
self.animeSeason.text = season
}
}
var number: String = "" {
didSet {
self.episodeNumber.text = number
}
}
var title: String = "" {
didSet {
self.episodeTitle.text = title
}
}
var hour: String = "" {
didSet {
self.releaseHour.text = hour
}
}
var imageURL: NSURL? = nil {
didSet {
self.animeImageView.image = UIImage()
if let url = imageURL {
ImageAPIService.fetchImage(url).then { [unowned self] data -> Void in
self.animeImageView.image = UIImage(data: data)
}
}
}
}
// MARK: - Outlet
@IBOutlet private weak var animeTitle: UILabel!
@IBOutlet private weak var animeSeason: UILabel!
@IBOutlet private weak var episodeNumber: UILabel!
@IBOutlet private weak var episodeTitle: UILabel!
@IBOutlet private weak var releaseHour: UILabel!
@IBOutlet private weak var animeImageView: UIImageView!
}
| ff38748c32156f75cd9744f14768daa2 | 22.354839 | 85 | 0.547652 | false | false | false | false |
krummler/SKPhotoBrowser | refs/heads/master | SKPhotoBrowser/SKPhotoBrowser.swift | mit | 1 | //
// SKPhotoBrowser.swift
// SKViewExample
//
// Created by suzuki_keishi on 2015/10/01.
// Copyright © 2015 suzuki_keishi. All rights reserved.
//
import UIKit
public let SKPHOTO_LOADING_DID_END_NOTIFICATION = "photoLoadingDidEndNotification"
// MARK: - SKPhotoBrowser
public class SKPhotoBrowser: UIViewController {
let pageIndexTagOffset: Int = 1000
private var closeButton: SKCloseButton!
private var deleteButton: SKDeleteButton!
private var toolbar: SKToolbar!
// actions
private var activityViewController: UIActivityViewController!
private var panGesture: UIPanGestureRecognizer!
// tool for controls
private var applicationWindow: UIWindow!
private var pagingScrollView: SKPagingScrollView!
var backgroundView: UIView!
var initialPageIndex: Int = 0
var currentPageIndex: Int = 0
// for status check property
private var isEndAnimationByToolBar: Bool = true
private var isViewActive: Bool = false
private var isPerformingLayout: Bool = false
// pangesture property
private var firstX: CGFloat = 0.0
private var firstY: CGFloat = 0.0
// timer
private var controlVisibilityTimer: NSTimer!
// delegate
private let animator = SKAnimator()
public weak var delegate: SKPhotoBrowserDelegate?
// photos
var photos: [SKPhotoProtocol] = [SKPhotoProtocol]()
var numberOfPhotos: Int {
return photos.count
}
// MARK - Initializer
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
public override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nil, bundle: nil)
setup()
}
public convenience init(photos: [SKPhotoProtocol]) {
self.init(nibName: nil, bundle: nil)
let picutres = photos.flatMap { $0 }
for photo in picutres {
photo.checkCache()
self.photos.append(photo)
}
}
public convenience init(originImage: UIImage, photos: [SKPhotoProtocol], animatedFromView: UIView) {
self.init(nibName: nil, bundle: nil)
animator.senderOriginImage = originImage
animator.senderViewForAnimation = animatedFromView
let picutres = photos.flatMap { $0 }
for photo in picutres {
photo.checkCache()
self.photos.append(photo)
}
}
deinit {
pagingScrollView = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func setup() {
guard let window = UIApplication.sharedApplication().delegate?.window else {
return
}
applicationWindow = window
modalPresentationCapturesStatusBarAppearance = true
modalPresentationStyle = .Custom
modalTransitionStyle = .CrossDissolve
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.handleSKPhotoLoadingDidEndNotification(_:)), name: SKPHOTO_LOADING_DID_END_NOTIFICATION, object: nil)
}
// MARK: - override
override public func viewDidLoad() {
super.viewDidLoad()
configureAppearance()
configureCloseButton()
configureDeleteButton()
configureToolbar()
animator.willPresent(self)
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
reloadData()
var i = 0
for photo: SKPhotoProtocol in photos {
photo.index = i
i = i + 1
}
}
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
isPerformingLayout = true
closeButton.updateFrame()
deleteButton.updateFrame()
pagingScrollView.updateFrame(view.bounds, currentPageIndex: currentPageIndex)
toolbar.frame = frameForToolbarAtOrientation()
// where did start
delegate?.didShowPhotoAtIndex?(currentPageIndex)
isPerformingLayout = false
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
isViewActive = true
}
// MARK: - Notification
public func handleSKPhotoLoadingDidEndNotification(notification: NSNotification) {
guard let photo = notification.object as? SKPhotoProtocol else {
return
}
dispatch_async(dispatch_get_main_queue(), {
guard let page = self.pagingScrollView.pageDisplayingAtPhoto(photo), let photo = page.photo else {
return
}
if photo.underlyingImage != nil {
page.displayImage(complete: true)
self.loadAdjacentPhotosIfNecessary(photo)
} else {
page.displayImageFailure()
}
})
}
public func loadAdjacentPhotosIfNecessary(photo: SKPhotoProtocol) {
pagingScrollView.loadAdjacentPhotosIfNecessary(photo, currentPageIndex: currentPageIndex)
}
// MARK: - initialize / setup
public func reloadData() {
performLayout()
view.setNeedsLayout()
}
public func performLayout() {
isPerformingLayout = true
toolbar.updateToolbar(currentPageIndex)
// reset local cache
pagingScrollView.reload()
// reframe
pagingScrollView.updateContentOffset(currentPageIndex)
pagingScrollView.tilePages()
delegate?.didShowPhotoAtIndex?(currentPageIndex)
isPerformingLayout = false
}
public func prepareForClosePhotoBrowser() {
cancelControlHiding()
applicationWindow.removeGestureRecognizer(panGesture)
NSObject.cancelPreviousPerformRequestsWithTarget(self)
}
public func dismissPhotoBrowser(animated animated: Bool, completion: (Void -> Void)? = nil) {
prepareForClosePhotoBrowser()
if !animated {
modalTransitionStyle = .CrossDissolve
}
dismissViewControllerAnimated(!animated) {
completion?()
self.delegate?.didDismissAtPageIndex?(self.currentPageIndex)
}
}
public func determineAndClose() {
delegate?.willDismissAtPageIndex?(currentPageIndex)
animator.willDismiss(self)
}
}
// MARK: - Public Function For Customizing Buttons
public extension SKPhotoBrowser {
func updateCloseButton(image: UIImage) {
if closeButton == nil {
configureCloseButton()
}
closeButton.setImage(image, forState: .Normal)
}
func updateDeleteButton(image: UIImage) {
if deleteButton == nil {
configureDeleteButton()
}
deleteButton.setImage(image, forState: .Normal)
}
}
// MARK: - Public Function For Browser Control
public extension SKPhotoBrowser {
func initializePageIndex(index: Int) {
var i = index
if index >= numberOfPhotos {
i = numberOfPhotos - 1
}
initialPageIndex = i
currentPageIndex = i
if isViewLoaded() {
jumpToPageAtIndex(index)
if !isViewActive {
pagingScrollView.tilePages()
}
}
}
func jumpToPageAtIndex(index: Int) {
if index < numberOfPhotos {
if !isEndAnimationByToolBar {
return
}
isEndAnimationByToolBar = false
toolbar.updateToolbar(currentPageIndex)
let pageFrame = frameForPageAtIndex(index)
pagingScrollView.animate(pageFrame)
}
hideControlsAfterDelay()
}
func photoAtIndex(index: Int) -> SKPhotoProtocol {
return photos[index]
}
func gotoPreviousPage() {
jumpToPageAtIndex(currentPageIndex - 1)
}
func gotoNextPage() {
jumpToPageAtIndex(currentPageIndex + 1)
}
func cancelControlHiding() {
if controlVisibilityTimer != nil {
controlVisibilityTimer.invalidate()
controlVisibilityTimer = nil
}
}
func hideControlsAfterDelay() {
// reset
cancelControlHiding()
// start
controlVisibilityTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(SKPhotoBrowser.hideControls(_:)), userInfo: nil, repeats: false)
}
func hideControls() {
setControlsHidden(true, animated: true, permanent: false)
}
func hideControls(timer: NSTimer) {
hideControls()
}
func toggleControls() {
setControlsHidden(!areControlsHidden(), animated: true, permanent: false)
}
func areControlsHidden() -> Bool {
return toolbar.alpha == 0.0
}
}
// MARK: - Internal Function
internal extension SKPhotoBrowser {
func showButtons() {
if SKPhotoBrowserOptions.displayCloseButton {
closeButton.alpha = 1
closeButton.frame = closeButton.showFrame
}
if SKPhotoBrowserOptions.displayDeleteButton {
deleteButton.alpha = 1
deleteButton.frame = deleteButton.showFrame
}
}
func pageDisplayedAtIndex(index: Int) -> SKZoomingScrollView? {
return pagingScrollView.pageDisplayedAtIndex(index)
}
func getImageFromView(sender: UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(sender.frame.size, true, 0.0)
sender.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
}
// MARK: - Internal Function For Frame Calc
internal extension SKPhotoBrowser {
func frameForToolbarAtOrientation() -> CGRect {
let currentOrientation = UIApplication.sharedApplication().statusBarOrientation
var height: CGFloat = navigationController?.navigationBar.frame.size.height ?? 44
if UIInterfaceOrientationIsLandscape(currentOrientation) {
height = 32
}
return CGRect(x: 0, y: view.bounds.size.height - height, width: view.bounds.size.width, height: height)
}
func frameForToolbarHideAtOrientation() -> CGRect {
let currentOrientation = UIApplication.sharedApplication().statusBarOrientation
var height: CGFloat = navigationController?.navigationBar.frame.size.height ?? 44
if UIInterfaceOrientationIsLandscape(currentOrientation) {
height = 32
}
return CGRect(x: 0, y: view.bounds.size.height + height, width: view.bounds.size.width, height: height)
}
func frameForPageAtIndex(index: Int) -> CGRect {
let bounds = pagingScrollView.bounds
var pageFrame = bounds
pageFrame.size.width -= (2 * 10)
pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + 10
return pageFrame
}
}
// MARK: - Internal Function For Button Pressed, UIGesture Control
internal extension SKPhotoBrowser {
func panGestureRecognized(sender: UIPanGestureRecognizer) {
guard let zoomingScrollView: SKZoomingScrollView = pagingScrollView.pageDisplayedAtIndex(currentPageIndex) else {
return
}
backgroundView.hidden = true
let viewHeight: CGFloat = zoomingScrollView.frame.size.height
let viewHalfHeight: CGFloat = viewHeight/2
var translatedPoint: CGPoint = sender.translationInView(self.view)
// gesture began
if sender.state == .Began {
firstX = zoomingScrollView.center.x
firstY = zoomingScrollView.center.y
hideControls()
setNeedsStatusBarAppearanceUpdate()
}
translatedPoint = CGPoint(x: firstX, y: firstY + translatedPoint.y)
zoomingScrollView.center = translatedPoint
let minOffset: CGFloat = viewHalfHeight / 4
let offset: CGFloat = 1 - (zoomingScrollView.center.y > viewHalfHeight
? zoomingScrollView.center.y - viewHalfHeight
: -(zoomingScrollView.center.y - viewHalfHeight)) / viewHalfHeight
view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(max(0.7, offset))
// gesture end
if sender.state == .Ended {
if zoomingScrollView.center.y > viewHalfHeight + minOffset
|| zoomingScrollView.center.y < viewHalfHeight - minOffset {
backgroundView.backgroundColor = view.backgroundColor
determineAndClose()
} else {
// Continue Showing View
setNeedsStatusBarAppearanceUpdate()
let velocityY: CGFloat = CGFloat(0.35) * sender.velocityInView(self.view).y
let finalX: CGFloat = firstX
let finalY: CGFloat = viewHalfHeight
let animationDuration: Double = Double(abs(velocityY) * 0.0002 + 0.2)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(animationDuration)
UIView.setAnimationCurve(UIViewAnimationCurve.EaseIn)
view.backgroundColor = UIColor.blackColor()
zoomingScrollView.center = CGPoint(x: finalX, y: finalY)
UIView.commitAnimations()
}
}
}
func deleteButtonPressed(sender: UIButton) {
delegate?.removePhoto?(self, index: currentPageIndex) { [weak self] in
self?.deleteImage()
}
}
func closeButtonPressed(sender: UIButton) {
determineAndClose()
}
func actionButtonPressed() {
delegate?.willShowActionSheet?(currentPageIndex)
guard numberOfPhotos > 0 else {
return
}
if let titles = SKPhotoBrowserOptions.actionButtonTitles {
let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
actionSheetController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action) -> Void in
}))
for idx in titles.indices {
actionSheetController.addAction(UIAlertAction(title: titles[idx], style: .Default, handler: { (action) -> Void in
self.delegate?.didDismissActionSheetWithButtonIndex?(idx, photoIndex: self.currentPageIndex)
}))
}
if UI_USER_INTERFACE_IDIOM() == .Phone {
presentViewController(actionSheetController, animated: true, completion: nil)
} else {
actionSheetController.modalPresentationStyle = .Popover
if let popoverController = actionSheetController.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.barButtonItem = toolbar.toolActionButton
}
presentViewController(actionSheetController, animated: true, completion: { () -> Void in
})
}
} else {
let photo = photos[currentPageIndex]
guard let underlyingImage = photo.underlyingImage else {
return
}
var activityItems: [AnyObject] = [underlyingImage]
if photo.caption != nil {
if let shareExtraCaption = SKPhotoBrowserOptions.shareExtraCaption {
activityItems.append(photo.caption + shareExtraCaption)
} else {
activityItems.append(photo.caption)
}
}
activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityViewController.completionWithItemsHandler = {
(activity, success, items, error) in
self.hideControlsAfterDelay()
self.activityViewController = nil
}
if UI_USER_INTERFACE_IDIOM() == .Phone {
presentViewController(activityViewController, animated: true, completion: nil)
} else {
activityViewController.modalPresentationStyle = .Popover
let popover: UIPopoverPresentationController! = activityViewController.popoverPresentationController
popover.barButtonItem = toolbar.toolActionButton
presentViewController(activityViewController, animated: true, completion: nil)
}
}
}
}
// MARK: - Private Function
private extension SKPhotoBrowser {
func configureAppearance() {
view.backgroundColor = .blackColor()
view.clipsToBounds = true
view.opaque = false
backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: SKMesurement.screenWidth, height: SKMesurement.screenHeight))
backgroundView.backgroundColor = .blackColor()
backgroundView.alpha = 0.0
applicationWindow.addSubview(backgroundView)
pagingScrollView = SKPagingScrollView(frame: view.frame, browser: self)
pagingScrollView.delegate = self
view.addSubview(pagingScrollView)
panGesture = UIPanGestureRecognizer(target: self, action: #selector(SKPhotoBrowser.panGestureRecognized(_:)))
panGesture.minimumNumberOfTouches = 1
panGesture.maximumNumberOfTouches = 1
if !SKPhotoBrowserOptions.disableVerticalSwipe {
view.addGestureRecognizer(panGesture)
}
}
func configureCloseButton() {
closeButton = SKCloseButton(frame: .zero)
closeButton.addTarget(self, action: #selector(closeButtonPressed(_:)), forControlEvents: .TouchUpInside)
closeButton.hidden = !SKPhotoBrowserOptions.displayCloseButton
view.addSubview(closeButton)
}
func configureDeleteButton() {
deleteButton = SKDeleteButton(frame: .zero)
deleteButton.addTarget(self, action: #selector(deleteButtonPressed(_:)), forControlEvents: .TouchUpInside)
deleteButton.hidden = !SKPhotoBrowserOptions.displayDeleteButton
view.addSubview(deleteButton)
}
func configureToolbar() {
toolbar = SKToolbar(frame: frameForToolbarAtOrientation(), browser: self)
view.addSubview(toolbar)
}
func setControlsHidden(hidden: Bool, animated: Bool, permanent: Bool) {
cancelControlHiding()
let captionViews = pagingScrollView.getCaptionViews()
UIView.animateWithDuration(0.35,
animations: { () -> Void in
let alpha: CGFloat = hidden ? 0.0 : 1.0
self.toolbar.alpha = alpha
self.toolbar.frame = hidden ? self.frameForToolbarHideAtOrientation() : self.frameForToolbarAtOrientation()
if SKPhotoBrowserOptions.displayCloseButton {
self.closeButton.alpha = alpha
self.closeButton.frame = hidden ? self.closeButton.hideFrame : self.closeButton.showFrame
}
if SKPhotoBrowserOptions.displayDeleteButton {
self.deleteButton.alpha = alpha
self.deleteButton.frame = hidden ? self.deleteButton.hideFrame : self.deleteButton.showFrame
}
captionViews.forEach { $0.alpha = alpha }
},
completion: nil)
if !permanent {
hideControlsAfterDelay()
}
setNeedsStatusBarAppearanceUpdate()
}
private func deleteImage() {
defer {
reloadData()
}
if photos.count > 1 {
pagingScrollView.deleteImage()
photos.removeAtIndex(currentPageIndex)
if currentPageIndex != 0 {
gotoPreviousPage()
}
toolbar.updateToolbar(currentPageIndex)
} else if photos.count == 1 {
dismissPhotoBrowser(animated: false)
}
}
}
// MARK: - UIScrollView Delegate
extension SKPhotoBrowser: UIScrollViewDelegate {
public func scrollViewDidScroll(scrollView: UIScrollView) {
guard isViewActive else {
return
}
guard !isPerformingLayout else {
return
}
// tile page
pagingScrollView.tilePages()
// Calculate current page
let previousCurrentPage = currentPageIndex
let visibleBounds = pagingScrollView.bounds
currentPageIndex = min(max(Int(floor(CGRectGetMidX(visibleBounds) / CGRectGetWidth(visibleBounds))), 0), numberOfPhotos - 1)
if currentPageIndex != previousCurrentPage {
delegate?.didShowPhotoAtIndex?(currentPageIndex)
toolbar.updateToolbar(currentPageIndex)
}
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
hideControlsAfterDelay()
let currentIndex = pagingScrollView.contentOffset.x / pagingScrollView.frame.size.width
delegate?.didScrollToIndex?(Int(currentIndex))
}
public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
isEndAnimationByToolBar = true
}
}
| 236c9d63c58b61f5e2508888fb0464f6 | 33.102201 | 189 | 0.619162 | false | false | false | false |
pj4533/OpenPics | refs/heads/master | Pods/Moya/Source/Moya.swift | gpl-3.0 | 1 | import Foundation
import Result
/// Closure to be executed when a request has completed.
public typealias Completion = (result: Result<Moya.Response, Moya.Error>) -> ()
/// Represents an HTTP method.
public enum Method: String {
case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT
}
public enum StubBehavior {
case Never
case Immediate
case Delayed(seconds: NSTimeInterval)
}
/// Protocol to define the base URL, path, method, parameters and sample data for a target.
public protocol TargetType {
var baseURL: NSURL { get }
var path: String { get }
var method: Moya.Method { get }
var parameters: [String: AnyObject]? { get }
var sampleData: NSData { get }
}
/// Protocol to define the opaque type returned from a request
public protocol Cancellable {
func cancel()
}
/// Request provider class. Requests should be made through this class only.
public class MoyaProvider<Target: TargetType> {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = Target -> Endpoint<Target>
/// Closure that resolves an Endpoint into an NSURLRequest.
public typealias RequestClosure = (Endpoint<Target>, NSURLRequest -> Void) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = Target -> Moya.StubBehavior
public let endpointClosure: EndpointClosure
public let requestClosure: RequestClosure
public let stubClosure: StubClosure
public let manager: Manager
/// A list of plugins
/// e.g. for logging, network activity indicator or credentials
public let plugins: [PluginType]
/// Initializes a provider.
public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping,
requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping,
stubClosure: StubClosure = MoyaProvider.NeverStub,
manager: Manager = Manager.sharedInstance,
plugins: [PluginType] = []) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
}
/// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure.
public func endpoint(token: Target) -> Endpoint<Target> {
return endpointClosure(token)
}
/// Designated request-making method. Returns a Cancellable token to cancel the request later.
public func request(target: Target, completion: Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
var cancellableToken = CancellableWrapper()
let performNetworking = { (request: NSURLRequest) in
if cancellableToken.isCancelled { return }
switch stubBehavior {
case .Never:
cancellableToken.innerCancellable = self.sendRequest(target, request: request, completion: completion)
default:
cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
/// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
internal func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let cancellableToken = CancellableToken { }
notifyPluginsOfImpendingStub(request, target: target)
let plugins = self.plugins
let stub: () -> () = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins)
switch stubBehavior {
case .Immediate:
stub()
case .Delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset)
dispatch_after(killTime, dispatch_get_main_queue()) {
stub()
}
case .Never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
}
/// Mark: Defaults
public extension MoyaProvider {
// These functions are default mappings to endpoings and requests.
public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> {
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters)
}
public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: NSURLRequest -> Void) {
return closure(endpoint.urlRequest)
}
}
/// Mark: Stubbing
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
public final class func NeverStub(_: Target) -> Moya.StubBehavior {
return .Never
}
public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior {
return .Immediate
}
public final class func DelayedStub(seconds: NSTimeInterval)(_: Target) -> Moya.StubBehavior {
return .Delayed(seconds: seconds)
}
}
internal extension MoyaProvider {
func sendRequest(target: Target, request: NSURLRequest, completion: Moya.Completion) -> CancellableToken {
let request = manager.request(request)
let plugins = self.plugins
// Give plugins the chance to alter the outgoing request
plugins.forEach { $0.willSendRequest(request, target: target) }
// Perform the actual request
let alamoRequest = request.response { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in
let result = convertResponseToResult(response, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceiveResponse(result, target: target) }
completion(result: result)
}
return CancellableToken(request: alamoRequest)
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
internal final func createStubFunction(token: CancellableToken, forTarget target: Target, withCompletion completion: Moya.Completion, endpoint: Endpoint<Target>, plugins: [PluginType]) -> (() -> ()) {
return {
if (token.canceled) {
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil))
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
return
}
switch endpoint.sampleResponseClosure() {
case .NetworkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, response: nil)
plugins.forEach { $0.didReceiveResponse(.Success(response), target: target) }
completion(result: .Success(response))
case .NetworkError(let error):
let error = Moya.Error.Underlying(error)
plugins.forEach { $0.didReceiveResponse(.Failure(error), target: target) }
completion(result: .Failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
internal final func notifyPluginsOfImpendingStub(request: NSURLRequest, target: Target) {
let request = manager.request(request)
plugins.forEach { $0.willSendRequest(request, target: target) }
}
}
internal func convertResponseToResult(response: NSHTTPURLResponse?, data: NSData?, error: NSError?) ->
Result<Moya.Response, Moya.Error> {
switch (response, data, error) {
case let (.Some(response), .Some(data), .None):
let response = Moya.Response(statusCode: response.statusCode, data: data, response: response)
return .Success(response)
case let (_, _, .Some(error)):
let error = Moya.Error.Underlying(error)
return .Failure(error)
default:
let error = Moya.Error.Underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil))
return .Failure(error)
}
}
private struct CancellableWrapper: Cancellable {
var innerCancellable: CancellableToken? = nil
private var isCancelled = false
func cancel() {
innerCancellable?.cancel()
}
}
| f48ed1c3c222862770fe6a3cd9f01767 | 40.475771 | 204 | 0.66787 | false | false | false | false |
LarkNan/SXMWB | refs/heads/master | SXMWeibo/SXMWeibo/Classes/Home/StatusListModel.swift | mit | 1 | //
// StatusListModel.swift
// SXMWeibo
//
// Created by 申铭 on 2017/3/12.
// Copyright © 2017年 shenming. All rights reserved.
//
import UIKit
import SDWebImage
class StatusListModel: NSObject {
// 保存所有微博数据
var statuses: [StatusViewModel]?
func loadData(lastStatus : Bool, finished: (models: [StatusViewModel]?, error: NSError?) -> ()) {
var since_id = statuses?.first?.status.idstr ?? "0"
var max_id = "0"
if lastStatus {
since_id = "0"
max_id = statuses?.last?.status.idstr ?? "0"
}
NetworkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (array, error) -> () in
if error != nil {
finished(models: nil, error: error)
return
}
// 将字典数组转换为模型数组
var models = [StatusViewModel]()
for dict in array! {
let status = StatusViewModel(status: Status(dict: dict))
models.append(status)
}
// 处理微博数据
if since_id != "0" {
self.statuses = models + self.statuses!
} else if max_id != "0" {
self.statuses = self.statuses! + models
} else {
self.statuses = models
}
// 缓存微博所有配图
self.cachesImages(models, finished: finished)
// self.refreshControl?.endRefreshing()
//
// // 显示刷新提醒
// self.showRefreshStatus(models.count)
}
}
private func cachesImages(viewModels: [StatusViewModel], finished: (models: [StatusViewModel]?, error: NSError?) -> ()) {
// 创建一个组
let group = dispatch_group_create()
for viewModel in viewModels {
guard let picurls = viewModel.thumbnail_pic else {
continue
}
// 遍历配图数组下载图片
for url in picurls {
// 将下载操作添加到组中
dispatch_group_enter(group)
// 下载图片
SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
SXMLog("图片下载完成")
// 将当前下载操作从组中移除
dispatch_group_leave(group)
})
}
}
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
SXMLog("全部图片下载完成");
finished(models: viewModels, error: nil)
}
}
}
| 1b0cf17db0928797d9f40bee7dfc7243 | 30.176471 | 179 | 0.491321 | false | false | false | false |
AbelSu131/ios-charts | refs/heads/master | Charts/Classes/Renderers/HorizontalBarChartRenderer.swift | apache-2.0 | 1 | //
// HorizontalBarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class HorizontalBarChartRenderer: BarChartRenderer
{
private var xOffset: CGFloat = 0.0;
private var yOffset: CGFloat = 0.0;
public override init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(delegate: delegate, animator: animator, viewPortHandler: viewPortHandler);
}
internal override func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context);
var barData = delegate!.barChartRendererData(self);
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self);
var dataSetOffset = (barData.dataSetCount - 1);
var groupSpace = barData.groupSpace;
var groupSpaceHalf = groupSpace / 2.0;
var barSpace = dataSet.barSpace;
var barSpaceHalf = barSpace / 2.0;
var containsStacks = dataSet.isStacked;
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var barWidth: CGFloat = 0.5;
var phaseY = _animator.phaseY;
var barRect = CGRect();
var barShadow = CGRect();
var y: Double;
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
// calculate the x-position, depending on datasetcount
var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(j) + groupSpaceHalf;
var vals = e.values;
if (!containsStacks || vals == nil)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue;
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor);
CGContextFillRect(context, barRect);
}
else
{
var all = e.value;
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0);
var left = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0);
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
barShadow.origin.x = viewPortHandler.contentLeft;
barShadow.origin.y = barRect.origin.y;
barShadow.size.width = viewPortHandler.contentWidth;
barShadow.size.height = barRect.size.height;
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor);
CGContextFillRect(context, barShadow);
}
// fill the stack
for (var k = 0; k < vals.count; k++)
{
all -= vals[k];
y = vals[k] + all;
var bottom = x - barWidth + barSpaceHalf;
var top = x + barWidth - barSpaceHalf;
var right = y >= 0.0 ? CGFloat(y) : 0.0;
var left = y <= 0.0 ? CGFloat(y) : 0.0;
// multiply the height of the rect with the phase
if (right > 0)
{
right *= phaseY;
}
else
{
left *= phaseY;
}
barRect.origin.x = left;
barRect.size.width = right - left;
barRect.origin.y = top;
barRect.size.height = bottom - top;
trans.rectValueToPixel(&barRect);
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break;
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break;
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor);
CGContextFillRect(context, barRect);
}
}
}
CGContextRestoreGState(context);
}
internal override func prepareBarHighlight(#x: CGFloat, y: Double, barspacehalf: CGFloat, from: Double, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5;
var top = x - barWidth + barspacehalf;
var bottom = x + barWidth - barspacehalf;
var left = y >= from ? CGFloat(y) : CGFloat(from);
var right = y <= from ? CGFloat(y) : CGFloat(from);
rect.origin.x = left;
rect.origin.y = top;
rect.size.width = right - left;
rect.size.height = bottom - top;
trans.rectValueToPixelHorizontal(&rect, phaseY: _animator.phaseY);
}
public override func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesHorizontalBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY);
}
public override func drawValues(#context: CGContext)
{
// if values are drawn
if (passesCheck())
{
var barData = delegate!.barChartRendererData(self);
var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self);
var dataSets = barData.dataSets;
var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self);
var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self);
var textAlign = drawValueAboveBar ? NSTextAlignment.Left : NSTextAlignment.Right;
let valueOffsetPlus: CGFloat = 5.0;
var posOffset: CGFloat;
var negOffset: CGFloat;
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
var dataSet = dataSets[i];
if (!dataSet.isDrawValuesEnabled)
{
continue;
}
var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency);
var valueFont = dataSet.valueFont;
var valueTextColor = dataSet.valueTextColor;
var yOffset = -valueFont.lineHeight / 2.0;
var formatter = dataSet.valueFormatter;
if (formatter === nil)
{
formatter = defaultValueFormatter;
}
var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency);
var entries = dataSet.yVals as! [BarChartDataEntry];
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i);
// if only single values are drawn (sum)
if (!drawValuesForWholeStackEnabled)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = entries[j].value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
else
{
// if each value of a potential stack should be drawn
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
var e = entries[j];
var vals = e.values;
// we still draw stacked bars, but there is one non-stacked in between
if (vals == nil)
{
if (!viewPortHandler.isInBoundsX(valuePoints[j].x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(valuePoints[j].y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(valuePoints[j].y))
{
continue;
}
var val = e.value;
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
drawValue(
context: context,
value: valueText,
xPos: valuePoints[j].x + (val >= 0.0 ? posOffset : negOffset),
yPos: valuePoints[j].y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
else
{
var transformed = [CGPoint]();
var cnt = 0;
var add = e.value;
for (var k = 0; k < vals.count; k++)
{
add -= vals[cnt];
transformed.append(CGPoint(x: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY, y: 0.0));
cnt++;
}
trans.pointValuesToPixel(&transformed);
for (var k = 0; k < transformed.count; k++)
{
var val = vals[k];
var valueText = formatter!.stringFromNumber(val)!;
// calculate the correct offset depending on the draw position of the value
var valueTextWidth = valueText.sizeWithAttributes([NSFontAttributeName: valueFont]).width;
posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus));
negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus);
if (isInverted)
{
posOffset = -posOffset - valueTextWidth;
negOffset = -negOffset - valueTextWidth;
}
var x = transformed[k].x + (val >= 0 ? posOffset : negOffset);
var y = valuePoints[j].y;
if (!viewPortHandler.isInBoundsX(x))
{
continue;
}
if (!viewPortHandler.isInBoundsTop(y))
{
break;
}
if (!viewPortHandler.isInBoundsBottom(y))
{
continue;
}
drawValue(context: context,
value: valueText,
xPos: x,
yPos: y + yOffset,
font: valueFont,
align: .Left,
color: valueTextColor);
}
}
}
}
}
}
}
internal override func passesCheck() -> Bool
{
var barData = delegate!.barChartRendererData(self);
if (barData === nil)
{
return false;
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleY;
}
} | cf7d72bb748add1d8fd69912bbd78a10 | 42.29638 | 171 | 0.425481 | false | false | false | false |
JovannyEspinal/FirebaseJokes-iOS | refs/heads/master | FirebaseJokes/JokesFeedTableViewController.swift | mit | 1 | //
// JokesFeedTableViewController.swift
// FirebaseJokes
//
// Created by Matthew Maher on 1/23/16.
// Copyright © 2016 Matt Maher. All rights reserved.
//
import UIKit
import Firebase
class JokesFeedTableViewController: UITableViewController {
var jokes = [Joke]()
override func viewDidLoad() {
super.viewDidLoad()
// observeEventType is called whenever anything changes in the firebase database - new jokes or votes
// It's always listening
DataService.dataService.JOKE_REF.observeEventType(.Value, withBlock: { snapshot in
// The snapshot is a current look at our jokes data
print(snapshot.value)
self.jokes = []
if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
for snap in snapshots {
if let postDictionary = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let joke = Joke(key: key, dictionary: postDictionary)
self.jokes.insert(joke, atIndex: 0)
}
}
}
self.tableView.reloadData()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jokes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let joke = jokes[indexPath.row]
if let cell = tableView.dequeueReusableCellWithIdentifier("JokeCellTableViewCell") as? JokeCellTableViewCell {
cell.configureCell(joke)
return cell
} else {
return JokeCellTableViewCell()
}
}
}
| 19ac0aba8e85273b9c2acded04144ef6 | 27.38961 | 118 | 0.554437 | false | false | false | false |
spark/photon-tinker-ios | refs/heads/master | Photon-Tinker/Global/Controls/ScaledHeightImageView.swift | apache-2.0 | 1 | //
// Created by Raimundas Sakalauskas on 2019-06-07.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
class ScaledHeightImageView: UIImageView {
override var intrinsicContentSize: CGSize {
if let image = self.image {
let imageWidth = image.size.width
let imageHeight = image.size.height
let viewHeight = self.frame.size.height
let ratio = viewHeight/imageHeight
let scaledWidth = imageWidth * ratio
return CGSize(width: scaledWidth, height: viewHeight)
}
return CGSize(width: -1.0, height: -1.0)
}
}
| 10f0cc21080171103c537523e1cbfbe2 | 25.5 | 65 | 0.63522 | false | false | false | false |
mbuchetics/RealmDataSource | refs/heads/master | Carthage/Checkouts/realm-cocoa/RealmSwift-swift1.2/SortDescriptor.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/**
A `SortDescriptor` stores a property name and a sort order for use with
`sorted(sortDescriptors:)`. It is similar to `NSSortDescriptor`, but supports
only the subset of functionality which can be efficiently run by Realm's query
engine.
*/
public struct SortDescriptor {
// MARK: Properties
/// The name of the property which this sort descriptor orders results by.
public let property: String
/// Whether this descriptor sorts in ascending or descending order.
public let ascending: Bool
/// Converts the receiver to an `RLMSortDescriptor`
internal var rlmSortDescriptorValue: RLMSortDescriptor {
return RLMSortDescriptor(property: property, ascending: ascending)
}
// MARK: Initializers
/**
Creates a `SortDescriptor` with the given property and ascending values.
:param: property The name of the property which this sort descriptor orders results by.
:param: ascending Whether this descriptor sorts in ascending or descending order.
*/
public init(property: String, ascending: Bool = true) {
self.property = property
self.ascending = ascending
}
// MARK: Functions
/// Returns a copy of the `SortDescriptor` with the sort order reversed.
public func reversed() -> SortDescriptor {
return SortDescriptor(property: property, ascending: !ascending)
}
}
// MARK: Printable
extension SortDescriptor: Printable {
/// Returns a human-readable description of the sort descriptor.
public var description: String {
let direction = ascending ? "ascending" : "descending"
return "SortDescriptor (property: \(property), direction: \(direction))"
}
}
// MARK: Equatable
extension SortDescriptor: Equatable {}
/// Returns whether the two sort descriptors are equal.
public func ==(lhs: SortDescriptor, rhs: SortDescriptor) -> Bool {
return lhs.property == rhs.property &&
lhs.ascending == lhs.ascending
}
// MARK: StringLiteralConvertible
extension SortDescriptor: StringLiteralConvertible {
/// `StringLiteralType`. Required for `StringLiteralConvertible` conformance.
public typealias UnicodeScalarLiteralType = StringLiteralType
/// `StringLiteralType`. Required for `StringLiteralConvertible` conformance.
public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
/**
Creates a `SortDescriptor` from a `UnicodeScalarLiteralType`.
:param: unicodeScalarLiteral Property name literal.
*/
public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {
self.init(property: value)
}
/**
Creates a `SortDescriptor` from an `ExtendedGraphemeClusterLiteralType`.
:param: extendedGraphemeClusterLiteral Property name literal.
*/
public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) {
self.init(property: value)
}
/**
Creates a `SortDescriptor` from a `StringLiteralType`.
:param: stringLiteral Property name literal.
*/
public init(stringLiteral value: StringLiteralType) {
self.init(property: value)
}
}
| e63e63c99028f491457788882e5bea58 | 31.566667 | 92 | 0.694473 | false | false | false | false |
skillz/Cookie-Crunch-Adventure | refs/heads/master | CookieCrunch/Cookie.swift | mit | 1 | /**
* Cookie.swift
* CookieCrunch
* Copyright (c) 2017 Razeware LLC
*
* 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.
*
* Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
* distribute, sublicense, create a derivative work, and/or sell copies of the
* Software in any work that is designed, intended, or marketed for pedagogical or
* instructional purposes related to programming, coding, application development,
* or information technology. Permission for such use, copying, modification,
* merger, publication, distribution, sublicensing, creation of derivative works,
* or sale is expressly withheld.
*
* 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 SpriteKit
// MARK: - CookieType
enum CookieType: Int {
case unknown = 0, croissant, cupcake, danish, donut, macaroon, sugarCookie
var spriteName: String {
let spriteNames = [
"Croissant",
"Cupcake",
"Danish",
"Donut",
"Macaroon",
"SugarCookie"]
return spriteNames[rawValue - 1]
}
var highlightedSpriteName: String {
return spriteName + "-Highlighted"
}
static func random() -> CookieType {
return CookieType(rawValue: Int(arc4random_uniform(6)) + 1)!
}
}
// MARK: - Cookie
class Cookie: CustomStringConvertible, Hashable {
var hashValue: Int {
return row * 10 + column
}
static func ==(lhs: Cookie, rhs: Cookie) -> Bool {
return lhs.column == rhs.column && lhs.row == rhs.row
}
var description: String {
return "type:\(cookieType) square:(\(column),\(row))"
}
var column: Int
var row: Int
let cookieType: CookieType
var sprite: SKSpriteNode?
init(column: Int, row: Int, cookieType: CookieType) {
self.column = column
self.row = row
self.cookieType = cookieType
}
}
| f054b5ce5719be74341ed956365b1ac3 | 31.183908 | 82 | 0.707857 | false | false | false | false |
NextFaze/FazeKit | refs/heads/master | FazeKit/Classes/UIApplicationAdditions.swift | apache-2.0 | 2 | //
// UIApplicationAdditions.swift
// FazeKit
//
// Created by Shane Woolcock on 3/10/19.
//
import Foundation
private var activityCount: Int = 0
public extension UIApplication {
static func incrementNetworkActivityIndicator() {
DispatchQueue.main.async {
activityCount += 1
self.shared.isNetworkActivityIndicatorVisible = true
}
}
static func decrementNetworkActivityIndicator() {
DispatchQueue.main.async {
activityCount = max(0, activityCount - 1)
self.shared.isNetworkActivityIndicatorVisible = activityCount > 0
}
}
static var appVersionString: String {
return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? ""
}
static var appBuildString: String {
return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String ?? ""
}
static var appBuildNumber: Int {
return Int(self.appBuildString) ?? 0
}
static var semanticVersionString: String {
return "\(self.appVersionString).\(self.appBuildString)"
}
static var versionBuildString: String {
let version = self.appVersionString, build = self.appBuildString
return version == build ? "v\(version)" : "v\(version) (\(build))"
}
static var bundleIdentifier: String {
return Bundle.main.bundleIdentifier ?? ""
}
static let isRunningUnitTests: Bool = {
let env = ProcessInfo.processInfo.environment
return env.keys.contains(where: { $0.starts(with: "XCTest") })
}()
}
| 9a25debd8b2f0d55a29c3b2950f844f5 | 28.375 | 103 | 0.644985 | false | false | false | false |
garygriswold/Bible.js | refs/heads/master | OBSOLETE/YourBible/plugins/com-shortsands-utility/src/ios/Utility.swift | mit | 2 | //
// Utility.swift
// Utility
//
// Created by Gary Griswold on 1/9/18.
// Copyright © 2018 ShortSands. All rights reserved.
//
import Foundation
import UIKit
/*
platform, modelType, modelName, deviceSize
*/
@objc(Utility) class Utility : CDVPlugin {
@objc(locale:) func locale(command: CDVInvokedUrlCommand) {
let loc = Locale.current
let message: [String?] = [ loc.identifier, loc.languageCode, loc.scriptCode, loc.regionCode ]
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(platform:) func platform(command: CDVInvokedUrlCommand) {
let message = "iOS"
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(modelType:) func modelType(command: CDVInvokedUrlCommand) {
let message = UIDevice.current.model
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(modelName:) func modelName(command: CDVInvokedUrlCommand) {
let message = DeviceSettings.modelName()
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(deviceSize:) func deviceSize(command: CDVInvokedUrlCommand) {
let message = DeviceSettings.deviceSize()
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
@objc(open:) func open(command: CDVInvokedUrlCommand) {
DispatchQueue.global().sync {
do {
let database = try Sqlite3.openDB(
dbname: command.arguments[0] as? String ?? "",
copyIfAbsent: command.arguments[1] as? Bool ?? false)
let result = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
}
@objc(queryJS:) func queryJS(command: CDVInvokedUrlCommand) {
DispatchQueue.global().sync {
do {
let database = try Sqlite3.findDB(dbname: command.arguments[0] as? String ?? "")
let resultSet = try database.queryJS(
sql: command.arguments[1] as? String ?? "",
values: command.arguments[2] as? [Any?] ?? [])
let json = String(data: resultSet, encoding: String.Encoding.utf8)
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: json)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
}
@objc(executeJS:) func executeJS(command: CDVInvokedUrlCommand) {
DispatchQueue.global().sync {
do {
let database = try Sqlite3.findDB(dbname: command.arguments[0] as? String ?? "")
let rowCount = try database.executeV1(
sql: command.arguments[1] as? String ?? "",
values: command.arguments[2] as? [Any?] ?? [])
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: rowCount)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
}
@objc(bulkExecuteJS:) func bulkExecuteJS(command: CDVInvokedUrlCommand) {
DispatchQueue.global().sync {
do {
let database = try Sqlite3.findDB(dbname: command.arguments[0] as? String ?? "")
let rowCount = try database.bulkExecuteV1(
sql: command.arguments[1] as? String ?? "",
values: command.arguments[2] as? [[Any?]] ?? [[]])
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: rowCount)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
}
@objc(close:) func close(command: CDVInvokedUrlCommand) {
DispatchQueue.global().sync {
Sqlite3.closeDB(dbname: command.arguments[0] as? String ?? "")
let result = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
}
@objc(listDB:) func listDB(command: CDVInvokedUrlCommand) {
do {
let files = try Sqlite3.listDB()
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: files)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
@objc(deleteDB:) func deleteDB(command: CDVInvokedUrlCommand) {
do {
try Sqlite3.deleteDB(dbname: command.arguments[0] as? String ?? "")
let result = CDVPluginResult(status: CDVCommandStatus_OK)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
@objc(hideKeyboard:) func hideKeyboard(command: CDVInvokedUrlCommand) {
do {
let hidden = self.webView.endEditing(true)
let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: hidden)
self.commandDelegate!.send(result, callbackId: command.callbackId)
} catch let err {
self.returnError(error: err, command: command)
}
}
private func returnError(error: Error, command: CDVInvokedUrlCommand) {
let message = Sqlite3.errorDescription(error: error)
let result = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: message)
self.commandDelegate!.send(result, callbackId: command.callbackId)
}
}
| 29f8a6bf387c97d840d81c84cdd2a14c | 39.565789 | 101 | 0.646286 | false | false | false | false |
igroomgrim/howtoplaysnapkit | refs/heads/master | FunnySnap/ViewController.swift | mit | 1 | //
// ViewController.swift
// FunnySnap
//
// Created by Anak Mirasing on 1/31/2559 BE.
// Copyright © 2559 iGROOMGRiM. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: UIViewController {
let button = UIButton()
var tapped = false
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(red:0.38, green:0.75, blue:0.88, alpha:1.0)
self.setupBottomRightButton()
self.setupCustomNavBar()
self.setupCustomDashboardView()
// Update constraints
self.updateConstraints()
}
// MARK: Setup UI
func setupBottomRightButton() {
let superview = self.view
button.layer.cornerRadius = 33
button.setTitle("+", forState: .Normal)
button.backgroundColor = UIColor.blackColor()
superview.addSubview(button)
button.snp_makeConstraints { (make) -> Void in
make.width.equalTo(66)
make.height.equalTo(66)
make.bottom.equalTo(superview.snp_bottom).offset(-20)
make.right.equalTo(superview.snp_right).offset(-20)
}
button.addTarget(self, action: "customButtonTapped", forControlEvents: .TouchUpInside)
}
// MARK: Navbar Example
func setupCustomNavBar() {
let superview = self.view
let navbar = UIView()
superview.addSubview(navbar)
navbar.backgroundColor = UIColor(red:0.38, green:0.85, blue:0.88, alpha:1)
navbar.snp_makeConstraints { (make) -> Void in
make.height.equalTo(64)
make.width.equalTo(superview)
}
let titleLabel = UILabel()
navbar.addSubview(titleLabel)
titleLabel.text = "FunnySnap"
titleLabel.textColor = UIColor.blackColor()
titleLabel.sizeToFit()
titleLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(navbar)
}
}
// MARK: Custom Dashboard
func setupCustomDashboardView() {
let superview = self.view
let dashboardView = UIView()
let miniView1 = UIView()
let miniView2 = UIView()
let bigView = UIView()
let miniLabel = UILabel()
let dashboarLabel = UILabel()
superview.addSubview(dashboardView)
dashboardView.addSubview(miniView1)
dashboardView.addSubview(miniView2)
dashboardView.addSubview(bigView)
miniView1.addSubview(miniLabel)
bigView.addSubview(dashboarLabel)
dashboardView.backgroundColor = UIColor(red:0.38, green:0.85, blue:0.88, alpha:1)
miniView1.backgroundColor = UIColor.whiteColor()
miniView2.backgroundColor = UIColor.lightGrayColor()
bigView.backgroundColor = UIColor.blackColor()
miniLabel.textColor = UIColor.whiteColor()
miniLabel.text = "MiniBox"
miniLabel.backgroundColor = UIColor.blackColor()
miniLabel.textAlignment = .Center
dashboarLabel.textColor = UIColor.whiteColor()
dashboarLabel.text = "Dashboard"
dashboardView.snp_makeConstraints { (make) -> Void in
make.width.equalTo(superview).multipliedBy(0.9)
make.height.equalTo(256)
make.top.equalTo(superview).offset(84)
make.centerX.equalTo(superview)
}
miniView1.snp_makeConstraints { (make) -> Void in
make.left.equalTo(dashboardView).offset(24)
make.top.equalTo(dashboardView).offset(20)
make.width.equalTo(dashboardView).dividedBy(2.5)
make.height.equalTo(dashboardView).multipliedBy(0.4)
}
miniView2.snp_makeConstraints { (make) -> Void in
make.left.equalTo(miniView1.snp_right).offset(20)
make.top.equalTo(dashboardView).offset(20)
make.size.equalTo(miniView1)
}
bigView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(dashboardView).offset(24)
make.top.equalTo(miniView1.snp_bottom).offset(20)
make.right.equalTo(dashboardView).offset(-24)
make.bottom.equalTo(dashboardView).offset(-20)
}
miniLabel.snp_makeConstraints { (make) -> Void in
make.edges.equalTo(miniView1).inset(UIEdgeInsetsMake(5, 5, 5, 5))
}
dashboarLabel.snp_makeConstraints { (make) -> Void in
make.center.equalTo(bigView)
}
}
// MARK: Modify Constraints
func updateConstraints() {
var widthConstraint: Constraint? = nil
var heightConstraint: Constraint? = nil
// snp_updateConstraints
self.button.layer.cornerRadius = 22
self.button.snp_updateConstraints { (make) -> Void in
widthConstraint = make.width.equalTo(44).constraint
heightConstraint = make.height.equalTo(44).constraint
make.bottom.equalTo(self.view.snp_bottom).offset(-20)
make.right.equalTo(self.view.snp_right).offset(-20)
}
tapped = true
// References
widthConstraint?.uninstall()
heightConstraint?.uninstall()
widthConstraint?.updateOffset(40)
heightConstraint?.updateOffset(40)
}
func customButtonTapped() {
self.modifyConstraints()
}
func modifyConstraints() {
// snp_remakeConstraints
if tapped {
button.layer.cornerRadius = 33
self.button.snp_remakeConstraints { (make) -> Void in
make.width.equalTo(66)
make.height.equalTo(66)
make.bottom.equalTo(self.view.snp_bottom).offset(-20)
make.right.equalTo(self.view.snp_right).offset(-20)
}
tapped = false
} else {
self.button.layer.cornerRadius = 22
self.button.snp_remakeConstraints { (make) -> Void in
make.width.equalTo(44)
make.height.equalTo(44)
make.bottom.equalTo(self.view.snp_bottom).offset(-20)
make.left.equalTo(self.view).offset(20)
}
tapped = true
}
}
}
| 984d8d939b1bea2a1fee444e14213260 | 31.637755 | 94 | 0.586994 | false | false | false | false |
kierangraham/OAuthToo | refs/heads/master | Source/OAuth2AccessToken.swift | mit | 1 | //
// OAuth2AccessToken.swift
// OAuthToo
//
// Created by Kieran Graham on 14/05/2015.
// Copyright (c) 2015 Kieran Graham. All rights reserved.
//
import Dollar
import Alamofire
import SwiftyJSON
public struct OAuth2AccessToken {
public let accessToken: String
public let refreshToken: String?
public let tokenType: String
public let scopes: [String]
public let expiresIn: Int?
public let createdAt: NSDate
public init(json: JSON) {
accessToken = json["access_token"].stringValue
refreshToken = json["refresh_token"].string
tokenType = json["token_type"].stringValue
scopes = json["scope"].stringValue.componentsSeparatedByString(" ")
expiresIn = json["expires_in"].int
createdAt = NSDate(timeIntervalSince1970: NSTimeInterval(json["created_at"].intValue))
}
public var expiresAt: NSDate? {
if let expiresIn = expiresIn {
return NSDate(timeInterval: NSTimeInterval(expiresIn), sinceDate: createdAt)
}
else {
return nil
}
}
public func willExpire() -> Bool {
return expiresIn != nil
}
public func isExpired() -> Bool {
guard let expiresAt = expiresAt else {
return false
}
return willExpire() && NSDate(timeIntervalSinceNow: 0).compare(expiresAt) == .OrderedDescending
}
public func isRefreshable() -> Bool {
return refreshToken != nil
}
public func refresh(client: OAuth2Client, callback: OAuth2AccessTokenCallback) {
let params = [
"grant_type": "refresh_token",
"refresh_token": refreshToken ?? ""
]
client.tokenRequest(params, callback: callback)
}
}
| 9a070f2685edb94df19dc16be7f1248c | 24.873016 | 99 | 0.679141 | false | false | false | false |
googlearchive/science-journal-ios | refs/heads/master | ScienceJournal/Operations/OperationCondition.swift | apache-2.0 | 1 | /*
* Copyright 2019 Google LLC. 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
/// An enum for the possible outcomes of an operation condition.
///
/// - passed: The condition was satisfied.
/// - failed: The condition failed.
public enum OperationConditionResult {
case passed
case failed(Error)
/// An error corresponding to a condition failure state.
var error: Error? {
if case .failed(let error) = self {
return error
}
return nil
}
}
/// Errors associated with the execution of an operation.
///
/// - conditionFailed: A condition failed.
/// - executionFailed: The execution failed.
enum OperationError: Error {
case conditionFailed
case executionFailed
}
/// Objects conforming to this protocol can evaluate conditions determining whether an operation
/// can execute or not.
public protocol OperationCondition {
/// A string key used to enforce mutual exclusivity, if necessary.
var exclusivityKey: String? { get }
/// A dependency required by the condition. This should be an operation to attempts to make the
/// condition pass, such as requesting permission.
///
/// - Parameter operation: The operation the condition is applied to.
/// - Returns: A new operattion.
func dependencyForOperation(_ operation: GSJOperation) -> Operation?
/// A method called to evaluate the condition. The method will call the completion with either
/// passed or failed.
///
/// - Parameters:
/// - operation: The operation the condition is applied to.
/// - completion: A completion called after the condition has been evaluated.
func evaluateForOperation(_ operation: GSJOperation,
completion: (OperationConditionResult) -> Void)
}
struct OperationConditionEvaluator {
/// Evaluates conditions for an operation.
///
/// - Parameters:
/// - conditions: An array of conditions.
/// - operation: The operation to evaluate against.
/// - completion: A closure called when the evaluation finished with an array of errors.
static func evaluate(conditions: [OperationCondition],
forOperation operation: GSJOperation,
completion: @escaping (([Error]) -> Void)) {
guard conditions.count > 0 else {
completion([])
return
}
// Use a dispatch group to evaluate the conditions concurrently.
let group = DispatchGroup()
// Define an array the size of the condition count in order to keep the errors in the same
// order as the conditions.
var results = [OperationConditionResult?](repeating: nil, count: conditions.count)
for (index, condition) in conditions.enumerated() {
group.enter()
condition.evaluateForOperation(operation, completion: { (result) in
results[index] = result
group.leave()
})
}
// Once all conditions are finished, call the completion.
group.notify(queue: .global()) {
let failures = results.compactMap { $0?.error }
completion(failures)
}
}
}
| 97455bd2ffacb90eef2186a9d31aae45 | 33.528846 | 97 | 0.690337 | false | false | false | false |
rpearl/PhotoWatch | refs/heads/master | PhotoWatch/ViewController.swift | mit | 2 | //
// ViewController.swift
// PhotoWatch
//
// Created by Leah Culver on 5/11/15.
// Copyright (c) 2015 Dropbox. All rights reserved.
//
import UIKit
import SwiftyDropbox
class ViewController: UIViewController, UIPageViewControllerDataSource {
var filenames: Array<String>?
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.filenames = []
// Check if the user is logged in
// If so, display photo view controller
if let client = Dropbox.authorizedClient {
// Display image background view w/logout button
let backgroundViewController = self.storyboard?.instantiateViewControllerWithIdentifier("BackgroundViewController") as! UIViewController
self.presentViewController(backgroundViewController, animated: false, completion: nil)
// List contents of app folder
client.filesListFolder(path: "").response { response, error in
if let result = response {
println("Folder contents:")
for entry in result.entries {
println(entry.name)
// Check that file is a photo (by file extension)
if entry.name.hasSuffix(".jpg") || entry.name.hasSuffix(".png") {
// Add photo!
self.filenames?.append(entry.name)
}
}
// Show page view controller for photos
let pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
pageViewController.dataSource = self
// Display the first photo screen
if self.filenames != nil {
let photoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PhotoViewController") as! PhotoViewController
photoViewController.filename = self.filenames![0]
pageViewController.setViewControllers([photoViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
}
// Change the size of page view controller
pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 30);
// Display the page view controller on top of background view controller
backgroundViewController.addChildViewController(pageViewController)
backgroundViewController.view.addSubview(pageViewController.view)
pageViewController.didMoveToParentViewController(self)
} else {
println("Error: \(error!)")
}
}
}
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let currentViewController = viewController as! PhotoViewController
var nextIndex = 0
if let index = find(self.filenames!, currentViewController.filename!) {
if index < self.filenames!.count - 1 {
nextIndex = index + 1
}
}
let photoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PhotoViewController") as! PhotoViewController
photoViewController.filename = self.filenames![nextIndex]
return photoViewController
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let currentViewController = viewController as! PhotoViewController
var nextIndex = self.filenames!.count - 1
if let index = find(self.filenames!, currentViewController.filename!) {
if index > 0 {
nextIndex = index - 1
}
}
let photoViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PhotoViewController") as! PhotoViewController
photoViewController.filename = self.filenames![nextIndex]
return photoViewController
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
// Number of pages is number of photos
return self.filenames!.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
@IBAction func linkButtonPressed(sender: AnyObject) {
// Present view to log in
Dropbox.authorizeFromController(self)
}
}
| 86b66209d455e3c1b918195882fa2213 | 42.336207 | 178 | 0.61289 | false | false | false | false |
pedrovsn/2reads | refs/heads/master | reads2/reads2/DetalheViewController.swift | mit | 1 | //
// DetalheViewController.swift
// reads2
//
// Created by Student on 11/30/16.
// Copyright © 2016 Student. All rights reserved.
//
import UIKit
class DetalheViewController: UIViewController {
@IBOutlet weak var capaDoLivro: UIImageView!
@IBOutlet weak var tituloDoLivro: UILabel!
@IBOutlet weak var autorDoLivro: UILabel!
@IBOutlet weak var editoraDoLivro: UILabel!
@IBOutlet weak var edicaoDoLivro: UILabel!
var livro: Livro = Livro(autor: "", titulo: "", editora: Editora(nome: ""), categoria: "", descricao: "", ano: 0, imagem: "", url: "")
override func viewDidLoad() {
super.viewDidLoad()
capaDoLivro.image = UIImage(named: livro.imagem!)
tituloDoLivro.text = livro.titulo
autorDoLivro.text = livro.autor
editoraDoLivro.text = livro.editora.nome
edicaoDoLivro.text = ""
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case "leitorViewControlerSegue":
if let LeitorViewController = segue.destinationViewController as? LeitorViewController {
LeitorViewController.urlDoLivro = livro.url
}
default:
break
}
}
}
| 638cc470d7729b0f9b4c9163a785fc8e | 29.754717 | 138 | 0.651534 | false | false | false | false |
vmanot/swift-package-manager | refs/heads/master | Sources/Basic/TemporaryFile.swift | apache-2.0 | 1 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import libc
import func POSIX.getenv
import class Foundation.FileHandle
import class Foundation.FileManager
public enum TempFileError: Swift.Error {
/// Could not create a unique temporary filename.
case couldNotCreateUniqueName
/// Some error thrown defined by posix's open().
// FIXME: This should be factored out into a open error enum.
case other(Int32)
}
private extension TempFileError {
init(errno: Int32) {
switch errno {
case libc.EEXIST:
self = .couldNotCreateUniqueName
default:
self = .other(errno)
}
}
}
/// Determines the directory in which the temporary file should be created. Also makes
/// sure the returning path has a trailing forward slash.
///
/// - Parameters:
/// - dir: If present this will be the temporary directory.
///
/// - Returns: Path to directory in which temporary file should be created.
public func determineTempDirectory(_ dir: AbsolutePath? = nil) -> AbsolutePath {
// FIXME: Add other platform specific locations.
let tmpDir = dir ?? cachedTempDirectory
// FIXME: This is a runtime condition, so it should throw and not crash.
precondition(localFileSystem.isDirectory(tmpDir))
return tmpDir
}
/// Returns temporary directory location by searching relevant env variables.
/// Evaluates once per execution.
private var cachedTempDirectory: AbsolutePath = {
return AbsolutePath(getenv("TMPDIR") ?? getenv("TEMP") ?? getenv("TMP") ?? "/tmp/")
}()
/// This class is basically a wrapper over posix's mkstemps() function to creates disposable files.
/// The file is deleted as soon as the object of this class is deallocated.
public final class TemporaryFile {
/// If specified during init, the temporary file name begins with this prefix.
let prefix: String
/// If specified during init, the temporary file name ends with this suffix.
let suffix: String
/// The directory in which the temporary file is created.
public let dir: AbsolutePath
/// The full path of the temporary file. For safety file operations should be done via the fileHandle instead of
/// using this path.
public let path: AbsolutePath
/// The file descriptor of the temporary file. It is used to create NSFileHandle which is exposed to clients.
private let fd: Int32
/// FileHandle of the temporary file, can be used to read/write data.
public let fileHandle: FileHandle
/// Creates an instance of Temporary file. The temporary file will live on disk until the instance
/// goes out of scope.
///
/// - Parameters:
/// - dir: If specified the temporary file will be created in this directory otherwise environment variables
/// TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env variables are
/// set, dir will be set to `/tmp/`.
/// - prefix: The prefix to the temporary file name.
/// - suffix: The suffix to the temporary file name.
///
/// - Throws: TempFileError
public init(dir: AbsolutePath? = nil, prefix: String = "TemporaryFile", suffix: String = "") throws {
self.suffix = suffix
self.prefix = prefix
// Determine in which directory to create the temporary file.
self.dir = determineTempDirectory(dir)
// Construct path to the temporary file.
let path = self.dir.appending(RelativePath(prefix + ".XXXXXX" + suffix))
// Convert path to a C style string terminating with null char to be an valid input
// to mkstemps method. The XXXXXX in this string will be replaced by a random string
// which will be the actual path to the temporary file.
var template = [UInt8](path.asString.utf8).map({ Int8($0) }) + [Int8(0)]
fd = libc.mkstemps(&template, Int32(suffix.utf8.count))
// If mkstemps failed then throw error.
if fd == -1 { throw TempFileError(errno: errno) }
self.path = AbsolutePath(String(cString: template))
fileHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
}
/// Remove the temporary file before deallocating.
deinit {
unlink(path.asString)
}
}
extension TemporaryFile: CustomStringConvertible {
public var description: String {
return "<TemporaryFile: \(path)>"
}
}
/// Contains the error which can be thrown while creating a directory using POSIX's mkdir.
//
// FIXME: This isn't right place to declare this, probably POSIX or merge with FileSystemError?
public enum MakeDirectoryError: Swift.Error {
/// The given path already exists as a directory, file or symbolic link.
case pathExists
/// The path provided was too long.
case pathTooLong
/// Process does not have permissions to create directory.
/// Note: Includes read-only filesystems or if file system does not support directory creation.
case permissionDenied
/// The path provided is unresolvable because it has too many symbolic links or a path component is invalid.
case unresolvablePathComponent
/// Exceeded user quota or kernel is out of memory.
case outOfMemory
/// All other system errors with their value.
case other(Int32)
}
private extension MakeDirectoryError {
init(errno: Int32) {
switch errno {
case libc.EEXIST:
self = .pathExists
case libc.ENAMETOOLONG:
self = .pathTooLong
case libc.EACCES, libc.EFAULT, libc.EPERM, libc.EROFS:
self = .permissionDenied
case libc.ELOOP, libc.ENOENT, libc.ENOTDIR:
self = .unresolvablePathComponent
case libc.ENOMEM, libc.EDQUOT:
self = .outOfMemory
default:
self = .other(errno)
}
}
}
/// A class to create disposable directories using POSIX's mkdtemp() method.
public final class TemporaryDirectory {
/// If specified during init, the temporary directory name begins with this prefix.
let prefix: String
/// The full path of the temporary directory.
public let path: AbsolutePath
/// If true, try to remove the whole directory tree before deallocating.
let shouldRemoveTreeOnDeinit: Bool
/// Creates a temporary directory which is automatically removed when the object of this class goes out of scope.
///
/// - Parameters:
/// - dir: If specified the temporary directory will be created in this directory otherwise environment
/// variables TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env
/// variables are set, dir will be set to `/tmp/`.
/// - prefix: The prefix to the temporary file name.
/// - removeTreeOnDeinit: If enabled try to delete the whole directory tree otherwise remove only if its empty.
///
/// - Throws: MakeDirectoryError
public init(
dir: AbsolutePath? = nil,
prefix: String = "TemporaryDirectory",
removeTreeOnDeinit: Bool = false
) throws {
self.shouldRemoveTreeOnDeinit = removeTreeOnDeinit
self.prefix = prefix
// Construct path to the temporary directory.
let path = determineTempDirectory(dir).appending(RelativePath(prefix + ".XXXXXX"))
// Convert path to a C style string terminating with null char to be an valid input
// to mkdtemp method. The XXXXXX in this string will be replaced by a random string
// which will be the actual path to the temporary directory.
var template = [UInt8](path.asString.utf8).map({ Int8($0) }) + [Int8(0)]
if libc.mkdtemp(&template) == nil {
throw MakeDirectoryError(errno: errno)
}
self.path = AbsolutePath(String(cString: template))
}
/// Remove the temporary file before deallocating.
deinit {
if shouldRemoveTreeOnDeinit {
_ = try? FileManager.default.removeItem(atPath: path.asString)
} else {
rmdir(path.asString)
}
}
}
extension TemporaryDirectory: CustomStringConvertible {
public var description: String {
return "<TemporaryDirectory: \(path)>"
}
}
| dc077b573603164cd125e565e4f6090e | 38.21659 | 119 | 0.676146 | false | false | false | false |
rizumita/ResourceInstantiatable | refs/heads/master | ResourceInstantiatable/FileInstantiator.swift | mit | 1 | //
// FileInstantiator.swift
// ResourceInstantiatable
//
// Created by 和泉田 領一 on 2015/09/29.
// Copyright © 2015年 CAPH. All rights reserved.
//
import Foundation
public protocol FileInstantiatable: ResourceInstantiatable {
var initialize: String throws -> InstanceType? { get }
}
public struct FileInstantiator<T>: FileInstantiatable {
public typealias InstanceType = T
public let name: String
public let type: String?
public let bundle: NSBundle
public let initialize: String throws -> InstanceType?
public func instantiate() throws -> InstanceType {
guard let path = bundle.pathForResource(name, ofType: type) else {
throw ResourceInstantiatableError.CannotRetrieveResourcePath
}
guard let result = try initialize(path) else {
throw ResourceInstantiatableError.CannotInstantiate
}
return result
}
init(name: String, type: String? = nil, bundle: NSBundle = NSBundle.mainBundle(), initialize: String throws -> InstanceType?) {
self.name = name
self.type = type
self.bundle = bundle
self.initialize = initialize
}
}
| 5f19c5ee9be836404eb9e37096e68a24 | 25.613636 | 131 | 0.676345 | false | false | false | false |
aikdong/CNTV | refs/heads/master | COCNTV/AVPlayerController.swift | mit | 1 |
import UIKit
import AVFoundation
class AVPlayerController: UIViewController {
var player: AVPlayer!
var url: NSURL!
init(url: NSURL!) {
self.url = url;
self.player = AVPlayer(URL: self.url)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
let layer = AVPlayerLayer(player: player)
layer.frame = self.view.frame
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(layer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
internal func play() {
player.play()
}
internal func pause() {
player.pause()
}
}
| 5eedfbb5105e25faf5b717eda9a0e2a4 | 19.863636 | 64 | 0.587146 | false | false | false | false |
MoonfaceRainbowGun/MFRG | refs/heads/master | Sholes/Sholes/Libraries/ACAutoMaton/Interval/IntervalTree.swift | apache-2.0 | 2 | func sizeSorter<T: Interval>(lhs: T, rhs: T) -> Bool {
if lhs.size == rhs.size {
return positionSorter(lhs: lhs, rhs: rhs)
} else {
return lhs.size > rhs.size
}
}
func positionSorter<T: Interval>(lhs: T, rhs: T) -> Bool {
return lhs.start <= rhs.start
}
public class IntervalTree<T: Interval> {
private var rootNode: IntervalNode<T>
public init(intervals: [T]) {
rootNode = IntervalNode(intervals: intervals)
}
public func removeOverlaps(intervals: [T]) -> [T] {
let intervalsSortedBySize = intervals.sorted(by: sizeSorter)
var removedIntervals: Set<T> = []
for interval in intervalsSortedBySize {
if !removedIntervals.contains(interval) {
let overlaps = findOverlaps(interval: interval)
for overlap in overlaps {
removedIntervals.insert(overlap)
}
}
}
let intervalsRemovingRemoved = Set(intervals).subtracting(removedIntervals)
return Array(intervalsRemovingRemoved).sorted(by: positionSorter)
}
public func findOverlaps(interval: T) -> [T] {
return rootNode.findOverlaps(interval: interval)
}
}
| bedb794da8034f454aa4f139be3313f0 | 27 | 83 | 0.609578 | false | false | false | false |
alltheflow/copypasta | refs/heads/master | Carthage/Checkouts/VinceRP/vincerpTests/Common/Util/FunctionalArraySpec.swift | mit | 2 | //
// Created by Viktor Belenyesi on 21/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
import Quick
import Nimble
class FunctionalArraySpec: QuickSpec {
override func spec() {
describe("prepend") {
it("prepends to non-empty array") {
// given
let s = [1, 2]
// when
let r = s.arrayByPrepending(0)
// then
expect(r) == [0, 1, 2]
}
it("prepends to empty array") {
// given
let s = [Int]()
// when
let r = s.arrayByPrepending(0)
// then
expect(r) == [0]
}
}
}
}
| d106ed6151c46d9581c11bdd9a55ecf6 | 17.829268 | 60 | 0.408031 | false | false | false | false |
Baglan/MCResource | refs/heads/master | Classes/LocalCacheSource.swift | mit | 1 | //
// LocalCacheSource.swift
// MCResourceLoader
//
// Created by Baglan on 06/11/2016.
// Copyright © 2016 Mobile Creators. All rights reserved.
//
import Foundation
extension MCResource {
class LocalCacheSource: MCResourceSource, ErrorSource {
let localUrl: URL
let priority: Int
let fractionCompleted: Double = 0
init(localUrl: URL, priority: Int = 0) {
self.localUrl = localUrl
self.priority = priority
}
convenience init(pathInCache: String, priority: Int) {
var cacheUrl = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
cacheUrl.appendPathComponent(pathInCache)
self.init(localUrl: cacheUrl, priority: priority)
}
private var request: NSBundleResourceRequest?
private var task: URLSessionDownloadTask?
func beginAccessing(completionHandler: @escaping (URL?, Error?) -> Void) {
if !FileManager.default.fileExists(atPath: localUrl.path) {
completionHandler(nil, ErrorHelper.error(for: ErrorCodes.NotFound.rawValue, source: self))
return
}
completionHandler(localUrl, nil)
}
func endAccessing() {
}
// MARK: - Errors
static let errorDomain = "MCResourceLocalCacheSourceErrorDomain"
enum ErrorCodes: Int {
case SchemeNotSupported
case NotFound
}
static let errorDescriptions: [Int: String] = [
ErrorCodes.SchemeNotSupported.rawValue: "URL scheme is not 'http' or 'https'",
ErrorCodes.NotFound.rawValue: "Item not found in local cache"
]
}
}
| 353ffe0c72acf842f3582bad71f37ece | 30.719298 | 106 | 0.59292 | false | false | false | false |
belatrix/iOSAllStars | refs/heads/master | AllStarsV2/AllStarsV2/iPhone/Classes/Profile/Categories/CategoriesViewController.swift | apache-2.0 | 1 | //
// CategoriesViewController.swift
// AllStarsV2
//
// Created by Kenyi Rodriguez Vergara on 2/08/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class CategoriesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tlbCategories: UITableView!
@IBOutlet weak var loadingView : CDMLoadingView!
var categoryCellSelected : CategoryTableViewCell!
var objUser : UserBE!
var arrayCategories = [CategoryBE]()
//MARK: - UITableViewDelegate, UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrayCategories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "CategoryTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! CategoryTableViewCell
cell.objCategory = self.arrayCategories[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
self.categoryCellSelected = tableView.cellForRow(at: indexPath) as! CategoryTableViewCell
self.performSegue(withIdentifier: "CategoryDetailViewController", sender: self.arrayCategories[indexPath.row])
}
//MARK: - WebService
func listCategories(){
if self.arrayCategories.count == 0 {
self.loadingView.iniciarLoading(conMensaje: "get_category_list".localized, conAnimacion: true)
}
CategoryBC.listCategories(toUser: self.objUser, withSuccessful: { (arrayCategories) in
if arrayCategories.count > 0 {
self.arrayCategories = arrayCategories
self.tlbCategories.reloadSections(IndexSet(integer: 0), with: .automatic)
self.loadingView.detenerLoading()
}
else {
self.loadingView.mostrarError(conMensaje: "no_categories".localized, conOpcionReintentar: false)
}
}) { (title, message) in
self.loadingView.mostrarError(conMensaje: message, conOpcionReintentar: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.tlbCategories.estimatedRowHeight = 30
self.tlbCategories.rowHeight = UITableViewAutomaticDimension
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.listCategories()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "CategoryDetailViewController" {
let controller = segue.destination as! CategoryDetailViewController
controller.objCategory = sender as! CategoryBE
controller.objUser = self.objUser
}
}
}
| de940c368b3a5d306934c098b354a305 | 31.788991 | 122 | 0.641858 | false | false | false | false |
SimonFairbairn/Stormcloud | refs/heads/master | Sources/Stormcloud/JPEGMetadata.swift | mit | 1 | //
// ImageMetadata.swift
// Stormcloud
//
// Created by Simon Fairbairn on 21/09/2017.
// Copyright © 2017 Voyage Travel Apps. All rights reserved.
//
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
open class JPEGMetadata : StormcloudMetadata {
public override init() {
super.init()
self.date = Date()
self.filename = UUID().uuidString + ".jpg"
self.type = .jpegImage
}
public override init( path : String ) {
super.init()
self.filename = path
self.date = Date()
self.type = .jpegImage
}
}
| 89aa79eb5cae288654e143b8ad58fd3d | 16.533333 | 61 | 0.671103 | false | false | false | false |
qbalsdon/br.cd | refs/heads/master | brcd/brcd/Model/CoreDataStackManager.swift | mit | 1 | //
// CoreDataStackManager.swift
// brcd
//
// Created by Quintin Balsdon on 2016/01/17.
// Copyright © 2016 Balsdon. All rights reserved.
//
import Foundation
import CoreData
private let SQLITE_FILE_NAME = "brcd.sqlite"
class CoreDataStackManager {
// MARK: - Shared Instance
static let sharedInstance = CoreDataStackManager()
// MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate.
lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = NSBundle.mainBundle().URLForResource("brcd", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
let coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SQLITE_FILE_NAME)
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "br.cd", code: 9999, userInfo: dict)
print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
} | 917dce4612ae194725a0be98aacae167 | 35.689189 | 130 | 0.657332 | false | false | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/AssistantV1/Models/Entity.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2016, 2020.
*
* 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 IBMSwiftSDKCore
/**
Entity.
*/
public struct Entity: Codable, Equatable {
/**
The name of the entity. This string must conform to the following restrictions:
- It can contain only Unicode alphanumeric, underscore, and hyphen characters.
- If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity
that you want to enable. (Any entity content specified with the request is ignored.).
*/
public var entity: String
/**
The description of the entity. This string cannot contain carriage return, newline, or tab characters.
*/
public var description: String?
/**
Any metadata related to the entity.
*/
public var metadata: [String: JSON]?
/**
Whether to use fuzzy matching for the entity.
*/
public var fuzzyMatch: Bool?
/**
The timestamp for creation of the object.
*/
public var created: Date?
/**
The timestamp for the most recent update to the object.
*/
public var updated: Date?
/**
An array of objects describing the entity values.
*/
public var values: [Value]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case entity = "entity"
case description = "description"
case metadata = "metadata"
case fuzzyMatch = "fuzzy_match"
case created = "created"
case updated = "updated"
case values = "values"
}
}
| f7a54edbcd4abb93fa9c896089af83aa | 28.513514 | 118 | 0.669872 | false | false | false | false |
CodaFi/swift | refs/heads/main | validation-test/compiler_crashers_fixed/00819-swift-constraints-constraintsystem-opengeneric.swift | apache-2.0 | 65 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class B<T where B = b: Boolean).substringWithRange(i<Int
return "cd""",")
var _ c())) {
typealias f = T)) in c == a: Hashable> String {
func a(v: a {
enum b in c : A, T -> (x) {
}
}
struct S : P> {
}
}
}
var a: B? = 1
| 773d3ba241aabdd4f0a749e4077dd736 | 28.333333 | 79 | 0.676948 | false | false | false | false |
ProfileCreator/ProfileCreator | refs/heads/master | ProfileCreator/ProfileCreator/Profile Editor OutlineView/PropertyListEditor Source/Converters/PropertyListXMLReader.swift | mit | 1 | // swiftlint:disable:next file_header
// PropertyListXMLReader.swift
// PropertyListEditor
//
// Created by Prachi Gauriar on 7/23/2015.
// Copyright © 2015 Quantum Lens Cap. 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
/// The `PropertyListXMLReaderError` enum declares errors that can occur when reading data in the
/// property list XML format.
enum PropertyListXMLReaderError: Error {
/// Indicates that the XML for the property list is invalid.
case invalidXML
}
/// Instances of `PropertyListXMLReader` read Property List XML data and return a property list item
/// representation of that data. These should be used to read Property List XML files instead of
/// using `NSPropertyListSerialization`s, as `PropertyListXMLReaders` create dictionaries whose
/// key/value pairs are ordered the same as in the XML.
class PropertyListXMLReader: NSObject {
/// The property list item that the reader has read.
private var propertyListItem: PropertyListItem?
/// The XML data that the reader reads.
let XMLData: Data
/// Initializes a new `PropertyListXMLReader` with the specified XML data.
/// - parameter XMLData: The XML data that the instance should read.
init(XMLData: Data) {
self.XMLData = XMLData
super.init()
}
/// Reads the instance’s XML data and returns the resulting property list item. If the reader has
/// previously read the data, it simply returns the property list item that resulted from the
/// previous read.
///
/// - throws: `PropertyListXMLReaderError.InvalidXML` if the instance’s XML data is not valid
/// Property List XML data.
/// - returns: A `PropertyListItem` representation of the instance’s XML data.
func readData() throws -> PropertyListItem {
if let propertyListItem = propertyListItem {
return propertyListItem
}
let XMLDocument = try Foundation.XMLDocument(data: XMLData, options: XMLNode.Options(rawValue: 0))
guard let propertyListXMLElement = XMLDocument.rootElement()?.children?.first as? XMLElement,
let propertyListItem = PropertyListItem(XMLElement: propertyListXMLElement) else {
throw PropertyListXMLReaderError.invalidXML
}
self.propertyListItem = propertyListItem
return propertyListItem
}
}
/// This private extension adds the ability to create a new `PropertyListItem` with an XML element. It
/// is used by `PropertyListXMLReader.readData()` to recursively create a property list item from a
/// Property List XML document’s root element.
extension PropertyListItem {
/// Returns the property list item representation of the specified XML element. Returns nil if the
/// element cannot be represented using a property list item.
/// - parameter XMLElement: The XML element
init?(XMLElement: Foundation.XMLElement) {
guard let elementName = XMLElement.name else {
return nil
}
switch elementName {
case "array":
var array = PropertyListArray()
if let children = XMLElement.children {
for childXMLNode in children where childXMLNode is Foundation.XMLElement {
guard
let childXMLElement = childXMLNode as? Foundation.XMLElement,
let element = PropertyListItem(XMLElement: childXMLElement) else {
return nil
}
array.append(element)
}
}
self = .array(array)
case "dict":
var dictionary = PropertyListDictionary()
if let children = XMLElement.children {
guard children.count % 2 == 0 else {
return nil
}
var childGenerator = children.makeIterator()
while let keyNode = childGenerator.next() {
guard let keyElement = keyNode as? Foundation.XMLElement,
keyElement.name == "key",
let key = keyElement.stringValue,
!dictionary.containsKey(key),
let valueElement = childGenerator.next() as? Foundation.XMLElement,
let value = PropertyListItem(XMLElement: valueElement) else {
return nil
}
dictionary.addKey(key, value: value)
}
}
self = .dictionary(dictionary)
case "data":
guard let base64EncodedString = XMLElement.stringValue,
let data = Data(base64Encoded: base64EncodedString) else {
return nil
}
self = .data(data as NSData)
case "date":
guard let dateString = XMLElement.stringValue,
let date = DateFormatter.propertyListXML.date(from: dateString) else {
return nil
}
self = .date(date as NSDate)
case "integer", "real":
guard let numberString = XMLElement.stringValue,
let number = NumberFormatter.propertyList.number(from: numberString) else {
return nil
}
self = .number(number)
case "true":
self = .boolean(true)
case "false":
self = .boolean(false)
case "string":
guard let string = XMLElement.stringValue else {
return nil
}
self = .string(string as NSString)
default:
return nil
}
}
}
| 41f81ff2412fe0fcfa350116237dd551 | 39.73494 | 106 | 0.632209 | false | false | false | false |
uberbruns/CompareTools | refs/heads/master | DeltaCamera/DeltaCamera/BaseComponents/Items/ColorTableViewCell.swift | mit | 1 | //
// StaticValueTableViewCell.swift
// CompareApp
//
// Created by Karsten Bruns on 29/08/15.
// Copyright © 2015 bruns.me. All rights reserved.
//
import UIKit
import UBRDelta
class ColorTableViewCell: UITableViewCell, UpdateableTableViewCell {
let colorView = UIView()
let counterView = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
userInteractionEnabled = false
selectionStyle = .None
addSubviews()
addViewConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addSubviews() {
// Color View
colorView.backgroundColor = UIColor.blackColor()
colorView.translatesAutoresizingMaskIntoConstraints = false
addSubview(colorView)
// Counter View
counterView.textAlignment = .Right
counterView.translatesAutoresizingMaskIntoConstraints = false
addSubview(counterView)
}
func addViewConstraints() {
let views = ["colorView": colorView, "counterView": counterView]
let h = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[colorView(40)]-[counterView]-|", options: [], metrics: nil, views: views)
let vColorView = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[colorView]-|", options: [], metrics: nil, views: views)
let vCounterView = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[counterView]-|", options: [], metrics: nil, views: views)
addConstraints(h + vColorView + vCounterView)
}
func updateCellWithItem(item: ComparableItem, animated: Bool) {
guard let colorItem = item as? ColorItem else { return }
colorView.backgroundColor = colorItem.color.color
counterView.text = "\(colorItem.color.count)"
}
} | 83d707f52b3a234508f4ad01c788b8b2 | 31.566667 | 142 | 0.671275 | false | false | false | false |
Rendel27/RDExtensionsSwift | refs/heads/master | RDExtensionsSwift/RDExtensionsSwift/Source/CLLocationCoordinate2D/CLLocationCoordinate2D+General.swift | mit | 1 | //
// CLLocationCoordinate2D+General.swift
//
// Created by Giorgi Iashvili on 08.01.19.
// Copyright (c) 2016 Giorgi Iashvili
//
// 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 CoreLocation
public extension CLLocationCoordinate2D {
/// RDExtensionsSwift: The coordinates with 0 latitude and 0 longitude
static var zero: CLLocationCoordinate2D { get { return CLLocationCoordinate2D(latitude: 0, longitude: 0) } }
/// RDExtensionsSwift: Returns distance between the receiver and the given coordinates using Haversine Formula. Note: result is given in meters.
func distance(from coordinate: CLLocationCoordinate2D) -> Double
{
let lat1rad = self.latitude * Double.pi/180
let lon1rad = self.longitude * Double.pi/180
let lat2rad = coordinate.latitude * Double.pi/180
let lon2rad = coordinate.longitude * Double.pi/180
let dLat = lat2rad - lat1rad
let dLon = lon2rad - lon1rad
let a = sin(dLat/2) * sin(dLat/2) + sin(dLon/2) * sin(dLon/2) * cos(lat1rad) * cos(lat2rad)
let c = 2 * asin(sqrt(a))
let R = 6372.8
return R * c * 1000
}
}
| 3ba6cdcbfa6d340d39bea443200517ac | 43.42 | 148 | 0.705538 | false | false | false | false |
jlukanta/OneMarket | refs/heads/master | OneMarket/OneMarket/ItemAddVC.swift | mit | 1 | import UIKit
class ItemAddVC: UIViewController {
@IBOutlet weak var nameInput:UITextField!
@IBOutlet weak var locationInput:UITextField!
@IBOutlet weak var dateInput:UIDatePicker!
// Item service this screen will use
public var itemService:ItemService!
// The item we're editing
private var item:Item!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Use a fresh item
item = itemService.createItem()
nameInput.text = item.name
locationInput.text = item.location
if let date = item.date {
dateInput.date = date
}
// Start editing name from the get-go
nameInput.becomeFirstResponder()
}
@IBAction func done (_ sender: UIBarButtonItem) {
// Persist item
item.name = nameInput.text
item.location = locationInput.text
item.date = dateInput.date
itemService.saveItem(item: item)
// Go back to prev page
navigationController!.popViewController(animated: true)
}
}
| 510c528d3bbe58e503204a4818369ac6 | 24.4 | 59 | 0.689961 | false | false | false | false |
eraydiler/password-locker | refs/heads/master | PasswordLockerSwift/Classes/Controller/TabBarVC/EditSelectedValuesTableViewController.swift | mit | 1 | //
// EditSelectedValuesTableViewController.swift
// PasswordLockerSwift
//
// Created by Eray on 08/04/15.
// Copyright (c) 2015 Eray. All rights reserved.
//
import UIKit
import CoreData
protocol EditSelectedValuesTableViewControllerDelegate {
func rowValueChanged()
}
class EditSelectedValuesTableViewController: UITableViewController, UITextViewDelegate {
let TAG = "EditSelectedValuesTableViewController"
// set by AppDelegate on application startup
var placeholder: String?
var rowID: NSManagedObjectID?
var row: Row?
@IBOutlet weak var editTextField: UITextField!
@IBOutlet weak var editTextView: UITextView!
@IBOutlet weak var textFieldCell: UITableViewCell!
@IBOutlet weak var textViewCell: UITableViewCell!
// delegate to send value to former controller
var delegate: EditValuesTableViewControllerDelegate! = nil
func configureView() {
self.tableView.allowsSelection = false
self.tableView.rowHeight = 44.0
self.row = NSManagedObjectContext.mr_default().object(with: self.rowID!) as? Row
self.title = "Edit"
// Check if it is note
if self.row?.section == "2" {
// let frameRect = editTextField.frame
// frameRect.size.height = 10.0
// editTextField.frame = frameRect
self.textViewCell.isHidden = false
self.textFieldCell.isHidden = true
configureTextView()
} else {
self.textViewCell.isHidden = true
self.textFieldCell.isHidden = false
configureTextField()
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
print("\(TAG) memory warning", terminator: "")
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 2
}
// MARK: - Actions
@IBAction func doneBarButtonPressed(_ sender: UIBarButtonItem) {
var newValue = ""
if self.row?.section != "2" { newValue = editTextField.text! }
else { newValue = editTextView.text }
self.row?.value = newValue
delegate.rowValueChanged()
_ = self.navigationController?.popViewController(animated: true)
}
// MARK: - UITextField Delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
// MARK: - Keyboard Notifications
@objc func keyboardDidShow(_ notification: Notification) {
if let rectValue = notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue {
let keyboardSize = rectValue.cgRectValue.size
updateTextViewSizeForKeyboardHeight(keyboardSize.height)
}
}
@objc func keyboardDidHide(_ notification: Notification) {
updateTextViewSizeForKeyboardHeight(0)
}
func updateTextViewSizeForKeyboardHeight(_ keyboardHeight: CGFloat) {
self.editTextView?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - keyboardHeight-200)
}
// MARK: - Helper Methods
func configureTextField() {
if self.row?.value == "" {
self.editTextField.placeholder = self.row?.key
} else {
self.editTextField.text = self.row?.value
}
self.editTextField.text = placeholder
}
func configureTextView() {
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardDidShow),
name: UIResponder.keyboardDidShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardDidHide),
name: UIResponder.keyboardDidHideNotification,
object: nil
)
if self.row?.value == "" {
self.editTextView.text = "No Note"
} else {
self.editTextView.text = self.row?.value
}
}
}
| e172ba0f7496cabfa2a5afdccc0658e4 | 28.822368 | 126 | 0.619016 | false | false | false | false |
justwudi/WDImagePicker | refs/heads/master | WDImagePicker/ViewController.swift | mit | 2 | //
// ViewController.swift
// WDImagePicker
//
// Created by Wu Di on 27/8/15.
// Copyright (c) 2015 Wu Di. All rights reserved.
//
import UIKit
class ViewController: UIViewController, WDImagePickerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
private var imagePicker: WDImagePicker!
private var popoverController: UIPopoverController!
private var imagePickerController: UIImagePickerController!
private var customCropButton: UIButton!
private var normalCropButton: UIButton!
private var imageView: UIImageView!
private var resizableButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.customCropButton = UIButton()
self.customCropButton.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(20, 20, 220, 44) :
CGRectMake(20, CGRectGetMaxY(self.customCropButton.frame) + 20 , CGRectGetWidth(self.view.bounds) - 40, 44)
self.customCropButton.setTitleColor(self.view.tintColor, forState: .Normal)
self.customCropButton.setTitle("Custom Crop", forState: .Normal)
self.customCropButton.addTarget(self, action: #selector(ViewController.showPicker(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.customCropButton)
self.normalCropButton = UIButton()
self.normalCropButton.setTitleColor(self.view.tintColor, forState: .Normal)
self.normalCropButton.setTitle("Apple's Build In Crop", forState: .Normal)
self.normalCropButton.addTarget(self, action: #selector(ViewController.showNormalPicker(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.normalCropButton)
self.resizableButton = UIButton()
self.resizableButton.setTitleColor(self.view.tintColor, forState: .Normal)
self.resizableButton.setTitle("Resizable Custom Crop", forState: .Normal)
self.resizableButton.addTarget(self, action: #selector(ViewController.showResizablePicker(_:)), forControlEvents: .TouchUpInside)
self.view.addSubview(self.resizableButton)
self.imageView = UIImageView(frame: CGRectZero)
self.imageView.contentMode = .ScaleAspectFit
self.imageView.backgroundColor = UIColor.grayColor()
self.view.addSubview(self.imageView)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.normalCropButton.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(260, 20, 220, 44) :
CGRectMake(20, CGRectGetMaxY(self.customCropButton.frame) + 20 , CGRectGetWidth(self.view.bounds) - 40, 44)
self.resizableButton.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(500, 20, 220, 44) :
CGRectMake(20, CGRectGetMaxY(self.normalCropButton.frame) + 20 , CGRectGetWidth(self.view.bounds) - 40, 44)
self.imageView.frame = UIDevice.currentDevice().userInterfaceIdiom == .Pad ?
CGRectMake(20, 84, CGRectGetWidth(self.view.bounds) - 40, CGRectGetHeight(self.view.bounds) - 104) :
CGRectMake(20, CGRectGetMaxY(self.resizableButton.frame) + 20, CGRectGetWidth(self.view.bounds) - 40, CGRectGetHeight(self.view.bounds) - 20 - (CGRectGetMaxY(self.resizableButton.frame) + 20))
}
func showPicker(button: UIButton) {
self.imagePicker = WDImagePicker()
self.imagePicker.cropSize = CGSizeMake(280, 280)
self.imagePicker.delegate = self
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController = UIPopoverController(contentViewController: self.imagePicker.imagePickerController)
self.popoverController.presentPopoverFromRect(button.frame, inView: self.view, permittedArrowDirections: .Any, animated: true)
} else {
self.presentViewController(self.imagePicker.imagePickerController, animated: true, completion: nil)
}
}
func showNormalPicker(button: UIButton) {
self.imagePickerController = UIImagePickerController()
self.imagePickerController.sourceType = .PhotoLibrary
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = true
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController = UIPopoverController(contentViewController: self.imagePickerController)
self.popoverController.presentPopoverFromRect(button.frame, inView: self.view, permittedArrowDirections: .Any, animated: true)
} else {
self.presentViewController(self.imagePickerController, animated: true, completion: nil)
}
}
func showResizablePicker(button: UIButton) {
self.imagePicker = WDImagePicker()
self.imagePicker.cropSize = CGSizeMake(280, 280)
self.imagePicker.delegate = self
self.imagePicker.resizableCropArea = true
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController = UIPopoverController(contentViewController: self.imagePicker.imagePickerController)
self.popoverController.presentPopoverFromRect(button.frame, inView: self.view, permittedArrowDirections: .Any, animated: true)
} else {
self.presentViewController(self.imagePicker.imagePickerController, animated: true, completion: nil)
}
}
func imagePicker(imagePicker: WDImagePicker, pickedImage: UIImage) {
self.imageView.image = pickedImage
self.hideImagePicker()
}
func hideImagePicker() {
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController.dismissPopoverAnimated(true)
} else {
self.imagePicker.imagePickerController.dismissViewControllerAnimated(true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.imageView.image = image
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
self.popoverController.dismissPopoverAnimated(true)
} else {
picker.dismissViewControllerAnimated(true, completion: nil)
}
}
}
| 8e396b97a2c7649adfe729e54cceefa3 | 46.712121 | 204 | 0.710861 | false | false | false | false |
SwiftyCache/SwiftyCache | refs/heads/master | Tests/DiskLRUCacheTests.swift | apache-2.0 | 1 | //
// DiskLRUCacheTests.swift
// SwiftyCache
//
// Created by Haoming Ma on 1/03/2016.
//
// Copyright (C) 2016 SwiftyCache
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import SwiftyCache
private let MAGIC = "io.github.swiftycache.DiskLRUCache"
private let VERSION_1 = "1"
private let VALUE_COUNT = 2
private let CACHE_VERSION = 100
private let WAIT_TIME: NSTimeInterval = 3.0
class DiskLRUCacheTests: XCTestCase {
private var cacheDir: String!
private var journalFile: String!
private var journalBkpFile: String!
private var cache: DiskLRUCache!
override func setUp() {
super.setUp()
let tmp = NSTemporaryDirectory() as NSString
self.cacheDir = tmp.stringByAppendingPathComponent("DiskLRUCacheTest")
print("cacheDir: \(cacheDir)")
let fileManager = NSFileManager.defaultManager()
var isDir = ObjCBool(false)
if fileManager.fileExistsAtPath(self.cacheDir, isDirectory: &isDir) && isDir {
let enumerator = fileManager.enumeratorAtPath(self.cacheDir)!
while let fileName = enumerator.nextObject() as? String {
try! fileManager.removeItemAtPath((self.cacheDir as NSString).stringByAppendingPathComponent(fileName))
}
}
self.journalFile = (self.cacheDir as NSString).stringByAppendingPathComponent("journal")
self.journalBkpFile = (self.cacheDir as NSString).stringByAppendingPathComponent("journal.bkp")
self.cache = newDiskLRUCacheInstance()
}
func newDiskLRUCacheInstance(maxSize maxSize: Int64 = INT64_MAX) -> DiskLRUCache {
return DiskLRUCache(cacheDir: cacheDir, cacheVersion: CACHE_VERSION, valueCount: VALUE_COUNT, maxSize: maxSize)
}
func newDiskLRUCacheInstance(redundantOpThreshold redundantOpThreshold: Int) -> DiskLRUCache {
let cache = DiskLRUCache(cacheDir: cacheDir, cacheVersion: CACHE_VERSION, valueCount: VALUE_COUNT, maxSize: INT64_MAX)
cache.setRedundantOpCompactThreshold(redundantOpThreshold)
return cache
}
override func tearDown() {
try! self.cache.closeNow()
self.cache = nil
super.tearDown()
}
func readJournalLines() -> [String] {
let journalContents = try! String(contentsOfFile: self.journalFile, encoding: NSUTF8StringEncoding)
return journalContents.characters.split(allowEmptySlices: true){$0 == "\n"}.map(String.init)
}
func assertJournalBodyEquals(lines: String...) {
var expectedLines = [String]()
expectedLines.append(MAGIC)
expectedLines.append(VERSION_1)
expectedLines.append("\(CACHE_VERSION)")
expectedLines.append("\(VALUE_COUNT)")
expectedLines.append("")
expectedLines.appendContentsOf(lines)
expectedLines.append("")
XCTAssertEqual(readJournalLines(), expectedLines)
}
func writeFile(path: String, content: String) {
try! content.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
}
func getJournalHeader(magic magic: String = MAGIC, version: String = VERSION_1,
cacheVersion: Int = CACHE_VERSION, valueCount: Int = VALUE_COUNT, blankLine: String = "") -> String {
return magic + "\n" + version + "\n" + "\(cacheVersion)" + "\n" + "\(valueCount)" + "\n" + blankLine + "\n"
}
func createJournalWithHeader(header: String, bodyLines: String...) {
var content = header
bodyLines.forEach { (line: String) -> () in
content = content + line + "\n"
}
writeFile(self.journalFile, content: content)
}
func createJournalWithHeader(header: String, body: String) {
writeFile(self.journalFile, content: header + body)
}
func createJournalWithBody(body: String) {
createJournalWithHeader(getJournalHeader(), body: body)
}
func getCleanFilePathForKey(key: String, index: Int) -> String {
return self.cacheDir + "/" + key + ".\(index)"
}
func getDirtyFilePathForKey(key: String, index: Int) -> String {
return self.cacheDir + "/" + key + ".\(index).tmp"
}
func testEmptyCache() {
try! cache.closeNow();
assertJournalBodyEquals()
}
func strToNSData(str: String) -> NSData {
return str.dataUsingEncoding(NSUTF8StringEncoding)!
}
func assertFileNotExists(path: String) {
let fileManager = NSFileManager.defaultManager()
XCTAssertFalse(fileManager.fileExistsAtPath(path), "should not exist: \(path)")
}
func assertFileExists(path: String) {
let fileManager = NSFileManager.defaultManager()
XCTAssertTrue(fileManager.fileExistsAtPath(path), "should exist: \(path)")
}
func assertFileAtPath(path: String, content: String) {
assertFileExists(path)
let str = try! String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
XCTAssertEqual(content, str)
}
func assertCacheFilesNotExistForKey(key: String) {
assertFileNotExists(self.cacheDir + "/" + key + ".0")
assertFileNotExists(self.cacheDir + "/" + key + ".1")
}
func assertCacheEntryForKey(key: String, index: Int, value: String) {
let path = self.cacheDir + "/" + key + ".\(index)"
assertFileExists(path)
assertFileAtPath(path, content: value)
}
func assertInvalidKey(invalidKey: String) {
XCTAssertFalse(self.cache.isValidKey(invalidKey))
let data1 = strToNSData("f1")
let expectation = self.expectationWithDescription("Caught invalid key: \(invalidKey)")
self.cache.setData([data1, data1], forKey: invalidKey) { (error: NSError?) in
guard let error = error else {
XCTFail("should not be here, '\(invalidKey)' should be an invalid key")
return
}
XCTAssertEqual(error.localizedDescription, "Invalid key: \(invalidKey)")
XCTAssertEqual(error.code, DiskLRUCacheErrorCode.ErrorCodeBadFormat.rawValue)
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertValidKey(key: String) {
XCTAssertTrue(self.cache.isValidKey(key), "'\(key)' should be a valid key.")
}
func assertSuccessOnRemoveEntryForKey(key: String, isRemoved: Bool = true) {
let expectation = self.expectationWithDescription("entry removed for key: \(key)")
self.cache.removeEntryForKey(key) { (error: NSError?, removed: Bool) in
XCTAssertNil(error, "should not be here, error happened when removing entry for key: \(key)")
XCTAssertEqual(removed, isRemoved)
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func testValidateKey() {
assertInvalidKey("invalid/key")
assertInvalidKey("invalid key")
assertInvalidKey("invalid\tkey")
assertInvalidKey("invalid\nkey")
assertInvalidKey("invalid\rkey")
assertInvalidKey("invalid\r\nkey")
assertInvalidKey("`")
assertValidKey("-")
assertValidKey("___-")
assertValidKey("A")
assertValidKey("ABCD")
assertValidKey("aaAA")
assertValidKey("a")
assertValidKey("abcd")
assertValidKey("1")
assertValidKey("1234")
assertValidKey("Aa1Bb2Cc3-Dd4_0")
assertInvalidKey("人")
assertInvalidKey("©")
let str120chars = "123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_"
assertValidKey(str120chars)
assertInvalidKey(str120chars + "a")
assertInvalidKey("😄😄😄")
assertInvalidKey("😄😄")
assertInvalidKey("😄")
assertInvalidKey("")
assertInvalidKey(" ")
assertInvalidKey("\n")
assertInvalidKey("\r\n")
assertInvalidKey("\t")
assertInvalidKey(" ")
}
func assertNilSnapshotForKey(key: String) {
let expectation = self.expectationWithDescription("getSnapshotForKey: \(key) returned nil as expected")
self.cache.getSnapshotForKey(key, readIndex: [true, true]) { (error: NSError?, snapshot:CacheEntrySnapshot?) in
XCTAssertNil(error, "should not be here, failed to getSnapshotForKey: \(key). Error: \(error)")
XCTAssertNil(snapshot)
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertSuccessOnSetDataForKey(key: String, value0: String, value1: String) {
assertSuccessOnSetDataForKey(key, value0: value0, value1: value1, cache: self.cache)
}
func assertSuccessOnSetDataForKey(key: String, value0: String, value1: String, cache diskCache: DiskLRUCache) {
let expectationSetData = self.expectationWithDescription("setData:forKey \(key) succeeded as expected")
diskCache.setData([strToNSData(value0), strToNSData(value1)], forKey: key) { (error: NSError?) in
XCTAssertNil(error, "should not be here, failed to setData:forKey \(key), error: \(error)")
expectationSetData.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertErrorOnSetDataForKey(key: String, value0: String, value1: String) {
assertErrorOnSetDataForKey(key, value0: value0, value1: value1, cache: self.cache)
}
func assertErrorOnSetDataForKey(key: String, value0: String, value1: String, cache diskCache: DiskLRUCache) {
let expectation = self.expectationWithDescription("setData:forKey \(key) had error as expected")
diskCache.setData([strToNSData(value0), strToNSData(value1)], forKey: key) { (error: NSError?) in
XCTAssertNotNil(error)
XCTAssertEqual(error!.localizedDescription, "Failed to set value for key:\(key) index:0")
XCTAssertEqual(error!.code, DiskLRUCacheErrorCode.ErrorCodeIOException.rawValue)
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertSuccessOnSetPartialDataForKey(key: String, value: String, index: Int, cache diskCache: DiskLRUCache) {
let expectationSetData = self.expectationWithDescription("setPartialData:forExistingKey \(key) succeeded as expected")
diskCache.setPartialData([(strToNSData(value), index)], forExistingKey: key) { (error: NSError?) in
XCTAssertNil(error, "should not be here, failed to setPartialData:forExistingKey \(key)")
expectationSetData.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertErrorOnSetPartialDataForKey(key: String, value: String, index: Int, cache diskCache: DiskLRUCache) {
let expectation = self.expectationWithDescription("setPartialData:forExistingKey \(key) had error as expected")
diskCache.setPartialData([(strToNSData(value), index)], forExistingKey: key) { (error: NSError?) in
XCTAssertNotNil(error)
XCTAssertEqual(error!.localizedDescription, "Failed to set partial data for key:\(key) index:\(index)")
XCTAssertEqual(error!.code, DiskLRUCacheErrorCode.ErrorCodeIOException.rawValue)
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertEmptyDir(path: String) {
let fileManager = NSFileManager.defaultManager()
let enumerator = fileManager.enumeratorAtPath(path)!
while let fileName = enumerator.nextObject() as? String {
XCTFail("\(path) should be empty, but file exits at \(fileName)")
}
}
func assertSuccessOnDeleteCache() {
let expectation = self.expectationWithDescription("cache deleted as expected")
self.cache.delete { (error: NSError?) in
XCTAssertNil(error, "should not be here, failed to delete the cache")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
assertFileNotExists(self.cacheDir)
XCTAssertTrue(self.cache.isClosed)
}
func assertErrorOnSetPartialDataForNewKey(key: String, value: String, index: Int, cache diskCache: DiskLRUCache) {
let expectation = self.expectationWithDescription("setPartialData:forExistingKey \(key) had error as expected")
diskCache.setPartialData([(strToNSData(value), index)], forExistingKey: key) { (error: NSError?) in
var indexWithoutValue = 0
if index == 0 {
indexWithoutValue = 1
}
XCTAssertNotNil(error)
XCTAssertEqual(error!.localizedDescription, "Newly created entry didn't create value for index: \(indexWithoutValue)")
XCTAssertEqual(error!.code, DiskLRUCacheErrorCode.ErrorCodeIllegalStateException.rawValue)
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
}
func assertOnGetSnapshotForKey(key: String, value0: String, value1: String, cache diskCache: DiskLRUCache) -> CacheEntrySnapshot? {
let expectationGetData = self.expectationWithDescription("getSnapshotForKey: \(key) returned the data as expected")
var ss: CacheEntrySnapshot? = nil
diskCache.getSnapshotForKey(key, readIndex: [true, true]) { (error: NSError?, snapshot: CacheEntrySnapshot?) in
XCTAssertNil(error)
ss = snapshot
XCTAssertNotNil(snapshot)
XCTAssertEqual(snapshot!.getDataAtIndex(0), self.strToNSData(value0))
XCTAssertEqual(snapshot!.getDataAtIndex(1), self.strToNSData(value1))
XCTAssertEqual(snapshot!.getStringDataAtIndex(0, encoding: NSUTF8StringEncoding), value0)
XCTAssertEqual(snapshot!.getStringDataAtIndex(1, encoding: NSUTF8StringEncoding), value1)
expectationGetData.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
return ss
}
func assertOnGetSnapshotForKey(key: String, value0: String, value1: String) -> CacheEntrySnapshot? {
return assertOnGetSnapshotForKey(key, value0: value0, value1: value1, cache: self.cache)
}
func assertSuccessOnCloseCache(diskCache: DiskLRUCache) {
XCTAssertFalse(diskCache.isClosed)
let expectationClose = self.expectationWithDescription("cache closed")
diskCache.close { (error: NSError?) in
XCTAssertNil(error)
expectationClose.fulfill()
}
self.waitForExpectationsWithTimeout(WAIT_TIME, handler: nil)
XCTAssertTrue(diskCache.isClosed)
}
func testWriteAndReadEntry() {
let key1 = "key1"
let abc = "abc"
let de = "de"
assertNilSnapshotForKey(key1)
assertSuccessOnSetDataForKey(key1, value0: abc, value1: de)
assertOnGetSnapshotForKey(key1, value0: abc, value1: de)
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2", "READ key1")
}
func testReadAndWriteEntryAcrossCacheOpenAndClose() {
let key1 = "key1"
let abc = "abc"
let de = "de"
assertNilSnapshotForKey(key1)
assertSuccessOnSetDataForKey(key1, value0: abc, value1: de)
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey(key1, value0: abc, value1: de)
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2", "READ key1")
}
func testReadAndWriteEntryWithoutProperClose() {
let key1 = "key1"
let abc = "abc"
let de = "de"
assertSuccessOnSetDataForKey(key1, value0: abc, value1: de)
// Simulate a dirty close of 'cache' (e.g. it is not close properly) by opening the cache directory again.
let cache2 = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey(key1, value0: abc, value1: de, cache: cache2)
assertSuccessOnSetDataForKey(key1, value0: abc, value1: "defg", cache: cache2)
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2", "READ key1", "DIRTY key1", "CLEAN key1 3 4")
assertSuccessOnCloseCache(cache2)
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2", "READ key1", "DIRTY key1", "CLEAN key1 3 4")
}
func testJournalWithEditAndPublish() {
assertSuccessOnSetDataForKey("key1", value0: "abc", value1: "de")
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2")
assertSuccessOnCloseCache(self.cache)
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2")
}
func testPartiallySetNewKeyIsRemoveInJournal() {
assertErrorOnSetPartialDataForNewKey("key1", value: "abc", index: 0, cache: self.cache)
assertJournalBodyEquals("DIRTY key1", "REMOVE key1")
assertCacheFilesNotExistForKey("key1")
}
func testSetPartialDataForKey() {
assertSuccessOnSetDataForKey("key1", value0: "abc", value1: "de")
assertSuccessOnSetPartialDataForKey("key1", value: "fghi", index: 1, cache: self.cache)
assertJournalBodyEquals("DIRTY key1", "CLEAN key1 3 2", "DIRTY key1", "CLEAN key1 3 4")
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey("key1", value0: "abc", value1: "fghi")
}
func testJournalWithEditAndPublishAndRead() {
assertSuccessOnSetDataForKey("k1", value0: "AB", value1: "C")
assertSuccessOnSetDataForKey("k2", value0: "DEF", value1: "G")
assertOnGetSnapshotForKey("k1", value0: "AB", value1: "C")
assertJournalBodyEquals("DIRTY k1", "CLEAN k1 2 1", "DIRTY k2", "CLEAN k2 3 1", "READ k1")
}
func testExplicitRemoveAppliedToDiskImmediately() {
assertSuccessOnSetDataForKey("k1", value0: "AB", value1: "C")
assertCacheEntryForKey("k1", index: 0, value: "AB")
assertCacheEntryForKey("k1", index: 1, value: "C")
assertSuccessOnRemoveEntryForKey("k1")
assertCacheFilesNotExistForKey("k1")
}
func testOpenWithDirtyKeyDeletesAllFilesForThatKey() {
assertSuccessOnCloseCache(self.cache)
let cleanFile0 = getCleanFilePathForKey("k1", index: 0)
let cleanFile1 = getCleanFilePathForKey("k1", index: 1)
let dirtyFile0 = getDirtyFilePathForKey("k1", index: 0)
let dirtyFile1 = getDirtyFilePathForKey("k1", index: 1)
writeFile(cleanFile0, content: "A")
writeFile(cleanFile1, content: "B")
writeFile(dirtyFile0, content: "C")
writeFile(dirtyFile1, content: "D");
createJournalWithBody("CLEAN k1 1 1\nDIRTY k1\n")
self.cache = newDiskLRUCacheInstance()
assertNilSnapshotForKey("k1")
assertFileNotExists(cleanFile0)
assertFileNotExists(cleanFile1)
assertFileNotExists(dirtyFile0)
assertFileNotExists(dirtyFile1)
}
func assertValidJournalLine(line: String, key: String, value0: String, value1: String) {
assertSuccessOnCloseCache(self.cache)
let cleanFile0 = getCleanFilePathForKey(key, index: 0)
let cleanFile1 = getCleanFilePathForKey(key, index: 1)
let dirtyFile0 = getDirtyFilePathForKey(key, index: 0)
let dirtyFile1 = getDirtyFilePathForKey(key, index: 1)
writeFile(cleanFile0, content: value0)
writeFile(cleanFile1, content: value1)
createJournalWithBody(line + "\n")
self.cache = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey(key, value0: value0, value1: value1)
assertFileExists(cleanFile0)
assertFileExists(cleanFile1)
assertFileNotExists(dirtyFile0)
assertFileNotExists(dirtyFile1)
}
func assertMalformedJournalLine(line: String, key: String, value0: String, value1: String) {
assertSuccessOnCloseCache(self.cache)
generateSomeGarbageFiles()
let cleanFile0 = getCleanFilePathForKey(key, index: 0)
let cleanFile1 = getCleanFilePathForKey(key, index: 1)
let dirtyFile0 = getDirtyFilePathForKey(key, index: 0)
let dirtyFile1 = getDirtyFilePathForKey(key, index: 1)
writeFile(cleanFile0, content: value0)
writeFile(cleanFile1, content: value1)
createJournalWithBody(line + "\n")
self.cache = newDiskLRUCacheInstance()
assertNilSnapshotForKey(key)
assertFileNotExists(cleanFile0)
assertFileNotExists(cleanFile1)
assertFileNotExists(dirtyFile0)
assertFileNotExists(dirtyFile1)
assertGarbageFilesAllDeleted()
}
func testJournalLines() {
assertValidJournalLine("CLEAN k1 1 1", key: "k1", value0: "A", value1: "B")
assertValidJournalLine("CLEAN k1 0 2", key: "k1", value0: "", value1: "Bc")
// wrong value size, but still valid!!
assertValidJournalLine("CLEAN k1 1 2", key: "k1", value0: "A", value1: "B")
// two spaces instead of one behind CLEAN
assertMalformedJournalLine("CLEAN k1 1 1", key: "k1", value0: "A", value1: "B")
// wrong value count
assertMalformedJournalLine("CLEAN k1 1 2 3", key: "k1", value0: "A", value1: "B")
// malformed number
assertMalformedJournalLine("CLEAN k1 1k 1", key: "k1", value0: "A", value1: "B")
// invalid status
assertMalformedJournalLine("BADStatus k1 1 1", key: "k1", value0: "A", value1: "B")
// invalid line
assertMalformedJournalLine("CLEAN k1 1 1\nBOGUS", key: "k1", value0: "A", value1: "B") }
func generateSomeGarbageFiles() {
let fileManager = NSFileManager.defaultManager()
let dir1 = self.cacheDir + "/dir1"
try! fileManager.createDirectoryAtPath(dir1, withIntermediateDirectories: false, attributes: nil)
let dir2 = self.cacheDir + "/dir2"
try! fileManager.createDirectoryAtPath(dir2, withIntermediateDirectories: false, attributes: nil)
let fileUnderDir2 = dir2 + "/otherFile1"
writeFile(fileUnderDir2, content: "F")
let cleanG1File0 = getCleanFilePathForKey("g1", index: 0)
writeFile(cleanG1File0, content: "A")
let cleanG1File1 = getCleanFilePathForKey("g1", index: 1)
writeFile(cleanG1File1, content: "B")
let cleanG2File0 = getCleanFilePathForKey("g2", index: 0)
writeFile(cleanG2File0, content: "C")
let cleanG2File1 = getCleanFilePathForKey("g2", index: 1)
writeFile(cleanG2File1, content: "D")
}
func assertGarbageFilesAllDeleted() {
let dir1 = self.cacheDir + "/dir1"
assertFileNotExists(dir1)
let dir2 = self.cacheDir + "/dir2"
assertFileNotExists(dir2)
let fileUnderDir2 = dir2 + "/otherFile1"
assertFileNotExists(fileUnderDir2)
assertFileNotExists(getCleanFilePathForKey("g1", index: 0))
assertFileNotExists(getCleanFilePathForKey("g1", index: 1))
assertFileNotExists(getCleanFilePathForKey("g2", index: 0))
assertFileNotExists(getCleanFilePathForKey("g2", index: 1))
}
func testEmptyJournalBody() {
assertSuccessOnCloseCache(self.cache)
let header = getJournalHeader()
createJournalWithHeader(header, body: "")
self.cache = newDiskLRUCacheInstance()
assertNilSnapshotForKey("NoSuchKey")
XCTAssertEqual(0, self.cache.size)
}
func assertInvalidJournalHeader(header: String) {
assertSuccessOnCloseCache(self.cache)
generateSomeGarbageFiles()
createJournalWithHeader(header)
self.cache = newDiskLRUCacheInstance()
assertNilSnapshotForKey("NoSuchKey")
XCTAssertEqual(0, self.cache.size)
assertGarbageFilesAllDeleted()
}
func testInvalidJournalHeaders() {
assertInvalidJournalHeader(getJournalHeader(version: "0"))
assertInvalidJournalHeader(getJournalHeader(cacheVersion: 101))
assertInvalidJournalHeader(getJournalHeader(valueCount: 1))
assertInvalidJournalHeader(getJournalHeader(magic: MAGIC + " "))
assertInvalidJournalHeader(getJournalHeader(blankLine: " "))
}
func testOpenWithTruncatedLineWillNotDiscardThatLine() {
assertSuccessOnCloseCache(self.cache)
let key = "k1"
let value0 = "A"
let value1 = "B"
let cleanFile0 = getCleanFilePathForKey(key, index: 0)
let cleanFile1 = getCleanFilePathForKey(key, index: 1)
writeFile(cleanFile0, content: value0)
writeFile(cleanFile1, content: value1)
createJournalWithBody("CLEAN k1 1 1") // no trailing newline
assertFileAtPath(journalFile, content: getJournalHeader() + "CLEAN k1 1 1")
self.cache = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey(key, value0: value0, value1: value1)
assertSuccessOnCloseCache(self.cache)
assertJournalBodyEquals("CLEAN k1 1 1", "READ k1")
assertFileAtPath(journalFile, content: getJournalHeader() + "CLEAN k1 1 1\nREAD k1\n")
}
func testEvictOnInsert() {
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(maxSize: 10)
assertSuccessOnSetDataForKey("a", value0: "a", value1: "aaa") // size 4
assertSuccessOnSetDataForKey("b", value0: "bb", value1: "bbbb") // size 6
XCTAssertEqual(10, self.cache.size)
// Cause the size to grow to 12 should evict 'a'.
assertSuccessOnSetDataForKey("c", value0: "c", value1: "c")
//XCTAssertEqual(12, self.cache.getSize()) // it is an async process to evict. The assert may fail sometimes.
assertNilSnapshotForKey("a")
XCTAssertEqual(8, self.cache.size)
assertJournalBodyEquals("DIRTY a", "CLEAN a 1 3", "DIRTY b", "CLEAN b 2 4", "DIRTY c", "CLEAN c 1 1", "REMOVE a")
// Causing the size to grow to 10 should evict nothing.
assertSuccessOnSetDataForKey("d", value0: "d", value1: "d")
assertNilSnapshotForKey("a")
XCTAssertEqual(10, self.cache.size)
assertOnGetSnapshotForKey("b", value0: "bb", value1: "bbbb")
assertOnGetSnapshotForKey("c", value0: "c", value1: "c")
assertOnGetSnapshotForKey("d", value0: "d", value1: "d")
// Causing the size to grow to 18 should evict 'B' and 'C'.
assertSuccessOnSetDataForKey("e", value0: "eeee", value1: "eeee")
assertNilSnapshotForKey("a")
assertNilSnapshotForKey("b")
assertNilSnapshotForKey("c")
assertOnGetSnapshotForKey("d", value0: "d", value1: "d")
assertOnGetSnapshotForKey("e", value0: "eeee", value1: "eeee")
}
func testEvictionHonorsLruFromCurrentSession() {
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(maxSize: 10)
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
assertSuccessOnSetDataForKey("c", value0: "c", value1: "c")
assertSuccessOnSetDataForKey("d", value0: "d", value1: "d")
assertSuccessOnSetDataForKey("e", value0: "e", value1: "e")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")// 'b' is now recently used.
// Causing the size to grow to 12 should evict 'a'.
assertSuccessOnSetDataForKey("f", value0: "f", value1: "f")
// Causing the size to grow to 12 should evict 'c'.
assertSuccessOnSetDataForKey("g", value0: "g", value1: "g")
assertNilSnapshotForKey("a")
assertNilSnapshotForKey("c")
XCTAssertEqual(10, self.cache.size)
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
assertOnGetSnapshotForKey("d", value0: "d", value1: "d")
assertOnGetSnapshotForKey("e", value0: "e", value1: "e")
assertOnGetSnapshotForKey("f", value0: "f", value1: "f")
assertOnGetSnapshotForKey("g", value0: "g", value1: "g")
}
func testEvictionHonorsLruFromPreviousSession() {
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
assertSuccessOnSetDataForKey("c", value0: "c", value1: "c")
assertSuccessOnSetDataForKey("d", value0: "d", value1: "d")
assertSuccessOnSetDataForKey("e", value0: "e", value1: "e")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")// 'b' is now recently used.
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(maxSize: 10)
// Causing the size to grow to 12 should evict 'a'.
assertSuccessOnSetDataForKey("f", value0: "f", value1: "f")
// Causing the size to grow to 12 should evict 'c'.
assertSuccessOnSetDataForKey("g", value0: "g", value1: "g")
assertNilSnapshotForKey("a")
assertNilSnapshotForKey("c")
XCTAssertEqual(10, self.cache.size)
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
assertOnGetSnapshotForKey("d", value0: "d", value1: "d")
assertOnGetSnapshotForKey("e", value0: "e", value1: "e")
assertOnGetSnapshotForKey("f", value0: "f", value1: "f")
assertOnGetSnapshotForKey("g", value0: "g", value1: "g")
}
func testCacheSingleEntryOfSizeGreaterThanMaxSize() {
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(maxSize: 10)
assertSuccessOnSetDataForKey("a", value0: "aaaaa", value1: "aaaaaa")
assertNilSnapshotForKey("a")
}
func testCacheSingleValueOfSizeGreaterThanMaxSize() {
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(maxSize: 10)
assertSuccessOnSetDataForKey("a", value0: "aaaaaaaaaaa", value1: "a")
assertNilSnapshotForKey("a")
}
func testRemoveAbsentElement() {
assertSuccessOnRemoveEntryForKey("a", isRemoved: false)
assertJournalBodyEquals()
}
func testRebuildJournalOnRepeatedReads() {
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(redundantOpThreshold: 200)
var lastJournalLength: Int64 = 0
while true {
let journalLen = try! Utils.getFileSizeAtPath(self.journalFile)
assertOnGetSnapshotForKey("a", value0: "a", value1: "a")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
if (journalLen < lastJournalLength) {
print("Journal compacted from \(lastJournalLength) bytes to \(journalLen) bytes")
break
}
if (self.cache.redundantOperationCountInJournal > self.cache.redundantOperationCompactThreshold) {
XCTFail()
break
}
lastJournalLength = journalLen
}
// Sanity check that a rebuilt journal behaves normally.
assertOnGetSnapshotForKey("a", value0: "a", value1: "a")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
}
func testRebuildJournalOnRepeatedEdits() {
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(redundantOpThreshold: 200)
var lastJournalLength: Int64 = 0
while true {
let journalLen = try! Utils.getFileSizeAtPath(self.journalFile)
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
if (journalLen < lastJournalLength) {
print("Journal compacted from \(lastJournalLength) bytes to \(journalLen) bytes")
break
}
if (self.cache.redundantOperationCountInJournal > self.cache.redundantOperationCompactThreshold) {
XCTFail()
break
}
lastJournalLength = journalLen
}
assertOnGetSnapshotForKey("a", value0: "a", value1: "a")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
}
func testRebuildJournalOnRepeatedReadsWithOpenAndClose() {
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(redundantOpThreshold: 200)
var lastJournalLength: Int64 = 0
while true {
let journalLen = try! Utils.getFileSizeAtPath(self.journalFile)
assertOnGetSnapshotForKey("a", value0: "a", value1: "a")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(redundantOpThreshold: 200)
if (journalLen < lastJournalLength) {
print("Journal compacted from \(lastJournalLength) bytes to \(journalLen) bytes")
break
}
if (self.cache.redundantOperationCountInJournal > self.cache.redundantOperationCompactThreshold) {
XCTFail()
break
}
lastJournalLength = journalLen
}
// Sanity check that a rebuilt journal behaves normally.
assertOnGetSnapshotForKey("a", value0: "a", value1: "a")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
}
func testRebuildJournalOnRepeatedEditsWithOpenAndClose() {
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(redundantOpThreshold: 200)
var lastJournalLength: Int64 = 0
while true {
let journalLen = try! Utils.getFileSizeAtPath(self.journalFile)
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertSuccessOnSetDataForKey("b", value0: "b", value1: "b")
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(redundantOpThreshold: 200)
if (journalLen < lastJournalLength) {
print("Journal compacted from \(lastJournalLength) bytes to \(journalLen) bytes")
break
}
if (self.cache.redundantOperationCountInJournal > self.cache.redundantOperationCompactThreshold) {
XCTFail()
break
}
lastJournalLength = journalLen
}
// Sanity check that a rebuilt journal behaves normally.
assertOnGetSnapshotForKey("a", value0: "a", value1: "a")
assertOnGetSnapshotForKey("b", value0: "b", value1: "b")
}
func testRestoreBackupFile() {
assertSuccessOnSetDataForKey("k1", value0: "ABC", value1: "DE")
assertSuccessOnCloseCache(self.cache)
try! Utils.renamePath(self.journalFile, toPath: self.journalBkpFile, deleteDestination: false)
assertFileExists(self.journalBkpFile)
assertFileNotExists(self.journalFile)
self.cache = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey("k1", value0: "ABC", value1: "DE")
assertFileNotExists(self.journalBkpFile)
assertFileExists(self.journalFile)
}
func testJournalFileIsPreferredOverBackupFile() {
assertSuccessOnSetDataForKey("k1", value0: "ABC", value1: "DE")
assertFileNotExists(self.journalBkpFile)
let fileManager = NSFileManager.defaultManager()
try! fileManager.copyItemAtPath(self.journalFile, toPath: self.journalBkpFile)
assertSuccessOnSetDataForKey("k2", value0: "F", value1: "GH")
assertSuccessOnCloseCache(self.cache)
assertFileExists(self.journalBkpFile)
assertFileExists(self.journalFile)
self.cache = newDiskLRUCacheInstance()
assertOnGetSnapshotForKey("k1", value0: "ABC", value1: "DE")
assertOnGetSnapshotForKey("k2", value0: "F", value1: "GH")
assertFileNotExists(self.journalBkpFile)
assertFileExists(self.journalFile)
}
func testOpenCreatesDirectoryIfNecessary() {
assertSuccessOnCloseCache(self.cache)
let oldCacheDir = self.cacheDir
self.cacheDir = oldCacheDir + "/testOpenCreatesDirectoryIfNecessary"
assertFileNotExists(self.cacheDir)
self.cache = newDiskLRUCacheInstance()
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
assertFileExists(self.cacheDir + "/a.0")
assertFileExists(self.cacheDir + "/a.1")
assertFileExists(self.cacheDir + "/journal")
}
func testFileDeletedExternally() {
assertSuccessOnSetDataForKey("a", value0: "a", value1: "a")
let a1path = self.cacheDir + "/a.1"
assertFileExists(a1path)
let fileManager = NSFileManager.defaultManager()
try! fileManager.removeItemAtPath(a1path)
assertNilSnapshotForKey("a")
}
func testExistingSnapshotStillValidAfterEntryEvicted() {
assertSuccessOnCloseCache(self.cache)
self.cache = newDiskLRUCacheInstance(maxSize: 10)
assertSuccessOnSetDataForKey("a", value0: "aa", value1: "aaa")
guard let snapshotA = assertOnGetSnapshotForKey("a", value0: "aa", value1: "aaa") else {
XCTFail()
return
}
assertSuccessOnSetDataForKey("b", value0: "bb", value1: "bbb") // size 10 reached
assertSuccessOnSetDataForKey("c", value0: "cc", value1: "ccc") // size 5; will evict 'a'
assertNilSnapshotForKey("a")
XCTAssertEqual(snapshotA.getStringDataAtIndex(0, encoding: NSUTF8StringEncoding), "aa")
XCTAssertEqual(snapshotA.getStringDataAtIndex(1, encoding: NSUTF8StringEncoding), "aaa")
}
func testUsingNSOutputStreamAfterFileDeleted() {
let path = self.cacheDir + "/testOutputStream"
assertFileNotExists(path)
let outputStream = NSOutputStream(toFileAtPath: path, append: true)
outputStream?.open()
try! outputStream?.IA_write("test line\n")
assertFileExists(path)
try! Utils.deleteFileIfExistsAtPath(path)
assertFileNotExists(path)
do {
try outputStream?.IA_write("second test line\n") //no error. TODO: handle the error using a custom NSStreamDelegate
XCTAssertNil(outputStream?.delegate)
} catch {
XCTFail()
}
}
func testCacheDelete() {
assertSuccessOnSetDataForKey("a", value0: "aa", value1: "aaa")
assertFileExists(self.journalFile)
assertSuccessOnDeleteCache()
assertFileNotExists(self.cacheDir)
XCTAssertTrue(self.cache.isClosed)
}
func testAggressiveClearingHandlesReadWriteRemoveKeyAndClose() {
assertSuccessOnSetDataForKey("a", value0: "aa", value1: "aaa")
assertSuccessOnSetDataForKey("c", value0: "cc", value1: "ccc")
assertSuccessOnSetDataForKey("b", value0: "bb", value1: "bbb") // wait async operations to finish, or deleting cache dir may fail
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtPath(self.cacheDir)
} catch {
print("------------ delete failed")
XCTFail()
}
assertFileNotExists(self.cacheDir)
// all public APIs should be tested after the cache dir was removed externally.
// the method delete call is not included below, since it will also close the cache
assertErrorOnSetDataForKey("d", value0: "dd", value1: "ddd")
assertErrorOnSetPartialDataForKey("a", value: "a0", index: 0, cache: self.cache)
assertSuccessOnRemoveEntryForKey("b", isRemoved: true) // TODO: isRemoved should be false if NSStreamDelegate is added for the journalWriter.
assertNilSnapshotForKey("a")
assertNilSnapshotForKey("b")
assertNilSnapshotForKey("c")
assertNilSnapshotForKey("d")
//test close
assertSuccessOnCloseCache(self.cache)
assertFileNotExists(self.cacheDir)
}
func testAggressiveClearingHandlesDelete() {
assertSuccessOnSetDataForKey("a", value0: "aa", value1: "aaa")
assertSuccessOnSetDataForKey("c", value0: "cc", value1: "ccc")
assertSuccessOnSetDataForKey("b", value0: "bb", value1: "bbb") // wait async operations to finish, or deleting cache dir may fail
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.removeItemAtPath(self.cacheDir)
} catch {
print("------------ delete failed")
XCTFail()
}
assertFileNotExists(self.cacheDir)
// all public APIs should be tested after the cache dir was removed externally.
assertNilSnapshotForKey("a")
assertNilSnapshotForKey("b")
assertNilSnapshotForKey("c")
assertNilSnapshotForKey("d")
assertSuccessOnDeleteCache()
XCTAssertTrue(self.cache.isClosed)
assertFileNotExists(self.cacheDir)
}
func testRemoveHandlesMissingFile() {
assertSuccessOnSetDataForKey("a", value0: "aa", value1: "aaa")
let cleanFile0 = getCleanFilePathForKey("a", index: 0)
assertFileExists(cleanFile0)
try! Utils.deleteFileIfExistsAtPath(cleanFile0)
assertFileNotExists(cleanFile0)
assertSuccessOnRemoveEntryForKey("a", isRemoved: true)
}
}
| 8eda18ab5222e1df8cf3e895daf866ef | 39.330579 | 149 | 0.633925 | false | false | false | false |
lyricli-app/lyricli | refs/heads/develop | Sources/lyricli/lyricli_command.swift | apache-2.0 | 1 | import Bariloche
class LyricliCommand: Command {
let usage: String? = "Fetch the lyrics for current playing track or the one specified via arguments"
// Flags
let version = Flag(short: "v", long: "version", help: "Prints the version.")
let showTitle = Flag(short: "t", long: "title", help: "Shows title of song if true")
let listSources = Flag(short: "l", long: "list", help: "Lists all sources")
// Named Arguments
let enableSource = Argument<String>(name: "source",
kind: .named(short: "e", long: "enable"),
optional: true,
help: "Enables a source")
let disableSource = Argument<String>(name: "source",
kind: .named(short: "d", long: "disable"),
optional: true,
help: "Disables a source")
let resetSource = Argument<String>(name: "source",
kind: .named(short: "r", long: "reset"),
optional: true,
help: "Resets a source")
// Positional Arguments
let artist = Argument<String>(name: "artist",
kind: .positional,
optional: true,
help: "The name of the artist")
let trackName = Argument<String>(name: "trackName",
kind: .positional,
optional: true,
help: "The name of the track")
func run() -> Bool {
return true
}
}
| 68c12eb50a59bb5831ca37212cd6b733 | 33.342105 | 104 | 0.603065 | false | false | false | false |
mountainKaku/Basic-Algorithms | refs/heads/master | BucketSort.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
print(str)
//BucketSort: 桶排序法
enum SortType {
case ascending //升序
case descending //降序
}
func bucketSortOf(_ arr: [Int], type:SortType = .ascending) -> [Int] {
guard arr.count > 1 else {
return arr
}
let maxNum = arr.max()
//桶的数目
var bucket:[Int] = Array.init(repeatElement(0, count: maxNum! + 1))
var newNum:[Int] = Array.init()
//给桶加标记
for index in arr {
let numId = index
bucket[numId] += 1
}
for index in bucket.indices {
_ = (type == .ascending) ? index : bucket.count - index
while bucket[index] > 0 {
newNum.append(index)
bucket[index] -= 1
}
}
return newNum
}
var numbersArray = [10,3,17,8,5,2,1,9,5,4]
print("桶排序方案: \(bucketSortOf(numbersArray))")
print("桶排序方案: \(bucketSortOf(numbersArray,type: .ascending))")
print("桶排序方案: \(bucketSortOf(numbersArray,type: .descending))")
| df978bc46cb062ae76f94adf9cb39042 | 21.911111 | 71 | 0.590689 | false | false | false | false |
hunterknepshield/MIPSwift | refs/heads/master | MIPSwift/main.swift | mit | 1 | //
// main.swift
// MIPSwift
//
// Created by Hunter Knepshield on 12/10/15.
// Copyright © 2015 Hunter Knepshield. All rights reserved.
//
import Foundation
print("MIPSwift v\(mipswiftVersion)")
let executableArgs = Process.arguments
var printUsageAndTerminate = false
var useDeveloperOptions = false
var defaultOptions = REPLOptions() // verbose = false, autodump = false, autoexecute = true, trace = false, printSetting = .Hex, inputSource = stdIn
var developerOptions = REPLOptions.developerOptions
// Parse command line arguments if there are any
for (index, argument) in executableArgs.enumerate() {
// print("\(index): \(argument)")
if index == 0 {
// This is the executable's name, nothing exciting to parse
continue
} else {
if ["-f", "--file", "--filename"].contains(executableArgs[index - 1]) {
// This was the file's name, just skip it
continue
}
}
switch(argument) {
case "-d", "--developer":
useDeveloperOptions = true
case "-noae", "--noautoexecute":
defaultOptions.autoexecute = false
// developerOptions.autoexecute is already false
case "-f", "--file", "--filename":
// The user is specifying a file name to read from
if index < executableArgs.count - 1 {
// There's at least 1 more argument, assume it's the file name
let filename = executableArgs[index + 1]
guard let fileHandle = NSFileHandle(forReadingAtPath: filename) else {
fatalError("Unable to open file: \(filename)")
}
defaultOptions.inputSource = fileHandle
developerOptions.inputSource = fileHandle
// Also turn off auto-execute, as labels may be used before they're defined within a file
defaultOptions.autoexecute = false
// developerOptions.autoexecute is already false
} else {
fatalError("Input file \(argument) argument specified, but no file name present.")
}
default:
print("Illegal argument: \(argument)")
printUsageAndTerminate = true
}
}
if printUsageAndTerminate {
print("Usage: \(executableArgs[0]) \(commandLineOptions)")
print("\td: start with 'developer' interpreter settings by default (auto-dump on, auto-execute off, trace on).")
print("\tnoae: start auto-execute off.")
print("\tf file: open file instead of reading instructions from standard input.")
} else {
REPL(options: useDeveloperOptions ? developerOptions : defaultOptions).run()
} | e39ef0972a9897bf1ddf0d1ec4531933 | 38 | 148 | 0.650991 | false | false | false | false |
xivol/MCS-V3-Mobile | refs/heads/master | assignments/task1/BattleShip.playground/Sources/Game/BattleField.swift | mit | 1 | import Foundation
public enum CellState {
case nonTouched
case missed
case enemyCell
}
public protocol Field{
func getCellAt(_ xPos: Int, yPos: Int) -> CellState
func markCellAtAs(_ xPos: Int, yPos: Int, state: CellState)
func isNonTouchedPosition(_ xPos: Int, yPos: Int) -> Bool
}
public class BattleField: Field {
private var field: [[CellState]]
public func getCellAt(_ xPos: Int, yPos: Int) -> CellState {
return field[xPos][yPos]
}
public func markCellAtAs(_ xPos: Int, yPos: Int, state: CellState) {
field[xPos][yPos] = state
}
public func isNonTouchedPosition(_ xPos: Int, yPos: Int) -> Bool {
return field[xPos][yPos] == CellState.nonTouched
}
public init(_ fieldSize: Int = 10) {
field = Array(repeating: (Array(repeating: CellState.nonTouched, count: fieldSize)), count: fieldSize)
}
}
| 15ba7eb9138efc87ff55d8cbda280eee | 22.324324 | 106 | 0.67555 | false | false | false | false |
kbelter/SnazzyList | refs/heads/TableViewCells | SnazzyList/Classes/src/CollectionView/Delegates/GenericCollectionViewDelegate.swift | apache-2.0 | 1 | //
// CollectionView.swift
// Noteworth2
//
// Created by Kevin on 12/20/18.
// Copyright © 2018 Noteworth. All rights reserved.
//
import UIKit
public class GenericCollectionViewDelegate: NSObject, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
weak var dataSource: GenericCollectionViewDataSource!
weak var actions: GenericCollectionActions?
public init(dataSource: GenericCollectionViewDataSource,
isSelfSizing: Bool,
insetsForSection: [Int: UIEdgeInsets]? = nil,
minimumLineSpacingForSection: [Int: CGFloat]? = nil,
minimumItemSpacingForSection: [Int: CGFloat]? = nil,
actions: GenericCollectionActions? = nil) {
self.actions = actions
self.dataSource = dataSource
self.insetsForSection = insetsForSection
self.minimumLineSpacingForSection = minimumLineSpacingForSection
self.minimumItemSpacingForSection = minimumItemSpacingForSection
super.init()
self.dataSource.collectionView.delegate = self
if let layout = self.dataSource.collectionView.collectionViewLayout as? UICollectionViewFlowLayout, isSelfSizing {
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
}
// MARK: - CollectionView Delegate Methods.
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return self.minimumLineSpacingForSection?[section] ?? (self.dataSource.collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.minimumLineSpacing ?? 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return self.minimumItemSpacingForSection?[section] ?? (self.dataSource.collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.minimumInteritemSpacing ?? 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let configFile = dataSource.configFiles.filter { $0.section == indexPath.section && $0.typeCell == .cell }[indexPath.item]
switch configFile.sizingType {
case .cell(let instance):
return instance.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath, with: configFile.item).sizeMinOfZero
case .specificSize(let size):
return size.sizeMinOfZero
case .specificHeight(let height):
return CGSize(width: collectionView.bounds.width, height: height).sizeMinOfZero
case .automatic:
return (collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize ?? CGSize(width: 50.0, height: 50.0)
case .fullRowAutomatic:
return (collectionViewLayout as? UICollectionViewFlowLayout)?.itemSize ?? CGSize(width: 50.0, height: 50.0)
default:
return .zero
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard let configFile = (dataSource.configFiles.filter { $0.section == section && $0.typeCell == .header }).first else { return .zero }
switch configFile.sizingType {
case .header(let instance):
return instance.collectionView(collectionView, layout: collectionViewLayout, referenceSizeForHeaderInSection: section, with: configFile.item).sizeMinOfZero
case .headerFooterHeight(let height):
return CGSize(width: collectionView.bounds.width, height: height)
case .headerFooterFullRowAutomatic:
// Get the view for the first header
let indexPath = IndexPath(row: 0, section: section)
let headerView = self.dataSource.collectionView(collectionView, viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionHeader, at: indexPath)
// Use this view to calculate the optimal size based on the collection view's width
return headerView.systemLayoutSizeFitting(CGSize(width: collectionView.frame.width, height: UIView.layoutFittingExpandedSize.height),
withHorizontalFittingPriority: .required, // Width is fixed
verticalFittingPriority: .fittingSizeLevel) // Height can be as large as needed
default:
return .zero
}
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
guard let configFile = (dataSource.configFiles.filter { $0.section == section && $0.typeCell == .footer }).first else { return .zero }
switch configFile.sizingType {
case .footer(let instance):
return instance.collectionView(collectionView, layout: collectionViewLayout, referenceSizeForFooterInSection: section, with: configFile.item).sizeMinOfZero
case .headerFooterHeight(let height):
return CGSize(width: collectionView.bounds.width, height: height)
case .headerFooterFullRowAutomatic:
// Get the view for the first footer
let indexPath = IndexPath(row: 0, section: section)
let headerView = self.dataSource.collectionView(collectionView, viewForSupplementaryElementOfKind: UICollectionView.elementKindSectionFooter, at: indexPath)
// Use this view to calculate the optimal size based on the collection view's width
return headerView.systemLayoutSizeFitting(CGSize(width: collectionView.frame.width, height: UIView.layoutFittingExpandedSize.height),
withHorizontalFittingPriority: .required, // Width is fixed
verticalFittingPriority: .fittingSizeLevel) // Height can be as large as needed
default:
return .zero
}
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? GenericCollectionCellProtocol else { return }
cell.collectionView?(collectionView: collectionView, didSelectItemAt: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? GenericCollectionCellProtocol else { return }
cell.collectionView?(collectionView: collectionView, didDeselectItemAt: indexPath)
}
public func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if dataSource.configFiles.count == 0 { return }
if checkIfReachLastCellInCollection(indexPath: indexPath) {
actions?.reachLastCellInCollection?()
actions?.reachLastCellInCollectionWithIndexPath?(indexPath: indexPath)
}
if checkIfReachLastSectionInCollection(indexPath: indexPath) {
actions?.reachLastSectionInCollection?()
}
actions?.willDisplayCell?(indexPath: indexPath)
guard let genericCell = cell as? GenericCollectionCellProtocol else { return }
let configFiles = dataSource.configFiles.filter { $0.section == indexPath.section && $0.typeCell == .cell }
if configFiles.count < indexPath.item + 1 { return }
let configFile = configFiles[indexPath.item]
genericCell.collectionView?(collectionView, willDisplay: cell, forItemAt: indexPath, with: configFile.item)
}
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let genericCell = cell as? GenericCollectionCellProtocol else { return }
let configFiles = dataSource.configFiles.filter { $0.section == indexPath.section && $0.typeCell == .cell }
if configFiles.count < indexPath.item + 1 { return }
let configFile = configFiles[indexPath.item]
genericCell.collectionView?(collectionView, didEndDisplaying: cell, forItemAt: indexPath, with: configFile.item)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
guard let insets = insetsForSection else {
return (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset ?? .zero
}
return insets[section] ?? (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.sectionInset ?? .zero
}
private var insetsForSection: [Int: UIEdgeInsets]?
private var minimumLineSpacingForSection: [Int: CGFloat]?
private var minimumItemSpacingForSection: [Int: CGFloat]?
}
//MARK: - Util Public Methods
extension GenericCollectionViewDelegate {
func cellOriginY(cell filter: @escaping (GenericCollectionCellConfigurator) -> Bool) -> CGFloat? {
guard let index = dataSource.getIndexPath(by: filter) else { return nil }
guard let superview = dataSource.collectionView.superview else { return nil }
guard let atts = dataSource.collectionView.layoutAttributesForItem(at: index) else { return nil }
let cellRect = atts.frame
let origin = dataSource.collectionView.convert(cellRect, to: superview).origin
return origin.y
}
func cellIsGoingOutWithProgress(offsetY additionalOffsetY: CGFloat = 0.0, cell filter: @escaping (GenericCollectionCellConfigurator) -> Bool) -> CGFloat? {
guard let index = dataSource.getIndexPath(by: filter) else { return nil }
guard let superview = dataSource.collectionView.superview else { return nil }
guard let atts = dataSource.collectionView.layoutAttributesForItem(at: index) else { return nil }
let cellRect = atts.frame
let origin = dataSource.collectionView.convert(cellRect, to: superview).origin
let offsetY = (origin.y - dataSource.collectionView.frame.origin.y - additionalOffsetY)
if offsetY > 0 { return nil }
let cellheight = cellRect.size.height
if cellheight <= 0 { return nil }
let absDis = abs(offsetY)
return (absDis/cellheight)
}
}
// MARK: - Private Inner Framework Methods
extension GenericCollectionViewDelegate {
private func checkIfReachLastCellInCollection(indexPath: IndexPath) -> Bool {
//Returning false because the user doesn't want to know if reached last cell in collection.
if actions?.reachLastCellInCollection == nil && actions?.reachLastCellInCollectionWithIndexPath == nil { return false }
let maxSection = dataSource.configFiles.map { $0.section }.sorted { $0 > $1 }.first
let numberOfRowsInLastSection = dataSource.configFiles.filter { $0.section == maxSection && $0.typeCell == .cell }.count
if maxSection != indexPath.section { return false }
if numberOfRowsInLastSection == 0 { return false }
return lastRowComparation(indexPath: indexPath, numberOfRows: numberOfRowsInLastSection)
}
private func lastRowComparation(indexPath: IndexPath, numberOfRows: Int) -> Bool {
if numberOfRows >= 3 {
return indexPath.item == numberOfRows - 3
} else if numberOfRows == 2 {
return indexPath.item == numberOfRows - 2
}
return indexPath.item == numberOfRows - 1
}
private func checkIfReachLastSectionInCollection(indexPath: IndexPath) -> Bool {
if actions?.reachLastSectionInCollection == nil { return false }
let maxSection = dataSource.configFiles.map { $0.section }.sorted { $0 > $1 }.first ?? 0
guard maxSection > 0 else { return false }
// 10 is the number of sections before ending
if maxSection == indexPath.section { return true }
if maxSection - 2 == indexPath.section {
let numberOfRowsInLastSection = dataSource.configFiles.filter { $0.section == maxSection && $0.typeCell == .cell }.count
return lastRowComparation(indexPath: indexPath, numberOfRows: numberOfRowsInLastSection)
}
return false
}
}
extension GenericCollectionViewDelegate: UIScrollViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
actions?.didScroll?(scrollView: scrollView)
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
actions?.willBeganScrolling?()
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
actions?.willEndDragging?(scrollView: scrollView, velocity: velocity, targetContentOffset: targetContentOffset)
}
/**
Assuming all pages are same size and paging is enabled.
*/
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
guard let callback = actions?.didEndScrollingAtIndex else { return }
if !scrollView.isPagingEnabled { return }
if dataSource.configFiles.count == 0 { return }
guard let flowLayout = dataSource.collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let fullSize = flowLayout.scrollDirection == .horizontal ?
dataSource.collectionView.contentSize.width :
dataSource.collectionView.contentSize.height
let size = fullSize / CGFloat(dataSource.configFiles.count)
let offset = flowLayout.scrollDirection == .horizontal ?
scrollView.contentOffset.x :
scrollView.contentOffset.y
callback(Int(round(offset/size)))
}
}
| 4e0bb47f3eb0e25d35aadc7836abb135 | 52.4 | 182 | 0.691913 | false | true | false | false |
piscoTech/Workout | refs/heads/master | Workout Core/Model/Workout/Additional Data/RunningHeartZones.swift | mit | 1 | //
// RunningHeartZones.swift
// Workout
//
// Created by Marco Boschi on 28/08/2018.
// Copyright © 2018 Marco Boschi. All rights reserved.
//
import UIKit
import HealthKit
import MBLibrary
public class RunningHeartZones: AdditionalDataProcessor, AdditionalDataProvider, PreferencesDelegate {
private weak var preferences: Preferences?
public static let defaultZones = [60, 70, 80, 94]
/// The maximum valid time between two samples.
static let maxInterval: TimeInterval = 60
private var maxHeartRate: Double?
private var zones: [Int]?
private var rawHeartData: [HKQuantitySample]?
private var zonesData: [TimeInterval]?
init(with preferences: Preferences) {
self.preferences = preferences
preferences.add(delegate: self)
runningHeartZonesConfigChanged()
}
public func runningHeartZonesConfigChanged() {
if let hr = preferences?.maxHeartRate {
self.maxHeartRate = Double(hr)
} else {
self.maxHeartRate = nil
}
self.zones = preferences?.runningHeartZones
self.updateZones()
}
// MARK: - Process Data
func wantData(for typeIdentifier: HKQuantityTypeIdentifier) -> Bool {
return typeIdentifier == .heartRate
}
func process(data: [HKQuantitySample], for _: WorkoutDataQuery) {
self.rawHeartData = data
updateZones()
}
private func zone(for s: HKQuantitySample, in zones: [Double]) -> Int? {
guard let maxHR = maxHeartRate else {
return nil
}
let p = s.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR
return zones.lastIndex { p >= $0 }
}
private func updateZones() {
guard let maxHR = maxHeartRate, let data = rawHeartData else {
zonesData = nil
return
}
let zones = (self.zones ?? RunningHeartZones.defaultZones).map({ Double($0) / 100 })
zonesData = [TimeInterval](repeating: 0, count: zones.count)
var previous: HKQuantitySample?
for s in data {
defer {
previous = s
}
guard let prev = previous else {
continue
}
let time = s.startDate.timeIntervalSince(prev.startDate)
guard time <= RunningHeartZones.maxInterval else {
continue
}
let pZone = zone(for: prev, in: zones)
let cZone = zone(for: s, in: zones)
if let c = cZone, pZone == c {
zonesData?[c] += time
} else if let p = pZone, let c = cZone, abs(p - c) == 1 {
let pH = prev.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR
let cH = s.quantity.doubleValue(for: WorkoutUnit.heartRate.default) / maxHR
/// Threshold between zones
let th = zones[max(p, c)]
guard th >= min(pH, cH), th <= max(pH, cH) else {
continue
}
/// Incline of a line joining the two data points
let m = (cH - pH) / time
/// The time after the previous data point when the zone change
let change = (th - pH) / m
zonesData?[p] += change
zonesData?[c] += time - change
}
}
}
// MARK: - Display Data
private static let header = NSLocalizedString("HEART_ZONES_TITLE", comment: "Heart zones")
private static let footer = NSLocalizedString("HEART_ZONES_FOOTER", comment: "Can be less than total")
private static let zoneTitle = NSLocalizedString("HEART_ZONES_ZONE_%lld", comment: "Zone x")
private static let zoneConfig = NSLocalizedString("HEART_ZONES_NEED_CONFIG", comment: "Zone config")
public let sectionHeader: String? = RunningHeartZones.header
public var sectionFooter: String? {
return zonesData == nil ? nil : RunningHeartZones.footer
}
public var numberOfRows: Int {
return zonesData?.count ?? 1
}
public func heightForRowAt(_ indexPath: IndexPath, in tableView: UITableView) -> CGFloat? {
if zonesData == nil {
return UITableView.automaticDimension
} else {
return nil
}
}
public func cellForRowAt(_ indexPath: IndexPath, for tableView: UITableView) -> UITableViewCell {
guard let data = zonesData?[indexPath.row] else {
let cell = tableView.dequeueReusableCell(withIdentifier: "msg", for: indexPath)
cell.textLabel?.text = RunningHeartZones.zoneConfig
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "basic", for: indexPath)
cell.textLabel?.text = String(format: RunningHeartZones.zoneTitle, indexPath.row + 1)
cell.detailTextLabel?.text = data > 0 ? data.formattedDuration : missingValueStr
return cell
}
public func export(for preferences: Preferences, withPrefix prefix: String, _ callback: @escaping ([URL]?) -> Void) {
guard prefix.range(of: "/") == nil else {
fatalError("Prefix must not contain '/'")
}
DispatchQueue.background.async {
guard let zonesData = self.zonesData else {
callback([])
return
}
let hzFile = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("\(prefix)heartZones.csv")
guard let file = OutputStream(url: hzFile, append: false) else {
callback(nil)
return
}
let sep = CSVSeparator
do {
file.open()
defer{
file.close()
}
try file.write("Zone\(sep)Time\n")
for (i, t) in zonesData.enumerated() {
try file.write("\(i + 1)\(sep)\(t.rawDuration().toCSV())\n")
}
callback([hzFile])
} catch {
callback(nil)
}
}
}
}
| 45c2b4257c8412bf266a6dc3f8f27492 | 26.244681 | 118 | 0.689574 | false | false | false | false |
banDedo/BDModules | refs/heads/master | Harness/HarnessTests/Model/UserAPIMapperTests.swift | apache-2.0 | 1 | //
// UserAPIMapperTests.swift
// Harness
//
// Created by Patrick Hogan on 3/14/15.
// Copyright (c) 2015 bandedo. All rights reserved.
//
import BDModules
import Foundation
import XCTest
class UserAPIMapperTests: XCTestCase {
// MARK:- Properties
var jsonSerializer = JSONSerializer()
var mockModelFactory = MockModelFactory()
lazy var userAPIMapper: UserAPIMapper = { return UserAPIMapper(delegate: self.mockModelFactory) }()
// MARK:- Setup
override func setUp() {
super.setUp()
jsonSerializer = JSONSerializer()
mockModelFactory = MockModelFactory()
userAPIMapper = UserAPIMapper(delegate: self.mockModelFactory)
}
// MARK:- Tests
func testParseUser() {
let dictionary = jsonSerializer.object(
resourceName: "me_stub",
bundle: NSBundle(forClass: User.self)) as! NSDictionary
let userDictionary = dictionary["data"] as! NSDictionary
let user = User(dictionary: userDictionary)
userAPIMapper.map(userDictionary, object: user)
XCTAssertEqual(user.uuid, userDictionary[kModelObjectIdApiKeyPath] as! String)
XCTAssertEqual(user.type, userDictionary[kValueObjectTypeApiKeyPath] as! String)
XCTAssertEqual(user.firstName, userDictionary[kUserFirstNameApiKeyPath] as! String)
XCTAssertEqual(user.lastName, userDictionary[kUserLastNameApiKeyPath] as! String)
XCTAssertEqual(user.email, userDictionary[kUserEmailApiKeyPath] as! String)
XCTAssertEqual(user.phoneNumber!, userDictionary[kUserPhoneNumberApiKeyPath] as! String)
XCTAssertEqual(user.coverImageURL!, userDictionary[kUserCoverImageURLApiKeyPath] as! String)
XCTAssertEqual(user.profileImageURL!, userDictionary[kUserProfileImageURLApiKeyPath] as! String)
}
}
| 243266ff13cd692a0ed81d1a9263e8f4 | 34.301887 | 104 | 0.701764 | false | true | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | Learn to Code 1.playgroundbook/Contents/Chapters/Document2.playgroundchapter/Pages/Challenge1.playgroundpage/Sources/Setup.swift | mit | 1 | //
// Setup.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
//let world = GridWorld(columns: 4, rows: 7)
let world: GridWorld = loadGridWorld(named: "2.3")
let actor = Actor()
public func playgroundPrologue() {
world.place(actor, facing: west, at: Coordinate(column: 3, row: 5))
placeItems()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world)
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeItems() {
let items = [
Coordinate(column: 0, row: 4),
Coordinate(column: 1, row: 1),
Coordinate(column: 3, row: 2),
Coordinate(column: 2, row: 5),
]
world.placeGems(at: items)
let switchLocations = [
Coordinate(column: 0, row: 3),
Coordinate(column: 1, row: 5),
Coordinate(column: 2, row: 1),
Coordinate(column: 3, row: 3),
]
world.place(nodeOfType: Switch.self, facing: west, at: switchLocations)
}
func placeFloor() {
let obstacles = world.coordinates(inColumns: 0...3, intersectingRows: [0,6])
world.removeNodes(at: obstacles)
world.placeWater(at: obstacles)
world.placeBlocks(at: world.coordinates(inColumns: [0,3], intersectingRows: 1...5))
let tiers = [
Coordinate(column: 0, row: 3),
Coordinate(column: 3, row: 3),
Coordinate(column: 1, row: 5),
Coordinate(column: 2, row: 5),
Coordinate(column: 1, row: 1),
Coordinate(column: 2, row: 1),
]
world.placeBlocks(at: tiers)
world.place(Stair(), facing: south, at: Coordinate(column: 0, row: 2))
world.place(Stair(), facing: north, at: Coordinate(column: 0, row: 4))
world.place(Stair(), facing: south, at: Coordinate(column: 3, row: 2))
world.place(Stair(), facing: north, at: Coordinate(column: 3, row: 4))
}
| 46e22c10ed793b5afafe0e654ce34fee | 30.457831 | 89 | 0.536576 | false | false | false | false |
nestlabs/connectedhomeip | refs/heads/master | examples/tv-casting-app/darwin/TvCasting/TvCasting/CommissionerDiscoveryViewModel.swift | apache-2.0 | 2 | /**
*
* Copyright (c) 2020-2022 Project CHIP Authors
*
* 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 os.log
class CommissionerDiscoveryViewModel: ObservableObject {
let Log = Logger(subsystem: "com.matter.casting",
category: "CommissionerDiscoveryViewModel")
@Published var commissioners: [DiscoveredNodeData] = []
@Published var discoveryRequestStatus: Bool?;
func discoverAndUpdate() {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
castingServerBridge.discoverCommissioners(DispatchQueue.main, discoveryRequestSentHandler: { (result: Bool) -> () in
self.discoveryRequestStatus = result
})
}
Task {
try? await Task.sleep(nanoseconds: 5_000_000_000) // Wait for commissioners to respond
updateCommissioners()
}
}
private func updateCommissioners() {
if let castingServerBridge = CastingServerBridge.getSharedInstance()
{
var i: Int32 = 0
var commissioner: DiscoveredNodeData?;
repeat {
castingServerBridge.getDiscoveredCommissioner(i, clientQueue: DispatchQueue.main, discoveredCommissionerHandler: { (result: DiscoveredNodeData?) -> () in
commissioner = result;
if(commissioner != nil){
if(self.commissioners.contains(commissioner!))
{
self.Log.info("Skipping previously discovered commissioner \(commissioner!.description)")
}
else
{
self.commissioners.append(commissioner!)
}
}
})
i += 1
} while(commissioner != nil)
}
}
}
| a4e65f273bef1a7e25299de65c68660c | 36.69697 | 169 | 0.587219 | false | false | false | false |
CGRrui/TestKitchen_1606 | refs/heads/master | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBWorksCell.swift | mit | 1 | //
// CBWorksCell.swift
// TestKitchen
//
// Created by Rui on 16/8/22.
// Copyright © 2016年 Rui. All rights reserved.
//
import UIKit
class CBWorksCell: UITableViewCell {
//显示数据
var model: CBRecommendWidgetListModel? {
didSet{
showData()
}
}
func showData(){
//i表示列的序号
for i in 0..<3 {
//i 0 1 2
//大图片
//index 0 3 6
if model?.widget_data?.count > i*3 {
let imageModel = model?.widget_data![i*3]
if imageModel?.type == "image" {
//显示,要先获取按钮
let subView = contentView.viewWithTag(100+i)
if subView?.isKindOfClass(UIButton.self) == true{
//如果是UIButton类型的话,因为cell上面的类型就是UIButton
let btn = subView as! UIButton
let url = NSURL(string: (imageModel?.content)!)
btn.kf_setImageWithURL(url!, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//用户图片
//index 1 4 7
if model?.widget_data?.count > i*3+1 {
let imageModel = model?.widget_data![i*3+1]
if imageModel?.type == "image" {
//显示,要先获取按钮
let subView = contentView.viewWithTag(200+i)
if subView?.isKindOfClass(UIButton.self) == true{
//如果是UIButton类型的话,因为cell上面的类型就是UIButton
let btn = subView as! UIButton
//设置btn的圆角
btn.layer.cornerRadius = 20
let url = NSURL(string: (imageModel?.content)!)
btn.kf_setImageWithURL(url!, forState: .Normal, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//用户名 2 5 8
if model?.widget_data?.count > i*3+2 {
let nameModel = model?.widget_data![i*3+2]
if nameModel?.type == "text" {
//获取用户名的label
let subView = contentView.viewWithTag(300+i)
if subView?.isKindOfClass(UILabel.self) == true{
//如果是UILabel类型的话,因为cell上面的类型就是UILabel
let nameLabel = subView as! UILabel
nameLabel.text = nameModel?.content
}
}
}
}
//描述文字
let subView = contentView.viewWithTag(400)
if subView?.isKindOfClass(UILabel.self) == true {
let descLabel = subView as! UILabel
descLabel.text = model?.desc
}
}
//创建cell的方法
class func createWorksCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withListModel listModel: CBRecommendWidgetListModel) -> CBWorksCell {
let cellId = "worksCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBWorksCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("CBWorksCell", owner: nil, options: nil).last as? CBWorksCell
}
cell?.model = listModel
return cell!
}
@IBAction func clickBtn(sender: UIButton) {
}
@IBAction func clickUserBtn(sender: UIButton) {
}
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
}
}
| 047e86ceba8a71718a4f3f60a4d18bc4 | 32.308943 | 184 | 0.488406 | false | false | false | false |
Subsets and Splits