repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
automationWisdri/WISData.JunZheng | WISData.JunZheng/View/DataSearch/DataSearchContentView.swift | 1 | 9998 | //
// DataSearchContentView.swift
// WISData.JunZheng
//
// Created by Jingwei Wu on 6/1/16.
// Copyright © 2016 Wisdri. All rights reserved.
//
import UIKit
class DataSearchContentView: UIView {
let ShiftPickerContentViewID = "ShiftPickerContentView"
let DataSearchButtonViewID = "DataSearchButtonView"
let DatePickerViewID = "DatePickerView"
var dataSearchWrapperView: UIScrollView!
var shiftPickerContentView: ShiftPickerContentView!
var datePickerView: DatePickerView!
var dataSearchButtonView: UIView!
weak var parentViewController: UIViewController?
var delegate: DataSearchContentViewDelegate?
var currentShiftSelection: ShiftType!
init(frame: CGRect, parentViewController: UIViewController!) {
super.init(frame: CGRectZero)
self.parentViewController = currentDevice.isPad ? nil : parentViewController
self.prepareView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func prepareView() {
// Constants for initializing
let dataSearchButtonViewHeight: CGFloat = 50
let mainScreenBound = UIScreen.mainScreen().applicationFrame
let navigationBarHeight = self.parentViewController?.navigationController?.navigationBar.bounds.height ?? NAVIGATION_BAR_HEIGHT
// let tabBarHeight = self.parentViewController.tabBarController?.tabBar.frame.size.height
let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.height
let filterContentViewMaxHeight = mainScreenBound.height - (statusBarHeight + navigationBarHeight) - dataSearchButtonViewHeight
let itemGapHeight: CGFloat = 2
let refFrame = currentDevice.isPad ? CGRectMake(0.0, 0.0, 360.0, filterContentViewMaxHeight)
: CGRectMake(0.0,
statusBarHeight + navigationBarHeight,
mainScreenBound.width,
filterContentViewMaxHeight)
let shiftPickerContentViewHeight: CGFloat = 155
let datePickerViewHeight: CGFloat = 180
//
// initial contents - in wrapper view
//
// When the device is not iPad and is in landscape orientation, the devicePortrait is false
var devicePortrait = true
if currentDevice.isPad == false && self.parentViewController!.traitCollection.verticalSizeClass == .Compact {
devicePortrait = false
} else {
devicePortrait = true
}
// ** Shift selection
if self.shiftPickerContentView == nil {
self.shiftPickerContentView = NSBundle.mainBundle().loadNibNamed(self.ShiftPickerContentViewID, owner: self, options: nil)!.last as! ShiftPickerContentView
}
if devicePortrait {
self.shiftPickerContentView!.frame = CGRectMake(0.0, 0.0, refFrame.size.width, self.shiftPickerContentView!.viewHeight)
} else {
self.shiftPickerContentView!.frame = CGRectMake(0.0, 0.0, refFrame.size.width / 2, shiftPickerContentViewHeight)
}
self.shiftPickerContentView.bindData(ShiftType.getShiftType(Int(SearchParameter["shiftNo"]!)!))
// add date picker
self.datePickerView = NSBundle.mainBundle().loadNibNamed(self.DatePickerViewID, owner: self, options: nil)!.last as! DatePickerView
// set default date and upper limit
let searchDateString = SearchParameter["date"]!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"
let searchDate = dateFormatter.dateFromString(searchDateString)!
let maximumDate = NSDate.today
self.datePickerView.searchDatePicker.date = searchDate
self.datePickerView.searchDatePicker.maximumDate = maximumDate
if devicePortrait {
self.datePickerView.frame = CGRectMake(refFrame.origin.x, shiftPickerContentView!.viewHeight - 1, refFrame.size.width, datePickerViewHeight)
} else {
self.datePickerView.frame = CGRectMake(refFrame.size.width / 2, 0, refFrame.size.width / 2, shiftPickerContentViewHeight)
}
// ** content wrapper
var contentHeight, wrapperHeight: CGFloat?
if devicePortrait {
contentHeight = currentDevice.isPad ? (self.shiftPickerContentView.bounds.size.height + self.datePickerView.bounds.size.height)
: (self.shiftPickerContentView.frame.origin.x + self.shiftPickerContentView.bounds.size.height + self.datePickerView.bounds.size.height)
wrapperHeight = currentDevice.isPad ? contentHeight! : min(contentHeight!, filterContentViewMaxHeight)
} else {
contentHeight = shiftPickerContentViewHeight
wrapperHeight = contentHeight
}
if self.dataSearchWrapperView == nil {
self.dataSearchWrapperView = UIScrollView.init(frame: CGRectZero)
}
self.dataSearchWrapperView.frame = CGRectMake(refFrame.origin.x, refFrame.origin.y, refFrame.size.width, wrapperHeight!)
self.dataSearchWrapperView.scrollEnabled = true
self.dataSearchWrapperView.bounces = true
self.dataSearchWrapperView.indicatorStyle = .Default
self.dataSearchWrapperView.showsVerticalScrollIndicator = true
self.dataSearchWrapperView.backgroundColor = UIColor.whiteColor()
self.dataSearchWrapperView.contentSize = CGSize(width: refFrame.width, height: contentHeight! + 2)
//
// initial button view
//
if self.dataSearchButtonView == nil {
self.dataSearchButtonView = UIView(frame: CGRectZero)
}
let contentWrapperFrame = self.dataSearchWrapperView.frame
let buttonViewX = contentWrapperFrame.origin.x
let buttonViewY = contentWrapperFrame.origin.y + contentWrapperFrame.size.height + itemGapHeight
self.dataSearchButtonView.frame = CGRectMake(buttonViewX, buttonViewY, contentWrapperFrame.size.width, dataSearchButtonViewHeight)
let okButton = UIButton(type: .System)
okButton.frame = CGRectMake(self.dataSearchButtonView!.frame.size.width / 2, 0.0, self.dataSearchButtonView!.frame.size.width / 2, dataSearchButtonViewHeight)
okButton.backgroundColor = UIColor.wisLogoColor().colorWithAlphaComponent(0.8)
okButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
okButton.setTitle(NSLocalizedString("OK", comment: ""), forState: .Normal)
okButton.titleLabel?.font = UIFont.systemFontOfSize(17)
// okButton.autoresizingMask = .FlexibleWidth
okButton.tag = ButtonType.OK.rawValue
okButton.addTarget(self, action: #selector(self.buttonPressed(_:)), forControlEvents: .TouchUpInside)
let cancelButton = UIButton(type: .System)
cancelButton.frame = CGRectMake(0.0, 0.0, self.dataSearchButtonView!.frame.size.width / 2, dataSearchButtonViewHeight)
cancelButton.backgroundColor = UIColor.whiteColor()
cancelButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
cancelButton.setTitle(NSLocalizedString("Cancel", comment: ""), forState: .Normal)
// cancelButton.titleLabel?.adjustsFontSizeToFitWidth = false
cancelButton.titleLabel?.font = UIFont.systemFontOfSize(17)
// cancelButton.autoresizingMask = .FlexibleWidth
cancelButton.tag = ButtonType.Cancel.rawValue
cancelButton.addTarget(self, action: #selector(self.buttonPressed(_:)), forControlEvents: .TouchUpInside)
//
// initial content view
//
let additionHeight = currentDevice.isPad ? CGFloat(0.0) : (statusBarHeight + navigationBarHeight)
self.frame = CGRectMake(0.0, 0.0, refFrame.size.width, (self.dataSearchWrapperView?.frame.size.height)! + itemGapHeight + dataSearchButtonViewHeight + additionHeight)
self.backgroundColor = UIColor.whiteColor()
// add views
if self.dataSearchWrapperView?.subviews.count > 0 {
self.dataSearchWrapperView?.removeAllSubviews()
}
if self.dataSearchButtonView?.subviews.count > 0 {
self.dataSearchButtonView?.removeAllSubviews()
}
if self.subviews.count > 0 {
self.removeAllSubviews()
}
self.addSubview(self.dataSearchWrapperView!)
self.addSubview(self.dataSearchButtonView!)
self.dataSearchWrapperView!.addSubview(self.shiftPickerContentView!)
self.dataSearchWrapperView!.addSubview(self.datePickerView!)
self.dataSearchButtonView?.addSubview(okButton)
self.dataSearchButtonView?.addSubview(cancelButton)
self.layoutIfNeeded()
}
func buttonPressed(sender: UIButton) {
guard self.delegate != nil else {
return
}
let buttonType: ButtonType = ButtonType(rawValue: (sender as UIButton).tag)!
switch buttonType {
case .OK:
SearchParameter["date"] = dateFormatterForSearch(self.datePickerView.searchDatePicker.date)
SearchParameter["shiftNo"] = ShiftType(rawValue: shiftPickerContentView.currentSelectedIndexPath.row)!.getShiftNoForSearch
// print(SearchParameter)
let notification = NSNotification(name: DataSearchNotification, object: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
self.delegate?.contentViewConfirmed()
case .Cancel:
self.delegate?.contentViewCancelled()
}
}
enum ButtonType: Int {
case OK = 0
case Cancel = 1
}
}
protocol DataSearchContentViewDelegate {
func contentViewConfirmed() -> Void
func contentViewCancelled() -> Void
}
| mit | e58fe860b5a2db129bebb0702ec4e971 | 44.235294 | 174 | 0.676603 | 5.185166 | false | false | false | false |
firebase/firebase-ios-sdk | ReleaseTooling/Sources/ZipBuilder/ZipBuilder.swift | 1 | 39617 | /*
* Copyright 2019 Google
*
* 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 FirebaseManifest
/// Misc. constants used in the build tool.
struct Constants {
/// Constants related to the Xcode project template.
struct ProjectPath {
// Required for building.
static let infoPlist = "Info.plist"
static let projectFile = "FrameworkMaker.xcodeproj"
/// All required files for building the Zip file.
static let requiredFilesForBuilding: [String] = [projectFile, infoPlist]
// Required for distribution.
static let readmeName = "README.md"
// Required from the Firebase pod.
static let firebaseHeader = "Firebase.h"
static let modulemap = "module.modulemap"
/// The dummy Firebase library for Carthage distribution.
static let dummyFirebaseLib = "dummy_Firebase_lib"
// Make the struct un-initializable.
@available(*, unavailable)
init() { fatalError() }
}
/// The text added to the README for a product if it contains Resources. The empty line at the end
/// is intentional.
static let resourcesRequiredText = """
You'll also need to add the resources in the Resources
directory into your target's main bundle.
"""
// Make the struct un-initializable.
@available(*, unavailable)
init() { fatalError() }
}
/// A zip file builder. The zip file can be built with the `buildAndAssembleReleaseDir()` function.
struct ZipBuilder {
/// Artifacts from building and assembling the release directory.
struct ReleaseArtifacts {
/// The Firebase version.
let firebaseVersion: String
/// The directory that contains the properly assembled release artifacts.
let zipDir: URL
/// The directory that contains the properly assembled release artifacts for Carthage if building it.
let carthageDir: URL?
}
/// Relevant paths in the filesystem to build the release directory.
struct FilesystemPaths {
// MARK: - Required Paths
/// The root of the `firebase-ios-sdk` git repo.
let repoDir: URL
/// The path to the directory containing the blank xcodeproj and Info.plist for building source
/// based frameworks. Generated based on the `repoDir`.
var templateDir: URL {
return type(of: self).templateDir(fromRepoDir: repoDir)
}
// MARK: - Optional Paths
/// The root directory for build artifacts. If `nil`, a temporary directory will be used.
let buildRoot: URL?
/// The output directory for any artifacts generated during the build. If `nil`, a temporary
/// directory will be used.
let outputDir: URL?
/// The path to where local podspecs are stored.
let localPodspecPath: URL?
/// The path to a directory to move all build logs to. If `nil`, a temporary directory will be
/// used.
var logsOutputDir: URL?
/// Creates the struct containing all properties needed for a build.
/// - Parameter repoDir: The root of the `firebase-ios-sdk` git repo.
/// - Parameter buildRoot: The root directory for build artifacts. If `nil`, a temporary
/// directory will be used.
/// - Parameter outputDir: The output directory for any artifacts generated. If `nil`, a
/// temporary directory will be used.
/// - Parameter localPodspecPath: A path to where local podspecs are stored.
/// - Parameter logsOutputDir: The output directory for any logs. If `nil`, a temporary
/// directory will be used.
init(repoDir: URL,
buildRoot: URL?,
outputDir: URL?,
localPodspecPath: URL?,
logsOutputDir: URL?) {
self.repoDir = repoDir
self.buildRoot = buildRoot
self.outputDir = outputDir
self.localPodspecPath = localPodspecPath
self.logsOutputDir = logsOutputDir
}
/// Returns the expected template directory given the repo directory provided.
static func templateDir(fromRepoDir repoDir: URL) -> URL {
return repoDir.appendingPathComponents(["ReleaseTooling", "Template"])
}
}
/// Paths needed throughout the process of packaging the Zip file.
public let paths: FilesystemPaths
/// The platforms to target for the builds.
public let platforms: [Platform]
/// Specifies if the builder is building dynamic frameworks instead of static frameworks.
private let dynamicFrameworks: Bool
/// Custom CocoaPods spec repos to be used. If not provided, the tool will only use the CocoaPods
/// master repo.
private let customSpecRepos: [URL]?
/// Creates a ZipBuilder struct to build and assemble zip files and Carthage builds.
///
/// - Parameters:
/// - paths: Paths that are needed throughout the process of packaging the Zip file.
/// - platforms: The platforms to target for the builds.
/// - dynamicFrameworks: Specifies if dynamic frameworks should be built, otherwise static
/// frameworks are built.
/// - customSpecRepo: A custom spec repo to be used for fetching CocoaPods from.
init(paths: FilesystemPaths,
platforms: [Platform],
dynamicFrameworks: Bool,
customSpecRepos: [URL]? = nil) {
self.paths = paths
self.platforms = platforms
self.customSpecRepos = customSpecRepos
self.dynamicFrameworks = dynamicFrameworks
}
/// Builds and assembles the contents for the zip build.
///
/// - Parameter podsToInstall: All pods to install.
/// - Parameter includeCarthage: Build Carthage distribution as well.
/// - Parameter includeDependencies: Include dependencies of requested pod in distribution.
/// - Returns: Arrays of pod install info and the frameworks installed.
func buildAndAssembleZip(podsToInstall: [CocoaPodUtils.VersionedPod],
includeCarthage: Bool,
includeDependencies: Bool) ->
([String: CocoaPodUtils.PodInfo], [String: [URL]], URL?) {
// Remove CocoaPods cache so the build gets updates after a version is rebuilt during the
// release process. Always do this, since it can be the source of subtle failures on rebuilds.
CocoaPodUtils.cleanPodCache()
// We need to install all the pods in order to get every single framework that we'll need
// for the zip file. We can't install each one individually since some pods depend on different
// subspecs from the same pod (ex: GoogleUtilities, GoogleToolboxForMac, etc). All of the code
// wouldn't be included so we need to install all of the subspecs to catch the superset of all
// required frameworks, then use that as the source of frameworks to pull from when including
// the folders in each product directory.
let linkage: CocoaPodUtils.LinkageType = dynamicFrameworks ? .dynamic : .standardStatic
var groupedFrameworks: [String: [URL]] = [:]
var carthageGoogleUtilitiesFrameworks: [URL] = []
var podsBuilt: [String: CocoaPodUtils.PodInfo] = [:]
var xcframeworks: [String: [URL]] = [:]
var resources: [String: URL] = [:]
for platform in platforms {
let projectDir = FileManager.default.temporaryDirectory(withName: "project-" + platform.name)
CocoaPodUtils.podInstallPrepare(inProjectDir: projectDir, templateDir: paths.templateDir)
let platformPods = podsToInstall.filter { $0.platforms.contains(platform.name) }
CocoaPodUtils.installPods(platformPods,
inDir: projectDir,
platform: platform,
customSpecRepos: customSpecRepos,
localPodspecPath: paths.localPodspecPath,
linkage: linkage)
// Find out what pods were installed with the above commands.
let installedPods = CocoaPodUtils.installedPodsInfo(inProjectDir: projectDir,
localPodspecPath: paths.localPodspecPath)
// If module maps are needed for static frameworks, build them here to be available to copy
// into the generated frameworks.
if !dynamicFrameworks {
ModuleMapBuilder(customSpecRepos: customSpecRepos,
selectedPods: installedPods,
platform: platform,
paths: paths).build()
}
let podsToBuild = includeDependencies ? installedPods : installedPods.filter {
platformPods.map { $0.name.components(separatedBy: "/").first }.contains($0.key)
}
// Build in a sorted order to make the build deterministic and to avoid exposing random
// build order bugs.
// Also AppCheck must be built after other pods so that its restricted architecture
// selection does not restrict any of its dependencies.
var sortedPods = podsToBuild.keys.sorted()
sortedPods.removeAll(where: { value in
value == "FirebaseAppCheck"
})
sortedPods.append("FirebaseAppCheck")
for podName in sortedPods {
guard let podInfo = podsToBuild[podName] else {
continue
}
if podName == "Firebase" {
// Don't build the Firebase pod.
} else if podInfo.isSourcePod {
let builder = FrameworkBuilder(projectDir: projectDir,
targetPlatforms: platform.platformTargets,
dynamicFrameworks: dynamicFrameworks)
let (frameworks, resourceContents) =
builder.compileFrameworkAndResources(withName: podName,
logsOutputDir: paths.logsOutputDir,
setCarthage: false,
podInfo: podInfo)
groupedFrameworks[podName] = (groupedFrameworks[podName] ?? []) + frameworks
if includeCarthage, podName == "GoogleUtilities" {
let (cdFrameworks, _) = builder.compileFrameworkAndResources(withName: podName,
logsOutputDir: paths
.logsOutputDir,
setCarthage: true,
podInfo: podInfo)
carthageGoogleUtilitiesFrameworks += cdFrameworks
}
if resourceContents != nil {
resources[podName] = resourceContents
}
} else if podsBuilt[podName] == nil {
// Binary pods need to be collected once, since the platforms should already be merged.
let binaryFrameworks = collectBinaryFrameworks(fromPod: podName, podInfo: podInfo)
xcframeworks[podName] = binaryFrameworks
}
// Union all pods built across platforms.
// Be conservative and favor iOS if it exists - and workaround
// bug where Firebase.h doesn't get installed for tvOS and macOS.
// Fixed in #7284.
if podsBuilt[podName] == nil {
podsBuilt[podName] = podInfo
}
}
}
// Now consolidate the built frameworks for all platforms into a single xcframework.
let xcframeworksDir = FileManager.default.temporaryDirectory(withName: "xcframeworks")
do {
try FileManager.default.createDirectory(at: xcframeworksDir,
withIntermediateDirectories: false)
} catch {
fatalError("Could not create XCFrameworks directory: \(error)")
}
for groupedFramework in groupedFrameworks {
let name = groupedFramework.key
let xcframework = FrameworkBuilder.makeXCFramework(withName: name,
frameworks: groupedFramework.value,
xcframeworksDir: xcframeworksDir,
resourceContents: resources[name])
xcframeworks[name] = [xcframework]
}
for (framework, paths) in xcframeworks {
print("Frameworks for pod: \(framework) were compiled at \(paths)")
}
guard includeCarthage else {
// No Carthage build necessary, return now.
return (podsBuilt, xcframeworks, nil)
}
let xcframeworksCarthageDir = FileManager.default.temporaryDirectory(withName: "xcf-carthage")
do {
try FileManager.default.createDirectory(at: xcframeworksCarthageDir,
withIntermediateDirectories: false)
} catch {
fatalError("Could not create XCFrameworks Carthage directory: \(error)")
}
let carthageGoogleUtilitiesXcframework = FrameworkBuilder.makeXCFramework(
withName: "GoogleUtilities",
frameworks: carthageGoogleUtilitiesFrameworks,
xcframeworksDir: xcframeworksCarthageDir,
resourceContents: nil
)
return (podsBuilt, xcframeworks, carthageGoogleUtilitiesXcframework)
}
/// Try to build and package the contents of the Zip file. This will throw an error as soon as it
/// encounters an error, or will quit due to a fatal error with the appropriate log.
///
/// - Parameter templateDir: The template project for pod install.
/// - Throws: One of many errors that could have happened during the build phase.
func buildAndAssembleFirebaseRelease(templateDir: URL) throws -> ReleaseArtifacts {
let manifest = FirebaseManifest.shared
var podsToInstall = manifest.pods.map {
CocoaPodUtils.VersionedPod(name: $0.name,
version: manifest.versionString($0),
platforms: $0.platforms)
}
guard !podsToInstall.isEmpty else {
fatalError("Failed to find versions for Firebase release")
}
// We don't release Google-Mobile-Ads-SDK and GoogleSignIn, but we include their latest
// version for convenience in the Zip and Carthage builds.
podsToInstall.append(CocoaPodUtils.VersionedPod(name: "Google-Mobile-Ads-SDK",
version: nil,
platforms: ["ios"]))
podsToInstall.append(CocoaPodUtils.VersionedPod(name: "GoogleSignIn",
version: nil,
platforms: ["ios"]))
print("Final expected versions for the Zip file: \(podsToInstall)")
let (installedPods, frameworks, carthageGoogleUtilitiesXcframeworkFirebase) =
buildAndAssembleZip(podsToInstall: podsToInstall,
includeCarthage: true,
// Always include dependencies for Firebase zips.
includeDependencies: true)
// We need the Firebase pod to get the version for Carthage and to copy the `Firebase.h` and
// `module.modulemap` file from it.
guard let firebasePod = installedPods["Firebase"] else {
fatalError("Could not get the Firebase pod from list of installed pods. All pods " +
"installed: \(installedPods)")
}
guard let carthageGoogleUtilitiesXcframework = carthageGoogleUtilitiesXcframeworkFirebase else {
fatalError("GoogleUtilitiesXcframework is missing")
}
let zipDir = try assembleDistributions(withPackageKind: "Firebase",
podsToInstall: podsToInstall,
installedPods: installedPods,
frameworksToAssemble: frameworks,
firebasePod: firebasePod)
// Replace Core Diagnostics
var carthageFrameworks = frameworks
carthageFrameworks["GoogleUtilities"] = [carthageGoogleUtilitiesXcframework]
let carthageDir = try assembleDistributions(withPackageKind: "CarthageFirebase",
podsToInstall: podsToInstall,
installedPods: installedPods,
frameworksToAssemble: carthageFrameworks,
firebasePod: firebasePod)
return ReleaseArtifacts(firebaseVersion: firebasePod.version,
zipDir: zipDir, carthageDir: carthageDir)
}
// MARK: - Private
/// Assemble the folder structure of the Zip file. In order to get the frameworks
/// required, we will `pod install` only those subspecs and then fetch the information for all
/// the frameworks that were installed, copying the frameworks from our list of compiled
/// frameworks. The whole process is:
/// 1. Copy any required files (headers, modulemap, etc) over beforehand to fail fast if anything
/// is misconfigured.
/// 2. Get the frameworks required for Analytics, copy them to the Analytics folder.
/// 3. Go through the rest of the subspecs (excluding those included in Analytics) and copy them
/// to a folder with the name of the subspec.
/// 4. Assemble the `README` file based off the template and copy it to the directory.
/// 5. Return the URL of the folder containing the contents of the Zip file.
///
/// - Returns: Return the URL of the folder containing the contents of the Zip or Carthage distribution.
/// - Throws: One of many errors that could have happened during the build phase.
private func assembleDistributions(withPackageKind packageKind: String,
podsToInstall: [CocoaPodUtils.VersionedPod],
installedPods: [String: CocoaPodUtils.PodInfo],
frameworksToAssemble: [String: [URL]],
firebasePod: CocoaPodUtils.PodInfo) throws -> URL {
// Create the directory that will hold all the contents of the Zip file.
let fileManager = FileManager.default
let zipDir = fileManager.temporaryDirectory(withName: packageKind)
do {
if fileManager.directoryExists(at: zipDir) {
try fileManager.removeItem(at: zipDir)
}
try fileManager.createDirectory(at: zipDir,
withIntermediateDirectories: true,
attributes: nil)
}
// Copy all required files from the Firebase pod. This will cause a fatalError if anything
// fails.
copyFirebasePodFiles(fromDir: firebasePod.installedLocation, to: zipDir)
// Start with installing Analytics, since we'll need to exclude those frameworks from the rest
// of the folders.
let analyticsFrameworks: [String]
let analyticsDir: URL
do {
// This returns the Analytics directory and a list of framework names that Analytics requires.
/// Example: ["FirebaseInstallations, "GoogleAppMeasurement", "nanopb", <...>]
let (dir, frameworks) = try installAndCopyFrameworks(forPod: "FirebaseAnalyticsSwift",
inFolder: "FirebaseAnalytics",
withInstalledPods: installedPods,
rootZipDir: zipDir,
builtFrameworks: frameworksToAssemble)
analyticsFrameworks = frameworks
analyticsDir = dir
} catch {
fatalError("Could not copy frameworks from Analytics into the zip file: \(error)")
}
// Start the README dependencies string with the frameworks built in Analytics.
var readmeDeps = dependencyString(for: "FirebaseAnalyticsSwift",
in: analyticsDir,
frameworks: analyticsFrameworks)
// Loop through all the other subspecs that aren't Core and Analytics and write them to their
// final destination, including resources.
let analyticsPods = analyticsFrameworks.map {
$0.replacingOccurrences(of: ".framework", with: "")
}
let manifest = FirebaseManifest.shared
let firebaseZipPods = manifest.pods.filter { $0.zip }.map { $0.name }
// Skip Analytics and the pods bundled with it.
let remainingPods = installedPods.filter {
$0.key == "Google-Mobile-Ads-SDK" ||
$0.key == "GoogleSignIn" ||
(firebaseZipPods.contains($0.key) &&
$0.key != "FirebaseAnalyticsSwift" &&
$0.key != "Firebase" &&
podsToInstall.map { $0.name }.contains($0.key))
}.sorted { $0.key < $1.key }
for pod in remainingPods {
let folder = pod.key == "GoogleSignInSwiftSupport" ? "GoogleSignIn" :
pod.key.replacingOccurrences(of: "Swift", with: "")
do {
if frameworksToAssemble[pod.key] == nil {
// Continue if the pod wasn't built.
continue
}
let (productDir, podFrameworks) =
try installAndCopyFrameworks(forPod: pod.key,
inFolder: folder,
withInstalledPods: installedPods,
rootZipDir: zipDir,
builtFrameworks: frameworksToAssemble,
frameworksToIgnore: analyticsPods)
// Update the README.
readmeDeps += dependencyString(for: folder, in: productDir, frameworks: podFrameworks)
} catch {
fatalError("Could not copy frameworks from \(pod) into the zip file: \(error)")
}
do {
// Update Resources: For the zip distribution, they get pulled from the xcframework to the
// top-level product directory. For the Carthage distribution, they propagate to each
// individual framework.
// TODO: Investigate changing the zip distro to also have Resources in the .frameworks to
// enable different platform Resources.
let productPath = zipDir.appendingPathComponent(folder)
let contents = try fileManager.contentsOfDirectory(atPath: productPath.path)
for fileOrFolder in contents {
let xcPath = productPath.appendingPathComponent(fileOrFolder)
let xcResourceDir = xcPath.appendingPathComponent("Resources")
// Ignore anything that not an xcframework with Resources
guard fileManager.isDirectory(at: xcPath),
xcPath.lastPathComponent.hasSuffix("xcframework"),
fileManager.directoryExists(at: xcResourceDir) else { continue }
if packageKind == "Firebase" {
// Move all the bundles in the frameworks out to a common "Resources" directory to
// match the existing Zip structure.
let resourcesDir = productPath.appendingPathComponent("Resources")
try fileManager.moveItem(at: xcResourceDir, to: resourcesDir)
} else {
let xcContents = try fileManager.contentsOfDirectory(atPath: xcPath.path)
for fileOrFolder in xcContents {
let platformPath = xcPath.appendingPathComponent(fileOrFolder)
guard fileManager.isDirectory(at: platformPath) else { continue }
let platformContents = try fileManager.contentsOfDirectory(atPath: platformPath.path)
for fileOrFolder in platformContents {
let frameworkPath = platformPath.appendingPathComponent(fileOrFolder)
// Ignore anything that not a framework.
guard fileManager.isDirectory(at: frameworkPath),
frameworkPath.lastPathComponent.hasSuffix("framework") else { continue }
let resourcesDir = frameworkPath.appendingPathComponent("Resources")
try fileManager.copyItem(at: xcResourceDir, to: resourcesDir)
}
}
try fileManager.removeItem(at: xcResourceDir)
}
}
} catch {
fatalError("Could not setup Resources for \(pod) for \(packageKind) \(error)")
}
// Special case for Crashlytics:
// Copy additional tools to avoid users from downloading another artifact to upload symbols.
let crashlyticsPodName = "FirebaseCrashlytics"
if pod.key == crashlyticsPodName {
for file in ["upload-symbols", "run"] {
let source = pod.value.installedLocation.appendingPathComponent(file)
let target = zipDir.appendingPathComponent(crashlyticsPodName)
.appendingPathComponent(file)
do {
try fileManager.copyItem(at: source, to: target)
} catch {
fatalError("Error copying Crashlytics tools from \(source) to \(target): \(error)")
}
}
}
}
// Assemble the README. Start with the version text, then use the template to inject the
// versions and the list of frameworks to include for each pod.
let readmePath = paths.templateDir.appendingPathComponent(Constants.ProjectPath.readmeName)
let readmeTemplate: String
do {
readmeTemplate = try String(contentsOf: readmePath)
} catch {
fatalError("Could not get contents of the README template: \(error)")
}
let versionsText = versionsString(for: installedPods)
let readmeText = readmeTemplate.replacingOccurrences(of: "__INTEGRATION__", with: readmeDeps)
.replacingOccurrences(of: "__VERSIONS__", with: versionsText)
do {
try readmeText.write(to: zipDir.appendingPathComponent(Constants.ProjectPath.readmeName),
atomically: true,
encoding: .utf8)
} catch {
fatalError("Could not write README to Zip directory: \(error)")
}
print("Contents of the packaged release were assembled at: \(zipDir)")
return zipDir
}
/// Copies all frameworks from the `InstalledPod` (pulling from the `frameworkLocations`) and copy
/// them to the destination directory.
///
/// - Parameters:
/// - installedPods: Names of all the pods installed, which will be used as a
/// list to find out what frameworks to copy to the destination.
/// - dir: Destination directory for all the frameworks.
/// - frameworkLocations: A dictionary containing the pod name as the key and a location to
/// the compiled frameworks.
/// - ignoreFrameworks: A list of Pod
/// - Returns: The filenames of the frameworks that were copied.
/// - Throws: Various FileManager errors in case the copying fails, or an error if the framework
/// doesn't exist in `frameworkLocations`.
@discardableResult
func copyFrameworks(fromPods installedPods: [String],
toDirectory dir: URL,
frameworkLocations: [String: [URL]],
frameworksToIgnore: [String] = []) throws -> [String] {
let fileManager = FileManager.default
if !fileManager.directoryExists(at: dir) {
try fileManager.createDirectory(at: dir, withIntermediateDirectories: false, attributes: nil)
}
// Keep track of the names of the frameworks copied over.
var copiedFrameworkNames: [String] = []
// Loop through each installedPod item and get the name so we can fetch the framework and copy
// it to the destination directory.
for podName in installedPods {
// Skip the Firebase pod and specifically ignored frameworks.
guard podName != "Firebase" else {
continue
}
guard let xcframeworks = frameworkLocations[podName] else {
let reason = "Unable to find frameworks for \(podName) in cache of frameworks built to " +
"include in the Zip file for that framework's folder."
let error = NSError(domain: "com.firebase.zipbuilder",
code: 1,
userInfo: [NSLocalizedDescriptionKey: reason])
throw error
}
// Copy each of the frameworks over, unless it's explicitly ignored.
for xcframework in xcframeworks {
let xcframeworkName = xcframework.lastPathComponent
let name = (xcframeworkName as NSString).deletingPathExtension
if frameworksToIgnore.contains(name) {
continue
}
let destination = dir.appendingPathComponent(xcframeworkName)
try fileManager.copyItem(at: xcframework, to: destination)
copiedFrameworkNames
.append(xcframeworkName.replacingOccurrences(of: ".xcframework", with: ""))
}
}
return copiedFrameworkNames
}
/// Copies required files from the Firebase pod (`Firebase.h`, `module.modulemap`, and `NOTICES`) into
/// the given `zipDir`. Will cause a fatalError if anything fails since the zip file can't exist
/// without these files.
private func copyFirebasePodFiles(fromDir firebasePodDir: URL, to zipDir: URL) {
let firebasePodFiles = ["NOTICES", "Sources/" + Constants.ProjectPath.firebaseHeader,
"Sources/" + Constants.ProjectPath.modulemap]
let firebaseFiles = firebasePodDir.appendingPathComponent("CoreOnly")
let firebaseFilesToCopy = firebasePodFiles.map {
firebaseFiles.appendingPathComponent($0)
}
// Copy each Firebase file.
for file in firebaseFilesToCopy {
// Each file should be copied to the destination project directory with the same name.
let destination = zipDir.appendingPathComponent(file.lastPathComponent)
do {
if !FileManager.default.fileExists(atPath: destination.path) {
print("Copying final distribution file \(file) to \(destination)...")
try FileManager.default.copyItem(at: file, to: destination)
}
} catch {
fatalError("Could not copy final distribution files to temporary directory before " +
"building. Failed while attempting to copy \(file) to \(destination). \(error)")
}
}
}
/// Creates the String required for this pod to be added to the README. Creates a header and
/// lists each framework in alphabetical order with the appropriate indentation, as well as a
/// message about resources if they exist.
///
/// - Parameters:
/// - subspec: The subspec that requires documentation.
/// - frameworks: All the frameworks required by the subspec.
/// - includesResources: A flag to include or exclude the text for adding Resources.
/// - Returns: A string with a header for the subspec name, and a list of frameworks required to
/// integrate for the product to work. Formatted and ready for insertion into the
/// README.
private func dependencyString(for podName: String, in dir: URL, frameworks: [String]) -> String {
var result = readmeHeader(podName: podName)
for framework in frameworks.sorted() {
// The .xcframework suffix has been stripped. The .framework suffix has not been.
if framework.hasSuffix(".framework") {
result += "- \(framework)\n"
} else {
result += "- \(framework).xcframework\n"
}
}
result += "\n" // Necessary for Resource message to print properly in markdown.
// Check if there is a Resources directory, and if so, add the disclaimer to the dependency
// string.
do {
let fileManager = FileManager.default
let resourceDirs = try fileManager.recursivelySearch(for: .directories(name: "Resources"),
in: dir)
if !resourceDirs.isEmpty {
result += Constants.resourcesRequiredText
result += "\n" // Separate from next pod in listing for text version.
}
} catch {
fatalError("""
Tried to find Resources directory for \(podName) in order to build the README, but an error
occurred: \(error).
""")
}
return result
}
/// Describes the dependency on other frameworks for the README file.
func readmeHeader(podName: String) -> String {
var header = "## \(podName)"
if !(podName == "FirebaseAnalytics" || podName == "GoogleSignIn") {
header += " (~> FirebaseAnalytics)"
}
header += "\n"
return header
}
/// Installs a subspec and attempts to copy all the frameworks required for it from
/// `buildFramework` and puts them into a new directory in the `rootZipDir` matching the
/// subspec's name.
///
/// - Parameters:
/// - subspec: The subspec to install and get the dependencies list.
/// - projectDir: Root of the project containing the Podfile.
/// - rootZipDir: The root directory to be turned into the Zip file.
/// - builtFrameworks: All frameworks that have been built, with the framework name as the key
/// and the framework's location as the value.
/// - podsToIgnore: Pods to avoid copying, if any.
/// - Throws: Throws various errors from copying frameworks.
/// - Returns: The product directory containing all frameworks and the names of the frameworks
/// that were copied for this subspec.
@discardableResult
func installAndCopyFrameworks(forPod podName: String,
inFolder folder: String,
withInstalledPods installedPods: [String: CocoaPodUtils.PodInfo],
rootZipDir: URL,
builtFrameworks: [String: [URL]],
frameworksToIgnore: [String] = []) throws
-> (productDir: URL, frameworks: [String]) {
let podsToCopy = [podName] +
CocoaPodUtils.transitiveMasterPodDependencies(for: podName, in: installedPods)
// Remove any duplicates from the `podsToCopy` array. The easiest way to do this is to wrap it
// in a set then back to an array.
let dedupedPods = Array(Set(podsToCopy))
// Copy the frameworks into the proper product directory.
let productDir = rootZipDir.appendingPathComponent(folder)
let namedFrameworks = try copyFrameworks(fromPods: dedupedPods,
toDirectory: productDir,
frameworkLocations: builtFrameworks,
frameworksToIgnore: frameworksToIgnore)
let copiedFrameworks = namedFrameworks.filter {
// Skip frameworks that aren't contained in the "frameworksToIgnore" array and the Firebase pod.
!(frameworksToIgnore.contains($0) || $0 == "Firebase")
}
return (productDir, copiedFrameworks)
}
/// Creates the String that displays all the versions of each pod, in alphabetical order.
///
/// - Parameter pods: All pods that were installed, with their versions.
/// - Returns: A String to be added to the README.
private func versionsString(for pods: [String: CocoaPodUtils.PodInfo]) -> String {
// Get the longest name in order to generate padding with spaces so it looks nicer.
let maxLength: Int = {
guard let pod = pods.keys.max(by: { $0.count < $1.count }) else {
// The longest pod as of this writing is 29 characters, if for whatever reason this fails
// just assume 30 characters long.
return 30
}
// Return room for a space afterwards.
return pod.count + 1
}()
let header: String = {
// Center the CocoaPods title within the spaces given. If there's an odd number of spaces, add
// the extra space after the CocoaPods title.
let cocoaPods = "CocoaPod"
let spacesToPad = maxLength - cocoaPods.count
let halfPadding = String(repeating: " ", count: spacesToPad / 2)
// Start with the spaces padding, then add the CocoaPods title.
var result = halfPadding + cocoaPods + halfPadding
if spacesToPad % 2 != 0 {
// Add an extra space since the padding isn't even
result += " "
}
// Add the versioning text and return.
result += "| Version\n"
// Add a line underneath each.
result += String(repeating: "-", count: maxLength) + "|" + String(repeating: "-", count: 9)
result += "\n"
return result
}()
// Sort the pods by name for a cleaner display.
let sortedPods = pods.sorted { $0.key < $1.key }
// Get the name and version of each pod, padding it along the way.
var podVersions = ""
for pod in sortedPods {
// Insert the name and enough spaces to reach the end of the column.
let podName = pod.key
podVersions += podName + String(repeating: " ", count: maxLength - podName.count)
// Add a pipe and the version.
podVersions += "| " + pod.value.version + "\n"
}
return header + podVersions
}
// MARK: - Framework Generation
/// Collects the .framework and .xcframeworks files from the binary pods. This will go through
/// the contents of the directory and copy the .frameworks to a temporary directory. Returns a
/// dictionary with the framework name for the key and all information for frameworks to install
/// EXCLUDING resources, as they are handled later (if not included in the .framework file
/// already).
private func collectBinaryFrameworks(fromPod podName: String,
podInfo: CocoaPodUtils.PodInfo) -> [URL] {
// Verify the Pods folder exists and we can get the contents of it.
let fileManager = FileManager.default
// Create the temporary directory we'll be storing the build/assembled frameworks in, and remove
// the Resources directory if it already exists.
let binaryZipDir = fileManager.temporaryDirectory(withName: "binary_zip")
do {
try fileManager.createDirectory(at: binaryZipDir,
withIntermediateDirectories: true,
attributes: nil)
} catch {
fatalError("Cannot create temporary directory to store binary frameworks: \(error)")
}
var frameworks: [URL] = []
// TODO: packageAllResources is disabled for binary frameworks since it's not needed for Firebase
// and it does not yet support xcframeworks.
// Package all resources into the frameworks since that's how Carthage needs it packaged.
// do {
// // TODO: Figure out if we need to exclude bundles here or not.
// try ResourcesManager.packageAllResources(containedIn: podInfo.installedLocation)
// } catch {
// fatalError("Tried to package resources for \(podName) but it failed: \(error)")
// }
// Copy each of the frameworks to a known temporary directory and store the location.
for framework in podInfo.binaryFrameworks {
// Copy it to the temporary directory and save it to our list of frameworks.
let zipLocation = binaryZipDir.appendingPathComponent(framework.lastPathComponent)
// Remove the framework if it exists since it could be out of date.
fileManager.removeIfExists(at: zipLocation)
do {
try fileManager.copyItem(at: framework, to: zipLocation)
} catch {
fatalError("Cannot copy framework at \(framework) while " +
"attempting to generate frameworks. \(error)")
}
frameworks.append(zipLocation)
}
return frameworks
}
}
| apache-2.0 | 2c617e9622b951229815fe27755d9c62 | 45.608235 | 106 | 0.638059 | 4.991433 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Helpers/CGSize+Zoom.swift | 1 | 1482 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import UIKit
extension CGSize {
func minZoom(imageSize: CGSize?) -> CGFloat {
guard let imageSize = imageSize else { return 1 }
guard imageSize != .zero else { return 1 }
guard self != .zero else { return 1 }
var minZoom = min(self.width / imageSize.width, self.height / imageSize.height)
if minZoom > 1 {
minZoom = 1
}
return minZoom
}
/// returns true if both with and height are longer than otherSize
///
/// - Parameter otherSize: other CGSize to compare
/// - Returns: true if both with and height are longer than otherSize
func contains(_ otherSize: CGSize) -> Bool {
return otherSize.width < width &&
otherSize.height < height
}
}
| gpl-3.0 | 5cb243c4c56de3fbffa9765b7554cba7 | 31.933333 | 87 | 0.67004 | 4.437126 | false | false | false | false |
mingxianzyh/D3View | D3View/D3View/D3Venders.swift | 1 | 15251 |
import UIKit
//MARK: UIView动画扩展
var DEFAULT_DURATION:NSTimeInterval = 0.25
typealias VoidBlock = (() -> Void)?
extension UIView{
//MARK: 加入动画效果
func addAnimation(type:String,subType:String!,duration:CFTimeInterval){
let action:CATransition = CATransition()
action.type = type
if subType != nil{
action.subtype = subType
}
action.duration = duration
self.layer.addAnimation(action, forKey: "animation")
}
func degreesToRadians(r:CGFloat)->CGFloat
{
return CGFloat(Double(r) * M_PI / 180)
}
func setX(x:CGFloat,finish:VoidBlock){
self.setX(x, duration: DEFAULT_DURATION, finish: finish)
}
func setX(x:CGFloat,duration:NSTimeInterval,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
var frame = self.frame
frame.origin.x = x
self.frame = frame
}, completion: {(f) in
finish?()
})
}
func setY(y:CGFloat,finish:VoidBlock){
self.setY(y, duration: DEFAULT_DURATION, finish: finish)
}
func setY(y:CGFloat,duration:NSTimeInterval,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
var frame = self.frame
frame.origin.y = y
self.frame = frame
}, completion: {(f) in
finish?()
})
}
func setRotation(r:CGFloat,finish:VoidBlock){
self.setRotation(r, duration: DEFAULT_DURATION, finish: finish)
}
func setRotation(r:CGFloat,duration:NSTimeInterval,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
let ratationTransform = CGAffineTransformIdentity
self.transform = CGAffineTransformRotate(ratationTransform, self.degreesToRadians(r))
},completion:{(f) in
finish?()
})
}
func setPoint(point:CGPoint,duration:NSTimeInterval,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
var frame = self.frame
frame.origin = point
self.frame = frame
}, completion: {(f) in
finish?()
})
}
func setPoint(point:CGPoint,finish:VoidBlock){
self.setPoint(point, duration: DEFAULT_DURATION, finish: finish)
}
//在原来基础上修改
func moveX(x:CGFloat,duration:NSTimeInterval,finish:VoidBlock){
self.setX(self.frame.origin.x+x, duration: duration, finish: finish)
}
func moveX(x:CGFloat,finish:VoidBlock){
self.moveX(x, duration: DEFAULT_DURATION, finish: finish)
}
func moveY(y:CGFloat,duration:NSTimeInterval,finish:VoidBlock){
self.setY(self.frame.origin.y+y, duration: duration, finish: finish)
}
func moveY(y:CGFloat,finish:VoidBlock){
self.moveY(y, duration: DEFAULT_DURATION, finish: finish)
}
func moveRotation(r:CGFloat,duration:NSTimeInterval,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
self.transform = CGAffineTransformRotate(self.transform, self.degreesToRadians(r))
}, completion: {(f) in
finish?()
})
}
func moveRotation(r:CGFloat,finish:VoidBlock){
self.moveRotation(r, duration: DEFAULT_DURATION, finish: finish)
}
func d3Animate(duration:NSTimeInterval,block:VoidBlock,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
block?()
}, completion: {(f) in
finish?()
})
}
func d3Animate(duration:NSTimeInterval,transition:UIViewAnimationTransition,forView:UIView,finish:VoidBlock){
UIView.animateWithDuration(duration, animations: {
UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut)
UIView.setAnimationTransition(transition, forView: forView, cache: true)
}, completion: {(f) in
finish?()
})
}
func d3Animate(transition:UIViewAnimationTransition,finish:VoidBlock){
self.d3Animate(1.0, transition: transition, forView: self, finish: finish)
}
func d3Animate(transition:UIViewAnimationTransition){
self.d3Animate(1.0, transition: transition, forView: self, finish: nil)
}
//MARK: 左右摇,dis是幅度,time是时间
func shake(dis:CGFloat,time:NSTimeInterval,finish:VoidBlock){
let dist:CGFloat = dis
let time:NSTimeInterval = time
self.moveX(-dist, duration: time, finish: {
self.moveX(dist*2, duration: time,finish: {
self.moveX(-dist*2, duration: time, finish: {
self.moveX(dist, duration: time,finish: {
finish?()
})
})
})
})
}
func shake(finish:VoidBlock){
self.shake(10.0, time: 0.15,finish:finish)
}
func shake(dis:CGFloat,time:NSTimeInterval){
self.shake(dis, time: time, finish: nil)
}
func shake(){
self.shake(10.0,time: 0.15,finish: nil)
}
//MARK: 上下反弹
func bounce(dis:CGFloat,time:NSTimeInterval,finish:VoidBlock){
let dist:CGFloat = dis
self.moveY(-dist, duration: time, finish: {
self.moveY(dist, duration: time, finish: {
self.moveY(-(dist/2), duration: time, finish: {
self.moveY(dist/2, duration: time, finish: {
finish?()
})
})
})
})
}
func bounce(finish:VoidBlock){
self.bounce(10.0, time: 0.15,finish:finish)
}
func bounce(dis:CGFloat,time:NSTimeInterval){
self.bounce(dis, time: time, finish: nil)
}
func bounce(){
self.bounce(10.0,time: 0.15,finish: nil)
}
//MARK: 心跳
func pulse(dis:CGFloat,time:NSTimeInterval,finish:VoidBlock){
UIView.animateWithDuration(time, animations: {
self.transform = CGAffineTransformMakeScale(dis, dis)
}, completion: {(f) in
UIView.animateWithDuration(time, delay: 0.1 as NSTimeInterval, options: UIViewAnimationOptions.LayoutSubviews, animations: {
self.transform = CGAffineTransformMakeScale(1, 1)
}, completion: {(f) in
finish?()
})
})
}
func pulse(finish:VoidBlock){
self.pulse(1.2, time: 0.5,finish:finish)
}
func pulse(dis:CGFloat,time:NSTimeInterval){
self.pulse(dis, time: time, finish: nil)
}
func pulse(){
self.pulse(1.2,time: 0.5,finish: nil)
}
//MARK: 摇摆
func swing(finish:VoidBlock){
let dist:CGFloat = 15
self.setRotation(dist, finish: {
self.setRotation(-dist, finish: {
self.setRotation(dist/2, finish: {
self.setRotation(-dist/2, finish: {
self.setRotation(0, finish: {
finish?()
})
})
})
})
})
}
func swing(){
self.swing(nil)
}
//MARK: 缩小到不见
func compress(finish:VoidBlock){
self.d3Animate(1.0, block: {
self.transform = CGAffineTransformMakeScale(0.01, 0.01)
}, finish: {
self.hidden = true
finish?()
})
}
func compress(){
self.compress(nil)
}
//MARK: 放大到一个倍数
func zoomin(size:CGFloat,finish:VoidBlock){
self.hidden = false
self.d3Animate(1.0, block: {
self.transform = CGAffineTransformMakeScale(size, size)
}, finish: finish)
}
func zoomin(size:CGFloat){
self.zoomin(size,finish: nil)
}
//MARK: 转轴
func hinge(finish:VoidBlock){
let time:NSTimeInterval = 0.5
let point = CGPointMake(self.frame.origin.x, self.frame.origin.y)
self.layer.anchorPoint = CGPointMake(0, 0)
self.center = point
self.setRotation(80, duration: time, finish: {
self.setRotation(70, duration: time, finish: {
self.setRotation(80, duration: time, finish: {
self.setRotation(70, duration: time, finish: {
self.moveY(self.window!.frame.size.height, duration: time, finish: {
finish?()
self.setRotation(0, finish: nil)
})
})
})
})
})
}
func hinge(){
self.hinge(nil)
}
//MARK: 翻转
func flip(finish:VoidBlock){
self.d3Animate(UIViewAnimationTransition.FlipFromLeft,finish: finish)
}
func flip(){
self.flip(nil)
}
//MARK: 翻页
func pageing(finish:VoidBlock){
self.d3Animate(UIViewAnimationTransition.CurlUp,finish: finish)
}
func pageing(){
self.pageing(nil)
}
}
//MARK: UIView位置扩展
extension UIView{
//位置控制
/**
左边界对齐目标view的右边界
:param: view 目标view
:param: padding 距离
*/
func right2View(view:UIView,padding:CGFloat){
frame.origin.x = view.frame.origin.x + view.frame.width + padding
}
/**
右边界对齐目标view的左边界
:param: view 目标view
:param: padding 距离
*/
func left2View(view:UIView,padding:CGFloat){
frame.origin.x = view.frame.origin.x - frame.width - padding
}
/**
右边界对齐目标view的右边界
:param: view 目标view
:param: padding 距离
*/
func right2ViewInner(view:UIView,padding:CGFloat){
frame.origin.x = view.frame.origin.x + view.frame.width - frame.width - padding
}
/**
左边界对齐目标view的左边界
:param: view 目标view
:param: padding 距离
*/
func left2ViewInner(view:UIView,padding:CGFloat){
frame.origin.x = view.frame.origin.x + padding
}
//下边界对齐目标上边界
func top2View(view:UIView,padding:CGFloat){
frame.origin.y = view.frame.origin.y - frame.height - padding
}
//上边界对齐目标下边界
func bottom2View(view:UIView,padding:CGFloat){
frame.origin.y = view.frame.origin.y + view.frame.height + padding
}
}
enum ViewStyle:Int{
case Round = 168//圆形
case Conrer = 169//圆角3.0
case Border = 170//边线0.5
case BorderM = 171//边线1
case ConrerM = 172//圆角10.0
case Shadow = 173//阴影
case ShadowDown = 174//下阴影
case BorderRight = 175//右边线
case BorderBottom = 176//下边线
case GrayBorder = 177//border灰颜色
case DarkGrayBorder = 178//border深灰颜色
}
//MARK: UIView样式扩展
extension UIView{
//加边线,边框
func addBorder(style:ViewStyle){
switch style{
case .Border: //边框宽度0.5
self.layer.borderWidth = 0.5
case .BorderM:
self.layer.borderWidth = 1 //边框宽度1
case .BorderRight: //右边框宽度0.5
let line = UIView(frame: CGRectMake(frame.width - 0.5, 0, 0.5, frame.height))
line.backgroundColor = UIColor(red: 100/255 , green: 100/255, blue: 100/255, alpha: 0.3)
self.addSubview(line)
case .BorderBottom: //下边框宽度0.5
let line = UIView(frame: CGRectMake(0, frame.height - 0.5, frame.width, 0.5))
line.backgroundColor = UIColor(red: 100/255 , green: 100/255, blue: 100/255, alpha: 0.3)
self.addSubview(line)
default:
break
}
self.layer.borderColor = UIColor.grayColor().CGColor
}
func changeBorderColor(style:ViewStyle){
switch style{
case .DarkGrayBorder:
self.layer.borderColor = UIColor(red: 100/255 , green: 100/255, blue: 100/255, alpha: 0.8).CGColor
case .GrayBorder:
self.layer.borderColor = UIColor(red: 200/255 , green: 200/255, blue: 200/255, alpha: 0.5).CGColor
default:
break
}
}
//加阴影
func addShadow(style:ViewStyle){
switch style{
case .Shadow:
layer.shadowOffset = CGSizeMake(0, 0) //x为向右偏移,y为向下偏移
case .ShadowDown:
layer.shadowOffset = CGSizeMake(0, 2)
default:
break
}
layer.shadowOpacity = 0.1 //透明度
layer.shadowRadius = 2.0 //阴影半径
layer.shadowColor = UIColor.blackColor().CGColor
}
//圆角
func showCorner(style:ViewStyle){
switch style{
case .ConrerM:
self.layer.cornerRadius = 10.0 //弧度为10,大弧度
case .Conrer:
self.layer.cornerRadius = 3.0 //弧度为3,小弧度
default:
break
}
self.layer.masksToBounds = true
}
//显示圆形
func showRound(){
self.layer.cornerRadius = self.frame.size.height/2
self.layer.masksToBounds = true
}
//初始化style
func initStyle(styles:ViewStyle...){
for style:ViewStyle in styles{
switch style{
case .Round:
showRound()
case .Conrer, .ConrerM:
showCorner(style)
case .Border, .BorderM, .BorderRight, .BorderBottom:
addBorder(style)
case .ShadowDown,.Shadow:
addShadow(style)
case .GrayBorder,.DarkGrayBorder:
changeBorderColor(style)
// default:
// break
}
}
}
//MARK: 获取所在的vc
func findMainViewController() -> UIViewController
{
var target:AnyObject = self
while(true)
{
target = (target as! UIResponder).nextResponder()!
if target is UIViewController
{
break
}
}
return target as! UIViewController
}
}
extension String {
func escapeStr() -> String {
let raw: NSString = self
let str:CFString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,raw,"[].","+",CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return str as NSString as String
}
//MARK: 字符包含扩展
func contain(s:String)->Bool{
let ns = self as NSString
if ns.rangeOfString(s).length > 0{
return true
}
return false
}
} | mit | ce5b6dc3c9e5b3b97ee948e455308c32 | 26.721805 | 165 | 0.549535 | 4.206218 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Experiments/Messaging/GleanPlumbMessage.swift | 2 | 2438 | // 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
protocol MessageDataProtocol {
var surface: MessageSurfaceId { get }
var isControl: Bool { get }
var title: String? { get }
var text: String { get }
var buttonLabel: String? { get }
}
extension MessageData: MessageDataProtocol {}
protocol StyleDataProtocol {
var priority: Int { get }
var maxDisplayCount: Int { get }
}
extension StyleData: StyleDataProtocol {}
/// Message is a representation of `MessageData` from `GleanPlumb` that we can better utilize.
struct GleanPlumbMessage {
/// The message Key, a unique identifier.
let id: String
/// An access point to MessageData from Nimbus Messaging.
let data: MessageDataProtocol
/// The action to be done when a user positively engages with the message (CTA).
let action: String
/// The conditions that need to be satisfied for a message to be considered eligible to present.
let triggers: [String]
/// The access point to StyleData from Nimbus Messaging.
let style: StyleDataProtocol
/// The minimal data about a message that we should persist.
var metadata: GleanPlumbMessageMetaData
var isExpired: Bool {
metadata.isExpired || metadata.impressions >= style.maxDisplayCount
}
func isUnderExperimentWith(key experimentKey: String?) -> Bool {
guard let experimentKey = experimentKey else { return false }
if data.isControl { return true }
if id.hasSuffix("-") {
return id.hasPrefix(experimentKey)
}
return id == experimentKey
}
}
/// `MessageMeta` is where we store parts of the message that help us aggregate, query and determine non-expired messages.
class GleanPlumbMessageMetaData: Codable {
/// The message Key.
let id: String
/// The number of times a message was seen by the user.
var impressions: Int
/// The number of times a user intentionally dismissed the message.
var dismissals: Int
/// A message expiry status.
var isExpired: Bool
init(id: String, impressions: Int, dismissals: Int, isExpired: Bool) {
self.id = id
self.impressions = impressions
self.dismissals = dismissals
self.isExpired = isExpired
}
}
| mpl-2.0 | 628e223971b9c8fc5227df90ed248a0d | 28.02381 | 122 | 0.685398 | 4.473394 | false | false | false | false |
benlangmuir/swift | test/Interpreter/protocol_lookup.swift | 13 | 3422 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// Note: JIT mode is checked in Interpreter/protocol_lookup_jit.swift.
protocol Fooable {
func foo()
}
struct S: Fooable {
func foo() { print("S") }
}
class C: Fooable {
func foo() { print("C") }
}
class D: C {
override func foo() { print("D") }
}
class E: D {
override func foo() { print("E") }
}
struct X {}
extension Int: Fooable {
func foo() { print("Int") }
}
func fooify<T>(_ x: T) {
if let foo = x as? Fooable {
foo.foo()
} else {
print("not fooable")
}
}
struct G<T>: Fooable {
func foo() { print("G") }
}
struct H<T> {}
fooify(1) // CHECK: Int
fooify(2) // CHECK-NEXT: Int
fooify(S()) // CHECK-NEXT: S
fooify(S()) // CHECK-NEXT: S
fooify(C()) // CHECK-NEXT: C
fooify(C()) // CHECK-NEXT: C
fooify(D()) // CHECK-NEXT: D
fooify(D()) // CHECK-NEXT: D
fooify(E()) // CHECK-NEXT: E
fooify(E()) // CHECK-NEXT: E
fooify(X()) // CHECK-NEXT: not fooable
fooify(X()) // CHECK-NEXT: not fooable
fooify(G<Int>()) // CHECK-NEXT: G
fooify(G<Float>()) // CHECK-NEXT: G
fooify(G<Int>()) // CHECK-NEXT: G
fooify(H<Int>()) // CHECK-NEXT: not fooable
fooify(H<Float>()) // CHECK-NEXT: not fooable
fooify(H<Int>()) // CHECK-NEXT: not fooable
// TODO: generics w/ dependent witness tables
// Check casts from existentials.
fooify(1 as Any) // CHECK: Int
fooify(2 as Any) // CHECK-NEXT: Int
fooify(S() as Any) // CHECK-NEXT: S
fooify(S() as Any) // CHECK-NEXT: S
fooify(C() as Any) // CHECK-NEXT: C
fooify(C() as Any) // CHECK-NEXT: C
fooify(D() as Any) // CHECK-NEXT: D
fooify(D() as Any) // CHECK-NEXT: D
fooify(E() as Any) // CHECK-NEXT: E
fooify(E() as Any) // CHECK-NEXT: E
fooify(X() as Any) // CHECK-NEXT: not fooable
fooify(X() as Any) // CHECK-NEXT: not fooable
fooify(G<Int>() as Any) // CHECK-NEXT: G
fooify(G<Float>() as Any) // CHECK-NEXT: G
fooify(G<Int>() as Any) // CHECK-NEXT: G
fooify(H<Int>() as Any) // CHECK-NEXT: not fooable
fooify(H<Float>() as Any) // CHECK-NEXT: not fooable
fooify(H<Int>() as Any) // CHECK-NEXT: not fooable
protocol Barrable {
func bar()
}
extension Int: Barrable {
func bar() { print("Int.bar") }
}
let foo: Fooable = 2
if let bar = foo as? Barrable {
bar.bar() // CHECK-NEXT: Int.bar
} else {
print("not barrable 1")
}
let foo2: Fooable = S()
if let bar2 = foo2 as? Barrable {
bar2.bar()
} else {
print("not barrable 2") // CHECK-NEXT: not barrable
}
protocol Runcible: class {
func runce()
}
extension C: Runcible {
func runce() { print("C") }
}
let c1: AnyObject = C()
let c2: Any = C()
if let fruncible = c1 as? Fooable & Runcible {
fruncible.foo() // CHECK-NEXT: C
fruncible.runce() // CHECK-NEXT: C
} else {
print("not fooable and runcible")
}
if let fruncible = c2 as? Fooable & Runcible {
fruncible.foo() // CHECK-NEXT: C
fruncible.runce() // CHECK-NEXT: C
} else {
print("not fooable and runcible")
}
// Protocol lookup for metatypes.
protocol StaticFoo {
static func foo() -> String
}
class StaticBar {
class func mightHaveFoo() -> String {
if let selfAsFoo = self as? StaticFoo.Type {
return selfAsFoo.foo()
} else {
return "no Foo for you"
}
}
}
class StaticWibble : StaticBar, StaticFoo {
static func foo() -> String { return "StaticWibble.foo" }
}
// CHECK: no Foo for you
print(StaticBar.mightHaveFoo())
// CHECK: StaticWibble.foo
print(StaticWibble.mightHaveFoo())
| apache-2.0 | 3dcd25e7fb172e34f989dde5c75edd16 | 21.077419 | 70 | 0.625658 | 2.919795 | false | false | false | false |
google/iosched-ios | Source/IOsched/Screens/Home/UpcomingItemsDataSource.swift | 1 | 4579 | //
// Copyright (c) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
@objc public class UpcomingItemsDataSource: NSObject, UICollectionViewDataSource,
UICollectionViewDelegate {
private let reservationDataSource: RemoteReservationDataSource
private let bookmarkDataSource: RemoteBookmarkDataSource
private let sessionsDataSource: LazyReadonlySessionsDataSource
private let navigator: ScheduleNavigator
let rootNavigator: RootNavigator
/// Called each time the data source's data changes.
public var updateHandler: ((UpcomingItemsDataSource) -> Void)?
public init(reservations: RemoteReservationDataSource = RemoteReservationDataSource(),
bookmarks: RemoteBookmarkDataSource = RemoteBookmarkDataSource(),
sessions: LazyReadonlySessionsDataSource,
scheduleNavigator: ScheduleNavigator,
rootNavigator: RootNavigator) {
reservationDataSource = reservations
bookmarkDataSource = bookmarks
sessionsDataSource = sessions
navigator = scheduleNavigator
self.rootNavigator = rootNavigator
super.init()
registerForUpdates()
}
lazy private(set) var upcomingEvents: [Session] = buildUpcomingEvents()
private func buildUpcomingEvents() -> [Session] {
let currentTimestamp = Date()
var userAgenda: [Session] = []
for reservedSession in reservationDataSource.reservedSessions where
reservedSession.status == .reserved {
if let session = sessionsDataSource[reservedSession.id],
session.startTimestamp > currentTimestamp {
userAgenda.append(session)
}
}
for bookmarkedSessionID in bookmarkDataSource.bookmarks.keys where
bookmarkDataSource.isBookmarked(sessionID: bookmarkedSessionID) {
// Don't duplicate reserved/waitlisted and bookmarked sessions here.
if reservationDataSource.reservationStatus(for: bookmarkedSessionID) != .reserved,
let session = sessionsDataSource[bookmarkedSessionID],
session.startTimestamp > currentTimestamp {
userAgenda.append(session)
}
}
return userAgenda.sorted { (lhs, rhs) -> Bool in
return lhs.startTimestamp < rhs.startTimestamp
}
}
func reloadData() {
upcomingEvents = buildUpcomingEvents()
updateHandler?(self)
}
private func registerForUpdates() {
reservationDataSource.observeReservationUpdates { [weak self] (_, _) in
self?.reloadData()
}
bookmarkDataSource.syncBookmarks { [weak self] (_) in
self?.reloadData()
}
}
private func unregisterForUpdates() {
reservationDataSource.stopObservingUpdates()
bookmarkDataSource.stopSyncingBookmarks()
}
deinit {
unregisterForUpdates()
}
public var isEmpty: Bool {
return upcomingEvents.isEmpty
}
// MARK: - UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return upcomingEvents.count
}
public func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: UpcomingItemCollectionViewCell.reuseIdentifier(),
for: indexPath
) as! UpcomingItemCollectionViewCell
let session = upcomingEvents[indexPath.item]
let isReserved = reservationDataSource.reservationStatus(for: session.id) == .reserved
let isBookmarked = bookmarkDataSource.isBookmarked(sessionID: session.id)
cell.populate(session: session, isReserved: isReserved, isBookmarked: isBookmarked)
return cell
}
// MARK: - UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView,
didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let session = upcomingEvents[indexPath.item]
navigator.navigate(to: session, popToRoot: false)
}
}
| apache-2.0 | 981e93d6612a2decb03f73df7d2f3152 | 34.496124 | 90 | 0.724394 | 5.263218 | false | false | false | false |
michael-yuji/spartanX | Sources/TypeBridges.swift | 2 | 5331 |
// Copyright (c) 2016, Yuji
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
//
// Created by yuuji on 6/2/16.
// Copyright © 2016 yuuji. All rights reserved.
//
#if !os(Linux)
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
public enum SocketDomains: UInt8 {
case unspec = 0
case unix = 1
case inet = 2
case implink = 3
case pup = 4
case chaos = 5
case bs = 6
case iso = 7
case ecma = 8
case datakit = 9
case ccitt = 10
case sna = 11
case deCnet = 12
case dli = 13
case lat = 14
case hylink = 15
case appleTalk = 16
case route = 17
case link = 18
case pseudo_AF_XTP = 19
case coip = 20
case cnt = 21
case pseudo_AF_RTIP = 22
case ipx = 23
case sip = 24
case pseudo_AF_PIP = 25
case ndrv = 27
case isdn = 28
case pseudo_AF_KEY = 29
case inet6 = 30
case natm = 31
case system = 32
case netBios = 33
case ppp = 34
case pseudo_AF_HDRCMPLT = 35
case reserved_36 = 36
case ieee80211 = 37
case utun = 38
case max = 40
}
#endif
#if os(FreeBSD)
public enum SocketDomains: UInt8 {
case unspec = 0
case unix = 1
case inet = 2
case implink = 3
case pup = 4
case chaos = 5
case bs = 6
case iso = 7
case ecma = 8
case datakit = 9
case ccitt = 10
case sna = 11
case deCnet = 12
case dli = 13
case lat = 14
case hylink = 15
case appleTalk = 16
case route = 17
case link = 18
case pseudo_AF_XTP = 19
case coip = 20
case cnt = 21
case pseudo_AF_RTIP = 22
case ipx = 23
case sip = 24
case pseudo_AF_PIP = 25
case isdn = 26
case pseudo_AF_KEY = 27
case inet6 = 28
case natm = 29
case atm = 30
case hdrcmplt = 31
case netgraph = 32
case slow = 33
case sluster = 34
case arp = 35
case bluetooth = 36
case ieee80211 = 37
case inetsdp = 40
case inet6sdp = 41
}
#endif
#else
public enum SocketDomains: UInt16 {
case unspec = 0
case unix = 1
case inet = 2
case ax25 = 3
case ipx = 4
case appleTalk = 5
case netrom = 6
case bridge = 7
case atmpvc = 8
case x25 = 9
case inet6 = 10
case rose = 11
case DECnet = 12
case netbeui = 13
case security = 14
case key = 15
case netlink = 16
case link = 17
case ash = 18
case econet = 19
case atmsvc = 20
case rds = 21
case sna = 22
case irda = 23
case ppp0x = 24
case wanpipe = 25
case llc = 26
case ib = 27
case mpls = 28
case can = 29
case tipc = 30
case bluetooth = 31
case iucv = 32
case rxrpc = 33
case isdn = 34
case phonet = 35
case ieee802154 = 36
}
#endif
public enum SocketTypes: Int32 {
case stream = 1
case dgram = 2
case raw = 3
case rdm = 4
case seqpacket = 5
}
| bsd-2-clause | 313338d8b08942cbdc18afee85b2e086 | 29.457143 | 83 | 0.526642 | 4.02568 | false | false | false | false |
1738004401/Swift3.0-- | SwiftCW/SwiftCW/Models/Home/SWHomeStatusModel.swift | 1 | 2169 | //
// SWHomeStatusModel.swift
// SwiftCW
//
// Created by YiXue on 17/3/15.
// Copyright © 2017年 赵刘磊. All rights reserved.
//
import UIKit
class SWHomeStatusModel: NSObject {
var attitudes_count : Int64?
var biz_feature : Int64?
var bmiddle_pic : String?
var cardid : String?
var comments_count : Int64?
var created_at : String!
var created_at_local:Date?{
get{
let dateStr:String = self.created_at
let formatter = DateFormatter()
// 2.设置时间的格式
formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
// 3. 设置时间的区域(真机必须设置,否则可能不会转换成功)
formatter.locale = NSLocale(localeIdentifier: "en_US") as Locale!
// 4.转换(转换好的时间是去除时区的时间)
let createdDate = formatter.date(from: dateStr)!
return createdDate
}
}
var darwin_tags : [AnyObject]?
var favorited : Int64?
var geo : String?
var gif_ids : String?
var hasActionTypeCard : Int64?
var hot_weibo_tags : [AnyObject]?
var ID : String?
var idstr : String?
var idsin_reply_to_screen_nametr : String?
var in_reply_to_status_id : String?
var in_reply_to_user_id : String?
var isLongText : Bool?
var is_show_bulletin : Int64?
var mid : Int64?
var mlevel : Int64?
var mlevelSource : String?
var original_pic : String?
var page_type : Int64?
var pic_urls : NSArray?
var positive_recom_flag : Int64?
var reposts_count : Int64?
var rid : String?
var source : NSString?
var source_allowclick : Int64?
var source_type : Int64?
var text : NSString?
var textLength : Int64?
var text_tag_tips : [AnyObject]?
var thumbnail_pic : NSDictionary?
var truncated : Int64?
var userType : Int64?
var user : SWStautsUser?
override static func mj_replacedKeyFromPropertyName() -> [AnyHashable : Any]! {
return ["ID":"id"]
}
override init(){
super.init()
}
}
| mit | 468d03602056cb62a565076df52178a5 | 25.831169 | 83 | 0.586641 | 3.695886 | false | false | false | false |
slavapestov/swift | test/DebugInfo/inlinescopes.swift | 2 | 1309 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: echo "public var x = Int64()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll
// RUN: FileCheck %s < %t.ll
// RUN: FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll
// CHECK: define{{( signext)?}} i32 @main
// CHECK: tail call { i64, i1 } @llvm.smul.with.overflow.i64(i64 %[[C:.*]], i64 %[[C]]), !dbg ![[MULSCOPE:.*]]
// CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "inlinescopes.swift"
import FooBar
func markUsed<T>(t: T) {}
@inline(__always)
func square(x: Int64) -> Int64 {
// CHECK-DAG: ![[MULSCOPE]] = !DILocation(line: [[@LINE+2]], column: {{.*}}, scope: ![[MUL:.*]], inlinedAt: ![[INLINED:.*]])
// CHECK-DAG: ![[MUL:.*]] = distinct !DILexicalBlock(
let res = x * x
// *(Int, Int) is a transparent function and should not show up in the debug info.
// TRANSPARENT-CHECK-NOT: !DISubprogram(name: "_TFsoi1mFTSiSi_Si"
return res
}
let c = Int64(x)
// CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]]
let y = square(c)
markUsed(y)
// Check if the inlined and removed square function still has the correct linkage name in the debug info.
// CHECK-DAG: !DISubprogram(name: "square", linkageName: "_TF4main6squareFVs5Int64S0_"
| apache-2.0 | dd284606264410905513437cacfb2fbd | 41.225806 | 124 | 0.633308 | 2.988584 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/CallNavigationHeaderView.swift | 1 | 27084 | //
// CallNavigationHeaderView.swift
// Telegram
//
// Created by keepcoder on 05/05/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import SwiftSignalKit
import TelegramCore
import Postbox
private let blue = NSColor(rgb: 0x0078ff)
private let lightBlue = NSColor(rgb: 0x59c7f8)
private let green = NSColor(rgb: 0x33c659)
private let purple = NSColor(rgb: 0x766EE9)
private let lightPurple = NSColor(rgb: 0xF05459)
class CallStatusBarBackgroundViewLegacy : View, CallStatusBarBackground {
var audioLevel: Float = 0
var speaking:(Bool, Bool, Bool)? = nil {
didSet {
if let speaking = self.speaking, (speaking.0 != oldValue?.0 || speaking.1 != oldValue?.1 || speaking.2 != oldValue?.2) {
let targetColors: [NSColor]
if speaking.1 {
if speaking.2 {
if speaking.0 {
targetColors = [green, blue]
} else {
targetColors = [blue, lightBlue]
}
} else {
targetColors = [purple, lightPurple]
}
} else {
targetColors = [theme.colors.grayIcon, theme.colors.grayIcon.lighter()]
}
self.backgroundColor = targetColors.first ?? theme.colors.accent
}
}
}
}
class CallStatusBarBackgroundView: View, CallStatusBarBackground {
private let foregroundView: View
private let foregroundGradientLayer: CAGradientLayer
private let maskCurveLayer: VoiceCurveLayer
var audioLevel: Float = 0.0 {
didSet {
self.maskCurveLayer.updateLevel(CGFloat(audioLevel))
}
}
var speaking:(Bool, Bool, Bool)? = nil {
didSet {
if let speaking = self.speaking, (speaking.0 != oldValue?.0 || speaking.1 != oldValue?.1 || speaking.2 != oldValue?.2) {
let initialColors = self.foregroundGradientLayer.colors
let targetColors: [CGColor]
if speaking.1 {
if speaking.2 {
if speaking.0 {
targetColors = [green.cgColor, blue.cgColor]
} else {
targetColors = [blue.cgColor, lightBlue.cgColor]
}
} else {
targetColors = [purple.cgColor, lightPurple.cgColor]
}
} else {
targetColors = [theme.colors.grayIcon.cgColor, theme.colors.grayIcon.lighter().cgColor]
}
self.foregroundGradientLayer.colors = targetColors
self.foregroundGradientLayer.animate(from: initialColors as AnyObject, to: targetColors as AnyObject, keyPath: "colors", timingFunction: .linear, duration: 0.3)
}
}
}
override init() {
self.foregroundView = View()
self.foregroundGradientLayer = CAGradientLayer()
self.maskCurveLayer = VoiceCurveLayer(frame: CGRect(), maxLevel: 2.5, smallCurveRange: (0.0, 0.0), mediumCurveRange: (0.1, 0.55), bigCurveRange: (0.1, 1.0))
self.maskCurveLayer.setColor(NSColor(rgb: 0xffffff))
super.init()
self.addSubview(self.foregroundView)
self.foregroundView.layer?.addSublayer(self.foregroundGradientLayer)
self.foregroundGradientLayer.colors = [theme.colors.grayIcon.cgColor, theme.colors.grayIcon.lighter().cgColor]
self.foregroundGradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
self.foregroundGradientLayer.endPoint = CGPoint(x: 2.0, y: 0.5)
self.foregroundView.layer?.mask = maskCurveLayer
//layer?.addSublayer(maskCurveLayer)
self.updateAnimations()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
override func layout() {
super.layout()
CATransaction.begin()
CATransaction.setDisableActions(true)
self.foregroundView.frame = NSMakeRect(0, 0, frame.width, frame.height)
self.foregroundGradientLayer.frame = foregroundView.bounds
self.maskCurveLayer.frame = NSMakeRect(0, 0, frame.width, frame.height)
CATransaction.commit()
}
private let occlusionDisposable = MetaDisposable()
private var isCurrentlyInHierarchy: Bool = false {
didSet {
updateAnimations()
}
}
deinit {
occlusionDisposable.dispose()
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if let window = window as? Window {
occlusionDisposable.set(window.takeOcclusionState.start(next: { [weak self] value in
self?.isCurrentlyInHierarchy = value.contains(.visible)
}))
} else {
occlusionDisposable.set(nil)
isCurrentlyInHierarchy = false
}
}
func updateAnimations() {
if !isCurrentlyInHierarchy {
self.foregroundGradientLayer.removeAllAnimations()
self.maskCurveLayer.stopAnimating()
return
}
self.maskCurveLayer.startAnimating()
}
}
private final class VoiceCurveLayer: SimpleLayer {
private let smallCurve: CurveLayer
private let mediumCurve: CurveLayer
private let bigCurve: CurveLayer
private let maxLevel: CGFloat
private var displayLinkAnimator: ConstantDisplayLinkAnimator?
private var audioLevel: CGFloat = 0.0
var presentationAudioLevel: CGFloat = 0.0
private(set) var isAnimating = false
public typealias CurveRange = (min: CGFloat, max: CGFloat)
public init(
frame: CGRect,
maxLevel: CGFloat,
smallCurveRange: CurveRange,
mediumCurveRange: CurveRange,
bigCurveRange: CurveRange
) {
self.maxLevel = maxLevel
self.smallCurve = CurveLayer(
pointsCount: 7,
minRandomness: 1,
maxRandomness: 1.3,
minSpeed: 0.9,
maxSpeed: 3.2,
minOffset: smallCurveRange.min,
maxOffset: smallCurveRange.max
)
self.mediumCurve = CurveLayer(
pointsCount: 7,
minRandomness: 1.2,
maxRandomness: 1.5,
minSpeed: 1.0,
maxSpeed: 4.4,
minOffset: mediumCurveRange.min,
maxOffset: mediumCurveRange.max
)
self.bigCurve = CurveLayer(
pointsCount: 7,
minRandomness: 1.2,
maxRandomness: 1.7,
minSpeed: 1.0,
maxSpeed: 5.8,
minOffset: bigCurveRange.min,
maxOffset: bigCurveRange.max
)
super.init()
self.addSublayer(bigCurve)
self.addSublayer(mediumCurve)
self.addSublayer(smallCurve)
displayLinkAnimator = ConstantDisplayLinkAnimator() { [weak self] in
guard let strongSelf = self else { return }
strongSelf.presentationAudioLevel = strongSelf.presentationAudioLevel * 0.9 + strongSelf.audioLevel * 0.1
strongSelf.smallCurve.level = strongSelf.presentationAudioLevel
strongSelf.mediumCurve.level = strongSelf.presentationAudioLevel
strongSelf.bigCurve.level = strongSelf.presentationAudioLevel
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setColor(_ color: NSColor) {
smallCurve.setColor(color.withAlphaComponent(1.0))
mediumCurve.setColor(color.withAlphaComponent(0.55))
bigCurve.setColor(color.withAlphaComponent(0.35))
}
public func updateLevel(_ level: CGFloat) {
let normalizedLevel = min(1, max(level / maxLevel, 0))
smallCurve.updateSpeedLevel(to: normalizedLevel)
mediumCurve.updateSpeedLevel(to: normalizedLevel)
bigCurve.updateSpeedLevel(to: normalizedLevel)
audioLevel = normalizedLevel
}
public func startAnimating() {
guard !isAnimating else { return }
isAnimating = true
updateCurvesState()
displayLinkAnimator?.isPaused = false
}
public func stopAnimating() {
self.stopAnimating(duration: 0.15)
}
public func stopAnimating(duration: Double) {
guard isAnimating else { return }
isAnimating = false
updateCurvesState()
displayLinkAnimator?.isPaused = true
}
private func updateCurvesState() {
if isAnimating {
if smallCurve.frame.size != .zero {
smallCurve.startAnimating()
mediumCurve.startAnimating()
bigCurve.startAnimating()
}
} else {
smallCurve.stopAnimating()
mediumCurve.stopAnimating()
bigCurve.stopAnimating()
}
}
override var frame: NSRect {
didSet {
if oldValue != frame {
smallCurve.frame = bounds
mediumCurve.frame = bounds
bigCurve.frame = bounds
updateCurvesState()
}
}
}
}
final class CurveLayer: CAShapeLayer {
let pointsCount: Int
let smoothness: CGFloat
let minRandomness: CGFloat
let maxRandomness: CGFloat
let minSpeed: CGFloat
let maxSpeed: CGFloat
let minOffset: CGFloat
let maxOffset: CGFloat
var level: CGFloat = 0 {
didSet {
guard self.minOffset > 0.0 else {
return
}
CATransaction.begin()
CATransaction.setDisableActions(true)
let lv = minOffset + (maxOffset - minOffset) * level
self.transform = CATransform3DMakeTranslation(0.0, lv * 16.0, 0.0)
CATransaction.commit()
}
}
private var curveAnimation: DisplayLinkAnimator?
private var speedLevel: CGFloat = 0
private var lastSpeedLevel: CGFloat = 0
private var transition: CGFloat = 0 {
didSet {
guard let currentPoints = currentPoints else { return }
let width = self.bounds.width
let smoothness = self.smoothness
let signal: Signal<CGPath, NoError> = Signal { subscriber in
subscriber.putNext(.smoothCurve(through: currentPoints, length: width, smoothness: smoothness, curve: true))
subscriber.putCompletion()
return EmptyDisposable
}
|> runOn(resourcesQueue)
|> deliverOnMainQueue
_ = signal.start(next: { [weak self] path in
self?.path = path
})
}
}
override var frame: CGRect {
didSet {
if oldValue != frame {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.position = CGPoint(x: self.bounds.width / 2.0, y: self.bounds.height / 2.0)
self.bounds = self.bounds
CATransaction.commit()
}
if self.frame.size != oldValue.size {
self.fromPoints = nil
self.toPoints = nil
self.curveAnimation = nil
self.animateToNewShape()
}
}
}
private var fromPoints: [CGPoint]?
private var toPoints: [CGPoint]?
private var currentPoints: [CGPoint]? {
guard let fromPoints = fromPoints, let toPoints = toPoints else { return nil }
return fromPoints.enumerated().map { offset, fromPoint in
let toPoint = toPoints[offset]
return CGPoint(
x: fromPoint.x + (toPoint.x - fromPoint.x) * transition,
y: fromPoint.y + (toPoint.y - fromPoint.y) * transition
)
}
}
init(
pointsCount: Int,
minRandomness: CGFloat,
maxRandomness: CGFloat,
minSpeed: CGFloat,
maxSpeed: CGFloat,
minOffset: CGFloat,
maxOffset: CGFloat
) {
self.pointsCount = pointsCount
self.minRandomness = minRandomness
self.maxRandomness = maxRandomness
self.minSpeed = minSpeed
self.maxSpeed = maxSpeed
self.minOffset = minOffset
self.maxOffset = maxOffset
self.smoothness = 0.35
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func setColor(_ color: NSColor) {
self.fillColor = color.cgColor
}
func updateSpeedLevel(to newSpeedLevel: CGFloat) {
speedLevel = max(speedLevel, newSpeedLevel)
}
func startAnimating() {
animateToNewShape()
}
func stopAnimating() {
fromPoints = currentPoints
toPoints = nil
self.curveAnimation?.invalidate()
curveAnimation = nil
}
private func animateToNewShape() {
if curveAnimation != nil {
fromPoints = currentPoints
toPoints = nil
curveAnimation = nil
}
if fromPoints == nil {
fromPoints = generateNextCurve(for: bounds.size)
}
if toPoints == nil {
toPoints = generateNextCurve(for: bounds.size)
}
let duration = CGFloat(1 / (minSpeed + (maxSpeed - minSpeed) * speedLevel))
let fromValue: CGFloat = 0
let toValue: CGFloat = 1
let animation = DisplayLinkAnimator(duration: Double(duration), from: fromValue, to: toValue, update: { [weak self] value in
self?.transition = value
}, completion: { [weak self] in
guard let `self` = self else {
return
}
self.fromPoints = self.currentPoints
self.toPoints = nil
self.curveAnimation = nil
self.animateToNewShape()
})
self.curveAnimation = animation
lastSpeedLevel = speedLevel
speedLevel = 0
}
private func generateNextCurve(for size: CGSize) -> [CGPoint] {
let randomness = minRandomness + (maxRandomness - minRandomness) * speedLevel
return curve(pointsCount: pointsCount, randomness: randomness).map {
return CGPoint(x: $0.x * CGFloat(size.width), y: size.height - 18.0 + $0.y * 12.0)
}
}
private func curve(pointsCount: Int, randomness: CGFloat) -> [CGPoint] {
let segment = 1.0 / CGFloat(pointsCount - 1)
let rgen = { () -> CGFloat in
let accuracy: UInt32 = 1000
let random = arc4random_uniform(accuracy)
return CGFloat(random) / CGFloat(accuracy)
}
let rangeStart: CGFloat = 1.0 / (1.0 + randomness / 10.0)
let points = (0 ..< pointsCount).map { i -> CGPoint in
let randPointOffset = (rangeStart + CGFloat(rgen()) * (1 - rangeStart)) / 2
let segmentRandomness: CGFloat = randomness
let pointX: CGFloat
let pointY: CGFloat
let randomXDelta: CGFloat
if i == 0 {
pointX = 0.0
pointY = 0.0
randomXDelta = 0.0
} else if i == pointsCount - 1 {
pointX = 1.0
pointY = 0.0
randomXDelta = 0.0
} else {
pointX = segment * CGFloat(i)
pointY = ((segmentRandomness * CGFloat(arc4random_uniform(100)) / CGFloat(100)) - segmentRandomness * 0.5) * randPointOffset
randomXDelta = segment - segment * randPointOffset
}
return CGPoint(x: pointX + randomXDelta, y: pointY)
}
return points
}
}
protocol CallStatusBarBackground : View {
var audioLevel: Float { get set }
var speaking:(Bool, Bool, Bool)? { get set }
}
class CallHeaderBasicView : NavigationHeaderView {
private let _backgroundView: CallStatusBarBackground
var backgroundView: CallStatusBarBackground {
return _backgroundView
}
private let container = View()
fileprivate let callInfo:TitleButton = TitleButton()
fileprivate let endCall:ImageButton = ImageButton()
fileprivate let statusTextView:TextView = TextView()
fileprivate let muteControl:ImageButton = ImageButton()
fileprivate let capView = View()
let disposable = MetaDisposable()
let hideDisposable = MetaDisposable()
override func hide(_ animated: Bool) {
super.hide(true)
disposable.set(nil)
hideDisposable.set(nil)
}
private var statusTimer: SwiftSignalKit.Timer?
var status: CallControllerStatusValue = .text("", nil) {
didSet {
if self.status != oldValue {
self.statusTimer?.invalidate()
if self.status.hasTimer == true {
self.statusTimer = SwiftSignalKit.Timer(timeout: 0.5, repeat: true, completion: { [weak self] in
self?.updateStatus()
}, queue: Queue.mainQueue())
self.statusTimer?.start()
self.updateStatus()
} else {
self.updateStatus()
}
}
}
}
private func updateStatus(animated: Bool = true) {
var statusText: String = ""
switch self.status {
case let .text(text, _):
statusText = text
case let .timer(referenceTime, _):
let duration = Int32(CFAbsoluteTimeGetCurrent() - referenceTime)
let durationString: String
if duration > 60 * 60 {
durationString = String(format: "%02d:%02d:%02d", arguments: [duration / 3600, (duration / 60) % 60, duration % 60])
} else {
durationString = String(format: "%02d:%02d", arguments: [(duration / 60) % 60, duration % 60])
}
statusText = durationString
case let .startsIn(time):
statusText = strings().chatHeaderVoiceChatStartsIn(timerText(time - Int(Date().timeIntervalSince1970)))
}
let layout = TextViewLayout.init(.initialize(string: statusText, color: .white, font: .normal(13)))
layout.measure(width: .greatestFiniteMagnitude)
self.statusTextView.update(layout)
needsLayout = true
}
deinit {
disposable.dispose()
hideDisposable.dispose()
}
override init(_ header: NavigationHeader) {
if #available(OSX 10.12, *) {
self._backgroundView = CallStatusBarBackgroundView()
} else {
self._backgroundView = CallStatusBarBackgroundViewLegacy()
}
super.init(header)
backgroundView.frame = bounds
backgroundView.wantsLayer = true
addSubview(capView)
addSubview(backgroundView)
addSubview(container)
statusTextView.backgroundColor = .clear
statusTextView.userInteractionEnabled = false
statusTextView.isSelectable = false
callInfo.set(font: .medium(.text), for: .Normal)
callInfo.disableActions()
container.addSubview(callInfo)
callInfo.userInteractionEnabled = false
endCall.disableActions()
container.addSubview(endCall)
endCall.scaleOnClick = true
muteControl.scaleOnClick = true
container.addSubview(statusTextView)
callInfo.set(handler: { [weak self] _ in
self?.showInfoWindow()
}, for: .Click)
endCall.set(handler: { [weak self] _ in
self?.hangUp()
}, for: .Click)
muteControl.autohighlight = false
container.addSubview(muteControl)
muteControl.set(handler: { [weak self] _ in
self?.toggleMute()
}, for: .Click)
updateLocalizationAndTheme(theme: theme)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func toggleMute() {
}
func showInfoWindow() {
}
func hangUp() {
}
func setInfo(_ text: String) {
self.callInfo.set(text: text, for: .Normal)
}
func setMicroIcon(_ image: CGImage) {
muteControl.set(image: image, for: .Normal)
_ = muteControl.sizeToFit()
}
override func mouseUp(with event: NSEvent) {
super.mouseUp(with: event)
let point = self.convert(event.locationInWindow, from: nil)
if let header = header, point.y <= header.height {
showInfoWindow()
}
}
var blueColor:NSColor {
return theme.colors.accentSelect
}
var grayColor:NSColor {
return theme.colors.grayText
}
func getEndText() -> String {
return strings().callHeaderEndCall
}
override func layout() {
super.layout()
capView.frame = NSMakeRect(0, 0, frame.width, height)
backgroundView.frame = bounds
container.frame = NSMakeRect(0, 0, frame.width, height)
muteControl.centerY(x:18)
statusTextView.centerY(x: muteControl.frame.maxX + 6)
endCall.centerY(x: frame.width - endCall.frame.width - 20)
_ = callInfo.sizeToFit(NSZeroSize, NSMakeSize(frame.width - statusTextView.frame.width - 60 - 20 - endCall.frame.width - 10, callInfo.frame.height), thatFit: false)
let rect = container.focus(callInfo.frame.size)
callInfo.setFrameOrigin(NSMakePoint(max(statusTextView.frame.maxX + 10, min(rect.minX, endCall.frame.minX - 10 - callInfo.frame.width)), rect.minY))
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
let theme = (theme as! TelegramPresentationTheme)
self.capView.backgroundColor = backgroundView.backgroundColor
endCall.set(image: theme.icons.callInlineDecline, for: .Normal)
endCall.set(image: theme.icons.callInlineDecline, for: .Highlight)
_ = endCall.sizeToFit(NSMakeSize(10, 10), thatFit: false)
callInfo.set(color: .white, for: .Normal)
needsLayout = true
}
}
class CallNavigationHeaderView: CallHeaderBasicView {
var session: PCallSession? {
get {
self.header?.contextObject as? PCallSession
}
}
private let audioLevelDisposable = MetaDisposable()
deinit {
audioLevelDisposable.dispose()
}
fileprivate weak var accountPeer: Peer?
fileprivate var state: CallState?
override func showInfoWindow() {
if let session = self.session {
showCallWindow(session)
}
}
override func hangUp() {
self.session?.hangUpCurrentCall()
}
override func toggleMute() {
session?.toggleMute()
}
override func update(with contextObject: Any) {
super.update(with: contextObject)
let session = contextObject as! PCallSession
let account = session.account
let signal = Signal<Peer?, NoError>.single(session.peer) |> then(session.account.postbox.loadedPeerWithId(session.peerId) |> map(Optional.init) |> deliverOnMainQueue)
let accountPeer: Signal<Peer?, NoError> = session.accountContext.sharedContext.activeAccounts |> mapToSignal { accounts in
if accounts.accounts.count == 1 {
return .single(nil)
} else {
return account.postbox.loadedPeerWithId(account.peerId) |> map(Optional.init)
}
}
disposable.set(combineLatest(queue: .mainQueue(), session.state, signal, accountPeer).start(next: { [weak self] state, peer, accountPeer in
if let peer = peer {
self?.setInfo(peer.displayTitle)
}
self?.updateState(state, accountPeer: accountPeer, animated: false)
self?.needsLayout = true
self?.ready.set(.single(true))
}))
audioLevelDisposable.set((session.audioLevel |> deliverOnMainQueue).start(next: { [weak self] value in
self?.backgroundView.audioLevel = value
}))
hideDisposable.set((session.canBeRemoved |> deliverOnMainQueue).start(next: { [weak self] value in
if value {
self?.hide(true)
}
}))
}
private func updateState(_ state:CallState, accountPeer: Peer?, animated: Bool) {
self.state = state
self.status = state.state.statusText(accountPeer, state.videoState)
var isConnected: Bool = false
let isMuted = state.isMuted
switch state.state {
case .active:
isConnected = true
default:
isConnected = false
}
self.backgroundView.speaking = (isConnected && !isMuted, isConnected, true)
if animated {
backgroundView.layer?.animateBackground()
}
setMicroIcon(!state.isMuted ? theme.icons.callInlineUnmuted : theme.icons.callInlineMuted)
needsLayout = true
switch state.state {
case let .terminated(_, reason, _):
if let reason = reason, reason.recall {
} else {
muteControl.removeAllHandlers()
endCall.removeAllHandlers()
callInfo.removeAllHandlers()
muteControl.change(opacity: 0.8, animated: animated)
endCall.change(opacity: 0.8, animated: animated)
statusTextView._change(opacity: 0.8, animated: animated)
callInfo._change(opacity: 0.8, animated: animated)
}
default:
break
}
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
if let state = state {
self.updateState(state, accountPeer: accountPeer, animated: false)
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(_ header: NavigationHeader) {
super.init(header)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
// Drawing code here.
}
}
| gpl-2.0 | e6d1e23389f849658d4f432cea101ed1 | 30.058486 | 176 | 0.583724 | 4.766455 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00952-swift-constraints-constraintgraph-gatherconstraints.swift | 11 | 637 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
class A = a: a<T {
}
case A.E
i> (A? = a
protocol B == "a() { }
enum A where f..a(a(x)
typealias d>(n: A: k.a("
var _ = A.E == b: Int
protocol P {
struct A {
}(b(Any) -> String {
if true as Boolean>(i("](B)
typealias f : d where H) + seq
func d
| apache-2.0 | 79e62da01ca4b51268498a527c2c74b9 | 27.954545 | 78 | 0.6719 | 3.0625 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/CollectionViewSlantedLayout-master/Examples/CollectionViewSlantedLayoutDemo/SettingsController.swift | 1 | 3348 | //
// SettingsController.swift
// CollectionViewSlantedLayoutDemo
//
// Created by Yassir Barchi on 28/02/2016.
// Copyright © 2016 Yassir Barchi. All rights reserved.
//
import Foundation
import UIKit
import CollectionViewSlantedLayout
class SettingsController: UITableViewController {
weak var collectionViewLayout: CollectionViewSlantedLayout!
@IBOutlet weak var slantingDirectionSegment: UISegmentedControl!
@IBOutlet weak var scrollDirectionSegment: UISegmentedControl!
@IBOutlet weak var zIndexOrderSegment: UISegmentedControl!
@IBOutlet weak var firstCellSlantingSwitch: UISwitch!
@IBOutlet weak var lastCellSlantingSwitch: UISwitch!
@IBOutlet weak var slantingSizeSlider: UISlider!
@IBOutlet weak var lineSpacingSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
self.slantingDirectionSegment.selectedSegmentIndex = (self.collectionViewLayout.slantingDirection == .downward) ? 0 : 1
self.scrollDirectionSegment.selectedSegmentIndex = (self.collectionViewLayout.scrollDirection == .horizontal) ? 0 : 1
self.zIndexOrderSegment.selectedSegmentIndex = (self.collectionViewLayout.zIndexOrder == .descending) ? 0 : 1
self.firstCellSlantingSwitch.isOn = self.collectionViewLayout.isFistCellExcluded
self.lastCellSlantingSwitch.isOn = self.collectionViewLayout.isLastCellExcluded
self.slantingSizeSlider.value = Float(self.collectionViewLayout.slantingSize)
self.lineSpacingSlider.value = Float(self.collectionViewLayout.lineSpacing)
UIApplication.shared.setStatusBarHidden(false, with: UIStatusBarAnimation.slide)
}
override var prefersStatusBarHidden : Bool {
return false
}
override var preferredStatusBarUpdateAnimation : UIStatusBarAnimation {
return UIStatusBarAnimation.slide
}
@IBAction func slantingDirectionChanged(_ sender: UISegmentedControl) {
self.collectionViewLayout.slantingDirection = (sender.selectedSegmentIndex == 0 ? .downward : .upward )
}
@IBAction func scrollDirectionChanged(_ sender: UISegmentedControl) {
self.collectionViewLayout.scrollDirection = (sender.selectedSegmentIndex == 0 ? .horizontal : .vertical)
}
@IBAction func zIndexOrderChanged(_ sender: UISegmentedControl) {
self.collectionViewLayout.zIndexOrder = (sender.selectedSegmentIndex == 0 ? .descending : .ascending)
}
@IBAction func firstCellSlantingSwitchChanged(_ sender: UISwitch) {
self.collectionViewLayout.isFistCellExcluded = sender.isOn
}
@IBAction func lastCellSlantingSwitchChanged(_ sender: UISwitch) {
self.collectionViewLayout.isLastCellExcluded = sender.isOn
}
@IBAction func slantingSizeChanged(_ sender: UISlider) {
self.collectionViewLayout.slantingSize = UInt(sender.value)
}
@IBAction func lineSpacingChanged(_ sender: UISlider) {
self.collectionViewLayout.lineSpacing = CGFloat(sender.value)
}
@IBAction func done(_ sender: AnyObject) {
self.presentingViewController?.dismiss(animated: true, completion: { () -> Void in
self.collectionViewLayout.collectionView?.scrollRectToVisible(CGRect(x: 0, y: 0, width: 0, height: 0), animated: true);
})
}
}
| mit | f891cfe5cb7436b31bc6fc47c021e6cd | 39.817073 | 131 | 0.731999 | 4.965875 | false | false | false | false |
CulturaMobile/culturamobile-api | Sources/App/Models/EventPrice.swift | 1 | 2185 | import Vapor
import FluentProvider
import AuthProvider
import HTTP
final class EventPrice: Model {
fileprivate static let databaseTableName = "event_prices"
static var entity = "event_prices"
let storage = Storage()
static let idKey = "id"
static let foreignIdKey = "event_prices_id"
var event: Identifier?
var price: Identifier?
init(event: Event, price: Price) {
self.event = event.id
self.price = price.id
}
// MARK: Row
/// Initializes from the database row
init(row: Row) throws {
event = try row.get("event_id")
price = try row.get("price_id")
}
// Serializes object to the database
func makeRow() throws -> Row {
var row = Row()
try row.set("event_id", event)
try row.set("price_id", price)
return row
}
}
// MARK: Preparation
extension EventPrice: Preparation {
/// Prepares a table/collection in the database for storing objects
static func prepare(_ database: Database) throws {
try database.create(self) { builder in
builder.id()
builder.int("event_id")
builder.int("price_id")
}
}
/// Undoes what was done in `prepare`
static func revert(_ database: Database) throws {
try database.delete(self)
}
}
// MARK: JSON
// How the model converts from / to JSON.
//
extension EventPrice: JSONConvertible {
convenience init(json: JSON) throws {
try self.init(
event: json.get("event_id"),
price: json.get("price_id")
)
id = try json.get("id")
}
func makeJSON() throws -> JSON {
var json = JSON()
let currentPrices = try Price.makeQuery().filter("id", price).all()
for p in currentPrices {
try json.set("value", p.value)
}
return json
}
}
extension EventPrice: ResponseRepresentable { }
extension EventPrice: Timestampable {
static var updatedAtKey: String { return "updated_at" }
static var createdAtKey: String { return "created_at" }
}
| mit | 78009c3c58c29af16fd8f2d8e7362af1 | 23.277778 | 75 | 0.579863 | 4.301181 | false | false | false | false |
jcsla/MusicoAudioPlayer | MusicoAudioPlayer/Classes/event/PlayerEventProducer.swift | 2 | 11191 | //
// PlayerEventProducer.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 08/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
import AVFoundation
// MARK: - AVPlayer+KVO
private extension AVPlayer {
//swiftlint:disable variable_name
/// The list of properties that is observed through KVO.
static var ap_KVOProperties: [String] {
return [
"currentItem.playbackBufferEmpty",
"currentItem.playbackLikelyToKeepUp",
"currentItem.duration",
"currentItem.status",
"currentItem.loadedTimeRanges",
"currentItem.timedMetadata"]
}
}
// MARK: - Selector+PlayerEventProducer
private extension Selector {
#if os(iOS) || os(tvOS)
/// The selector to call when the audio session is interrupted.
static let audioSessionInterrupted =
#selector(PlayerEventProducer.audioSessionGotInterrupted(note:))
#endif
/// The selector to call when the audio session route changes.
static let audioRouteChanged = #selector(PlayerEventProducer.audioSessionRouteChanged(note:))
/// The selector to call when the audio session get messed up.
static let audioSessionMessedUp = #selector(PlayerEventProducer.audioSessionMessedUp(note:))
/// The selector to call when an audio item ends playing.
static let itemDidEnd = #selector(PlayerEventProducer.playerItemDidEnd(note:))
}
// MARK: - PlayerEventProducer
/// A `PlayerEventProducer` listens to notifications and observes events generated by an AVPlayer.
class PlayerEventProducer: NSObject, EventProducer {
/// A `PlayerEvent` is an event a player generates over time.
///
/// - startedBuffering: The player started buffering the audio file.
/// - readyToPlay: The player is ready to play. It buffered enough data.
/// - loadedMoreRange: The player loaded more range of time.
/// - loadedMetadata: The player loaded metadata.
/// - loadedDuration: The player has found audio item duration.
/// - progressed: The player progressed in its playing.
/// - endedPlaying: The player ended playing the current item because it went through the
/// file or because of an error.
/// - interruptionBegan: The player got interrupted (phone call, Siri, ...).
/// - interruptionEnded: The interruption ended.
/// - routeChanged: The player's route changed.
/// - sessionMessedUp: The audio session is messed up.
enum PlayerEvent: Event {
case startedBuffering
case readyToPlay
case loadedMoreRange(CMTime, CMTime)
case loadedMetadata([AVMetadataItem])
case loadedDuration(CMTime)
case progressed(CMTime)
case endedPlaying(Error?)
case interruptionBegan
case interruptionEnded
case routeChanged
case sessionMessedUp
}
/// The player to produce events with.
///
/// Note that setting it has the same result as calling `stopProducingEvents`.
var player: AVPlayer? {
willSet {
stopProducingEvents()
}
}
/// The listener that will be alerted a new event occured.
weak var eventListener: EventListener?
/// The time observer for the player.
private var timeObserver: Any?
/// A boolean value indicating whether we're currently listening to events on the player.
private var listening = false
/// Stops producing events on deinitialization.
deinit {
stopProducingEvents()
}
/// Starts listening to the player events.
func startProducingEvents() {
guard let player = player, !listening else {
return
}
//Observing notifications sent through `NSNotificationCenter`
let center = NotificationCenter.default
#if os(iOS) || os(tvOS)
center.addObserver(self,
selector: .audioSessionInterrupted,
name: .AVAudioSessionInterruption,
object: nil)
center.addObserver(
self,
selector: .audioRouteChanged,
name: .AVAudioSessionRouteChange,
object: nil)
center.addObserver(
self,
selector: .audioSessionMessedUp,
name: .AVAudioSessionMediaServicesWereLost,
object: nil)
center.addObserver(
self,
selector: .audioSessionMessedUp,
name: .AVAudioSessionMediaServicesWereReset,
object: nil)
#endif
center.addObserver(self, selector: .itemDidEnd, name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
//Observing AVPlayer's property
for keyPath in AVPlayer.ap_KVOProperties {
player.addObserver(self, forKeyPath: keyPath, options: .new, context: nil)
}
//Observing timing event
timeObserver = player.addPeriodicTimeObserver(forInterval: CMTimeMake(1, 2), queue: .main) { [weak self] time in
if let `self` = self {
self.eventListener?.onEvent(PlayerEvent.progressed(time), generetedBy: self)
}
}
listening = true
}
/// Stops listening to the player events.
func stopProducingEvents() {
guard let player = player, listening else {
return
}
//Unobserving notifications sent through `NSNotificationCenter`
let center = NotificationCenter.default
#if os(iOS) || os(tvOS)
center.removeObserver(self, name: .AVAudioSessionInterruption, object: nil)
center.removeObserver(self, name: .AVAudioSessionRouteChange, object: nil)
center.removeObserver(self, name: .AVAudioSessionMediaServicesWereLost, object: nil)
center.removeObserver(self, name: .AVAudioSessionMediaServicesWereReset, object: nil)
#endif
center.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
//Unobserving AVPlayer's property
for keyPath in AVPlayer.ap_KVOProperties {
player.removeObserver(self, forKeyPath: keyPath)
}
//Unobserving timing event
if let timeObserver = timeObserver {
player.removeTimeObserver(timeObserver)
}
timeObserver = nil
listening = false
}
/// This message is sent to the receiver when the value at the specified key path relative to the given object has
/// changed. The receiver must be registered as an observer for the specified `keyPath` and `object`.
///
/// - Parameters:
/// - keyPath: The key path, relative to `object`, to the value that has changed.
/// - object: The source object of the key path `keyPath`.
/// - change: A dictionary that describes the changes that have been made to the value of the property at the key
/// path `keyPath` relative to `object`. Entries are described in Change Dictionary Keys.
/// - context: The value that was provided when the receiver was registered to receive key-value observation
/// notifications.
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey: Any]?,
context: UnsafeMutableRawPointer?) {
if let keyPath = keyPath, let p = object as? AVPlayer, let currentItem = p.currentItem {
switch keyPath {
case "currentItem.duration":
let duration = currentItem.duration
eventListener?.onEvent(PlayerEvent.loadedDuration(duration), generetedBy: self)
let metadata = currentItem.asset.commonMetadata
eventListener?.onEvent(PlayerEvent.loadedMetadata(metadata), generetedBy: self)
case "currentItem.playbackBufferEmpty" where currentItem.isPlaybackBufferEmpty:
eventListener?.onEvent(PlayerEvent.startedBuffering, generetedBy: self)
case "currentItem.playbackLikelyToKeepUp" where currentItem.isPlaybackLikelyToKeepUp:
eventListener?.onEvent(PlayerEvent.readyToPlay, generetedBy: self)
case "currentItem.status" where currentItem.status == .failed:
eventListener?.onEvent(
PlayerEvent.endedPlaying(currentItem.error), generetedBy: self)
case "currentItem.loadedTimeRanges":
if let range = currentItem.loadedTimeRanges.last?.timeRangeValue {
eventListener?.onEvent(
PlayerEvent.loadedMoreRange(range.start, range.end), generetedBy: self)
}
case "currentItem.timedMetadata":
if let metadata = currentItem.timedMetadata {
eventListener?.onEvent(PlayerEvent.loadedMetadata(metadata), generetedBy: self)
}
default:
break
}
}
}
#if os(iOS) || os(tvOS)
/// Audio session got interrupted by the system (call, Siri, ...). If interruption begins, we should ensure the
/// audio pauses and if it ends, we should restart playing if state was `.playing` before.
///
/// - Parameter note: The notification information.
@objc fileprivate func audioSessionGotInterrupted(note: NSNotification) {
if let userInfo = note.userInfo,
let typeInt = userInfo[AVAudioSessionInterruptionTypeKey] as? UInt,
let type = AVAudioSessionInterruptionType(rawValue: typeInt) {
if type == .began {
eventListener?.onEvent(PlayerEvent.interruptionBegan, generetedBy: self)
} else {
if let optionInt = userInfo[AVAudioSessionInterruptionOptionKey] as? UInt {
let options = AVAudioSessionInterruptionOptions(rawValue: optionInt)
if options.contains(.shouldResume) {
eventListener?.onEvent(PlayerEvent.interruptionEnded, generetedBy: self)
}
}
}
}
}
#endif
/// Audio session route changed (ex: earbuds plugged in/out). This can change the player state, so we just adapt it.
///
/// - Parameter note: The notification information.
@objc fileprivate func audioSessionRouteChanged(note: NSNotification) {
eventListener?.onEvent(PlayerEvent.routeChanged, generetedBy: self)
}
/// Audio session got messed up (media services lost or reset). We gotta reactive the audio session and reset
/// player.
///
/// - Parameter note: The notification information.
@objc fileprivate func audioSessionMessedUp(note: NSNotification) {
eventListener?.onEvent(PlayerEvent.sessionMessedUp, generetedBy: self)
}
/// Playing item did end. We can play next or stop the player if queue is empty.
///
/// - Parameter note: The notification information.
@objc fileprivate func playerItemDidEnd(note: NSNotification) {
eventListener?.onEvent(PlayerEvent.endedPlaying(nil), generetedBy: self)
}
}
| mit | 0354de0b887216589cf6453e44aaa6e9 | 40.291513 | 120 | 0.643878 | 5.144828 | false | false | false | false |
raspu/Highlightr | Pod/Classes/Highlightr.swift | 1 | 8355 | //
// Highlightr.swift
// Pods
//
// Created by Illanes, J.P. on 4/10/16.
//
//
import Foundation
import JavaScriptCore
#if os(OSX)
import AppKit
#endif
/// Utility class for generating a highlighted NSAttributedString from a String.
open class Highlightr
{
/// Returns the current Theme.
open var theme : Theme!
{
didSet
{
themeChanged?(theme)
}
}
/// This block will be called every time the theme changes.
open var themeChanged : ((Theme) -> Void)?
/// Defaults to `false` - when `true`, forces highlighting to finish even if illegal syntax is detected.
open var ignoreIllegals = false
private let hljs: JSValue
private let bundle : Bundle
private let htmlStart = "<"
private let spanStart = "span class=\""
private let spanStartClose = "\">"
private let spanEnd = "/span>"
private let htmlEscape = try! NSRegularExpression(pattern: "&#?[a-zA-Z0-9]+?;", options: .caseInsensitive)
/**
Default init method.
- parameter highlightPath: The path to `highlight.min.js`. Defaults to `Highlightr.framework/highlight.min.js`
- returns: Highlightr instance.
*/
public init?(highlightPath: String? = nil)
{
let jsContext = JSContext()!
let window = JSValue(newObjectIn: jsContext)
jsContext.setObject(window, forKeyedSubscript: "window" as NSString)
#if SWIFT_PACKAGE
let bundle = Bundle.module
#else
let bundle = Bundle(for: Highlightr.self)
#endif
self.bundle = bundle
guard let hgPath = highlightPath ?? bundle.path(forResource: "highlight.min", ofType: "js") else
{
return nil
}
let hgJs = try! String.init(contentsOfFile: hgPath)
let value = jsContext.evaluateScript(hgJs)
if value?.toBool() != true
{
return nil
}
guard let hljs = window?.objectForKeyedSubscript("hljs") else
{
return nil
}
self.hljs = hljs
guard setTheme(to: "pojoaque") else
{
return nil
}
}
/**
Set the theme to use for highlighting.
- parameter to: Theme name
- returns: true if it was possible to set the given theme, false otherwise
*/
@discardableResult
open func setTheme(to name: String) -> Bool
{
guard let defTheme = bundle.path(forResource: name+".min", ofType: "css") else
{
return false
}
let themeString = try! String.init(contentsOfFile: defTheme)
theme = Theme(themeString: themeString)
return true
}
/**
Takes a String and returns a NSAttributedString with the given language highlighted.
- parameter code: Code to highlight.
- parameter languageName: Language name or alias. Set to `nil` to use auto detection.
- parameter fastRender: Defaults to true - When *true* will use the custom made html parser rather than Apple's solution.
- returns: NSAttributedString with the detected code highlighted.
*/
open func highlight(_ code: String, as languageName: String? = nil, fastRender: Bool = true) -> NSAttributedString?
{
let ret: JSValue
if let languageName = languageName
{
ret = hljs.invokeMethod("highlight", withArguments: [languageName, code, ignoreIllegals])
}else
{
// language auto detection
ret = hljs.invokeMethod("highlightAuto", withArguments: [code])
}
let res = ret.objectForKeyedSubscript("value")
guard var string = res!.toString() else
{
return nil
}
var returnString : NSAttributedString?
if(fastRender)
{
returnString = processHTMLString(string)!
}else
{
string = "<style>"+theme.lightTheme+"</style><pre><code class=\"hljs\">"+string+"</code></pre>"
let opt: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
let data = string.data(using: String.Encoding.utf8)!
safeMainSync
{
returnString = try? NSMutableAttributedString(data:data, options: opt, documentAttributes:nil)
}
}
return returnString
}
/**
Returns a list of all the available themes.
- returns: Array of Strings
*/
open func availableThemes() -> [String]
{
let paths = bundle.paths(forResourcesOfType: "css", inDirectory: nil) as [NSString]
var result = [String]()
for path in paths {
result.append(path.lastPathComponent.replacingOccurrences(of: ".min.css", with: ""))
}
return result
}
/**
Returns a list of all supported languages.
- returns: Array of Strings
*/
open func supportedLanguages() -> [String]
{
let res = hljs.invokeMethod("listLanguages", withArguments: [])
return res!.toArray() as! [String]
}
/**
Execute the provided block in the main thread synchronously.
*/
private func safeMainSync(_ block: @escaping ()->())
{
if Thread.isMainThread
{
block()
}else
{
DispatchQueue.main.sync { block() }
}
}
private func processHTMLString(_ string: String) -> NSAttributedString?
{
let scanner = Scanner(string: string)
scanner.charactersToBeSkipped = nil
var scannedString: NSString?
let resultString = NSMutableAttributedString(string: "")
var propStack = ["hljs"]
while !scanner.isAtEnd
{
var ended = false
if scanner.scanUpTo(htmlStart, into: &scannedString)
{
if scanner.isAtEnd
{
ended = true
}
}
if scannedString != nil && scannedString!.length > 0 {
let attrScannedString = theme.applyStyleToString(scannedString! as String, styleList: propStack)
resultString.append(attrScannedString)
if ended
{
continue
}
}
scanner.scanLocation += 1
let string = scanner.string as NSString
let nextChar = string.substring(with: NSMakeRange(scanner.scanLocation, 1))
if(nextChar == "s")
{
scanner.scanLocation += (spanStart as NSString).length
scanner.scanUpTo(spanStartClose, into:&scannedString)
scanner.scanLocation += (spanStartClose as NSString).length
propStack.append(scannedString! as String)
}
else if(nextChar == "/")
{
scanner.scanLocation += (spanEnd as NSString).length
propStack.removeLast()
}else
{
let attrScannedString = theme.applyStyleToString("<", styleList: propStack)
resultString.append(attrScannedString)
scanner.scanLocation += 1
}
scannedString = nil
}
let results = htmlEscape.matches(in: resultString.string,
options: [.reportCompletion],
range: NSMakeRange(0, resultString.length))
var locOffset = 0
for result in results
{
let fixedRange = NSMakeRange(result.range.location-locOffset, result.range.length)
let entity = (resultString.string as NSString).substring(with: fixedRange)
if let decodedEntity = HTMLUtils.decode(entity)
{
resultString.replaceCharacters(in: fixedRange, with: String(decodedEntity))
locOffset += result.range.length-1;
}
}
return resultString
}
}
| mit | e1ce7899638d1de3f0f8c0871b205abd | 29.944444 | 130 | 0.558229 | 4.991039 | false | false | false | false |
swixbase/multithreading | Sources/Multithreading/PSXThreadPool.swift | 1 | 7018 | /// Copyright 2017 Sergei Egorov
///
/// 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
public class PSXThreadPool {
/// Scheduler for assign jobs between threads.
fileprivate var scheduler: PSXScheduler?
/// The worker threads.
fileprivate var workerThreads: [Int: PSXWorkerThread] = [:]
/// The keys with which the user created threads.
fileprivate var userThreadsKeys: [AnyHashable: Int] = [:]
/// Mutex for waiting to complete all jobs from the global queue.
fileprivate let jobsMutex = PSXMutex()
/// Mutex for get (alive, waiting, working, paused) threads.
fileprivate let threadsMutex = PSXMutex()
/// Prefix for threads name.
internal var prefix = "com.swixbase.multithreading"
/// Global jobs queue.
internal let globalQueue = PSXJobQueue()
/// Condition variable for get notification when all jobs from global queue are complete.
internal let jobsHasFinished = PSXCondition()
/// The status of waiting for the completion of all jobs from the global queue.
internal var waiting = false
// TODO: - NEW
public var autopause = false
public var autocreate = false
public var maxThreadsCount = 50
public var minThreadsCount = 1
public var threadsInactivityTime = 300
fileprivate var _maxPrivateJobs = 5
public var maxPrivateJobsCount: Int {
get {
if autocreate == true {
return _maxPrivateJobs
} else {
return Int.max
}
}
set {
if autocreate == true {
_maxPrivateJobs = newValue
}
}
}
/// Returns alive worker threads in pool.
public var aliveThreads: [PSXWorkerThread] {
threadsMutex.lock()
let alive = workerThreads.filter{ $0.value.status != .inactive }.map{ $0.value }
threadsMutex.unlock()
return alive
}
/// Returns the worker threads that are waiting for jobs.
public var waitingThreads: [PSXWorkerThread] {
threadsMutex.lock()
let waiting = workerThreads.filter{ $0.value.status == .waiting }.map{ $0.value }
threadsMutex.unlock()
return waiting
}
/// Returns the worker threads that are currently working.
public var workingThreads: [PSXWorkerThread] {
threadsMutex.lock()
let working = workerThreads.filter{ $0.value.status == .working }.map{ $0.value }
threadsMutex.unlock()
return working
}
/// Returns the worker threads that are currently paused.
public var pausedThreads: [PSXWorkerThread] {
threadsMutex.lock()
let working = workerThreads.filter{ $0.value.status == .paused }.map{ $0.value }
threadsMutex.unlock()
return working
}
/// Returns the default singleton instance.
private static let _default = PSXThreadPool(count: 1)
public class var `default`: PSXThreadPool {
return _default
}
/// Initialization
///
/// Parameter count: The number of threads with which the thread pool will be initialized.
///
public convenience init(count: Int) {
self.init()
createThreads(count)
while aliveThreads.count != count {}
scheduler = PSXScheduler(forPool: self)
}
deinit { destroy() }
}
extension PSXThreadPool {
/// Creates a certain number of threads.
///
/// Parameter count: The number of threads to create.
///
fileprivate func createThreads(_ count: Int) {
for _ in 0 ..< count { createThread() }
}
/// Creates new thread.
/// Returns the key of the created thread from the worker threads array.
///
@discardableResult
fileprivate func createThread() -> Int {
let id = workerThreads.count
let thread = PSXWorkerThread(pool: self, id: id)
let name = "\(prefix).psxthread-\(id)"
thread.name = name
workerThreads[id] = thread
thread.start()
return id
}
/// Creates new thread.
///
@discardableResult
public func newThread() -> PSXThread {
let id = createThread()
let thread = workerThreads[id]
return thread!
}
/// Creates thread with specified key.
///
/// Parameter key: The key with which the thread will be created.
///
@discardableResult
public func newThread(forKey key: AnyHashable) -> PSXThread {
let id = createThread()
userThreadsKeys[key] = id
let thread = workerThreads[id]
return thread!
}
/// Returns user thread, if exists. Otherwise returns nil.
///
/// Parameter key: The key with which the thread is associated.
///
public func getThread(forKey key: AnyHashable) -> PSXThread? {
guard let id = userThreadsKeys[key], let thread = workerThreads[id] else {
return nil
}
return thread
}
/// Destroys user thread, if exists.
///
/// Parameter key: The key with which the thread is associated.
///
public func destroyThread(forKey key: AnyHashable) {
guard let id = userThreadsKeys[key], let thread = workerThreads.removeValue(forKey: id) else {
return
}
thread.cancel()
}
}
extension PSXThreadPool {
/// Adds job to the thread pool.
///
/// - Parameter block: A block of code that will be performed.
///
public func addJob(_ block: @escaping () -> Void) {
let job = PSXJob(block: block)
globalQueue.put(newJob: job, priority: .normal)
}
}
extension PSXThreadPool {
/// Waits until all jobs from global queue have finished.
///
public func wait() {
jobsMutex.lock()
waiting = true
while globalQueue.jobsCount > 0 || workingThreads.count > 0 {
jobsHasFinished.wait(mutex: jobsMutex)
}
waiting = false
jobsMutex.unlock()
}
/// Terminates all worker threads, and scheduler threads.
///
internal func destroy() {
for worker in workerThreads { worker.value.cancel() }
if let sh = scheduler { sh.destroy() }
}
}
| apache-2.0 | 6f4b606649e4ea5ca7efcf55b062f457 | 29.191111 | 102 | 0.597606 | 4.653846 | false | false | false | false |
mercadopago/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/Identification.swift | 1 | 1078 | //
// Identification.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 28/12/14.
// Copyright (c) 2014 com.mercadopago. All rights reserved.
//
import Foundation
public class Identification : NSObject {
public var type : String?
public var number : String?
public override init() {
super.init()
}
public init (type: String?, number : String?) {
super.init()
self.type = type
self.number = number
}
public class func fromJSON(json : NSDictionary) -> Identification {
let identification : Identification = Identification()
identification.type = JSON(json["type"]!).asString
identification.number = JSON(json["number"]!).asString
return identification
}
public func toJSONString() -> String {
let obj:[String:AnyObject] = [
"type": String.isNullOrEmpty(self.type) ? JSON.null : self.type!,
"number": String.isNullOrEmpty(self.number) ? JSON.null : self.number!
]
return JSON(obj).toString()
}
} | mit | 27458ef2f6f9c9063fe1eb59d56e6589 | 26.666667 | 82 | 0.613173 | 4.382114 | false | false | false | false |
breadwallet/breadwallet-ios | breadwalletWidget/Services/ImageStorageService.swift | 1 | 3307 | //
// ImageStorageService.swift
// breadwalletWidgetExtension
//
// Created by stringcode on 18/02/2021.
// Copyright © 2021 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
protocol ImageStoreService: class {
func loadImagesIfNeeded()
func bgFolder() -> URL
func noBgFolder() -> URL
func imageFolder() -> URL
}
// MARK: - DefaultImageStoreService
class DefaultImageStoreService: ImageStoreService {
func loadImagesIfNeeded() {
guard needsToRefreshImages() else {
return
}
guard let tarURL = Bundle.main.url(forResource: Constant.tokensFileName,
withExtension: "tar") else {
return
}
let fileManager = FileManager.default
if fileManager.fileExists(atPath: imageFolder().path) {
try? fileManager.removeItem(at: imageFolder())
}
try? BRTar.createFilesAndDirectoriesAtPath(imageFolder().path,
withTarPath: tarURL.path)
markFilesExtracted()
}
func bgFolder() -> URL {
return DefaultImageStoreService.bgFolder
}
func noBgFolder() -> URL {
return DefaultImageStoreService.noBgFolder
}
func imageFolder() -> URL {
return DefaultImageStoreService.imageFolder
}
}
// MARK: - Utilities
private extension DefaultImageStoreService {
func needsToRefreshImages() -> Bool {
let defautls = UserDefaults.standard
let lastVersion = defautls.string(forKey: Constant.refreshedVersionKey) ?? ""
return lastVersion != currentVersionString() && isRunningInWidgetExtension()
}
func markFilesExtracted() {
UserDefaults.standard.set(currentVersionString(),
forKey: Constant.refreshedVersionKey)
UserDefaults.standard.synchronize()
}
func isRunningInWidgetExtension() -> Bool {
return Bundle.main.bundleIdentifier?.contains("breadwalletWidget") ?? false
}
func currentVersionString() -> String {
var versionString = Bundle.main.releaseVersionNumber ?? ""
versionString += " - "
versionString += Bundle.main.buildVersionNumber ?? ""
return versionString
}
static var bgFolder: URL {
return imageFolder.appendingPathComponent(Constant.bgFolder)
}
static var noBgFolder: URL {
return imageFolder.appendingPathComponent(Constant.noBgFolder)
}
static var imageFolder: URL {
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory,
in: .userDomainMask)[0]
return documentsURL.appendingPathComponent(Constant.imageFolder)
}
}
// MARK: - Constants
private extension DefaultImageStoreService {
enum Constant {
static let refreshedVersionKey = "lastRefreshVersionKey"
static let tokensFileName = "brd-tokens"
static let imageFolder = "brd-tokens"
static let noBgFolder = "white-no-bg"
static let bgFolder = "white-square-bg"
}
}
| mit | 394a0f1afc390c83bc9abd07c98b1a9e | 28.517857 | 85 | 0.624319 | 5.086154 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCIReadClockOffset.swift | 1 | 2310 | //
// HCIReadClockOffset.swift
// Bluetooth
//
// Created by Carlos Duclos on 8/8/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
// MARK: - Method
public extension BluetoothHostControllerInterface {
/// Read Clock Offset Command
///
/// Both the System Clock and the clock offset to a remote device are used to determine what hopping frequency is used by a remote device for page scan. This command allows the Host to read clock offset to remote devices. The clock offset can be used to speed up the paging procedure when the local device tries to establish a connection to a remote device, for example, when the local Host has issued Create_Connection or Remote_Name_Request. The Connection_Handle must be a Connection_Handle for an ACL connection.
func readClockOffset(handle: UInt16,
timeout: HCICommandTimeout = .default) async throws -> HCIReadClockOffsetComplete.ClockOffset {
let completeEvent = HCIReadClockOffset(handle: handle)
return try await deviceRequest(completeEvent,
HCIReadClockOffsetComplete.self,
timeout: timeout).clockOffset
}
}
// MARK: - Command
/// Read Clock Offset Command
///
/// Both the System Clock and the clock offset to a remote device are used to determine what hopping frequency is used by a remote device for page scan. This command allows the Host to read clock offset to remote devices. The clock offset can be used to speed up the paging procedure when the local device tries to establish a connection to a remote device, for example, when the local Host has issued Create_Connection or Remote_Name_Request. The Connection_Handle must be a Connection_Handle for an ACL connection.
@frozen
public struct HCIReadClockOffset: HCICommandParameter {
public static let command = LinkControlCommand.readClockOffset
/// Specifies which Connection_Handle’s LMP-supported features list to get.
public var handle: UInt16
public init(handle: UInt16) {
self.handle = handle
}
public var data: Data {
let handleBytes = handle.littleEndian.bytes
return Data([handleBytes.0, handleBytes.1])
}
}
| mit | 6d9c48f53ef2f48dbbddb4d197951e06 | 42.528302 | 520 | 0.704811 | 4.786307 | false | false | false | false |
tardieu/swift | test/Interpreter/SDK/NSDecimal.swift | 14 | 3006 | // RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
enum NSDecimalResult: ExpressibleByStringLiteral, Equatable, CustomStringConvertible {
case Some(Decimal)
case Error(Decimal.CalculationError)
init() {
self = .Some(Decimal())
}
init(stringLiteral: String) {
if let value = Decimal(string: stringLiteral) {
self = .Some(value)
} else {
self = .Error(.lossOfPrecision)
}
}
init(unicodeScalarLiteral: String) {
self.init(stringLiteral: unicodeScalarLiteral)
}
init(extendedGraphemeClusterLiteral: String) {
self.init(stringLiteral: extendedGraphemeClusterLiteral)
}
var description: String {
switch self {
case .Some(var decimal):
return NSDecimalString(&decimal, nil)
case .Error:
return "NaN"
}
}
func pow10(_ power: Int) -> NSDecimalResult {
switch self {
case .Some(var decimal):
var result = Decimal()
let error = NSDecimalMultiplyByPowerOf10(&result, &decimal, Int16(power),
.plain)
if error != .noError {
return .Error(error)
} else {
return .Some(result)
}
case .Error:
return self
}
}
}
func ==(x: NSDecimalResult, y: NSDecimalResult) -> Bool {
switch (x, y) {
case var (.Some(x1), .Some(x2)):
return NSDecimalCompare(&x1, &x2) == .orderedSame
default:
return false
}
}
func +(x: NSDecimalResult, y: NSDecimalResult) -> NSDecimalResult {
switch (x, y) {
case var (.Some(x1), .Some(y1)):
var result = Decimal()
let error = NSDecimalAdd(&result, &x1, &y1, .plain)
if error != .noError {
return .Error(error)
} else {
return .Some(result)
}
case let (.Error(error), _):
return .Error(error)
case let (_, .Error(error)):
return .Error(error)
// FIXME rdar://problem/19165412
default:
fatalError("impossible")
}
}
let zero = NSDecimalResult()
print(zero) // CHECK: 0
let two: NSDecimalResult = "1" + "1"
print(two) // CHECK: 2
let point95: NSDecimalResult = "0.8" + "0.1" + "0.05"
print(point95) // CHECK: 0.95
let twoAgain = point95 + "1.05"
print(twoAgain) // CHECK: 2
print(two == twoAgain) // CHECK: true
print(two + "not a number") // CHECK: NaN
print(two + "not a number" == "still not a number") // CHECK: false
print(two + "not a number" == two) // CHECK: false
let one: NSDecimalResult = "1"
print(one.pow10(2)) // CHECK: 100
print(one.pow10(-2)) // CHECK: 0.01
var twenty = Decimal(20)
var ten = Decimal(10)
twenty.multiply(by: ten)
print(twenty) // CHECK: 200
twenty = Decimal(20)
ten = Decimal(10)
twenty.divide(by: ten)
print(twenty) // CHECK: 2
twenty = NSDecimalNumber(mantissa: 2, exponent: 1, isNegative: false) as Decimal
print(twenty.significand) // CHECK: 2
print(twenty.exponent) // CHECK: 1
print(twenty.ulp) // CHECK: 10
print(Decimal(sign: .plus, exponent: -2, significand: 100)) // CHECK: 1
| apache-2.0 | f3b7bc9a59a8c2069b5f556a4a421c38 | 22.857143 | 86 | 0.630073 | 3.487239 | false | false | false | false |
garyshirk/ThriftStoreLocator1 | ThriftStoreLocator/DropMenuButton.swift | 1 | 6119 | //
// DropMenuButton.swift
// DropDownMenu
//
// Created by Marcos Paulo Rodrigues Castro on 9/1/16.
// Copyright © 2016 HackTech. All rights reserved.
//
//import UIKit
//
//class DropMenuButton: UIButton, UITableViewDelegate, UITableViewDataSource
//{
// var items = [String]()
// var table = UITableView()
// var act = [() -> (Void)]()
//
// var superSuperView = UIView()
//
// func initTitle(to title: String) {
// self.setTitle(title, for: UIControlState())
// self.setTitle(title, for: UIControlState.highlighted)
// self.setTitle(title, for: UIControlState.selected)
// }
//
// func showItems()
// {
//
// fixLayout()
//
// if(table.alpha == 0)
// {
// self.layer.zPosition = 1
// UIView.animate(withDuration: 0.3
// , animations: {
// self.table.alpha = 1;
// })
//
// }
//
// else
// {
//
// UIView.animate(withDuration: 0.3
// , animations: {
// self.table.alpha = 0;
// self.layer.zPosition = 0
// })
//
// }
//
// }
//
//
// func initMenu(_ items: [String], actions: [() -> (Void)])
// {
// self.items = items
// self.act = actions
//
// var resp = self as UIResponder
//
// while !(resp.isKind(of: UIViewController.self) || (resp.isKind(of: UITableViewCell.self))) && resp.next != nil
// {
// resp = resp.next!
//
// }
//
// if let vc = resp as? UIViewController{
// superSuperView = vc.view
// }
// else if let vc = resp as? UITableViewCell{
// superSuperView = vc
// }
//
// table = UITableView()
// table.rowHeight = self.frame.height
// table.delegate = self
// table.dataSource = self
// table.isUserInteractionEnabled = true
// table.alpha = 0
// table.separatorColor = self.backgroundColor
// superSuperView.addSubview(table)
// self.addTarget(self, action:#selector(DropMenuButton.showItems), for: .touchUpInside)
//
// //table.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "cell")
//
// }
//
// func initMenu(_ items: [String])
// {
// self.items = items
//
// var resp = self as UIResponder
//
// while !(resp.isKind(of: UIViewController.self) || (resp.isKind(of: UITableViewCell.self))) && resp.next != nil
// {
// resp = resp.next!
//
// }
//
// if let vc = resp as? UIViewController{
//
// superSuperView = vc.view
// }
// else if let vc = resp as? UITableViewCell{
//
// superSuperView = vc
//
// }
//
// table = UITableView()
// table.rowHeight = self.frame.height
// table.delegate = self
// table.dataSource = self
// table.isUserInteractionEnabled = true
// table.alpha = 0
// table.separatorColor = self.backgroundColor
// superSuperView.addSubview(table)
// self.addTarget(self, action:#selector(DropMenuButton.showItems), for: .touchUpInside)
//
// //table.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "cell")
//
// }
//
//
// func fixLayout()
// {
//
// let auxPoint2 = superSuperView.convert(self.frame.origin, from: self.superview)
//
// var tableFrameHeight = CGFloat()
//
// if (items.count >= 3){
// tableFrameHeight = self.frame.height * CGFloat(items.count)
// }else{
//
// tableFrameHeight = self.frame.height * CGFloat(items.count)
// }
// table.frame = CGRect(x: auxPoint2.x, y: auxPoint2.y + self.frame.height, width: self.frame.width, height:tableFrameHeight)
// table.rowHeight = self.frame.height
//
// table.reloadData()
//
// }
//
//
// override func layoutSubviews() {
// super.layoutSubviews()
//
// self.setNeedsDisplay()
// fixLayout()
//
//
// }
//
// func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
// {
// return items.count
// }
//
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
// {
//
// self.setTitle(items[(indexPath as NSIndexPath).row], for: UIControlState())
// self.setTitle(items[(indexPath as NSIndexPath).row], for: UIControlState.highlighted)
// self.setTitle(items[(indexPath as NSIndexPath).row], for: UIControlState.selected)
//
// if self.act.count > 1
// {
// self.act[indexPath.row]()
// }
//
// showItems()
//
// }
//
//
// func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
// {
//
// let itemLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
// itemLabel.textAlignment = NSTextAlignment.center
// itemLabel.text = items[(indexPath as NSIndexPath).row]
// itemLabel.font = self.titleLabel?.font
// itemLabel.textColor = self.backgroundColor
//
// let bgColorView = UIView()
// bgColorView.backgroundColor = UIColor.blue
//
// let cell = UITableViewCell(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
// cell.backgroundColor = self.titleLabel?.textColor
// cell.selectedBackgroundView = bgColorView
// cell.separatorInset = UIEdgeInsetsMake(0, self.frame.width, 0, self.frame.width)
// cell.addSubview(itemLabel)
//
//
// return cell
// }
//
//}
| mit | 6dc2c814e07db6c0ad40c628e2097bc3 | 29.743719 | 132 | 0.524027 | 3.869703 | false | false | false | false |
Reality-Virtually-Hackathon/Team-2 | WorkspaceAR/Additional View Controllers/VirtualObjectSelection.swift | 1 | 6612 | /*
See LICENSE folder for this sample’s licensing information.
Abstract:
Popover view controller for choosing virtual objects to place in the AR scene.
*/
import UIKit
// MARK: - ObjectCell
class ObjectCell: UITableViewCell {
static let reuseIdentifier = "ObjectCell"
@IBOutlet weak var objectTitleLabel: UILabel!
@IBOutlet weak var objectImageView: UIImageView!
var modelName = "" {
didSet {
objectTitleLabel.text = modelName.capitalized
objectImageView.image = UIImage(named: modelName)
}
}
}
class ObjectCellSub: UITableViewCell {
static let reuseIdentifier = "ObjectCellSub"
@IBOutlet weak var objectTitleLabel: UILabel!
@IBOutlet weak var objectImageView: UIImageView!
var titleText = ""{
didSet {
objectTitleLabel.text = titleText.capitalized
}
}
var imageName = "" {
didSet {
objectImageView.image = UIImage(named: imageName)
}
}
}
// MARK: - VirtualObjectSelectionViewControllerDelegate
/// A protocol for reporting which objects have been selected.
protocol VirtualObjectSelectionViewControllerDelegate: class {
func virtualObjectSelectionViewController(_ selectionViewController: VirtualObjectSelectionViewController, didSelectObject: SharedARObjectDescriptor)
func virtualObjectSelectionViewController(_ selectionViewController: VirtualObjectSelectionViewController, didDeselectObject: SharedARObjectDescriptor)
}
/// A custom table view controller to allow users to select `VirtualObject`s for placement in the scene.
class VirtualObjectSelectionViewController: UITableViewController {
/// The collection of `VirtualObject`s to select from.
var sharedObjectDescriptors = [SharedARObjectDescriptor]()
/// The rows of the currently selected `VirtualObject`s.
var selectedVirtualObjectRows = IndexSet()
var objectSelector = UISegmentedControl()
weak var delegate: VirtualObjectSelectionViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.view.layoutIfNeeded()
tableView.separatorEffect = UIVibrancyEffect(blurEffect: UIBlurEffect(style: .light))
objectSelector.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30)
objectSelector.insertSegment(withTitle: "Learn", at: 0, animated: false)
objectSelector.insertSegment(withTitle: "Play", at: 1, animated: false)
objectSelector.insertSegment(withTitle: "Build", at: 2, animated: false)
self.tableView.tableHeaderView = objectSelector
objectSelector.selectedSegmentIndex = DataManager.shared().lastSelectedObjectSet
objectSelector.tintColor = UIColor.black
objectSelector.addTarget(self, action: #selector(newObjectSetClicked(sender:)), for: .valueChanged)
}
@objc func newObjectSetClicked(sender: UISegmentedControl){
let newValue = sender.selectedSegmentIndex
switch newValue {
case 0:
sharedObjectDescriptors = DataManager.shared().solarSystemObjects
case 1:
sharedObjectDescriptors = DataManager.shared().chessObjects
case 2:
sharedObjectDescriptors = DataManager.shared().constructionObjects
default:
sharedObjectDescriptors = DataManager.shared().solarSystemObjects
}
DataManager.shared().lastSelectedObjectSet = newValue
tableView.reloadData()
}
override func viewWillLayoutSubviews() {
preferredContentSize = CGSize(width: 300, height: tableView.contentSize.height)
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let maxWidth = self.view.frame.width - 60
let font = UIFont(name: "Avenir-Book", size: 16)
let objectRep = sharedObjectDescriptors[indexPath.row]
var text = ""
if objectRep.description != ""{
text = "\(objectRep.name) - \(objectRep.description)"
}else{
text = "\(objectRep.name)"
}
let label = UILabel()
label.font = font
label.text = text
label.numberOfLines = 0
let size = label.sizeThatFits(CGSize(width: maxWidth, height: .greatestFiniteMagnitude))
return size.height + 10
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let object = sharedObjectDescriptors[indexPath.row]
// Check if the current row is already selected, then deselect it.
if selectedVirtualObjectRows.contains(indexPath.row) {
delegate?.virtualObjectSelectionViewController(self, didDeselectObject: object)
} else {
delegate?.virtualObjectSelectionViewController(self, didSelectObject: object)
}
dismiss(animated: true, completion: nil)
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sharedObjectDescriptors.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ObjectCellSub.reuseIdentifier, for: indexPath) as? ObjectCellSub else {
fatalError("Expected `\(ObjectCell.self)` type for reuseIdentifier \(ObjectCell.reuseIdentifier). Check the configuration in Main.storyboard.")
}
let objectRep = sharedObjectDescriptors[indexPath.row]
var text = ""
if objectRep.description != ""{
text = "\(objectRep.name) - \(objectRep.description)"
}else{
text = "\(objectRep.name)"
}
cell.titleText = text
cell.imageName = objectRep.modelName
if selectedVirtualObjectRows.contains(indexPath.row) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
override func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
}
override func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
cell?.backgroundColor = .clear
}
}
| mit | 18fc7e6d01c6f6e5404c9fbf1d3410c1 | 37.208092 | 155 | 0.679728 | 5.322061 | false | false | false | false |
kevintavog/WatchThis | Source/WatchThis/SlideshowListProvider.swift | 1 | 3912 | //
//
import AppKit
import Foundation
import RangicCore
protocol SlideshowListProviderDelegate
{
func wantToSaveEditedSlideshow() -> WtButtonId
func saveSlideshow(_ slideshow: SlideshowData) -> Bool
}
class SlideshowListProvider
{
var savedSlideshows = [SlideshowData]()
var editedSlideshow = SlideshowData()
var delegate: SlideshowListProviderDelegate? = nil
init()
{
if FileManager.default.fileExists(atPath: Preferences.lastEditedFilename) {
do {
editedSlideshow = try SlideshowData.load(Preferences.lastEditedFilename)
} catch let error {
Logger.error("Error loading last edited: \(error)")
}
}
}
/// Starts enumerating saved slideshows - this is a blocking call. Fires the
/// SlideshowListProvider.EnumerationCompleted notification on completion
func findSavedSlideshows()
{
var foundSlideshows = [SlideshowData]()
if FileManager.default.fileExists(atPath: Preferences.slideshowFolder) {
if let urlList = getFiles(Preferences.slideshowFolder) {
for url in urlList {
do {
let slideshowData = try SlideshowData.load(url.path)
foundSlideshows.append(slideshowData)
}
catch let error {
Logger.error("Failed loading \(error)")
}
}
}
}
savedSlideshows = foundSlideshows
Notifications.postNotification(Notifications.SlideshowListProvider.EnumerationCompleted, object: self, userInfo: nil)
}
func canClose() -> Bool
{
// If it hasn't been saved yet, save it as the lastEdited so it can be loaded on the next run.
if editedSlideshow.filename == nil {
editedSlideshow.filename = Preferences.lastEditedFilename
editedSlideshow.name = ""
do {
try editedSlideshow.save()
} catch let error as NSError {
Logger.error("Error saving last edited: \(error)")
}
editedSlideshow.filename = nil
return true
}
return saveIfChanged()
}
// If the editedSlideshow has changes, ask the user if they want to save changes. Returns true
// if the caller can continue, false otherwise.
// True is returned if
// 1) There are no changes to editedSlideshow - or there aren't 'worthwhile' changes
// 2) The user does NOT want to save
// 3) The user wants to save and the save succeeds
// False is returned if there are worthwhile changes and:
// 1) The user canceled the 'want to save' question
// 2) The user canceled the request for the save name
// 3) The save failed
fileprivate func saveIfChanged() -> Bool
{
if editedSlideshow.hasChanged && editedSlideshow.folderList.count > 0 {
let response = delegate?.wantToSaveEditedSlideshow()
switch response! {
case .cancel:
return false
case .no:
return true
case .yes:
return (delegate?.saveSlideshow(editedSlideshow))!
default:
return false
}
}
return true
}
fileprivate func getFiles(_ folderName:String) -> [URL]?
{
do {
let urlList = try FileManager.default.contentsOfDirectory(
at: URL(fileURLWithPath: folderName),
includingPropertiesForKeys: nil,
options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
return urlList.filter( {
return $0.pathExtension == Preferences.SlideshowFileExtension
})
}
catch {
return nil
}
}
}
| mit | 7c676d6f7415970a0d1c108e6c6537a3 | 31.6 | 125 | 0.58998 | 5.140604 | false | false | false | false |
kalvish21/AndroidMessenger | AndroidMessengerMacDesktopClient/AndroidMessenger/Classes/NSImageView-Extension.swift | 1 | 858 | //
// NSImage-Extension.swift
// AndroidMessenger
//
// Created by Kalyan Vishnubhatla on 8/21/16.
// Copyright © 2016 Kalyan Vishnubhatla. All rights reserved.
//
import Cocoa
import Foundation
import AsyncImageDownloaderOSX
extension NSImageView {
func loadImageFromUrl(url: String) {
let image: NSImage? = NSImage.loadImageForUrl(url)
if image != nil {
self.wantsLayer = true
self.layer!.borderColor = NSColor.blueColor().CGColor
self.image = image
return
}
// Download if the image was not cached
AsyncImageDownloader.init(mediaURL: url, successBlock: { (image) in
image.saveImageInCache(url)
self.image = image
}, failBlock: { (error) in
NSLog("%@", error)
}).startDownload()
}
}
| mit | ca2d2c6f335a7a8e2f83616f5b764a3b | 25.78125 | 75 | 0.6021 | 4.486911 | false | false | false | false |
ImperialCollegeDocWebappGroup/webappProject | webapp/ToppingsScrollVC.swift | 1 | 12645 | //
// ScroolVC.swift
// webapp
//
// Created by Timeless on 07/06/2015.
// Copyright (c) 2015 Shan, Jinyi. All rights reserved.
//
import UIKit
class ToppingsScrollVC: UIViewController, UIScrollViewDelegate {
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var pageControl: UIPageControl!
var pageImages: [UIImage?] = []
var pageViews: [UIImageView?] = []
var topss:[NSString] = []
var imgURLs: [String] = []
let link1 : String = "http://www.doc.ic.ac.uk/~jl6613/"
let link : String = "http://www.doc.ic.ac.uk/~jl6613/"
let fileName : String = "serverIp.txt"
var serverIp : String = ""
var str2 = ""
override func viewDidLoad() {
super.viewDidLoad()
// need to load images from DB
pageImages = []
let reallink = link + fileName
let url = NSURL(string: reallink)
if let data1 = NSData(contentsOfURL: url!) {
println("!!!!!")
var datastring = NSString(data:data1, encoding:NSUTF8StringEncoding) as! String
println(datastring)
serverIp = datastring
}
if (postToDB()) {
parseJson(str2)
}
let pageCount = pageImages.count
pageControl.currentPage = 0
pageControl.numberOfPages = pageCount
for _ in 0..<pageCount {
pageViews.append(nil)
}
let pagesScrollViewSize = scrollView.frame.size
scrollView.contentSize = CGSize(width: pagesScrollViewSize.width * CGFloat(pageImages.count),
height: pagesScrollViewSize.height)
loadVisiblePages()
}
func getServerIp() {
let reallink = link + fileName
let url = NSURL(string: reallink)
if let data1 = NSData(contentsOfURL: url!) {
println("!!!!!")
var datastring = NSString(data:data1, encoding:NSUTF8StringEncoding) as! String
println(datastring)
serverIp = datastring
}
}
func loadPage(page: Int) {
if page < 0 || page >= pageImages.count {
// If it's outside the range of what you have to display, then do nothing
return
}
if let pageView = pageViews[page] {
} else {
var frame = scrollView.bounds
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0.0
let newPageView = UIImageView(image: pageImages[page])
newPageView.contentMode = .ScaleAspectFit
newPageView.frame = frame
scrollView.addSubview(newPageView)
pageViews[page] = newPageView
}
}
func purgePage(page: Int) {
if page < 0 || page >= pageImages.count {
// If it's outside the range of display, do nothing
return
}
// Remove a page from the scroll view
// reset the container array
if let pageView = pageViews[page] {
pageView.removeFromSuperview()
pageViews[page] = nil
}
}
func loadVisiblePages() {
let pageWidth = scrollView.frame.size.width
let page = Int(floor((scrollView.contentOffset.x * 2.0 + pageWidth) / (pageWidth * 2.0)))
pageControl.currentPage = page
let firstPage = page - 1
let lastPage = page + 1
for var index = 0; index < firstPage; ++index {
purgePage(index)
}
for index in firstPage...lastPage {
loadPage(index)
}
for var index = lastPage+1; index < pageImages.count; ++index {
purgePage(index)
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
loadVisiblePages()
}
func postToDB() -> Bool {
println("posting")
// post user information to database
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let logname = (prefs.valueForKey("USERNAME") as! NSString as String)
var requestLine = "SELECT unnest(tops) FROM userprofile WHERE login = '" + logname + "';\n"
println(requestLine)
var client:TCPClient = TCPClient(addr: serverIp, port: 1111)
var (success,errmsg)=client.connect(timeout: 10)
if success{
println("Connection success!")
var (success,errmsg)=client.send(str: requestLine)
var i: Int = 0
var dd : Bool = false
while true {
if success && i < 10 {
println("sent success!")
var data=client.read(1024*10)
if let d = data {
if let str1 = NSString(bytes: d, length: d.count, encoding: NSUTF8StringEncoding) {
println("read success")
println(str1)
println("----")
var str = str1.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
println(str)
if (str == "ERROR") {
println("--ERROR")
client.close()
return false
} else if (str == "NOERROR"){ // NOERROR
println("--NOERROR")
(success,errmsg)=client.send(str: "GOOD\n")
} else if (str == "NOR") {
println("--NOR")
client.close()
return true
} else if (str == "YESR") {
println("--YESR")
dd = true
(success,errmsg)=client.send(str: "GOOD\n")
} else if dd && str.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) != 0 {
//data
println("this is data")
println(str)
str2 = str
return true
} else {
println("er...")
(success,errmsg)=client.send(str: "GOOD\n")
}
}
}
i+=1
} else {
client.close()
println(errmsg)
return false
}
}
}else{
client.close()
println(errmsg)
return false
}
}
func parseJson(str: NSString) {
println("===")
println(str)
var data: NSData = str.dataUsingEncoding(NSUTF8StringEncoding)!
var error1: NSError?
var jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &error1)
if let e = error1 {
println("Error: \(error1)")
}
topss = (jsonObject as! NSDictionary)["unnest"] as! [NSString]
let length = topss.count
pageImages = [UIImage?] (count: length, repeatedValue: nil)
for i in 0..<length {
println(topss[i])
pageImages[i] = loadImage(topss[i] as String, i:i)
}
}
func loadImage(str: String, i: Int) -> UIImage? {
var error_msg: String = ""
var invalidURL: Bool = false
var realURL = str
var imageURL = ""
if let myURL = NSURL(string: realURL) {
var error: NSError?
var myHTMLString = NSString(contentsOfURL: myURL, encoding: NSUTF8StringEncoding, error: &error)
if let error = error {
invalidURL = true
error_msg = "Your URL is not valid"
println("Error : \(error)")
return nil
} else {
// check the url is from selfridges.com
if realURL.rangeOfString("selfridges") == nil {
invalidURL = true
error_msg = "URL is not from selfridges.com"
return nil
} else {
// println("HTML : \(myHTMLString)")
println("success")
let altSearchTerm:String = "<div class=\"productImage\">"
let altScanner = NSScanner(string: myHTMLString! as String)
var altResult:NSString?
altScanner.scanUpToString(altSearchTerm, intoString:&altResult)
var len2 = altResult!.length
// println(len2)
var someString = (myHTMLString! as NSString).substringFromIndex(len2)
//println(someString)
let altSearchTerm2:String = "/>"
let altScanner2 = NSScanner(string: someString)
var altResult22:NSString?
altScanner.scanUpToString(altSearchTerm2, intoString:&altResult22)
// println(altResult22!)
let altSearchTerm222:String = "src=\""
let altScanner3 = NSScanner(string: altResult22! as String)
var altResult5:NSString?
altScanner3.scanUpToString(altSearchTerm222, intoString:&altResult5)
var len22 = altResult5!.length
//println(len22)
var someString2 = (altResult22! as NSString).substringFromIndex(len22+5)
//println(someString2)
let altSearchTerm3:String = "\""
let altScanner4 = NSScanner(string: someString2)
altScanner4.scanUpToString(altSearchTerm3, intoString:&altResult5)
println(altResult5!)
imageURL = altResult5! as String
}
}
} else {
return nil
}
let url = NSURL(string: imageURL)
if let data = NSData(contentsOfURL: url!) {
imgURLs.append(imageURL)
return UIImage(data: data)
} else {
imgURLs.append(imageURL)
return nil
}
}
@IBAction func shareTapped(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("shared", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "shared") {
println("topss count is \(topss.count)")
println(topss[0])
var width:CGFloat = scrollView.frame.size.width;
var page:NSInteger = NSInteger((scrollView.contentOffset.x + (0.5 * width)) / width);
println("top scroll current number is \(page)")
var svc = segue.destinationViewController as! SharingVC;
svc.webURL = topss[page] as String
svc.imgURL = imgURLs[page]
}
}
/*
let scrollView = UIScrollView(frame: CGRectMake(0, 0, 100, 100))
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * 3, scrollView.frame.size.height)
scrollView.delegate = self
let pageControl = UIPageControl(frame:CGRectMake(0, 90, scrollView.frame.size.width, 20))
pageControl.numberOfPages = Int(scrollView.contentSize.width / scrollView.frame.size.width)
pageControl.addTarget(self, action: Selector("changePage:"), forControlEvents: UIControlEvents.ValueChanged)
func changePage(sender: AnyObject) -> () {
let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
scrollView.setContentOffset(CGPointMake(x, 0), animated: true)
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) -> () {
let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width);
pageControl.currentPage = Int(pageNumber)
}
func changePage(sender: AnyObject) -> () {
if let page = sender.currentPage {
var frame:CGRect = scrollView.frame;
frame.origin.x = frame.size.width * CGFloat(page)
frame.origin.y = 0
scrollView.scrollRectToVisible(frame, animated: true)
}
}
*/
}
| gpl-3.0 | 7a4de363502fb60ff4d1e63957f27da7 | 35.973684 | 137 | 0.513484 | 5.109091 | false | false | false | false |
LeoMobileDeveloper/PullToRefreshKit | Sources/PullToRefreshKit/Classes/PullToRefresh.swift | 1 | 8657 | //
// PullToRefreshKit.swift
// PullToRefreshKit
//
// Created by huangwenchen on 16/7/11.
// I refer a lot logic for MJRefresh https://github.com/CoderMJLee/MJRefresh ,thanks to this lib and all contributors.
// Copyright © 2016年 Leo. All rights reserved.
import Foundation
import UIKit
import ObjectiveC
// MARK: - Header API -
@objc class AttachObject:NSObject{
init(closure:@escaping ()->()) {
onDeinit = closure
super.init()
}
var onDeinit:()->()
deinit {
onDeinit()
}
}
@objc public enum RefreshResult:Int{
case success = 200
case failure = 400
case none = 0
}
public enum HeaderRefresherState {
case refreshing //刷新中
case normal(RefreshResult,TimeInterval)//正常状态
case removed //移除
}
public extension UIScrollView{
func invalidateRefreshControls(){
let tags = [PullToRefreshKitConst.headerTag,
PullToRefreshKitConst.footerTag,
PullToRefreshKitConst.leftTag,
PullToRefreshKitConst.rightTag]
tags.forEach { (tag) in
let oldContain = self.viewWithTag(tag)
oldContain?.removeFromSuperview()
}
}
func configAssociatedObject(object:AnyObject){
guard objc_getAssociatedObject(object, &AssociatedObject.key) == nil else{
return;
}
let attach = AttachObject { [weak self] in
self?.invalidateRefreshControls()
}
objc_setAssociatedObject(object, &AssociatedObject.key, attach, .OBJC_ASSOCIATION_RETAIN)
}
}
struct AssociatedObject {
static var key:UInt8 = 0
static var footerBottomKey:UInt8 = 0
}
public extension UIScrollView{
func configRefreshHeader(with refrehser:UIView & RefreshableHeader = DefaultRefreshHeader.header(),
container object: AnyObject,
action:@escaping ()->()){
let oldContain = self.viewWithTag(PullToRefreshKitConst.headerTag)
oldContain?.removeFromSuperview()
let containFrame = CGRect(x: 0, y: -self.frame.height, width: self.frame.width, height: self.frame.height)
let containComponent = RefreshHeaderContainer(frame: containFrame)
if let endDuration = refrehser.durationOfHideAnimation?(){
containComponent.durationOfEndRefreshing = endDuration
}
containComponent.tag = PullToRefreshKitConst.headerTag
containComponent.refreshAction = action
self.addSubview(containComponent)
containComponent.delegate = refrehser
refrehser.autoresizingMask = [.flexibleWidth,.flexibleHeight]
let refreshHeight = refrehser.heightForHeader()
let bounds = CGRect(x: 0,y: containFrame.height - refreshHeight,width: self.frame.width,height: refreshHeight)
refrehser.frame = bounds
containComponent.addSubview(refrehser)
configAssociatedObject(object: object)
}
func switchRefreshHeader(to state:HeaderRefresherState){
let header = self.viewWithTag(PullToRefreshKitConst.headerTag) as? RefreshHeaderContainer
switch state {
case .refreshing:
header?.beginRefreshing()
case .normal(let result, let delay):
header?.endRefreshing(result,delay: delay)
case .removed:
header?.removeFromSuperview()
}
}
}
// MARK: - Footer API -
public enum FooterRefresherState {
case refreshing //刷新中
case normal //正常状态,转换到这个状态会结束刷新
case noMoreData //没有数据,转换到这个状态会结束刷新
case removed //移除
}
public extension UIScrollView{
/// Whether footer should stay at the bottom of tableView when cells count is small.
var footerAlwaysAtBottom:Bool{
get{
let object = objc_getAssociatedObject(self, &AssociatedObject.footerBottomKey)
guard let number = object as? NSNumber else {
return false
}
return number.boolValue
}set{
let number = NSNumber(value: newValue)
objc_setAssociatedObject(self, &AssociatedObject.footerBottomKey, number, .OBJC_ASSOCIATION_RETAIN)
guard let footerContainer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer else{
return;
}
footerContainer.handleContentSizeChange(nil)
}
}
func configRefreshFooter(with refrehser:UIView & RefreshableFooter = DefaultRefreshFooter.footer(),
container object: AnyObject,
action:@escaping ()->()){
let oldContain = self.viewWithTag(PullToRefreshKitConst.footerTag)
oldContain?.removeFromSuperview()
let containComponent = RefreshFooterContainer(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: refrehser.heightForFooter()))
containComponent.tag = PullToRefreshKitConst.footerTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = refrehser
refrehser.autoresizingMask = [.flexibleWidth,.flexibleHeight]
refrehser.frame = containComponent.bounds
containComponent.addSubview(refrehser)
configAssociatedObject(object: object)
}
func switchRefreshFooter(to state:FooterRefresherState){
let footer = self.viewWithTag(PullToRefreshKitConst.footerTag) as? RefreshFooterContainer
switch state {
case .refreshing:
footer?.beginRefreshing()
case .normal:
footer?.endRefreshing()
footer?.resetToDefault()
case .noMoreData:
footer?.endRefreshing()
footer?.updateToNoMoreData()
case .removed:
footer?.removeFromSuperview()
}
}
}
// MARK: - Left & Right API -
public enum SideRefreshDestination {
case left,right
}
public extension UIScrollView{
func configSideRefresh(with refrehser:UIView & RefreshableLeftRight,
container object: AnyObject,
at destination:SideRefreshDestination,
action:@escaping ()->()){
switch destination {
case .left:
let oldContain = self.viewWithTag(PullToRefreshKitConst.leftTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: -1.0 * refrehser.frame.size.width,
y: 0.0,
width: refrehser.widthForComponent(),
height: self.frame.height)
let containComponent = RefreshLeftContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.leftTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = refrehser
refrehser.autoresizingMask = [.flexibleWidth,.flexibleHeight]
refrehser.frame = containComponent.bounds
containComponent.addSubview(refrehser)
case .right:
let oldContain = self.viewWithTag(PullToRefreshKitConst.rightTag)
oldContain?.removeFromSuperview()
let frame = CGRect(x: 0 ,
y: 0 ,
width: refrehser.frame.size.width ,
height: self.frame.height)
let containComponent = RefreshRightContainer(frame: frame)
containComponent.tag = PullToRefreshKitConst.rightTag
containComponent.refreshAction = action
self.insertSubview(containComponent, at: 0)
containComponent.delegate = refrehser
refrehser.autoresizingMask = [.flexibleWidth,.flexibleHeight]
refrehser.frame = containComponent.bounds
containComponent.addSubview(refrehser)
}
configAssociatedObject(object: object)
}
func removeSideRefresh(at destination:SideRefreshDestination){
switch destination {
case .left:
let oldContain = self.viewWithTag(PullToRefreshKitConst.leftTag)
oldContain?.removeFromSuperview()
case .right:
let oldContain = self.viewWithTag(PullToRefreshKitConst.rightTag)
oldContain?.removeFromSuperview()
}
}
}
| mit | 565e35e6871beeb4b9de8a2c1c64a2d5 | 37.54955 | 147 | 0.626315 | 5.312228 | false | false | false | false |
CanyFrog/HCComponent | HCSource/HCStatusViewController.swift | 1 | 2983 | //
// HCStatusViewController.swift
// HCComponents
//
// Created by Magee Huang on 6/21/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
import UIKit
public enum HCViewControllerStatus: Int {
case loading, empty, error, success
}
open class HCStatusRootViewController: UIViewController, HCStatusControllerProtocol {
open var statusDict: [HCViewControllerStatus: HCStatusModel] = {
let loading = HCStatusModel(isLoading: true, title: "loading", subTitle: "We are hard to loading......", actionTitle: "retry", image: nil, action: {
print("retry loading.....")
})
let empty = HCStatusModel(isLoading: false, title: "empty", subTitle: "Oh, this page is empty", actionTitle: "reloading", action: {
print("It's empty page")
})
let error = HCStatusModel(isLoading: false, title: "error", subTitle: "Holy shit, we make a mistake", actionTitle: "retry again", image: nil, action: {
print("kill the mistake")
})
let success = HCStatusModel(isLoading: false, title: "success", subTitle: "Aha, finally we are win", actionTitle: "cheers", image: nil, action: {
print("this is a success page, please enjoy the beautiful app")
})
return [
.loading: loading,
.empty: empty,
.error: error,
.success: success
]
}()
open var status: HCViewControllerStatus! {
didSet {
show(status: statusDict[status]!)
}
}
open override func viewDidLoad() {
super.viewDidLoad()
status = .loading
Timer.every(3.0) {
let s = self.status.rawValue
self.status = HCViewControllerStatus.init(rawValue: (s+1)%4)
}
}
}
/// protocol
public protocol HCStatusControllerProtocol {
var onView: HCStatusViewContainerProtocol { get }
var statusView: HCStatusView? { get }
func show(status: HCStatusModel)
func hideStatus()
}
extension HCStatusControllerProtocol {
public var statusView: HCStatusView? {
return HCStatusView()
}
public func hideStatus() {
onView.statusContainerView = nil
}
public func show(status: HCStatusModel) {
guard let sv = statusView else { return }
sv.statusModel = status
onView.statusContainerView = sv.view
}
}
extension HCStatusControllerProtocol where Self: UIView {
public var onView: HCStatusViewContainerProtocol {
return self
}
}
extension HCStatusControllerProtocol where Self: UIViewController {
public var onView: HCStatusViewContainerProtocol {
return view
}
}
extension HCStatusControllerProtocol where Self: UITableViewController {
public var onView: HCStatusViewContainerProtocol {
if let backgroundView = tableView.backgroundView {
return backgroundView
}
return view
}
}
| mit | 03fc3f090e068bf33e8710eec0e46666 | 29.428571 | 159 | 0.632126 | 4.681319 | false | false | false | false |
crossroadlabs/Twist | Sources/Twist/Observable.swift | 1 | 9609 | //===--- Observable.swift ----------------------------------------------===//
//Copyright (c) 2016 Crossroad Labs s.r.o.
//
//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 ExecutionContext
import Event
public protocol AccessableProtocol {
associatedtype Payload
func async(_ f:@escaping (Payload)->Void)
}
public enum ObservableWillChangeEvent<T> : Event {
public typealias Payload = T
case event
}
public enum ObservableDidChangeEvent<T> : Event {
public typealias Payload = T
case event
}
public struct ObservableEventGroup<T, E : Event> {
fileprivate let event:E
private init(_ event:E) {
self.event = event
}
public static var willChange:ObservableEventGroup<T, ObservableWillChangeEvent<T>> {
return ObservableEventGroup<T, ObservableWillChangeEvent<T>>(.event)
}
public static var didChange:ObservableEventGroup<T, ObservableDidChangeEvent<T>> {
return ObservableEventGroup<T, ObservableDidChangeEvent<T>>(.event)
}
}
public protocol ObservableProtocol : EventEmitter, SignalStreamProtocol {
associatedtype Payload
typealias ChangePayload = (Payload, Payload)
func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableWillChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload>
func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableDidChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload>
}
public extension ObservableProtocol {
public var stream:SignalStream<Payload> {
get {
return self.on(.didChange).map {(_, value) in value}
}
}
}
public extension ObservableProtocol where Self : AccessableProtocol {
var stream:SignalStream<Payload> {
get {
let node = SignalNode<Payload>(context: context)
let sig:Set<Int> = [self.signature]
//TODO: WTF?
let off = self.on(.didChange).map {(_, value) in value}.pour(to: node)
async { value in
node.signal(signature: sig, payload: value)
}
return node
}
}
}
public extension ObservableProtocol {
public func chain(_ f: @escaping Chainer) -> Off {
return self.on(.didChange).map {(_, value) in value}.chain(f)
}
}
public extension ObservableProtocol where Self : AccessableProtocol {
internal func chainNoInitial(_ f: @escaping Chainer) -> Off {
return self.on(.didChange).map {(_, value) in value}.chain(f)
}
public func chain(_ f: @escaping Chainer) -> Off {
let sig:Set<Int> = [self.signature]
let off = self.on(.didChange).map {(_, value) in value}.chain(f)
async { payload in
f((sig, payload))
}
return off
}
}
public extension SignalNodeProtocol where Self : ObservableProtocol, Self : AccessableProtocol {
public func bind<SN : SignalNodeProtocol>(to node: SN) -> Off where SN.Payload == Payload {
let forth = chainNoInitial(node.signal)
let back = subscribe(to: node)
return {
forth()
back()
}
}
}
public protocol MutableObservableProtocol : ObservableProtocol, AccessableProtocol, SignalNodeProtocol {
//function passed for mutation
typealias Mutator = (Signal<Payload>) -> Void
//current, mutator
func async(_ f:@escaping (Payload, Mutator)->Void)
func sync(_ f:@escaping (Payload, Mutator)->Void) -> Payload
}
public extension MutableObservableProtocol {
public func mutate(_ f:@escaping (Payload, (Payload)->Void)->Void) {
async { payload, mutator in
f(payload) { new in
mutator(([], new))
}
}
}
}
public extension MutableObservableProtocol {
func sync() -> Payload {
return sync {_,_ in}
}
}
public extension AccessableProtocol where Self : MutableObservableProtocol {
public func async(_ f:@escaping (Payload)->Void) {
self.async { value, _ in
f(value)
}
}
}
public protocol ParametrizableObservableProtocol : ObservableProtocol {
typealias Subscriber = (Bool) -> SignalStream<ChangePayload>
init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber)
}
public protocol ParametrizableMutableObservableProtocol : ParametrizableObservableProtocol, MutableObservableProtocol {
typealias Accessor = () -> Payload
typealias Mutator = (Signal<Payload>) -> Void
init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber, accessor:@escaping Accessor, mutator:@escaping Mutator)
}
public class ReadonlyObservable<T> : ParametrizableObservableProtocol {
public typealias Payload = T
public typealias ChangePayload = (Payload, Payload)
//early if true, late otherwise
public typealias Subscriber = (Bool) -> SignalStream<ChangePayload>
public let dispatcher:EventDispatcher = EventDispatcher()
public let context: ExecutionContextProtocol
private let _subscriber:Subscriber
public required init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber) {
self.context = context
self._subscriber = subscriber
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableWillChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return _subscriber(true)
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableDidChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return _subscriber(false)
}
}
public class MutableObservable<T> : ReadonlyObservable<T>, ParametrizableMutableObservableProtocol {
public typealias ChangePayload = (Payload, Payload)
public typealias Accessor = () -> Payload
public typealias Mutator = (Signal<Payload>) -> Void
private let _accessor:Accessor
private let _mutator:Mutator
public required init(context:ExecutionContextProtocol, subscriber:@escaping Subscriber, accessor:@escaping Accessor, mutator:@escaping Mutator) {
self._accessor = accessor
self._mutator = mutator
super.init(context: context, subscriber: subscriber)
}
public required init(context: ExecutionContextProtocol, subscriber: @escaping Subscriber) {
fatalError("init(context:subscriber:) has not been implemented")
}
public func async(_ f: @escaping (T, Mutator) -> Void) {
context.immediateIfCurrent {
f(self._accessor(), self._mutator)
}
}
public func sync(_ f:@escaping (Payload, Mutator)->Void) -> T {
return context.sync {
f(self._accessor(), self._mutator)
return self._accessor()
}
}
}
//TODO: combine latest
public class ObservableValue<T> : MutableObservableProtocol {
public typealias Payload = T
//old, new
public typealias ChangePayload = (Payload, Payload)
//function passed for mutation
public typealias Mutator = (Signal<Payload>) -> Void
public let dispatcher:EventDispatcher = EventDispatcher()
public let context: ExecutionContextProtocol
private var _var:T
public init(_ value:T, context:ExecutionContextProtocol = ExecutionContext.current) {
_var = value
self.context = context
}
private func _mutate(signature:Set<Int>, value:T) {
let old = _var
self.emit(.willChange, payload: (old, value), signature: signature)
_var = value
self.emit(.didChange, payload: (old, value), signature: signature)
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableWillChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return self.on(groupedEvent.event)
}
public func on(_ groupedEvent: ObservableEventGroup<ChangePayload, ObservableDidChangeEvent<ChangePayload>>) -> SignalStream<ChangePayload> {
return self.on(groupedEvent.event)
}
public func async(_ f:@escaping (Payload)->Void) {
context.immediateIfCurrent {
f(self._var)
}
}
//current, mutator
public func async(_ f:@escaping (Payload, Mutator)->Void) {
context.immediateIfCurrent {
f(self._var, self._mutate)
}
}
public func sync(_ f:@escaping (Payload, Mutator)->Void = {_,_ in}) -> T {
return context.sync {
f(self._var, self._mutate)
return self._var
}
}
}
extension MutableObservableProtocol {
fileprivate func emit<E : Event>(_ groupedEvent: ObservableEventGroup<ChangePayload, E>, payload:E.Payload, signature:Set<Int>) {
self.emit(groupedEvent.event, payload: payload, signature:signature)
}
}
extension MutableObservableProtocol {
public func signal(signature:Set<Int>, payload: Payload) {
async { _, mutator in
mutator((signature, payload))
}
}
}
| apache-2.0 | fd6ffe6a3da7040dee3e9a1e891b21dd | 32.249135 | 149 | 0.65959 | 4.624158 | false | false | false | false |
gaelfoppolo/handicarparking | HandiParking/HandiParking/UIViewExtension.swift | 1 | 1927 | //
// UIViewExtension.swift
// HandiCarParking
//
// Created by Gaël on 17/03/2015.
// Copyright (c) 2015 KeepCore. All rights reserved.
//
import UIKit
/// Extension de UIView
extension UIView {
/**
Charge un xib grâce à son nom
:param: name Le nom identifiant le nib
:returns: une instance du xib
*/
class func viewFromNibName(name: String) -> UIView? {
let views = NSBundle.mainBundle().loadNibNamed(name, owner: nil, options: nil)
return views.first as? UIView
}
/**
Lock la vue appelante : vue devient sombre et un message de chargement s'affiche
*/
func lock() {
if let lockView = viewWithTag(10) {
// la vue est déjà lock
}
else {
let lockView = UIView(frame: bounds)
lockView.backgroundColor = UIColor(white: 0.0, alpha: 1)
lockView.tag = 10
lockView.alpha = 0.0
var label: UILabel = UILabel()
label.text = NSLocalizedString("LOADING", comment: "Loading additionnal information")
label.textColor = UIColor.whiteColor()
label.numberOfLines = 1
label.textAlignment = NSTextAlignment.Center
label.font = UIFont.systemFontOfSize(15.0)
label.sizeToFit()
lockView.addSubview(label)
label.center = lockView.center
self.addSubview(lockView)
UIView.animateWithDuration(0.5) {
lockView.alpha = 1.0
}
}
}
/**
Unlock la vue appelante : on supprime la vue de lock
*/
func unlock() {
if let lockView = self.viewWithTag(10) {
UIView.animateWithDuration(0.5, animations: {
lockView.alpha = 0.0
}) { finished in
lockView.removeFromSuperview()
}
}
}
} | gpl-3.0 | 395e3e6a5ec3903ddd481d0ba1a574a8 | 27.279412 | 97 | 0.555671 | 4.328829 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalServiceKit/src/Storage/Jobs/OWSBroadcastMediaMessageJobRecord+SDS.swift | 1 | 3096 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
import GRDB
import SignalCoreKit
// NOTE: This file is generated by /Scripts/sds_codegen/sds_generate.py.
// Do not manually edit it, instead run `sds_codegen.sh`.
// MARK: - Typed Convenience Methods
@objc
public extension OWSBroadcastMediaMessageJobRecord {
// NOTE: This method will fail if the object has unexpected type.
class func anyFetchBroadcastMediaMessageJobRecord(uniqueId: String,
transaction: SDSAnyReadTransaction) -> OWSBroadcastMediaMessageJobRecord? {
assert(uniqueId.count > 0)
guard let object = anyFetch(uniqueId: uniqueId,
transaction: transaction) else {
return nil
}
guard let instance = object as? OWSBroadcastMediaMessageJobRecord else {
owsFailDebug("Object has unexpected type: \(type(of: object))")
return nil
}
return instance
}
// NOTE: This method will fail if the object has unexpected type.
func anyUpdateBroadcastMediaMessageJobRecord(transaction: SDSAnyWriteTransaction, block: (OWSBroadcastMediaMessageJobRecord) -> Void) {
anyUpdate(transaction: transaction) { (object) in
guard let instance = object as? OWSBroadcastMediaMessageJobRecord else {
owsFailDebug("Object has unexpected type: \(type(of: object))")
return
}
block(instance)
}
}
}
// MARK: - SDSSerializer
// The SDSSerializer protocol specifies how to insert and update the
// row that corresponds to this model.
class OWSBroadcastMediaMessageJobRecordSerializer: SDSSerializer {
private let model: OWSBroadcastMediaMessageJobRecord
public required init(model: OWSBroadcastMediaMessageJobRecord) {
self.model = model
}
// MARK: - Record
func asRecord() throws -> SDSRecord {
let id: Int64? = model.sortId > 0 ? Int64(model.sortId) : nil
let recordType: SDSRecordType = .broadcastMediaMessageJobRecord
let uniqueId: String = model.uniqueId
// Base class properties
let failureCount: UInt = model.failureCount
let label: String = model.label
let status: SSKJobRecordStatus = model.status
// Subclass properties
let attachmentIdMap: Data? = optionalArchive(model.attachmentIdMap)
let contactThreadId: String? = nil
let envelopeData: Data? = nil
let invisibleMessage: Data? = nil
let messageId: String? = nil
let removeMessageAfterSending: Bool? = nil
let threadId: String? = nil
return JobRecordRecord(id: id, recordType: recordType, uniqueId: uniqueId, failureCount: failureCount, label: label, status: status, attachmentIdMap: attachmentIdMap, contactThreadId: contactThreadId, envelopeData: envelopeData, invisibleMessage: invisibleMessage, messageId: messageId, removeMessageAfterSending: removeMessageAfterSending, threadId: threadId)
}
}
| gpl-3.0 | 0d3372266cbe9f05d9839059f6da7618 | 38.189873 | 368 | 0.677649 | 5.083744 | false | false | false | false |
roambotics/swift | test/Interpreter/generic_objc_subclass.swift | 4 | 6897 | // RUN: %empty-directory(%t)
//
// RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o
// RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
import ObjCClasses
@objc protocol P {
func calculatePrice() -> Int
}
protocol PP {
func calculateTaxes() -> Int
}
//
// Generic subclass of an @objc class
//
class A<T> : HasHiddenIvars, P {
var first: Int = 16
var second: T?
var third: Int = 61
override var description: String {
return "Grilled artichokes"
}
func calculatePrice() -> Int {
return 400
}
}
let a = A<Int>()
// CHECK: Grilled artichokes
// CHECK: Grilled artichokes
print(a.description)
print((a as NSObject).description)
let f = { (a.x, a.y, a.z, a.t, a.first, a.second, a.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(f())
// CHECK: (25, 225, 255, 2255, 16, nil, 61)
a.x = 25
a.y = 225
a.z = 255
a.t = 2255
print(f())
// CHECK: (36, 225, 255, 2255, 16, nil, 61)
a.x = 36
print(f())
// CHECK: (36, 225, 255, 2255, 16, Optional(121), 61)
a.second = 121
print(f())
//
// Instantiate the class with a different set of generic parameters
//
let aa = A<(Int, Int)>()
let ff = { (aa.x, aa.y, aa.z, aa.t, aa.first, aa.second, aa.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(ff())
aa.x = 101
aa.second = (19, 84)
aa.third = 17
// CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17)
print(ff())
//
// Concrete subclass of generic subclass of @objc class
//
class B : A<(Int, Int)> {
override var description: String {
return "Salmon"
}
@nonobjc override func calculatePrice() -> Int {
return 1675
}
}
class BB : B {}
class C : A<(Int, Int)>, PP {
@nonobjc override var description: String {
return "Invisible Chicken"
}
override func calculatePrice() -> Int {
return 650
}
func calculateTaxes() -> Int {
return 110
}
}
// CHECK: 400
// CHECK: 400
// CHECK: 650
// CHECK: 110
print((BB() as P).calculatePrice())
print((B() as P).calculatePrice())
print((C() as P).calculatePrice())
print((C() as PP).calculateTaxes())
// CHECK: Salmon
// CHECK: Grilled artichokes
print((B() as NSObject).description)
print((C() as NSObject).description)
let b = B()
let g = { (b.x, b.y, b.z, b.t, b.first, b.second, b.third) }
// CHECK: (0, 0, 0, 0, 16, nil, 61)
print(g())
b.x = 101
b.second = (19, 84)
b.third = 17
// CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17)
print(g())
//
// Generic subclass of @objc class without any generically-sized members
//
class FixedA<T> : HasHiddenIvars, P {
var first: Int = 16
var second: [T] = []
var third: Int = 61
override var description: String {
return "Grilled artichokes"
}
func calculatePrice() -> Int {
return 400
}
}
let fixedA = FixedA<Int>()
// CHECK: Grilled artichokes
// CHECK: Grilled artichokes
print(fixedA.description)
print((fixedA as NSObject).description)
let fixedF = { (fixedA.x, fixedA.y, fixedA.z, fixedA.t, fixedA.first, fixedA.second, fixedA.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedF())
// CHECK: (25, 225, 255, 2255, 16, [], 61)
fixedA.x = 25
fixedA.y = 225
fixedA.z = 255
fixedA.t = 2255
print(fixedF())
// CHECK: (36, 225, 255, 2255, 16, [], 61)
fixedA.x = 36
print(fixedF())
// CHECK: (36, 225, 255, 2255, 16, [121], 61)
fixedA.second = [121]
print(fixedF())
//
// Instantiate the class with a different set of generic parameters
//
let fixedAA = FixedA<(Int, Int)>()
let fixedFF = { (fixedAA.x, fixedAA.y, fixedAA.z, fixedAA.t, fixedAA.first, fixedAA.second, fixedAA.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedFF())
fixedAA.x = 101
fixedAA.second = [(19, 84)]
fixedAA.third = 17
// CHECK: (101, 0, 0, 0, 16, [(19, 84)], 17)
print(fixedFF())
//
// Concrete subclass of generic subclass of @objc class
// without any generically-sized members
//
class FixedB : FixedA<Int> {
override var description: String {
return "Salmon"
}
override func calculatePrice() -> Int {
return 1675
}
}
// CHECK: 675
print((FixedB() as P).calculatePrice())
// CHECK: Salmon
print((FixedB() as NSObject).description)
let fixedB = FixedB()
let fixedG = { (fixedB.x, fixedB.y, fixedB.z, fixedB.t, fixedB.first, fixedB.second, fixedB.third) }
// CHECK: (0, 0, 0, 0, 16, [], 61)
print(fixedG())
fixedB.x = 101
fixedB.second = [19, 84]
fixedB.third = 17
// CHECK: (101, 0, 0, 0, 16, [19, 84], 17)
print(fixedG())
// https://github.com/apple/swift/issues/45191
// Problem with field alignment in direct generic subclass of 'NSObject'.
public class PandorasBox<T>: NSObject {
final public var value: T
public init(_ value: T) {
// Uses ConstantIndirect access pattern
self.value = value
}
}
let c = PandorasBox(30)
// CHECK: 30
// Uses ConstantDirect access pattern
print(c.value)
// Super method calls from a generic subclass of an @objc class
class HasDynamicMethod : NSObject {
@objc dynamic class func funkyTown() {
print("Here we are with \(self)")
}
}
class GenericOverrideOfDynamicMethod<T> : HasDynamicMethod {
override class func funkyTown() {
print("Hello from \(self) with T = \(T.self)")
super.funkyTown()
print("Goodbye from \(self) with T = \(T.self)")
}
}
class ConcreteOverrideOfDynamicMethod : GenericOverrideOfDynamicMethod<Int> {
override class func funkyTown() {
print("Hello from \(self)")
super.funkyTown()
print("Goodbye from \(self)")
}
}
// CHECK: Hello from ConcreteOverrideOfDynamicMethod
// CHECK: Hello from ConcreteOverrideOfDynamicMethod with T = Int
// CHECK: Here we are with ConcreteOverrideOfDynamicMethod
// CHECK: Goodbye from ConcreteOverrideOfDynamicMethod with T = Int
// CHECK: Goodbye from ConcreteOverrideOfDynamicMethod
ConcreteOverrideOfDynamicMethod.funkyTown()
class Foo {}
class Bar {}
class DependOnAlignOf<T> : HasHiddenIvars2 {
var first = Foo()
var second = Bar()
var third: T?
}
let ad = DependOnAlignOf<Double>()
let ai = DependOnAlignOf<Int>()
do {
let fd = { (ad.x, ad.first, ad.second, ad.third) }
let fi = { (ai.x, ai.first, ai.second, ai.third) }
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fd())
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fi())
}
// Same as above, but there's another class in between the
// Objective-C class and us
class HasHiddenIvars3 : HasHiddenIvars2 { }
class AlsoDependOnAlignOf<T> : HasHiddenIvars3 {
var first = Foo()
var second = Bar()
var third: T?
}
do {
let ad = AlsoDependOnAlignOf<Double>()
let ai = AlsoDependOnAlignOf<Int>()
let fd = { (ad.x, ad.first, ad.second, ad.third) }
let fi = { (ai.x, ai.first, ai.second, ai.third) }
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fd())
// CHECK: (nil, a.Foo, a.Bar, nil)
print(fi())
}
| apache-2.0 | f14fa910aa67329a7d3591a2b6aeeb56 | 20.027439 | 108 | 0.643323 | 3.043689 | false | false | false | false |
Pyroh/CoreGeometry | Sources/CoreGeometry/Extensions/CGPointExtension.swift | 1 | 13875 | //
// CGPointExtension.swift
//
// CoreGeometry
//
// MIT License
//
// Copyright (c) 2020 Pierre Tacchi
//
// 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 CoreGraphics
import SwiftUI
public extension CGPoint {
enum Alignment { case whole, half }
func aligned(_ alignment: Alignment = .whole) -> Self {
alignment == .whole ?
.init(simd2: simd2.rounded(.toNearestOrAwayFromZero)) :
.init(simd2: (simd2 * 2).rounded(.toNearestOrAwayFromZero) / 2)
}
mutating func align(_ alignment: Alignment = .whole) {
if alignment == .whole { simd2 = simd2.rounded(.toNearestOrAwayFromZero) }
else { simd2 = (simd2 * 2).rounded(.toNearestOrAwayFromZero) / 2 }
}
}
public extension CGPoint {
/// Creates a point with coordinates specified as integer values.
@inlinable init<T: BinaryInteger>(x: T, y: T) {
self.init(x: x.cgFloat, y: y.cgFloat)
}
/// Creates a point with coordinates specified as floating-point values.
@inlinable init<T: BinaryFloatingPoint>(x: T, y: T) {
self.init(x: x.cgFloat, y: y.cgFloat)
}
/// Creates a point with coordinates specified as integer values.
@inlinable init<T: BinaryInteger>(_ x: T, _ y: T) {
self.init(x: x.cgFloat, y: y.cgFloat)
}
/// Creates a point with coordinates specified as floating-point values.
@inlinable init<T: BinaryFloatingPoint>(_ x: T, _ y: T) {
self.init(x: x.cgFloat, y: y.cgFloat)
}
/// Creates a point with coordinates specified as floating-point values.
@inlinable init(_ x: CGFloat, _ y: CGFloat) {
self.init(x: x, y: y)
}
}
public extension CGPoint {
/// The receiver's SIMD representation.
@inlinable var simd2: SIMD2<CGFloat.NativeType> {
get { .init(x.native, y.native) }
set { (x, y) = (newValue.x.cgFloat, newValue.y.cgFloat) }
}
@inlinable init(simd2: SIMD2<CGFloat.NativeType>) {
self.init(x: simd2.x, y: simd2.y)
}
}
public extension CGPoint {
/// Returns the vector that exists between `self` and `p2`.
@inlinable func formVector(with p2: CGPoint) -> CGVector {
.init(simd2: p2.simd2 - simd2)
}
/// Returns a copy of `self` translated along the given vector.
@inlinable func translated(along vector: CGVector) -> CGPoint {
.init(simd2: simd2 + vector.simd2)
}
/// Returns a copy of `self` translated by `tx` on the X-axis and by `ty` on the Y-axis.
@inlinable func translated<I: BinaryInteger>(tx: I, ty: I) -> CGPoint {
.init(simd2: simd2 + .init(tx.native, ty.native))
}
/// Returns a copy of `self` translated by `tx` on the X-axis and by `ty` on the Y-axis.
@inlinable func translated<F: BinaryFloatingPoint>(tx: F, ty: F) -> CGPoint {
.init(simd2: simd2 + .init(tx.native, ty.native))
}
/// Returns a copy of `self` translated by `tx` on the X-axis and by `ty` on the Y-axis.
@inlinable func translated(tx: CGFloat.NativeType, ty: CGFloat.NativeType) -> CGPoint {
.init(simd2: simd2 + .init(tx, ty))
}
/// FIXME: deprecated.
/// Translates `self` along the given vector.
@available(*, deprecated, renamed: "translate(along:)")
@inlinable mutating func translate(by vector: CGVector) {
simd2 += vector.simd2
}
/// Translates `self` along the given vector.
@inlinable mutating func translate(along vector: CGVector) {
simd2 += vector.simd2
}
/// Translates `self` by `tx` on the X-axis and by `ty` on the Y-axis.
@inlinable mutating func translate<I: BinaryInteger>(tx: I, ty: I) {
simd2 += .init(tx.native, ty.native)
}
/// Translates `self` by `tx` on the X-axis and by `ty` on the Y-axis.
@inlinable mutating func translate<F: BinaryFloatingPoint>(tx: F, ty: F) {
simd2 += .init(tx.native, ty.native)
}
/// Translates `self` by `tx` on the X-axis and by `ty` on the Y-axis.
@inlinable mutating func translate(tx: CGFloat.NativeType, ty: CGFloat.NativeType) {
simd2 += .init(tx, ty)
}
/// Returns a copy of `self` rotated around the given center by the given angle.
///
/// - note: Rotates clockwise on iOS and counter-clockwise on OS X.
@inlinable func rotated(relativeTo center: CGPoint, by angle: CGFloat) -> CGPoint {
var transform = CGAffineTransform(translationX: center.x, y: center.y)
transform = transform.rotated(by: angle)
transform = transform.translatedBy(x: -center.x, y: -center.y)
return applying(transform)
}
/// Rotates `self` around the givent center by the given angle.
///
/// - note: Rotates clockwise on iOS and counter-clockwise on OS X.
@inlinable mutating func rotate(relativeTo center: CGPoint, by angle: CGFloat) {
self = self.rotated(relativeTo: center, by: angle)
}
}
extension CGPoint {
/// Creates a new `CGRect` with the receiver for its origin and sized to the given size.
/// - Parameter size: The size of the `CGRect`.
/// - Returns: The resulting `CGRect`.
@inlinable public func makeRect(withSize size: CGSize) -> CGRect {
.init(origin: self, size: size)
}
/// Creates a new `CGRect` with the receiver for its center and sized to the given size.
/// - Parameter size: The size of the `CGRect`.
/// - Returns: The resulting `CGRect`.
@inlinable public func makeRect(centeredWithSize size: CGSize) -> CGRect {
.init(center: self, size: size)
}
}
public extension CGPoint {
/// Multiplies `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to multiply components.
/// - rhs: The value to multiply.
@inlinable static func * <I: BinaryInteger>(lhs: CGPoint, rhs: I) -> CGPoint {
.init(simd2: lhs.simd2 * rhs.native)
}
/// Multiplies `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to multiply components.
/// - rhs: The value to multiply.
@inlinable static func * <F: BinaryFloatingPoint>(lhs: CGPoint, rhs: F) -> CGPoint {
.init(simd2: lhs.simd2 * rhs.native)
}
/// Multiplies `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to multiply components.
/// - rhs: The value to multiply.
@inlinable
static func * (lhs: CGPoint, rhs: CGFloat.NativeType) -> CGPoint {
.init(simd2: lhs.simd2 * rhs)
}
/// Multiplies `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to multiply components.
/// - rhs: The value to multiply.
@inlinable
static func * <I: BinaryInteger>(lhs: CGPoint, rhs: (x: I, y: I)) -> CGPoint {
.init(simd2: lhs.simd2 * .init(rhs.x.native, rhs.y.native))
}
/// Multiplies `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to multiply components.
/// - rhs: The value to multiply.
@inlinable
static func * <F: BinaryFloatingPoint>(lhs: CGPoint, rhs: (x: F, y: F)) -> CGPoint {
.init(simd2: lhs.simd2 * .init(rhs.x.native, rhs.y.native))
}
/// Multiplies `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to multiply components.
/// - rhs: The value to multiply.
@inlinable
static func * (lhs: CGPoint, rhs: (x: CGFloat.NativeType, y: CGFloat.NativeType)) -> CGPoint {
.init(simd2: lhs.simd2 * .init(rhs.x, rhs.y))
}
/// Multiplies a point's components by another one's and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: A point to multiply.
/// - rhs: Another point the multiply.
@inlinable static func * (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
.init(simd2: lhs.simd2 * rhs.simd2)
}
/// Divides `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to divide components.
/// - rhs: The value to devide by.
@inlinable
static func / <I: BinaryInteger>(lhs: CGPoint, rhs: I) -> CGPoint {
.init(simd2: lhs.simd2 / rhs.native)
}
/// Divides `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to divide components.
/// - rhs: The value to devide by.
@inlinable
static func / <F: BinaryFloatingPoint>(lhs: CGPoint, rhs: F) -> CGPoint {
.init(simd2: lhs.simd2 / rhs.native)
}
/// Divides `x` and `y` by the given value and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: The point to divide components.
/// - rhs: The value to devide by.
@inlinable
static func / (lhs: CGPoint, rhs: CGFloat.NativeType) -> CGPoint {
.init(simd2: lhs.simd2 / rhs)
}
/// Divides a point's components by another one's and returns the resulting `CGPoint`.
/// - Parameters:
/// - lhs: A point to devide.
/// - rhs: Another point the devide.
@inlinable
static func / (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
.init(simd2: lhs.simd2 / rhs.simd2)
}
}
extension CGPoint: AdditiveArithmetic {
@inlinable public static func + (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
.init(simd2: lhs.simd2 + rhs.simd2)
}
/// Adds a value to a point's component.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to add.
/// - Returns: The resulting point.
@inlinable public static func + <I: BinaryInteger>(lhs: CGPoint, rhs: I) -> CGPoint {
.init(simd2: lhs.simd2 + rhs.native)
}
/// Adds a value to a point's component.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to add.
/// - Returns: The resulting point.
@inlinable public static func + <I: BinaryFloatingPoint>(lhs: CGPoint, rhs: I) -> CGPoint {
.init(simd2: lhs.simd2 + rhs.native)
}
/// Adds a value to a point's component.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to add.
/// - Returns: The resulting point.
@inlinable public static func + <I: BinaryInteger>(lhs: CGPoint, rhs: (I, I)) -> CGPoint {
.init(simd2: lhs.simd2 + .init(rhs.0.native, rhs.1.native))
}
/// Adds a value to a point's component.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to add.
/// - Returns: The resulting point.
@inlinable public static func + <I: BinaryFloatingPoint>(lhs: CGPoint, rhs: (I, I)) -> CGPoint {
.init(simd2: lhs.simd2 + .init(rhs.0.native, rhs.1.native))
}
/// Adds a value to a point's component.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to add.
/// - Returns: The resulting point.
@inlinable public static func + (lhs: CGPoint, rhs: CGFloat.NativeType) -> CGPoint {
.init(simd2: lhs.simd2 + rhs.native)
}
@inlinable public static func - (lhs: CGPoint, rhs: CGPoint) -> CGPoint {
.init(simd2: lhs.simd2 - rhs.simd2)
}
/// Substracts a value from a point's components.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to substract.
/// - Returns: The resulting vector.
@inlinable public static func - <I: BinaryInteger>(lhs: CGPoint, rhs: I) -> CGPoint {
.init(simd2: lhs.simd2 - rhs.native)
}
/// Substracts a value from a point's components.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to substract.
/// - Returns: The resulting vector.
@inlinable public static func - <F: BinaryFloatingPoint>(lhs: CGPoint, rhs: F) -> CGPoint {
.init(simd2: lhs.simd2 - rhs.native)
}
/// Substracts a value from a point's components.
/// - Parameters:
/// - lhs: A point.
/// - rhs: The value to substract.
/// - Returns: The resulting vector.
@inlinable public static func - (lhs: CGPoint, rhs: CGFloat.NativeType) -> CGPoint {
.init(simd2: lhs.simd2 - rhs)
}
@inlinable public static prefix func - (rhs: CGPoint) -> CGPoint {
.init(simd2: -rhs.simd2)
}
}
public extension CGPoint {
@inlinable mutating func clamp(to rect: CGRect) {
self = clamped(to: rect)
}
@inlinable func clamped(to rect: CGRect) -> CGPoint {
.init(simd2: self.simd2.clamped(lowerBound: rect.origin.simd2, upperBound: rect.origin.simd2 + rect.size.simd2))
}
}
| mit | 791967418f371844071714b0797abf1c | 36.5 | 120 | 0.613261 | 3.788913 | false | false | false | false |
tresorit/ZeroKit-Realm-encrypted-tasks | ios/RealmTasks iOS/OnboardView.swift | 1 | 2780 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 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 Cartography
import UIKit
class OnboardView: UIView {
private let contentColor = UIColor(white: 0.13, alpha: 1)
private let contentPadding: CGFloat = 15
private let imageView = UIImageView(image: UIImage(named: "PullToRefresh")?.withRenderingMode(.alwaysTemplate))
private let labelView = UILabel()
static func add(to tableView: UITableView) -> OnboardView {
let onBoard = OnboardView()
tableView.addSubview(onBoard)
onBoard.center = tableView.center
return onBoard
}
init() {
labelView.text = "Pull Down to Start"
labelView.font = .systemFont(ofSize: 20, weight: UIFontWeightMedium)
labelView.textColor = contentColor
labelView.textAlignment = .center
labelView.sizeToFit()
imageView.tintColor = contentColor
var frame = CGRect.zero
frame.size.width = labelView.frame.size.width
frame.size.height = imageView.frame.height + contentPadding + labelView.frame.height
super.init(frame: frame)
addSubview(imageView)
addSubview(labelView)
autoresizingMask = [.flexibleBottomMargin, .flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin]
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupConstraints() {
constrain(labelView, imageView) { labelView, imageView in
labelView.centerX == labelView.superview!.centerX
labelView.bottom == labelView.superview!.bottom
imageView.centerX == imageView.superview!.centerX
imageView.top == imageView.superview!.top
}
}
func toggle(isVisible: Bool, animated: Bool = false) {
func updateAlpha() {
alpha = isVisible ? 1 : 0
}
if animated {
UIView.animate(withDuration: 0.3, animations: updateAlpha)
} else {
updateAlpha()
}
}
}
| bsd-3-clause | 32c1e9d85c9c25e337ba7e37f63766a6 | 31.705882 | 115 | 0.630935 | 5.063752 | false | false | false | false |
fabiomassimo/eidolon | Kiosk/Bid Fulfillment/LoadingViewController.swift | 1 | 8672 | import UIKit
import Artsy_UILabels
import ARAnalytics
import ReactiveCocoa
public class LoadingViewController: UIViewController {
@IBOutlet weak var titleLabel: ARSerifLabel!
@IBOutlet var bidDetailsPreviewView: BidDetailsPreviewView!
@IBOutlet weak var statusMessage: ARSerifLabel!
@IBOutlet weak var spinner: Spinner!
@IBOutlet weak var bidConfirmationImageView: UIImageView!
public var placingBid = true
public var performNetworking = true
public var animate = true
public var bidderNetworkModel: BidderNetworkModel!
public var bidCheckingModel: BidCheckingNetworkModel!
public var placeBidNetworkModel: PlaceBidNetworkModel!
@IBOutlet public weak var backToAuctionButton: SecondaryActionButton!
@IBOutlet public weak var placeHigherBidButton: ActionButton!
public lazy var bidDetails: (() -> (BidDetails)) = {
return (self as UIViewController).fulfillmentNav().bidDetails
}
override public func viewDidLoad() {
super.viewDidLoad()
if placingBid {
bidDetailsPreviewView.bidDetails = bidDetails()
} else {
bidDetailsPreviewView.hidden = true
}
statusMessage.hidden = true
backToAuctionButton.hidden = true
placeHigherBidButton.hidden = true
spinner.animate(animate)
titleLabel.text = placingBid ? "Placing bid..." : "Registering..."
bidderNetworkModel = bidderNetworkModel ?? BidderNetworkModel()
bidderNetworkModel.fulfillmentNav = fulfillmentNav()
if !performNetworking { return }
bidderNetworkModel.createOrGetBidder().doError { (error) -> Void in
self.bidderError(error)
} .then {
if !self.placingBid {
ARAnalytics.event("Registered New User Only")
return RACSignal.empty()
}
ARAnalytics.event("Started Placing Bid")
return self.placeBid()
} .then { [weak self] (_) in
if self == nil { return RACSignal.empty() }
self?.bidCheckingModel = self?.bidCheckingModel ?? self?.createBidCheckingModel()
if self?.placingBid == false { return RACSignal.empty() }
return self!.bidCheckingModel.waitForBidResolution()
} .subscribeCompleted { [weak self] (_) in
self?.finishUp()
return
}
}
func createBidCheckingModel() -> BidCheckingNetworkModel {
let nav = fulfillmentNav()
return BidCheckingNetworkModel(details: nav.bidDetails, provider: nav.loggedInProvider!)
}
func placeBid() -> RACSignal {
placeBidNetworkModel = placeBidNetworkModel ?? PlaceBidNetworkModel()
let auctionID = self.fulfillmentNav().auctionID!
placeBidNetworkModel.fulfillmentNav = self.fulfillmentNav()
return placeBidNetworkModel.bidSignal(bidDetails()).doError { (error) in
self.bidPlacementFailed(error: error)
}
}
func finishUp() {
self.spinner.hidden = true
let reserveNotMet = bidCheckingModel.reserveNotMet
let isHighestBidder = bidCheckingModel.isHighestBidder
let bidIsResolved = bidCheckingModel.bidIsResolved
let createdNewBidder = bidderNetworkModel.createdNewBidder
if placingBid {
ARAnalytics.event("Placed a bid", withProperties: ["top_bidder" : isHighestBidder])
if bidIsResolved {
if reserveNotMet {
handleReserveNotMet()
} else if isHighestBidder {
handleHighestBidder()
} else {
handleLowestBidder()
}
} else {
handleUnknownBidder()
}
} else { // Not placing bid
if createdNewBidder { // Creating new user
handleRegistered()
} else { // Updating existing user
handleUpdate()
}
}
let showPlaceHigherButton = placingBid && (!isHighestBidder || reserveNotMet)
placeHigherBidButton.hidden = !showPlaceHigherButton
let showAuctionButton = showPlaceHigherButton || isHighestBidder || (!placingBid && !createdNewBidder)
backToAuctionButton.hidden = !showAuctionButton
let title = reserveNotMet ? "NO, THANKS" : (createdNewBidder ? "CONTINUE" : "BACK TO AUCTION")
backToAuctionButton.setTitle(title, forState: .Normal)
}
func handleRegistered() {
titleLabel.text = "Registration Complete"
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
fulfillmentContainer()?.cancelButton.setTitle("DONE", forState: .Normal)
RACSignal.interval(1, onScheduler: RACScheduler.mainThreadScheduler()).take(1).subscribeCompleted { [weak self] () -> Void in
self?.performSegue(.PushtoRegisterConfirmed)
return
}
}
func handleUpdate() {
titleLabel.text = "Updated your Information"
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
fulfillmentContainer()?.cancelButton.setTitle("DONE", forState: .Normal)
}
func handleUnknownBidder() {
titleLabel.text = "Bid Confirmed"
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
}
func handleReserveNotMet() {
titleLabel.text = "Reserve Not Met"
statusMessage.hidden = false
statusMessage.text = "Your bid is still below this lot's reserve. Please place a higher bid."
bidConfirmationImageView.image = UIImage(named: "BidNotHighestBidder")
}
func handleHighestBidder() {
titleLabel.text = "High Bid!"
statusMessage.hidden = false
statusMessage.text = "You are the high bidder for this lot."
bidConfirmationImageView.image = UIImage(named: "BidHighestBidder")
fulfillmentContainer()?.cancelButton.setTitle("DONE", forState: .Normal)
}
func handleLowestBidder() {
titleLabel.text = "Higher bid needed"
titleLabel.textColor = UIColor.artsyRed()
statusMessage.hidden = false
statusMessage.text = "Another bidder has placed a higher maximum bid. Place a higher bid to secure the lot."
bidConfirmationImageView.image = UIImage(named: "BidNotHighestBidder")
}
// MARK: - Error Handling
func bidderError(error: NSError?) {
if placingBid {
// If you are bidding, we show a bidding error regardless of whether or not you're also registering.
bidPlacementFailed(error: error)
} else {
// If you're not placing a bid, you're here because you're just registering.
presentError("Registration Failed", message: "There was a problem registering for the auction. Please speak to an Artsy representative.")
}
}
func bidPlacementFailed(error: NSError? = nil) {
presentError("Bid Failed", message: "There was a problem placing your bid. Please speak to an Artsy representative.")
if let error = error {
statusMessage.presentOnLongPress("Error: \(error.localizedDescription). \n \(error.artsyServerError())", title: "Bidding error", closure: { [weak self] (alertController) -> Void in
self?.presentViewController(alertController, animated: true, completion: nil)
})
}
}
func presentError(title: String, message: String) {
spinner.hidden = true
titleLabel.textColor = UIColor.artsyRed()
titleLabel.text = title
statusMessage.text = message
statusMessage.hidden = false
}
override public func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue == .PushtoRegisterConfirmed {
let detailsVC = segue.destinationViewController as! YourBiddingDetailsViewController
detailsVC.confirmationImage = bidConfirmationImageView.image
}
if segue == .PlaceaHigherBidAfterNotBeingHighestBidder {
let placeBidVC = segue.destinationViewController as! PlaceBidViewController
placeBidVC.hasAlreadyPlacedABid = true
}
}
@IBAction func placeHigherBidTapped(sender: AnyObject) {
self.fulfillmentNav().bidDetails.bidAmountCents = 0
self.performSegue(.PlaceaHigherBidAfterNotBeingHighestBidder)
}
@IBAction func backToAuctionTapped(sender: AnyObject) {
if bidderNetworkModel.createdNewBidder {
self.performSegue(.PushtoRegisterConfirmed)
} else {
fulfillmentContainer()?.closeFulfillmentModal()
}
}
}
| mit | d56b81c60d35d557e5b579f82be548bf | 36.059829 | 192 | 0.654866 | 5.183503 | false | false | false | false |
hshidara/iOS | Ready?/Ready?/AppDelegate.swift | 1 | 7511 | //
// AppDelegate.swift
// Ready?
//
// Created by Hidekazu Shidara on 9/16/15.
// Copyright (c) 2015 Hidekazu Shidara. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// let tabBarController = window!.rootViewController as! UITabBarController
// let vc = tabBarController.viewControllers![2] as! UINavigationController
// let v = vc.viewControllers.first as! Runner
// v.managedObjectContext = managedObjectContext
// let vc = RunningStart()
// vc.managedObjectContext = managedObjectContext
// let controller = tabBarController.viewControllers as! RunningStart
// let controller = RunningStart()
// controller.managedObjectContext = managedObjectContext
// UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
// UIViewController *firstViewController = tabBarController.viewControllers[0];
// firstViewController.managedObjectContext = [[MUNSharedDatabaseController sharedDatabaseController] managedObjectContext];
// UIViewController *secondViewController = tabBarController.viewControllers[1];
// secondVC.managedObjectContext = [[MUNSharedDatabaseController sharedDatabaseController] managedObjectContext];
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
// self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Hidekazu-Shidara.Ready_" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Ready_", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Ready_.sqlite")
var error: NSError? = nil
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 error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges {
do {
try moc.save()
} catch let error1 as NSError {
error = error1
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
}
| mit | 56dd27b69c6618ad7dc13a37d8949614 | 53.427536 | 290 | 0.700706 | 5.845136 | false | false | false | false |
kstaring/swift | stdlib/public/core/StringCore.swift | 4 | 23688 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// The core implementation of a highly-optimizable String that
/// can store both ASCII and UTF-16, and can wrap native Swift
/// _StringBuffer or NSString instances.
///
/// Usage note: when elements are 8 bits wide, this code may
/// dereference one past the end of the byte array that it owns, so
/// make sure that storage is allocated! You want a null terminator
/// anyway, so it shouldn't be a burden.
//
// Implementation note: We try hard to avoid branches in this code, so
// for example we use integer math to avoid switching on the element
// size with the ternary operator. This is also the cause of the
// extra element requirement for 8 bit elements. See the
// implementation of subscript(Int) -> UTF16.CodeUnit below for details.
@_fixed_layout
public struct _StringCore {
//===--------------------------------------------------------------------===//
// Internals
public var _baseAddress: UnsafeMutableRawPointer?
var _countAndFlags: UInt
public var _owner: AnyObject?
/// (private) create the implementation of a string from its component parts.
init(
baseAddress: UnsafeMutableRawPointer?,
_countAndFlags: UInt,
owner: AnyObject?
) {
self._baseAddress = baseAddress
self._countAndFlags = _countAndFlags
self._owner = owner
_invariantCheck()
}
func _invariantCheck() {
// Note: this code is intentionally #if'ed out. It unconditionally
// accesses lazily initialized globals, and thus it is a performance burden
// in non-checked builds.
#if INTERNAL_CHECKS_ENABLED
_sanityCheck(count >= 0)
if _baseAddress == nil {
#if _runtime(_ObjC)
_sanityCheck(hasCocoaBuffer,
"Only opaque cocoa strings may have a null base pointer")
#endif
_sanityCheck(elementWidth == 2,
"Opaque cocoa strings should have an elementWidth of 2")
}
else if _baseAddress == _emptyStringBase {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(count == 0, "Empty string storage with non-zero count")
_sanityCheck(_owner == nil, "String pointing at empty storage has owner")
}
else if let buffer = nativeBuffer {
_sanityCheck(!hasCocoaBuffer)
_sanityCheck(elementWidth == buffer.elementWidth,
"_StringCore elementWidth doesn't match its buffer's")
_sanityCheck(_baseAddress! >= buffer.start)
_sanityCheck(_baseAddress! <= buffer.usedEnd)
_sanityCheck(_pointer(toElementAt: count) <= buffer.usedEnd)
}
#endif
}
/// Bitmask for the count part of `_countAndFlags`.
var _countMask: UInt {
return UInt.max >> 2
}
/// Bitmask for the flags part of `_countAndFlags`.
var _flagMask: UInt {
return ~_countMask
}
/// Value by which to multiply a 2nd byte fetched in order to
/// assemble a UTF-16 code unit from our contiguous storage. If we
/// store ASCII, this will be zero. Otherwise, it will be 0x100.
var _highByteMultiplier: UTF16.CodeUnit {
return UTF16.CodeUnit(elementShift) << 8
}
/// Returns a pointer to the Nth element of contiguous
/// storage. Caveats: The string must have contiguous storage; the
/// element may be 1 or 2 bytes wide, depending on elementWidth; the
/// result may be null if the string is empty.
func _pointer(toElementAt n: Int) -> UnsafeMutableRawPointer {
_sanityCheck(hasContiguousStorage && n >= 0 && n <= count)
return _baseAddress! + (n << elementShift)
}
static func _copyElements(
_ srcStart: UnsafeMutableRawPointer, srcElementWidth: Int,
dstStart: UnsafeMutableRawPointer, dstElementWidth: Int,
count: Int
) {
// Copy the old stuff into the new storage
if _fastPath(srcElementWidth == dstElementWidth) {
// No change in storage width; we can use memcpy
_memcpy(
dest: dstStart,
src: srcStart,
size: UInt(count << (srcElementWidth - 1)))
}
else if (srcElementWidth < dstElementWidth) {
// Widening ASCII to UTF-16; we need to copy the bytes manually
var dest = dstStart.assumingMemoryBound(to: UTF16.CodeUnit.self)
var src = srcStart.assumingMemoryBound(to: UTF8.CodeUnit.self)
let srcEnd = src + count
while (src != srcEnd) {
dest.pointee = UTF16.CodeUnit(src.pointee)
dest += 1
src += 1
}
}
else {
// Narrowing UTF-16 to ASCII; we need to copy the bytes manually
var dest = dstStart.assumingMemoryBound(to: UTF8.CodeUnit.self)
var src = srcStart.assumingMemoryBound(to: UTF16.CodeUnit.self)
let srcEnd = src + count
while (src != srcEnd) {
dest.pointee = UTF8.CodeUnit(src.pointee)
dest += 1
src += 1
}
}
}
//===--------------------------------------------------------------------===//
// Initialization
public init(
baseAddress: UnsafeMutableRawPointer?,
count: Int,
elementShift: Int,
hasCocoaBuffer: Bool,
owner: AnyObject?
) {
_sanityCheck(elementShift == 0 || elementShift == 1)
self._baseAddress = baseAddress
self._countAndFlags
= (UInt(elementShift) << (UInt._sizeInBits - 1))
| ((hasCocoaBuffer ? 1 : 0) << (UInt._sizeInBits - 2))
| UInt(count)
self._owner = owner
_sanityCheck(UInt(count) & _flagMask == 0, "String too long to represent")
_invariantCheck()
}
/// Create a _StringCore that covers the entire length of the _StringBuffer.
init(_ buffer: _StringBuffer) {
self = _StringCore(
baseAddress: buffer.start,
count: buffer.usedCount,
elementShift: buffer.elementShift,
hasCocoaBuffer: false,
owner: buffer._anyObject
)
}
/// Create the implementation of an empty string.
///
/// - Note: There is no null terminator in an empty string.
public init() {
self._baseAddress = _emptyStringBase
self._countAndFlags = 0
self._owner = nil
_invariantCheck()
}
//===--------------------------------------------------------------------===//
// Properties
/// The number of elements stored
/// - Complexity: O(1).
public var count: Int {
get {
return Int(_countAndFlags & _countMask)
}
set(newValue) {
_sanityCheck(UInt(newValue) & _flagMask == 0)
_countAndFlags = (_countAndFlags & _flagMask) | UInt(newValue)
}
}
/// Left shift amount to apply to an offset N so that when
/// added to a UnsafeMutableRawPointer, it traverses N elements.
var elementShift: Int {
return Int(_countAndFlags >> (UInt._sizeInBits - 1))
}
/// The number of bytes per element.
///
/// If the string does not have an ASCII buffer available (including the case
/// when we don't have a utf16 buffer) then it equals 2.
public var elementWidth: Int {
return elementShift &+ 1
}
public var hasContiguousStorage: Bool {
#if _runtime(_ObjC)
return _fastPath(_baseAddress != nil)
#else
return true
#endif
}
/// Are we using an `NSString` for storage?
public var hasCocoaBuffer: Bool {
return Int((_countAndFlags << 1)._value) < 0
}
public var startASCII: UnsafeMutablePointer<UTF8.CodeUnit> {
_sanityCheck(elementWidth == 1, "String does not contain contiguous ASCII")
return _baseAddress!.assumingMemoryBound(to: UTF8.CodeUnit.self)
}
/// True iff a contiguous ASCII buffer available.
public var isASCII: Bool {
return elementWidth == 1
}
public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {
_sanityCheck(
count == 0 || elementWidth == 2,
"String does not contain contiguous UTF-16")
return _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self)
}
public var asciiBuffer: UnsafeMutableBufferPointer<UTF8.CodeUnit>? {
if elementWidth != 1 {
return nil
}
return UnsafeMutableBufferPointer(start: startASCII, count: count)
}
/// the native _StringBuffer, if any, or `nil`.
public var nativeBuffer: _StringBuffer? {
if !hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, to: _StringBuffer.self)
}
}
return nil
}
#if _runtime(_ObjC)
/// the Cocoa String buffer, if any, or `nil`.
public var cocoaBuffer: _CocoaString? {
if hasCocoaBuffer {
return _owner.map {
unsafeBitCast($0, to: _CocoaString.self)
}
}
return nil
}
#endif
//===--------------------------------------------------------------------===//
// slicing
/// Returns the given sub-`_StringCore`.
public subscript(bounds: Range<Int>) -> _StringCore {
_precondition(
bounds.lowerBound >= 0,
"subscript: subrange start precedes String start")
_precondition(
bounds.upperBound <= count,
"subscript: subrange extends past String end")
let newCount = bounds.upperBound - bounds.lowerBound
_sanityCheck(UInt(newCount) & _flagMask == 0)
if hasContiguousStorage {
return _StringCore(
baseAddress: _pointer(toElementAt: bounds.lowerBound),
_countAndFlags: (_countAndFlags & _flagMask) | UInt(newCount),
owner: _owner)
}
#if _runtime(_ObjC)
return _cocoaStringSlice(self, bounds)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
/// Get the Nth UTF-16 Code Unit stored.
@_versioned
func _nthContiguous(_ position: Int) -> UTF16.CodeUnit {
let p =
UnsafeMutablePointer<UInt8>(_pointer(toElementAt: position)._rawValue)
// Always dereference two bytes, but when elements are 8 bits we
// multiply the high byte by 0.
// FIXME(performance): use masking instead of multiplication.
#if _endian(little)
return UTF16.CodeUnit(p.pointee)
+ UTF16.CodeUnit((p + 1).pointee) * _highByteMultiplier
#else
return _highByteMultiplier == 0 ? UTF16.CodeUnit(p.pointee) : UTF16.CodeUnit((p + 1).pointee) + UTF16.CodeUnit(p.pointee) * _highByteMultiplier
#endif
}
/// Get the Nth UTF-16 Code Unit stored.
public subscript(position: Int) -> UTF16.CodeUnit {
@inline(__always)
get {
_precondition(
position >= 0,
"subscript: index precedes String start")
_precondition(
position <= count,
"subscript: index points past String end")
if _fastPath(_baseAddress != nil) {
return _nthContiguous(position)
}
#if _runtime(_ObjC)
return _cocoaStringSubscript(self, position)
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
}
/// Write the string, in the given encoding, to output.
func encode<Encoding: UnicodeCodec>(
_ encoding: Encoding.Type,
into processCodeUnit: (Encoding.CodeUnit) -> Void)
{
if _fastPath(_baseAddress != nil) {
if _fastPath(elementWidth == 1) {
for x in UnsafeBufferPointer(
start: _baseAddress!.assumingMemoryBound(to: UTF8.CodeUnit.self),
count: count
) {
Encoding.encode(UnicodeScalar(x), into: processCodeUnit)
}
}
else {
let hadError = transcode(
UnsafeBufferPointer(
start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self),
count: count
).makeIterator(),
from: UTF16.self,
to: encoding,
stoppingOnError: true,
into: processCodeUnit
)
_sanityCheck(!hadError, "Swift.String with native storage should not have unpaired surrogates")
}
}
else if (hasCocoaBuffer) {
#if _runtime(_ObjC)
_StringCore(
_cocoaStringToContiguous(
source: cocoaBuffer!, range: 0..<count, minimumCapacity: 0)
).encode(encoding, into: processCodeUnit)
#else
_sanityCheckFailure("encode: non-native string without objc runtime")
#endif
}
}
/// Attempt to claim unused capacity in the String's existing
/// native buffer, if any. Return zero and a pointer to the claimed
/// storage if successful. Otherwise, returns a suggested new
/// capacity and a null pointer.
///
/// - Note: If successful, effectively appends garbage to the String
/// until it has newSize UTF-16 code units; you must immediately copy
/// valid UTF-16 into that storage.
///
/// - Note: If unsuccessful because of insufficient space in an
/// existing buffer, the suggested new capacity will at least double
/// the existing buffer's storage.
mutating func _claimCapacity(
_ newSize: Int, minElementWidth: Int) -> (Int, UnsafeMutableRawPointer?) {
if _fastPath((nativeBuffer != nil) && elementWidth >= minElementWidth) {
var buffer = nativeBuffer!
// In order to grow the substring in place, this _StringCore should point
// at the substring at the end of a _StringBuffer. Otherwise, some other
// String is using parts of the buffer beyond our last byte.
let usedStart = _pointer(toElementAt:0)
let usedEnd = _pointer(toElementAt:count)
// Attempt to claim unused capacity in the buffer
if _fastPath(
buffer.grow(
oldBounds: UnsafeRawPointer(usedStart)..<UnsafeRawPointer(usedEnd),
newUsedCount: newSize)
) {
count = newSize
return (0, usedEnd)
}
else if newSize > buffer.capacity {
// Growth failed because of insufficient storage; double the size
return (Swift.max(_growArrayCapacity(buffer.capacity), newSize), nil)
}
}
return (newSize, nil)
}
/// Ensure that this String references a _StringBuffer having
/// a capacity of at least newSize elements of at least the given width.
/// Effectively appends garbage to the String until it has newSize
/// UTF-16 code units. Returns a pointer to the garbage code units;
/// you must immediately copy valid data into that storage.
mutating func _growBuffer(
_ newSize: Int, minElementWidth: Int
) -> UnsafeMutableRawPointer {
let (newCapacity, existingStorage)
= _claimCapacity(newSize, minElementWidth: minElementWidth)
if _fastPath(existingStorage != nil) {
return existingStorage!
}
let oldCount = count
_copyInPlace(
newSize: newSize,
newCapacity: newCapacity,
minElementWidth: minElementWidth)
return _pointer(toElementAt:oldCount)
}
/// Replace the storage of self with a native _StringBuffer having a
/// capacity of at least newCapacity elements of at least the given
/// width. Effectively appends garbage to the String until it has
/// newSize UTF-16 code units.
mutating func _copyInPlace(
newSize: Int, newCapacity: Int, minElementWidth: Int
) {
_sanityCheck(newCapacity >= newSize)
let oldCount = count
// Allocate storage.
let newElementWidth =
minElementWidth >= elementWidth
? minElementWidth
: isRepresentableAsASCII() ? 1 : 2
let newStorage = _StringBuffer(capacity: newCapacity, initialSize: newSize,
elementWidth: newElementWidth)
if hasContiguousStorage {
_StringCore._copyElements(
_baseAddress!, srcElementWidth: elementWidth,
dstStart: UnsafeMutableRawPointer(newStorage.start),
dstElementWidth: newElementWidth, count: oldCount)
}
else {
#if _runtime(_ObjC)
// Opaque cocoa buffers might not store ASCII, so assert that
// we've allocated for 2-byte elements.
// FIXME: can we get Cocoa to tell us quickly that an opaque
// string is ASCII? Do we care much about that edge case?
_sanityCheck(newStorage.elementShift == 1)
_cocoaStringReadAll(cocoaBuffer!,
newStorage.start.assumingMemoryBound(to: UTF16.CodeUnit.self))
#else
_sanityCheckFailure("_copyInPlace: non-native string without objc runtime")
#endif
}
self = _StringCore(newStorage)
}
/// Append `c` to `self`.
///
/// - Complexity: O(1) when amortized over repeated appends of equal
/// character values.
mutating func append(_ c: UnicodeScalar) {
let width = UTF16.width(c)
append(
width == 2 ? UTF16.leadSurrogate(c) : UTF16.CodeUnit(c.value),
width == 2 ? UTF16.trailSurrogate(c) : nil
)
}
/// Append `u` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(_ u: UTF16.CodeUnit) {
append(u, nil)
}
mutating func append(_ u0: UTF16.CodeUnit, _ u1: UTF16.CodeUnit?) {
_invariantCheck()
let minBytesPerCodeUnit = u0 <= 0x7f ? 1 : 2
let utf16Width = u1 == nil ? 1 : 2
let destination = _growBuffer(
count + utf16Width, minElementWidth: minBytesPerCodeUnit)
if _fastPath(elementWidth == 1) {
_sanityCheck(_pointer(toElementAt:count) == destination + 1)
destination.assumingMemoryBound(to: UTF8.CodeUnit.self)[0]
= UTF8.CodeUnit(u0)
}
else {
let destination16
= destination.assumingMemoryBound(to: UTF16.CodeUnit.self)
destination16[0] = u0
if u1 != nil {
destination16[1] = u1!
}
}
_invariantCheck()
}
@inline(never)
mutating func append(_ rhs: _StringCore) {
_invariantCheck()
let minElementWidth
= elementWidth >= rhs.elementWidth
? elementWidth
: rhs.isRepresentableAsASCII() ? 1 : 2
let destination = _growBuffer(
count + rhs.count, minElementWidth: minElementWidth)
if _fastPath(rhs.hasContiguousStorage) {
_StringCore._copyElements(
rhs._baseAddress!, srcElementWidth: rhs.elementWidth,
dstStart: destination, dstElementWidth:elementWidth, count: rhs.count)
}
else {
#if _runtime(_ObjC)
_sanityCheck(elementWidth == 2)
_cocoaStringReadAll(rhs.cocoaBuffer!,
destination.assumingMemoryBound(to: UTF16.CodeUnit.self))
#else
_sanityCheckFailure("subscript: non-native string without objc runtime")
#endif
}
_invariantCheck()
}
/// Returns `true` iff the contents of this string can be
/// represented as pure ASCII.
///
/// - Complexity: O(*n*) in the worst case.
func isRepresentableAsASCII() -> Bool {
if _slowPath(!hasContiguousStorage) {
return false
}
if _fastPath(elementWidth == 1) {
return true
}
let unsafeBuffer =
UnsafeBufferPointer(
start: _baseAddress!.assumingMemoryBound(to: UTF16.CodeUnit.self),
count: count)
return !unsafeBuffer.contains { $0 > 0x7f }
}
}
extension _StringCore : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
public // @testable
var startIndex: Int {
return 0
}
public // @testable
var endIndex: Int {
return count
}
}
extension _StringCore : RangeReplaceableCollection {
/// Replace the elements within `bounds` with `newElements`.
///
/// - Complexity: O(`bounds.count`) if `bounds.upperBound
/// == self.endIndex` and `newElements.isEmpty`, O(*n*) otherwise.
public mutating func replaceSubrange<C>(
_ bounds: Range<Int>,
with newElements: C
) where C : Collection, C.Iterator.Element == UTF16.CodeUnit {
_precondition(
bounds.lowerBound >= 0,
"replaceSubrange: subrange start precedes String start")
_precondition(
bounds.upperBound <= count,
"replaceSubrange: subrange extends past String end")
let width = elementWidth == 2 || newElements.contains { $0 > 0x7f } ? 2 : 1
let replacementCount = numericCast(newElements.count) as Int
let replacedCount = bounds.count
let tailCount = count - bounds.upperBound
let growth = replacementCount - replacedCount
let newCount = count + growth
// Successfully claiming capacity only ensures that we can modify
// the newly-claimed storage without observably mutating other
// strings, i.e., when we're appending. Already-used characters
// can only be mutated when we have a unique reference to the
// buffer.
let appending = bounds.lowerBound == endIndex
let existingStorage = !hasCocoaBuffer && (
appending || isKnownUniquelyReferenced(&_owner)
) ? _claimCapacity(newCount, minElementWidth: width).1 : nil
if _fastPath(existingStorage != nil) {
let rangeStart = _pointer(toElementAt:bounds.lowerBound)
let tailStart = rangeStart + (replacedCount << elementShift)
if growth > 0 {
(tailStart + (growth << elementShift)).copyBytes(
from: tailStart, count: tailCount << elementShift)
}
if _fastPath(elementWidth == 1) {
var dst = rangeStart.assumingMemoryBound(to: UTF8.CodeUnit.self)
for u in newElements {
dst.pointee = UInt8(truncatingBitPattern: u)
dst += 1
}
}
else {
var dst = rangeStart.assumingMemoryBound(to: UTF16.CodeUnit.self)
for u in newElements {
dst.pointee = u
dst += 1
}
}
if growth < 0 {
(tailStart + (growth << elementShift)).copyBytes(
from: tailStart, count: tailCount << elementShift)
}
}
else {
var r = _StringCore(
_StringBuffer(
capacity: newCount,
initialSize: 0,
elementWidth:
width == 1 ? 1
: isRepresentableAsASCII() && !newElements.contains { $0 > 0x7f } ? 1
: 2
))
r.append(contentsOf: self[0..<bounds.lowerBound])
r.append(contentsOf: newElements)
r.append(contentsOf: self[bounds.upperBound..<count])
self = r
}
}
public mutating func reserveCapacity(_ n: Int) {
if _fastPath(!hasCocoaBuffer) {
if _fastPath(isKnownUniquelyReferenced(&_owner)) {
let bounds: Range<UnsafeRawPointer>
= UnsafeRawPointer(_pointer(toElementAt:0))
..< UnsafeRawPointer(_pointer(toElementAt:count))
if _fastPath(nativeBuffer!.hasCapacity(n, forSubRange: bounds)) {
return
}
}
}
_copyInPlace(
newSize: count,
newCapacity: Swift.max(count, n),
minElementWidth: 1)
}
public mutating func append<S : Sequence>(contentsOf s: S)
where S.Iterator.Element == UTF16.CodeUnit {
var width = elementWidth
if width == 1 {
if let hasNonAscii = s._preprocessingPass({
s.contains { $0 > 0x7f }
}) {
width = hasNonAscii ? 2 : 1
}
}
let growth = s.underestimatedCount
var iter = s.makeIterator()
if _fastPath(growth > 0) {
let newSize = count + growth
let destination = _growBuffer(newSize, minElementWidth: width)
if elementWidth == 1 {
let destination8
= destination.assumingMemoryBound(to: UTF8.CodeUnit.self)
for i in 0..<growth {
destination8[i] = UTF8.CodeUnit(iter.next()!)
}
}
else {
let destination16
= destination.assumingMemoryBound(to: UTF16.CodeUnit.self)
for i in 0..<growth {
destination16[i] = iter.next()!
}
}
}
// Append any remaining elements
for u in IteratorSequence(iter) {
self.append(u)
}
}
}
// Used to support a tighter invariant: all strings with contiguous
// storage have a non-NULL base address.
var _emptyStringStorage: UInt32 = 0
var _emptyStringBase: UnsafeMutableRawPointer {
return UnsafeMutableRawPointer(Builtin.addressof(&_emptyStringStorage))
}
| apache-2.0 | 2378c62312884716aaed7539095ef5da | 31.010811 | 147 | 0.639944 | 4.578276 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/DataModel/HealthKit/HealthKitManager.swift | 1 | 21082 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import HealthKit
import CocoaLumberjack
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class HealthKitManager {
// MARK: Access, availability, authorization
static let sharedInstance = HealthKitManager()
fileprivate init() {
DDLogVerbose("trace")
}
let healthStore: HKHealthStore? = {
return HKHealthStore.isHealthDataAvailable() ? HKHealthStore() : nil
}()
let isHealthDataAvailable: Bool = {
return HKHealthStore.isHealthDataAvailable()
}()
func authorizationRequestedForBloodGlucoseSamples() -> Bool {
return UserDefaults.standard.bool(forKey: "authorizationRequestedForBloodGlucoseSamples")
}
func authorizationRequestedForBloodGlucoseSampleWrites() -> Bool {
return UserDefaults.standard.bool(forKey: "authorizationRequestedForBloodGlucoseSampleWrites")
}
func authorizationRequestedForWorkoutSamples() -> Bool {
return UserDefaults.standard.bool(forKey: "authorizationRequestedForWorkoutSamples")
}
func authorize(shouldAuthorizeBloodGlucoseSampleReads: Bool, shouldAuthorizeBloodGlucoseSampleWrites: Bool, shouldAuthorizeWorkoutSamples: Bool, completion: @escaping (_ success:Bool, _ error:NSError?) -> Void = {(_, _) in })
{
DDLogVerbose("trace")
var authorizationSuccess = false
var authorizationError: NSError?
defer {
if authorizationError != nil {
DDLogInfo("authorization error: \(authorizationError)")
completion(authorizationSuccess, authorizationError)
}
}
guard isHealthDataAvailable else {
authorizationError = NSError(domain: "HealthKitManager", code: -1, userInfo: [NSLocalizedDescriptionKey:"HealthKit is not available on this device"])
return
}
var readTypes: Set<HKSampleType>?
var writeTypes: Set<HKSampleType>?
if (shouldAuthorizeBloodGlucoseSampleReads) {
readTypes = Set<HKSampleType>()
readTypes!.insert(HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!)
}
if (shouldAuthorizeBloodGlucoseSampleWrites) {
writeTypes = Set<HKSampleType>()
writeTypes!.insert(HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!)
}
if (shouldAuthorizeWorkoutSamples) {
if readTypes == nil {
readTypes = Set<HKSampleType>()
}
readTypes!.insert(HKObjectType.workoutType())
}
guard readTypes != nil || writeTypes != nil else {
DDLogVerbose("No health data authorization requested, ignoring")
return
}
if (isHealthDataAvailable) {
healthStore!.requestAuthorization(toShare: writeTypes, read: readTypes) { (success, error) -> Void in
if success {
if (shouldAuthorizeBloodGlucoseSampleReads) {
UserDefaults.standard.set(true, forKey: "authorizationRequestedForBloodGlucoseSamples");
}
if (shouldAuthorizeBloodGlucoseSampleWrites) {
UserDefaults.standard.set(true, forKey: "authorizationRequestedForBloodGlucoseSampleWrites");
}
if shouldAuthorizeWorkoutSamples {
UserDefaults.standard.set(true, forKey: "authorizationRequestedForWorkoutSamples");
}
UserDefaults.standard.synchronize()
}
authorizationSuccess = success
authorizationError = error as NSError?
DDLogInfo("authorization success: \(authorizationSuccess), error: \(authorizationError)")
completion(authorizationSuccess, authorizationError)
}
}
}
// MARK: Observation
func startObservingBloodGlucoseSamples(_ observationHandler: @escaping (NSError?) -> (Void)) {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if bloodGlucoseObservationQuery != nil {
healthStore?.stop(bloodGlucoseObservationQuery!)
bloodGlucoseObservationQuery = nil
}
let sampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!
bloodGlucoseObservationQuery = HKObserverQuery(sampleType: sampleType, predicate: nil) {
(query, observerQueryCompletion, error) in
DDLogVerbose("Observation query called")
if error != nil {
DDLogError("HealthKit observation error \(error)")
}
observationHandler(error as NSError?)
// Per HealthKit docs: Calling this block tells HealthKit that you have successfully received the background data. If you do not call this block, HealthKit continues to attempt to launch your app using a back off algorithm. If your app fails to respond three times, HealthKit assumes that your app cannot receive data, and stops sending you background updates
observerQueryCompletion()
}
healthStore?.execute(bloodGlucoseObservationQuery!)
}
func stopObservingBloodGlucoseSamples() {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if bloodGlucoseObservationQuery != nil {
healthStore?.stop(bloodGlucoseObservationQuery!)
bloodGlucoseObservationQuery = nil
}
}
// NOTE: resultsHandler is called on a separate process queue!
func startObservingWorkoutSamples(_ resultsHandler: (([HKSample]?, [HKDeletedObject]?, NSError?) -> Void)!) {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if !workoutsObservationSuccessful {
if workoutsObservationQuery != nil {
healthStore?.stop(workoutsObservationQuery!)
}
let sampleType = HKObjectType.workoutType()
workoutsObservationQuery = HKObserverQuery(sampleType: sampleType, predicate: nil) {
[unowned self](query, observerQueryCompletion, error) in
if error == nil {
self.workoutsObservationSuccessful = true
self.readWorkoutSamples(resultsHandler)
} else {
DDLogError("HealthKit observation error \(error), \((error as! NSError).userInfo)")
resultsHandler?(nil, nil, (error as! NSError))
}
observerQueryCompletion()
}
healthStore?.execute(workoutsObservationQuery!)
}
}
func stopObservingWorkoutSamples() {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if workoutsObservationSuccessful {
if workoutsObservationQuery != nil {
healthStore?.stop(workoutsObservationQuery!)
workoutsObservationQuery = nil
}
workoutsObservationSuccessful = false
}
}
// MARK: Background delivery
func enableBackgroundDeliveryBloodGlucoseSamples() {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if !bloodGlucoseBackgroundDeliveryEnabled {
healthStore?.enableBackgroundDelivery(
for: HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!,
frequency: HKUpdateFrequency.immediate) {
success, error -> Void in
if error == nil {
self.bloodGlucoseBackgroundDeliveryEnabled = true
DDLogError("Enabled background delivery of health data")
} else {
DDLogError("Error enabling background delivery of health data \(error), \(error!._userInfo)")
}
}
}
}
func disableBackgroundDeliveryBloodGlucoseSamples() {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if bloodGlucoseBackgroundDeliveryEnabled {
healthStore?.disableBackgroundDelivery(for: HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!) {
success, error -> Void in
if error == nil {
self.bloodGlucoseBackgroundDeliveryEnabled = false
DDLogError("Disabled background delivery of health data")
} else {
DDLogError("Error disabling background delivery of health data \(error), \(error!._userInfo)")
}
}
}
}
func enableBackgroundDeliveryWorkoutSamples() {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if !workoutsBackgroundDeliveryEnabled {
healthStore?.enableBackgroundDelivery(
for: HKObjectType.workoutType(),
frequency: HKUpdateFrequency.immediate) {
success, error -> Void in
if error == nil {
self.workoutsBackgroundDeliveryEnabled = true
DDLogError("Enabled background delivery of health data")
} else {
DDLogError("Error enabling background delivery of health data \(error), \(error!._userInfo)")
}
}
}
}
func disableBackgroundDeliveryWorkoutSamples() {
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
if workoutsBackgroundDeliveryEnabled {
healthStore?.disableBackgroundDelivery(for: HKObjectType.workoutType()) {
success, error -> Void in
if error == nil {
self.workoutsBackgroundDeliveryEnabled = false
DDLogError("Disabled background delivery of health data")
} else {
DDLogError("Error disabling background delivery of health data \(error), \((error as! NSError).userInfo)")
}
}
}
}
func readBloodGlucoseSamplesFromAnchor(_ resultsHandler: @escaping ((NSError?, [HKSample]?, _ completion: @escaping (NSError?) -> (Void)) -> Void))
{
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
var queryAnchor: HKQueryAnchor?
let queryAnchorData = UserDefaults.standard.object(forKey: "bloodGlucoseQueryAnchor")
if queryAnchorData != nil {
queryAnchor = NSKeyedUnarchiver.unarchiveObject(with: queryAnchorData as! Data) as? HKQueryAnchor
}
let sampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!
let sampleQuery = HKAnchoredObjectQuery(type: sampleType,
predicate: nil, // TODO: my - We should probably use a LIKE predicate with wildcard to have the query filter Dexcom samples rather than filtering results as we receive them
anchor: queryAnchor,
limit: 288) { // Limit to 288 samples (about one day of samples at 5 minute intervals)
(query, newSamples, deletedSamples, newAnchor, error) -> Void in
if error != nil {
DDLogError("Error reading samples: \(error)")
}
resultsHandler((error as? NSError), newSamples) {
(error: NSError?) in
if error == nil && newAnchor != nil {
let queryAnchorData = NSKeyedArchiver.archivedData(withRootObject: newAnchor!)
UserDefaults.standard.set(queryAnchorData, forKey: "bloodGlucoseQueryAnchor")
UserDefaults.standard.synchronize()
}
}
}
healthStore?.execute(sampleQuery)
}
func readBloodGlucoseSamples(startDate: Date, endDate: Date, limit: Int, resultsHandler: @escaping (((NSError?, [HKSample]?, _ completion: @escaping (NSError?) -> (Void)) -> Void)))
{
DDLogInfo("readBloodGlucoseSamples startDate: \(startDate), endDate: \(endDate), limit: \(limit)")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [.strictEndDate, .strictEndDate])
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
let sampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: limit, sortDescriptors: [sortDescriptor]) {
(query, newSamples, error) -> Void in
if error != nil {
DDLogError("Error reading samples: \(error)")
}
resultsHandler(error as NSError?, newSamples) {
(error: NSError?) in
// Nothing to do
}
}
healthStore?.execute(sampleQuery)
}
func countBloodGlucoseSamples(_ completion: @escaping (_ error: NSError?, _ totalSamplesCount: Int, _ totalDexcomSamplesCount: Int) -> (Void)) {
let sampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.bloodGlucose)!
let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: nil, limit: HKObjectQueryNoLimit, sortDescriptors: nil) {
(query, newSamples, error) -> Void in
var totalSamplesCount = 0
var totalDexcomSamplesCount = 0
if newSamples != nil {
for sample in newSamples! {
let sourceRevision = sample.sourceRevision
let source = sourceRevision.source
totalSamplesCount += 1
if source.name.lowercased().range(of: "dexcom") != nil {
totalDexcomSamplesCount += 1
}
}
}
completion(error as NSError?, totalSamplesCount, totalDexcomSamplesCount)
}
healthStore?.execute(sampleQuery)
}
func findSampleDateRange(sampleType: HKSampleType, completion: @escaping (_ error: NSError?, _ startDate: Date?, _ endDate: Date?) -> Void)
{
DDLogVerbose("trace")
var startDate: Date? = nil
var endDate: Date? = nil
let predicate = HKQuery.predicateForSamples(withStart: Date.distantPast, end: Date.distantFuture, options: [])
let startDateSortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: true)
let endDateSortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierStartDate, ascending: false)
// Kick of query to find startDate
let startDateSampleQuery = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: 1, sortDescriptors: [startDateSortDescriptor]) {
(query: HKSampleQuery, samples: [HKSample]?, error: Error?) -> Void in
if error == nil && samples != nil {
// Get startDate of oldest sample
if samples?.count > 0 {
startDate = samples![0].startDate
}
// Kick of query to find endDate
let endDateSampleQuery = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: 1, sortDescriptors: [endDateSortDescriptor]) {
(query: HKSampleQuery, samples: [HKSample]?, error: Error?) -> Void in
if error == nil && samples?.count > 0 {
endDate = samples![0].endDate
}
completion((error as? NSError), startDate, endDate)
}
self.healthStore?.execute(endDateSampleQuery)
} else {
completion((error as? NSError), startDate, endDate)
}
}
healthStore?.execute(startDateSampleQuery)
}
func readWorkoutSamples(_ resultsHandler: @escaping (([HKSample]?, [HKDeletedObject]?, NSError?) -> Void) = {(_, _, _) in })
{
DDLogVerbose("trace")
guard isHealthDataAvailable else {
DDLogError("Unexpected HealthKitManager call when health data not available")
return
}
var queryAnchor: HKQueryAnchor?
let queryAnchorData = UserDefaults.standard.object(forKey: "workoutQueryAnchor")
if queryAnchorData != nil {
queryAnchor = NSKeyedUnarchiver.unarchiveObject(with: queryAnchorData as! Data) as? HKQueryAnchor
}
let sampleType = HKObjectType.workoutType()
let sampleQuery = HKAnchoredObjectQuery(type: sampleType,
predicate: nil,
anchor: queryAnchor,
limit: Int(HKObjectQueryNoLimit /* 100 */)) { // TODO: need to limit to like 100 or so once clients are properly handling the "more" case like we do for observing/caching blood glucose data
(query, newSamples, deletedSamples, newAnchor, error) -> Void in
resultsHandler(newSamples, deletedSamples, (error as? NSError))
if error == nil && newAnchor != nil {
let queryAnchorData = NSKeyedArchiver.archivedData(withRootObject: newAnchor!)
UserDefaults.standard.set(queryAnchorData, forKey: "workoutQueryAnchor")
UserDefaults.standard.synchronize()
}
}
healthStore?.execute(sampleQuery)
}
// MARK: Private
fileprivate var bloodGlucoseObservationQuery: HKObserverQuery?
fileprivate var bloodGlucoseBackgroundDeliveryEnabled = false
fileprivate var bloodGlucoseQueryAnchor = Int(HKAnchoredObjectQueryNoAnchor)
fileprivate var workoutsObservationSuccessful = false
fileprivate var workoutsObservationQuery: HKObserverQuery?
fileprivate var workoutsBackgroundDeliveryEnabled = false
fileprivate var workoutsQueryAnchor = Int(HKAnchoredObjectQueryNoAnchor)
}
| bsd-2-clause | 0ea87746d561bb5a23e46ef6f00ec85d | 41.418511 | 383 | 0.609145 | 5.902016 | false | false | false | false |
ReactiveKit/Bond | Sources/Bond/AppKit/NSButton.swift | 1 | 3711 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 Tony Arnold (@tonyarnold)
//
// 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.
//
#if os(macOS)
import AppKit
import ReactiveKit
extension ReactiveExtensions where Base: NSButton {
public var state: DynamicSubject<NSControl.StateValue> {
return dynamicSubject(
signal: controlEvent.eraseType(),
get: { $0.state },
set: { $0.state = $1 }
)
}
public var title: Bond<String> {
return bond { $0.title = $1 }
}
public var alternateTitle: Bond<String> {
return bond { $0.alternateTitle = $1 }
}
public var image: Bond<NSImage?> {
return bond { $0.image = $1 }
}
public var alternateImage: Bond<NSImage?> {
return bond { $0.alternateImage = $1 }
}
public var imagePosition: Bond<NSControl.ImagePosition> {
return bond { $0.imagePosition = $1 }
}
public var imageScaling: Bond<NSImageScaling> {
return bond { $0.imageScaling = $1 }
}
@available(macOS 10.12, *)
public var imageHugsTitle: Bond<Bool> {
return bond { $0.imageHugsTitle = $1 }
}
public var isBordered: Bond<Bool> {
return bond { $0.isBordered = $1 }
}
public var isTransparent: Bond<Bool> {
return bond { $0.isTransparent = $1 }
}
public var keyEquivalent: Bond<String> {
return bond { $0.keyEquivalent = $1 }
}
public var keyEquivalentModifierMask: Bond<NSEvent.ModifierFlags> {
return bond { $0.keyEquivalentModifierMask = $1 }
}
@available(macOS 10.10.3, *)
public var isSpringLoaded: Bond<Bool> {
return bond { $0.isSpringLoaded = $1 }
}
@available(macOS 10.10.3, *)
public var maxAcceleratorLevel: Bond<Int> {
return bond { $0.maxAcceleratorLevel = $1 }
}
@available(macOS 10.12.2, *)
public var bezelColor: Bond<NSColor?> {
return bond { $0.bezelColor = $1 }
}
public var attributedTitle: Bond<NSAttributedString> {
return bond { $0.attributedTitle = $1 }
}
public var attributedAlternateTitle: Bond<NSAttributedString> {
return bond { $0.attributedAlternateTitle = $1 }
}
public var bezelStyle: Bond<NSButton.BezelStyle> {
return bond { $0.bezelStyle = $1 }
}
public var allowsMixedState: Bond<Bool> {
return bond { $0.allowsMixedState = $1 }
}
public var showsBorderOnlyWhileMouseInside: Bond<Bool> {
return bond { $0.showsBorderOnlyWhileMouseInside = $1 }
}
public var sound: Bond<NSSound?> {
return bond { $0.sound = $1 }
}
}
#endif
| mit | 4306653d2ffbf458ba122402758da469 | 28.688 | 81 | 0.646187 | 3.952077 | false | false | false | false |
bazelbuild/tulsi | src/Tulsi/OptionsTargetSelectorController.swift | 1 | 3808 | // Copyright 2016 The Tulsi 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 Cocoa
import TulsiGenerator
/// Models a UIRuleEntry as a node suitable for display in the options target selector.
class OptionsTargetNode: UISelectableOutlineViewNode {
/// Tooltip to be displayed for this node.
@objc var toolTip: String? = nil
@objc var boldFont: Bool {
return !children.isEmpty
}
}
protocol OptionsTargetSelectorControllerDelegate: AnyObject {
/// Invoked when the target selection has been changed.
func didSelectOptionsTargetNode(_ node: OptionsTargetNode)
}
// Delegate for the target selector outline view.
class OptionsTargetSelectorController: NSObject, NSOutlineViewDelegate {
static let projectSectionTitle =
NSLocalizedString("OptionsTarget_ProjectSectionTitle",
comment: "Short header shown before the project in the options editor's target selector.")
static let targetSectionTitle =
NSLocalizedString("OptionsTarget_TargetSectionTitle",
comment: "Short header shown before the build targets in the options editor's target selector.")
weak var view: NSOutlineView!
@objc dynamic var nodes = [OptionsTargetNode]()
weak var delegate: OptionsTargetSelectorControllerDelegate?
weak var model: OptionsEditorModelProtocol! = nil {
didSet {
if model == nil || model.projectName == nil { return }
let projectSection = OptionsTargetNode(name: OptionsTargetSelectorController.projectSectionTitle)
projectSection.addChild(OptionsTargetNode(name: model.projectName!))
var newNodes = [projectSection]
if model.shouldShowPerTargetOptions, let targetEntries = model.optionsTargetUIRuleEntries {
let targetSection = OptionsTargetNode(name: OptionsTargetSelectorController.targetSectionTitle)
for entry in targetEntries {
let node = OptionsTargetNode(name: entry.targetName!)
node.toolTip = entry.fullLabel
node.entry = entry
targetSection.addChild(node)
}
newNodes.append(targetSection)
}
nodes = newNodes
// Expand all children in the target selector and select the project.
view.expandItem(nil, expandChildren: true)
view.selectRowIndexes(IndexSet(integer: 1), byExtendingSelection: false)
}
}
init(view: NSOutlineView, delegate: OptionsTargetSelectorControllerDelegate) {
self.view = view
self.delegate = delegate
super.init()
self.view.delegate = self
}
func outlineView(_ outlineView: NSOutlineView, shouldSelectItem item: Any) -> Bool {
// The top level items are not selectable.
return outlineView.level(forItem: item) > 0
}
func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
return false
}
func outlineView(_ outlineView: NSOutlineView, shouldShowOutlineCellForItem item: Any) -> Bool {
return false
}
func outlineViewSelectionDidChange(_ notification: Notification) {
if delegate == nil { return }
let selectedTreeNode = view.item(atRow: view.selectedRow) as! NSTreeNode
let selectedTarget = selectedTreeNode.representedObject as! OptionsTargetNode
delegate!.didSelectOptionsTargetNode(selectedTarget)
}
}
| apache-2.0 | b318300d53321d6353f3e07843615bcd | 36.333333 | 120 | 0.733981 | 4.820253 | false | false | false | false |
ascode/pmn | AnimationDemo/Controller/RecursionSetToChangeImageViewController.swift | 1 | 3801 | //
// RecursionSetToChangeImageViewController.swift
// AnimationDemo
//
// Created by 金飞 on 2016/10/17.
// Copyright © 2016年 JL. All rights reserved.
//
import UIKit
class RecursionSetToChangeImageViewController: UIViewController {
var img: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
img = UIImageView()
img.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 50)
self.view.addSubview(img)
let btnStart: UIButton = UIButton()
btnStart.frame = CGRect(x: UIScreen.main.bounds.width * 0/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnStart.setTitle("播放", for: UIControlState.normal)
btnStart.layer.borderColor = UIColor.white.cgColor
btnStart.layer.borderWidth = 3
btnStart.layer.cornerRadius = 3
btnStart.layer.masksToBounds = true
btnStart.backgroundColor = UIColor.blue
btnStart.addTarget(self, action: #selector(ImageViewAnimationViewController.btnStartPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnStart)
let btnStop: UIButton = UIButton()
btnStop.frame = CGRect(x: UIScreen.main.bounds.width * 1/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnStop.setTitle("暂停", for: UIControlState.normal)
btnStop.layer.borderColor = UIColor.white.cgColor
btnStop.layer.borderWidth = 3
btnStop.layer.cornerRadius = 3
btnStop.layer.masksToBounds = true
btnStop.backgroundColor = UIColor.blue
btnStop.addTarget(self, action: #selector(ImageViewAnimationViewController.btnStopPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnStop)
let btnBack: UIButton = UIButton()
btnBack.frame = CGRect(x: UIScreen.main.bounds.width * 2/3, y: UIScreen.main.bounds.height - 50, width: UIScreen.main.bounds.width / 3, height: 50)
btnBack.setTitle("返回", for: UIControlState.normal)
btnBack.layer.borderColor = UIColor.white.cgColor
btnBack.layer.borderWidth = 3
btnBack.layer.cornerRadius = 3
btnBack.layer.masksToBounds = true
btnBack.backgroundColor = UIColor.blue
btnBack.addTarget(self, action: #selector(ImageViewAnimationViewController.btnBackPressed), for: UIControlEvents.touchUpInside)
self.view.addSubview(btnBack)
self.perform(#selector(RecursionSetToChangeImageViewController.changeImages), with: img, afterDelay: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var imgCode = 1
var state = 1
func changeImages(imgView: UIImageView){
if imgCode <= 25 && state == 1{
img.image = UIImage(named: "\(imgCode)")
imgCode += 1
}
self.perform(#selector(RecursionSetToChangeImageViewController.changeImages), with: img, afterDelay: 1)
}
func btnBackPressed(){
self.dismiss(animated: true) {
}
}
func btnStartPressed(){
state = 1
}
func btnStopPressed(){
state = 0
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 0a6e645eae50dda3bc6429aae74766ca | 35.019048 | 156 | 0.65468 | 4.657635 | false | false | false | false |
team-supercharge/boa | lib/boa/module/templates/swift/ModuleInterface.swift | 1 | 268 | //
// <%= @prefixed_module %>ModuleInterface.swift
// <%= @project %>
//
// Created by <%= @author %> on <%= @date %>.
//
//
import Foundation
protocol <%= @prefixed_module %>ModuleInterface: class
{
}
protocol <%= @prefixed_module %>ModuleDelegate: class
{
}
| mit | 8d67a9a57b39f4c1d70a81229ee5abcb | 13.105263 | 54 | 0.600746 | 3.35 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame | JKWayfairPriceGame/FinalScoreIndicatorView.swift | 1 | 4703 | //
// FinalScoreIndicatorView.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli Backup on 8/20/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import Foundation
import UIKit
class FinalScoreIndicatorView: UIView {
let viewModel: FinalScoreIndicatorViewModel
init(viewModel: FinalScoreIndicatorViewModel, frame: CGRect) {
self.viewModel = viewModel
super.init(frame: frame)
self.backgroundColor = UIColor(hex: 0xbdc3c7)
self.layer.cornerRadius = 20
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor(hex: 0x27ae60).CGColor
let goBackButton = CustomButton()
goBackButton.translatesAutoresizingMaskIntoConstraints = false
goBackButton.setTitleColor(.blackColor(), forState: .Normal)
goBackButton.layer.borderColor = UIColor.lightGrayColor().CGColor
goBackButton.backgroundColor = Appearance.secondaryButtonBackgroundColor()
goBackButton.rac_command = self.viewModel.goBackButtonActionCommand
goBackButton.titleLabel?.font = Appearance.buttonsFont()
goBackButton.setTitle("Go Back", forState: .Normal)
self.addSubview(goBackButton)
let newGameButton = CustomButton()
newGameButton.translatesAutoresizingMaskIntoConstraints = false
newGameButton.setTitleColor(.blackColor(), forState: .Normal)
newGameButton.layer.borderColor = UIColor.lightGrayColor().CGColor
newGameButton.backgroundColor = Appearance.secondaryButtonBackgroundColor()
newGameButton.titleLabel?.font = Appearance.buttonsFont()
newGameButton.rac_command = self.viewModel.newGameButtonActionCommand
newGameButton.setTitle("New Game", forState: .Normal)
self.addSubview(newGameButton)
let viewStatisticsButton = CustomButton()
viewStatisticsButton.translatesAutoresizingMaskIntoConstraints = false
viewStatisticsButton.setTitleColor(.blackColor(), forState: .Normal)
viewStatisticsButton.rac_command = self.viewModel.viewStatisticsButtonActionCommand
viewStatisticsButton.layer.borderColor = UIColor.lightGrayColor().CGColor
viewStatisticsButton.setTitle("Statistics", forState: .Normal)
viewStatisticsButton.titleLabel?.font = Appearance.buttonsFont()
viewStatisticsButton.backgroundColor = Appearance.secondaryButtonBackgroundColor()
let answeredAtleastOneQuestion = self.viewModel.gameViewModel.answersCollection.count > 0
viewStatisticsButton.userInteractionEnabled = answeredAtleastOneQuestion
viewStatisticsButton.alpha = answeredAtleastOneQuestion == true ? 1.0 : 0.5
self.addSubview(viewStatisticsButton)
let gameStatsLabel = UILabel()
gameStatsLabel.translatesAutoresizingMaskIntoConstraints = false
gameStatsLabel.numberOfLines = 0
gameStatsLabel.textAlignment = .Center
gameStatsLabel.font = Appearance.defaultFont()
gameStatsLabel.text = self.viewModel.totalStats
gameStatsLabel.textColor = self.viewModel.finalScoreLabelTextColor
self.addSubview(gameStatsLabel)
let views = ["gameStatsLabel": gameStatsLabel, "goBackButton": goBackButton, "newGameButton": newGameButton, "viewStatisticsButton": viewStatisticsButton]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[gameStatsLabel]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[goBackButton]-[newGameButton(==goBackButton)]-[viewStatisticsButton(==newGameButton)]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[gameStatsLabel]-[goBackButton]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[gameStatsLabel]-[newGameButton]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[gameStatsLabel]-[viewStatisticsButton]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
RACObserve(self.viewModel, keyPath: "finalScoreScreenOption").skip(1).subscribeNext {
[unowned self] selectedOption in
self.removeFromSuperview()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | mit | e3eb3d37ec1618f648680124cdc55414 | 54.988095 | 244 | 0.732454 | 5.454756 | false | false | false | false |
iSapozhnik/SILoadingControllerDemo | LoadingControllerDemo/LoadingControllerDemo/LoadingController/Views/LoadingViews/ActivityViews/MulticolorActivityView.swift | 1 | 3800 | //
// MulticolorLoadingView.swift
// LoadingControllerDemo
//
// Created by Sapozhnik Ivan on 28.06.16.
// Copyright © 2016 Sapozhnik Ivan. All rights reserved.
//
import UIKit
class MulticolorActivityView: UIView {
let defaultLineWidth: CGFloat = 2.0
let defaultColor = UIColor.orangeColor()
let defaultRoundTime = 1.5
var colorArray = [UIColor.greenColor(), UIColor.redColor(), UIColor.blueColor(), UIColor.purpleColor(),] {
didSet {
updateAnimations()
}
}
private var circleLayer = CAShapeLayer()
private var strokeLineAnimation = CAAnimationGroup()
private let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
private let strokeColorAnimation = CAKeyframeAnimation(keyPath: "strokeColor")
override init(frame: CGRect) {
super.init(frame: frame)
initialSetup()
}
required internal init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
// MARK:- Public
func startAnimating() {
circleLayer.addAnimation(strokeLineAnimation, forKey: "strokeLineAnimation")
circleLayer.addAnimation(rotationAnimation, forKey: "rotationAnimation")
circleLayer.addAnimation(strokeColorAnimation, forKey: "strokeColorAnimation")
}
func stopAnimating() {
circleLayer.removeAnimationForKey("strokeLineAnimation")
circleLayer.removeAnimationForKey("rotationAnimation")
circleLayer.removeAnimationForKey("strokeColorAnimation")
}
// MARK:- Private
private func initialSetup() {
self.layer.addSublayer(circleLayer)
backgroundColor = .clearColor()
circleLayer.fillColor = nil
circleLayer.lineWidth = defaultLineWidth
circleLayer.lineCap = "round"
updateAnimations()
}
private func updateAnimations() {
// Stroke head
let headAnimation = CABasicAnimation(keyPath: "strokeStart")
headAnimation.beginTime = defaultRoundTime / 3.0
headAnimation.fromValue = 0
headAnimation.toValue = 1
headAnimation.duration = 2 * defaultRoundTime / 3.0
headAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Stroke tail
let tailAnimation = CABasicAnimation(keyPath: "strokeEnd")
tailAnimation.fromValue = 0
tailAnimation.toValue = 1
tailAnimation.duration = 2 * defaultRoundTime / 3.0
tailAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
// Stroke line group
strokeLineAnimation.duration = defaultRoundTime
strokeLineAnimation.repeatCount = Float.infinity
strokeLineAnimation.animations = [headAnimation, tailAnimation]
// Rotation
rotationAnimation.fromValue = 0
rotationAnimation.toValue = 2 * M_PI
rotationAnimation.duration = defaultRoundTime
rotationAnimation.repeatCount = Float.infinity
// Color animation
strokeColorAnimation.values = colorArray.map({$0.CGColor})
strokeColorAnimation.keyTimes = keyTimes()
strokeColorAnimation.calculationMode = kCAAnimationDiscrete;
strokeColorAnimation.duration = Double(colorArray.count) * defaultRoundTime
strokeColorAnimation.repeatCount = Float.infinity
}
private func keyTimes() -> Array<Double> {
var array: Array<Double> = []
for (index, _) in colorArray.enumerate() {
array.append(Double(index)/Double(colorArray.count))
}
array.append(1.0)
return array
}
// MARK:- Layout
override func layoutSubviews() {
super.layoutSubviews()
let center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))
let radius = min(self.bounds.size.width, self.bounds.size.height) / 2.0 - circleLayer.lineWidth / 2.0
let startAngle = 0.0 as CGFloat
let endAngle = CGFloat(2 * M_PI)
let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
circleLayer.path = path.CGPath
circleLayer.frame = bounds
}
}
| mit | 0eef5db4eed9e2559c3f596a8f50672b | 29.392 | 121 | 0.758357 | 4.225806 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Synchronization/Strategies/LabelDownstreamRequestStrategyTests.swift | 1 | 13295 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@testable import WireSyncEngine
class LabelDownstreamRequestStrategyTests: MessagingTest {
var sut: LabelDownstreamRequestStrategy!
var mockSyncStatus: MockSyncStatus!
var mockSyncStateDelegate: MockSyncStateDelegate!
var mockApplicationStatus: MockApplicationStatus!
var conversation1: ZMConversation!
var conversation2: ZMConversation!
override func setUp() {
super.setUp()
mockSyncStateDelegate = MockSyncStateDelegate()
mockSyncStatus = MockSyncStatus(managedObjectContext: syncMOC, syncStateDelegate: mockSyncStateDelegate)
mockApplicationStatus = MockApplicationStatus()
mockApplicationStatus.mockSynchronizationState = .slowSyncing
sut = LabelDownstreamRequestStrategy(withManagedObjectContext: syncMOC, applicationStatus: mockApplicationStatus, syncStatus: mockSyncStatus)
syncMOC.performGroupedBlockAndWait {
self.conversation1 = ZMConversation.insertNewObject(in: self.syncMOC)
self.conversation1.remoteIdentifier = UUID()
self.conversation2 = ZMConversation.insertNewObject(in: self.syncMOC)
self.conversation2.remoteIdentifier = UUID()
}
}
override func tearDown() {
sut = nil
mockSyncStatus = nil
mockApplicationStatus = nil
mockSyncStateDelegate = nil
conversation1 = nil
conversation2 = nil
super.tearDown()
}
func successfullFolderResponse() -> ZMTransportResponse {
let encoder = JSONEncoder()
let data = try! encoder.encode(self.folderResponse(name: "folder", conversations: []))
let urlResponse = HTTPURLResponse(url: URL(string: "properties/labels")!, statusCode: 200, httpVersion: nil, headerFields: nil)!
return ZMTransportResponse(httpurlResponse: urlResponse, data: data, error: nil, apiVersion: APIVersion.v0.rawValue)
}
func favoriteResponse(identifier: UUID = UUID(), favorites: [UUID]) -> WireSyncEngine.LabelPayload {
let update = WireSyncEngine.LabelUpdate(id: identifier, type: Label.Kind.favorite.rawValue, name: "", conversations: favorites)
let response = WireSyncEngine.LabelPayload(labels: [update])
return response
}
func folderResponse(identifier: UUID = UUID(), name: String, conversations: [UUID]) -> WireSyncEngine.LabelPayload {
let update = WireSyncEngine.LabelUpdate(id: identifier, type: Label.Kind.folder.rawValue, name: name, conversations: conversations)
let response = WireSyncEngine.LabelPayload(labels: [update])
return response
}
func updateEvent(with labels: WireSyncEngine.LabelPayload) -> ZMUpdateEvent {
let encoder = JSONEncoder()
let data = try! encoder.encode(labels)
let dict = try! JSONSerialization.jsonObject(with: data, options: [])
let payload = ["value": dict,
"key": "labels",
"type": ZMUpdateEvent.eventTypeString(for: .userPropertiesSet)!
] as [String: Any]
return ZMUpdateEvent(fromEventStreamPayload: payload as ZMTransportData, uuid: nil)!
}
// MARK: - Slow Sync
func testThatItRequestsLabels_DuringSlowSync() {
syncMOC.performGroupedBlockAndWait {
// GIVEN
self.mockSyncStatus.mockPhase = .fetchingLabels
// WHEN
guard let request = self.sut.nextRequest(for: .v0) else { return XCTFail() }
// THEN
XCTAssertEqual(request.path, "/properties/labels")
}
}
func testThatItRequestsLabels_WhenRefetchingIsNecessary() {
syncMOC.performGroupedBlockAndWait {
// GIVEN
ZMUser.selfUser(in: self.syncMOC).needsToRefetchLabels = true
// WHEN
guard let request = self.sut.nextRequest(for: .v0) else { return XCTFail() }
// THEN
XCTAssertEqual(request.path, "/properties/labels")
}
}
func testThatItResetsFlag_WhenLabelsExist() {
syncMOC.performGroupedBlockAndWait {
// GIVEN
ZMUser.selfUser(in: self.syncMOC).needsToRefetchLabels = true
guard let request = self.sut.nextRequest(for: .v0) else { return XCTFail() }
// WHEN
request.complete(with: self.successfullFolderResponse())
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
XCTAssertFalse(ZMUser.selfUser(in: self.syncMOC).needsToRefetchLabels)
}
}
func testThatItResetsFlag_WhenLabelsDontExist() {
syncMOC.performGroupedBlockAndWait {
// GIVEN
ZMUser.selfUser(in: self.syncMOC).needsToRefetchLabels = true
guard let request = self.sut.nextRequest(for: .v0) else { return XCTFail() }
// WHEN
request.complete(with: ZMTransportResponse(payload: nil, httpStatus: 404, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
XCTAssertFalse(ZMUser.selfUser(in: self.syncMOC).needsToRefetchLabels)
}
}
func testThatItFinishSlowSyncPhase_WhenLabelsExist() {
syncMOC.performGroupedBlockAndWait {
// GIVEN
self.mockSyncStatus.mockPhase = .fetchingLabels
guard let request = self.sut.nextRequest(for: .v0) else { return XCTFail() }
// WHEN
request.complete(with: self.successfullFolderResponse())
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
XCTAssertTrue(self.mockSyncStatus.didCallFinishCurrentSyncPhase)
}
}
func testThatItFinishSlowSyncPhase_WhenLabelsDontExist() {
syncMOC.performGroupedBlockAndWait {
// GIVEN
self.mockSyncStatus.mockPhase = .fetchingLabels
guard let request = self.sut.nextRequest(for: .v0) else { return XCTFail() }
// WHEN
request.complete(with: ZMTransportResponse(payload: nil, httpStatus: 404, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
XCTAssertTrue(self.mockSyncStatus.didCallFinishCurrentSyncPhase)
}
}
// MARK: - Event Processing
func testThatItUpdatesLabels_OnPropertiesUpdateEvent() {
var conversation: ZMConversation!
let conversationId = UUID()
syncMOC.performGroupedBlockAndWait {
// GIVEN
conversation = ZMConversation.insertNewObject(in: self.syncMOC)
conversation.remoteIdentifier = conversationId
self.syncMOC.saveOrRollback()
let event = self.updateEvent(with: self.favoriteResponse(favorites: [conversationId]))
// WHEN
self.sut.processEvents([event], liveEvents: false, prefetchResult: nil)
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
XCTAssertTrue(conversation.isFavorite)
}
}
// MARK: - Label Processing
func testThatItIgnoresIdentifier_WhenUpdatingFavoritelabel() {
let favoriteIdentifier = UUID()
let responseIdentifier = UUID()
syncMOC.performGroupedBlockAndWait {
// GIVEN
let label = Label.insertNewObject(in: self.syncMOC)
label.kind = .favorite
label.remoteIdentifier = favoriteIdentifier
self.syncMOC.saveOrRollback()
// WHEN
self.sut.update(with: self.favoriteResponse(identifier: responseIdentifier, favorites: [self.conversation1.remoteIdentifier!]))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
let label = Label.fetchFavoriteLabel(in: self.syncMOC)
XCTAssertEqual(label.remoteIdentifier, favoriteIdentifier)
XCTAssertEqual(label.conversations, [self.conversation1])
}
}
func testThatItResetsLocallyModifiedKeys_WhenUpdatingLabel() {
let folderIdentifier = UUID()
syncMOC.performGroupedBlockAndWait {
// GIVEN
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: folderIdentifier, create: true, in: self.syncMOC, created: &created)
label?.name = "Folder A"
label?.conversations = Set([self.conversation1])
label?.modifiedKeys = Set(["conversations"])
self.syncMOC.saveOrRollback()
// WHEN
self.sut.update(with: self.folderResponse(identifier: folderIdentifier, name: "Folder A", conversations: [self.conversation2.remoteIdentifier!]))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: folderIdentifier, create: false, in: self.syncMOC, created: &created)!
XCTAssertNil(label.modifiedKeys)
}
}
func testThatItItUpdatesFolderName() {
let folderIdentifier = UUID()
let updatedName = "Folder B"
syncMOC.performGroupedBlockAndWait {
// GIVEN
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: folderIdentifier, create: true, in: self.syncMOC, created: &created)
label?.name = "Folder A"
self.syncMOC.saveOrRollback()
// WHEN
self.sut.update(with: self.folderResponse(identifier: folderIdentifier, name: updatedName, conversations: [self.conversation1.remoteIdentifier!]))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: folderIdentifier, create: false, in: self.syncMOC, created: &created)!
XCTAssertEqual(label.name, updatedName)
}
}
func testThatItItUpdatesFolderConversations() {
let folderIdentifier = UUID()
syncMOC.performGroupedBlockAndWait {
// GIVEN
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: folderIdentifier, create: true, in: self.syncMOC, created: &created)
label?.name = "Folder A"
label?.conversations = Set([self.conversation1])
self.syncMOC.saveOrRollback()
// WHEN
self.sut.update(with: self.folderResponse(identifier: folderIdentifier, name: "Folder A", conversations: [self.conversation2.remoteIdentifier!]))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
var created = false
let label = Label.fetchOrCreate(remoteIdentifier: folderIdentifier, create: false, in: self.syncMOC, created: &created)!
XCTAssertEqual(label.conversations, [self.conversation2])
}
}
func testThatItDeletesLocalLabelsNotIncludedInResponse() {
var label1: Label!
var label2: Label!
syncMOC.performGroupedBlockAndWait {
// GIVEN
var created = false
label1 = Label.fetchOrCreate(remoteIdentifier: UUID(), create: true, in: self.syncMOC, created: &created)
label1.name = "Folder A"
label1.conversations = Set([self.conversation1])
label2 = Label.fetchOrCreate(remoteIdentifier: UUID(), create: true, in: self.syncMOC, created: &created)
label2.name = "Folder B"
label2.conversations = Set([self.conversation2])
self.syncMOC.saveOrRollback()
// WHEN
self.sut.update(with: self.folderResponse(identifier: label1.remoteIdentifier!, name: "Folder A", conversations: [self.conversation1.remoteIdentifier!]))
}
XCTAssertTrue(self.waitForAllGroupsToBeEmpty(withTimeout: 0.5))
// THEN
syncMOC.performGroupedBlockAndWait {
XCTAssertTrue(label2.isZombieObject)
}
}
}
| gpl-3.0 | 3446d645cb0eeba59561daa1d02c6c5b | 38.218289 | 165 | 0.658368 | 5.20556 | false | false | false | false |
kjifw/Senses | senses-client/Senses/Senses/ViewControllers/PartyInformationTableViewController.swift | 1 | 1485 | //
// PartyInformationTableViewController.swift
// Senses
//
// Created by Jeff on 3/31/17.
// Copyright © 2017 Telerik Academy. All rights reserved.
//
import UIKit
class PartyInformationTableViewController: UITableViewController {
var users: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Users list"
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "party-user-list-cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "party-user-list-cell", for: indexPath)
cell.textLabel?.text = users[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let nextVC = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "UserDetailsVC") as! UserDetailsViewController
nextVC.userUsername = self.users[indexPath.row]
self.show(nextVC, sender: self)
}
}
| mit | 2cefcefd6fb82bf3b7edf30e02f89ef2 | 28.68 | 109 | 0.681267 | 4.930233 | false | false | false | false |
wordpress-mobile/WordPress-Aztec-iOS | AztecTests/Formatters/FontFormatterTests.swift | 2 | 2258 | import XCTest
@testable import Aztec
// MARK: - FontFormatter Tests
//
class FontFormatterTests: XCTestCase
{
let boldFormatter = BoldFormatter()
let italicFormatter = ItalicFormatter()
func testApplyAttribute() {
var attributes: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: UIFont.systemFontSize)]
var font: UIFont?
//test adding a non-existent testApplyAttribute
attributes = boldFormatter.apply(to: attributes)
//this should add a new attribute to it
font = attributes[.font] as? UIFont
XCTAssertNotNil(font)
XCTAssertTrue(font!.containsTraits(.traitBold))
//test addding a existent attribute
attributes = boldFormatter.apply(to: attributes)
// this shouldn't change anything in the attributes
font = attributes[.font] as? UIFont
XCTAssertNotNil(font)
XCTAssertTrue(font!.containsTraits(.traitBold))
}
func testRemoveAttributes() {
var attributes: [NSAttributedString.Key : Any] = [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]
var font: UIFont?
//test removing a existent attribute
attributes = boldFormatter.remove(from: attributes)
font = attributes[.font] as? UIFont
XCTAssertNotNil(font)
XCTAssertFalse(font!.containsTraits(.traitBold))
attributes = [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]
//test removing a non-existent testApplyAttribute
attributes = italicFormatter.remove(from: attributes)
font = attributes[.font] as? UIFont
XCTAssertNotNil(font)
XCTAssertTrue(font!.containsTraits(.traitBold))
}
func testPresentAttributes() {
var attributes: [NSAttributedString.Key : Any] = [.font: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]
//test when attribute is present
XCTAssertTrue(boldFormatter.present(in: attributes))
//test when attributes is not present
XCTAssertFalse(italicFormatter.present(in: attributes))
// apply attribute and check again
attributes = italicFormatter.apply(to: attributes)
XCTAssertTrue(italicFormatter.present(in: attributes))
}
}
| gpl-2.0 | 80fe5b1eb81f2611d2a3ff76674a4bb6 | 36.633333 | 118 | 0.685562 | 5.06278 | false | true | false | false |
icylydia/PlayWithLeetCode | 53. Maximum Subarray/solution.swift | 1 | 531 | class Solution {
func maxSubArray(nums: [Int]) -> Int {
if nums.count < 1 {
return 0
}
var chosen = Array<Int>()
var skipped = Array<Int>()
chosen.append(nums[0])
skipped.append(Int.min)
for i in 1..<nums.count {
let x = nums[i]
let iChosen = max(x, chosen[i-1] + x)
let iSkipped = max(chosen[i-1], skipped[i-1])
chosen.append(iChosen)
skipped.append(iSkipped)
}
return max(chosen.last!, skipped.last!)
}
} | mit | 1cff228dcb0a8364b3753acc629b1094 | 27 | 54 | 0.521657 | 3.298137 | false | false | false | false |
lixiangzhou/ZZLib | Source/ZZExtension/ZZUIExtension/UITableView+ZZExtension.swift | 1 | 11239 | //
// UITableView+ZZExtension.swift
// ZZLib
//
// Created by lixiangzhou on 2017/4/4.
// Copyright © 2017年 lixiangzhou. All rights reserved.
//
import UIKit
/// cell 拖动的代理
public protocol ZZTableViewMovableCellDelegate: NSObjectProtocol {
func zz_tableViewStartMoveWithOriginData(_ tableView: UITableView) -> [Any]
func zz_tableView(_ tableView: UITableView, didMoveWith newData: [Any])
}
public extension UITableView {
/// 开启 cell 拖动功能
///
/// - Parameters:
/// - tag: cell 中可以拖动的View的 tag, 0 时则整个cell拖动
/// - pressTime: 触发拖动的最小时间
/// - movableDelegate: 拖动时的代理方法
/// - edgeScrollSpeed: 到达边界时滚动的速度,0 时不滚动
func zz_movableCell(withMovableViewTag tag: Int = 0, pressTime: TimeInterval, movableDelegate: ZZTableViewMovableCellDelegate, edgeScrollSpeed: Double = 0) {
self.movableViewTag = tag
movableLongPressGesture.minimumPressDuration = pressTime
movableLongPressGesture.delegate = self
self.movableDelegate = movableDelegate
edgeScrollDirection = .top
self.edgeScrollSpeed = edgeScrollSpeed > 0 ? edgeScrollSpeed : 0
addGestureRecognizer(movableLongPressGesture)
}
/// 取消拖动功能
func zz_disableMovableCell() {
removeGestureRecognizer(movableLongPressGesture)
}
}
extension UITableView: UIGestureRecognizerDelegate {
// MARK: 监听
@objc func gestureProcess(gesture: UILongPressGestureRecognizer) {
let point = gesture.location(in: self)
// 如果超出了范围,就取消返回
guard let indexPath = indexPathForRow(at: point), isInMovableScrope else {
cancelOperation()
return
}
switch gesture.state {
case .began:
if let cell = cellForRow(at: indexPath) {
startCellSnap = UIImageView(frame: cell.frame)
startCellSnap.layer.masksToBounds = true
startCellSnap.image = cell.zz_snapshotImage()
startCellSnap.layer.shadowOffset = CGSize(width: 5, height: 5)
startCellSnap.layer.shadowRadius = 5
addSubview(startCellSnap)
cell.isHidden = true
UIView.animate(withDuration: 0.25, animations: {
self.startCellSnap.center.y = point.y
})
startIndexPath = indexPath
}
case .changed:
startCellSnap.center.y = point.y
if shouldEdgeScroll {
startEdgeScrollTimer()
} else {
stopEdgeScrollTimer()
}
if indexPath != startIndexPath {
exchangeIndexData(indexPath: indexPath)
}
default:
cancelOperation()
}
}
// MARK: UIGestureRecognizerDelegate
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == movableLongPressGesture {
return isInMovableScrope
} else {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
}
// MARK: 辅助
fileprivate enum EndgeScrollDirection {
case top, bottom
}
/// 是否在tag view 所在的范围
private var isInMovableScrope: Bool {
let point = movableLongPressGesture.location(in: self)
if let indexPath = indexPathForRow(at: point),
let cell = cellForRow(at: indexPath),
let tagView = cell.viewWithTag(self.movableViewTag) {
let tagFrame = cell == tagView ? cell.frame : cell.convert(tagView.frame, to: self)
return tagFrame.contains(point)
} else {
return false
}
}
/// 拖动时的数据处理
private func exchangeIndexData(indexPath: IndexPath) {
guard
let numberOfSections = dataSource?.numberOfSections!(in: self),
var originData = movableDelegate?.zz_tableViewStartMoveWithOriginData(self) else {
return
}
if numberOfSections > 1 {
// 同一组
if startIndexPath.section == indexPath.section,
var sectionData = originData[startIndexPath.section] as? [Any]
{
sectionData.swapAt(startIndexPath.row, indexPath.row)
originData[startIndexPath.section] = sectionData
} else { // 不同组
guard // 获取cell上的数据
var originSectionData = originData[startIndexPath.section] as? [Any],
var currentSectionData = originData[indexPath.section] as? [Any] else {
return
}
let currentIndexData = currentSectionData[indexPath.row]
let originIndexData = originSectionData[startIndexPath.row]
// 交互数据
originSectionData[startIndexPath.row] = currentIndexData
currentSectionData[indexPath.row] = originIndexData
// 更新数据
originData[startIndexPath.section] = originSectionData
originData[indexPath.section] = currentSectionData
}
} else { // 只有一组
originData.swapAt(startIndexPath.row, indexPath.row)
}
movableDelegate?.zz_tableView(self, didMoveWith: originData)
beginUpdates()
moveRow(at: startIndexPath, to: indexPath)
moveRow(at: indexPath, to: startIndexPath)
endUpdates()
startIndexPath = indexPath
}
/// 取消操作
private func cancelOperation() {
startCellSnap?.removeFromSuperview()
stopEdgeScrollTimer()
if
let startIndexPath = startIndexPath,
let cell = cellForRow(at: startIndexPath) {
cell.isHidden = false
}
}
/// 开启边界滚动
private func startEdgeScrollTimer() {
if timer == nil {
timer = CADisplayLink(target: self, selector: #selector(edgeScroll))
timer.add(to: RunLoop.main, forMode: .commonModes)
}
}
/// 停止边界滚动
private func stopEdgeScrollTimer() {
timer?.invalidate()
timer = nil
}
/// 在边界自动滚动
@objc private func edgeScroll() {
let factor: CGFloat = 1.5
switch edgeScrollDirection {
case .top:
if contentOffset.y > 0 {
contentOffset.y -= factor
startCellSnap.center.y -= factor
}
case .bottom:
if contentOffset.y + bounds.height < contentSize.height {
contentOffset.y += factor
startCellSnap.center.y += factor
}
}
// 防止边界自动滚动时没有自动更新界面和数据的问题
if let indexPath = indexPathForRow(at: startCellSnap.center), indexPath != startIndexPath {
exchangeIndexData(indexPath: indexPath)
}
}
/// 是否可以在边界滚动
private var shouldEdgeScroll: Bool {
if edgeScrollSpeed <= 0 {
return false
}
if startCellSnap.frame.minY < contentOffset.y {
edgeScrollDirection = .top
return true
}
if startCellSnap.frame.maxY > frame.height + contentOffset.y {
edgeScrollDirection = .bottom
return true
}
return false
}
}
// MARK: - 拖动属性 key
private var longPressGestureKey: Void?
private var startCellSnapKey: Void?
private var startIndexPathKey: Void?
private var edgeScrollDirectionKey: Void?
private var timerKey: Void?
private var movableDelegateKey: Void?
private var edgeScrollSpeedKey: Void?
private var movableViewTagKey: Void?
extension UITableView {
/// 拖动长按手势
fileprivate var movableLongPressGesture: UILongPressGestureRecognizer {
get {
var longPressGesture = objc_getAssociatedObject(self, &longPressGestureKey) as? UILongPressGestureRecognizer
if longPressGesture == nil {
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(gestureProcess))
objc_setAssociatedObject(self, &longPressGestureKey, longPressGesture, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return longPressGesture!
}
}
/// 开始拖动时cell的快照
fileprivate var startCellSnap: UIImageView! {
set {
objc_setAssociatedObject(self, &startCellSnapKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &startCellSnapKey) as! UIImageView
}
}
/// 开始拖动的IndexPath
fileprivate var startIndexPath: IndexPath! {
set {
objc_setAssociatedObject(self, &startIndexPathKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &startIndexPathKey) as! IndexPath
}
}
/// 拖动方向
fileprivate var edgeScrollDirection: EndgeScrollDirection {
set {
objc_setAssociatedObject(self, &edgeScrollDirectionKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &edgeScrollDirectionKey) as! EndgeScrollDirection
}
}
/// 自动滚动定时器
fileprivate var timer: CADisplayLink! {
set {
objc_setAssociatedObject(self, &timerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &timerKey) as? CADisplayLink
}
}
/// 拖动代理
fileprivate weak var movableDelegate: ZZTableViewMovableCellDelegate! {
set {
objc_setAssociatedObject(self, &movableDelegateKey, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
get {
return objc_getAssociatedObject(self, &movableDelegateKey) as! ZZTableViewMovableCellDelegate
}
}
/// 边界滚动速度
fileprivate var edgeScrollSpeed: Double {
set {
objc_setAssociatedObject(self, &edgeScrollSpeedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &edgeScrollSpeedKey) as! Double
}
}
/// cell 中可以拖动的View的 tag, 0 时则整个cell拖动
fileprivate var movableViewTag: Int {
set {
objc_setAssociatedObject(self, &movableViewTagKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &movableViewTagKey) as! Int
}
}
}
| mit | d746e4dd25f68715d20c68a81e64e55b | 31.354354 | 161 | 0.59328 | 4.987963 | false | false | false | false |
devpunk/cartesian | cartesian/Controller/Draw/CDrawProjectShare.swift | 1 | 7831 | import UIKit
class CDrawProjectShare:CController
{
private(set) weak var model:DProject!
private weak var viewShare:VDrawProjectShare!
private(set) var shareImage:UIImage?
private let kDefaultResolution:CGFloat = 1
private let kResolutionRetina:CGFloat = 0
init(model:DProject)
{
self.model = model
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewShare:VDrawProjectShare = VDrawProjectShare(
controller:self)
self.viewShare = viewShare
view = viewShare
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidDisappear(animated)
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.render()
}
}
//MARK: private
private func render()
{
guard
let nodes:[DNode] = model.nodes?.array as? [DNode],
let labels:[DLabel] = model.labels?.array as? [DLabel],
let links:[DLink] = model.links?.array as? [DLink]
else
{
return
}
let canvasWidth:CGFloat = CGFloat(model.width)
let canvasHeight:CGFloat = CGFloat(model.height)
let canvasSize:CGSize = CGSize(
width:canvasWidth,
height:canvasHeight)
let canvasRect:CGRect = CGRect(
origin:CGPoint.zero,
size:canvasSize)
let resolution:CGFloat
if let retina:Bool = MSession.sharedInstance.settings?.retina
{
if retina
{
resolution = kResolutionRetina
}
else
{
resolution = kDefaultResolution
}
}
else
{
resolution = kDefaultResolution
}
UIGraphicsBeginImageContextWithOptions(canvasSize, true, resolution)
guard
let context:CGContext = UIGraphicsGetCurrentContext()
else
{
return
}
context.setFillColor(UIColor.white.cgColor)
context.addRect(canvasRect)
context.drawPath(using:CGPathDrawingMode.fill)
for link:DLink in links
{
MDrawProjectShareRender.renderLink(
link:link,
context:context)
}
for node:DNode in nodes
{
MDrawProjectShareRender.renderNode(
node:node,
context:context)
}
for label:DLabel in labels
{
MDrawProjectShareRender.renderLabel(
label:label,
context:context)
}
guard
let image:UIImage = UIGraphicsGetImageFromCurrentImageContext()
else
{
UIGraphicsEndImageContext()
return
}
UIGraphicsEndImageContext()
self.shareImage = image
DispatchQueue.main.async
{ [weak self] in
self?.endRendering()
}
}
private func endRendering()
{
viewShare.stopLoading()
}
private func asyncPostImage()
{
guard
let userId:String = MSession.sharedInstance.settings?.userId,
let image:UIImage = shareImage,
let imageData:Data = UIImagePNGRepresentation(image)
else
{
return
}
let modelGalleryItem:FDbGalleryItem = FDbGalleryItem(
userId:userId)
guard
let jsonGallery:Any = modelGalleryItem.json()
else
{
return
}
let galleryItemId:String = FMain.sharedInstance.db.createChild(
path:FDb.gallery,
json:jsonGallery)
let galleryPath:String = "\(FStorage.gallery)/\(galleryItemId)"
FMain.sharedInstance.storage.saveData(
path:galleryPath,
data:imageData)
{ [weak self] (error:String?) in
if let error:String = error
{
VAlert.message(message:error)
self?.finishActivity()
}
else
{
DManager.sharedInstance?.createData(
entityName:DGalleryPost.entityName)
{ [weak self] (data) in
guard
let project:DProject = self?.model,
let galleryPost:DGalleryPost = data as? DGalleryPost
else
{
return
}
project.sharedId = galleryItemId
galleryPost.galleryItemId = galleryItemId
MSession.sharedInstance.settings?.addToGalleryPost(galleryPost)
DManager.sharedInstance?.save()
self?.finishActivity()
}
}
}
}
private func asyncUpdateImage()
{
guard
let image:UIImage = shareImage,
let imageData:Data = UIImagePNGRepresentation(image),
let galleryItemId:String = model.sharedId
else
{
return
}
let updatedPath:String = "\(FDb.gallery)/\(galleryItemId)/\(FDbGalleryItem.updated)"
let timestamp:TimeInterval = Date().timeIntervalSince1970
let folderPath:String = "\(FStorage.gallery)/\(galleryItemId)"
FMain.sharedInstance.db.updateChild(
path:updatedPath,
json:timestamp)
FMain.sharedInstance.storage.saveData(
path:folderPath,
data:imageData)
{ [weak self] (error:String?) in
if let error:String = error
{
VAlert.message(message:error)
}
self?.finishActivity()
}
}
private func finishActivity()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewShare.stopLoading()
}
}
//MARK: public
func close()
{
parentController.dismissAnimateOver(completion:nil)
}
func exportImage()
{
guard
let image:UIImage = shareImage
else
{
return
}
let activity:UIActivityViewController = UIActivityViewController(
activityItems:[image],
applicationActivities:nil)
if let popover:UIPopoverPresentationController = activity.popoverPresentationController
{
popover.sourceView = viewShare
popover.sourceRect = CGRect.zero
popover.permittedArrowDirections = UIPopoverArrowDirection.up
}
present(activity, animated:true)
}
func postImage()
{
viewShare.startLoading()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncPostImage()
}
}
func updateImage()
{
viewShare.startLoading()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncUpdateImage()
}
}
}
| mit | 1eef8f25fddc4dc617c849dfd4fcb000 | 24.343042 | 95 | 0.498148 | 5.822305 | false | false | false | false |
tsolomko/SWCompression | Sources/GZip/FileSystemType+Gzip.swift | 1 | 717 | // Copyright (c) 2022 Timofey Solomko
// Licensed under MIT License
//
// See LICENSE for license information
import Foundation
extension FileSystemType {
init(_ gzipOS: UInt8) {
switch gzipOS {
case 0:
self = .fat
case 3:
self = .unix
case 7:
self = .macintosh
case 11:
self = .ntfs
default:
self = .other
}
}
var osTypeByte: UInt8 {
switch self {
case .fat:
return 0
case .unix:
return 3
case .macintosh:
return 7
case .ntfs:
return 11
default:
return 255
}
}
}
| mit | fde2343f1f8c7620a6fff097c07dc75b | 16.925 | 38 | 0.460251 | 4.509434 | false | false | false | false |
Conaaando/swift-hacker-rank | 00.Warmup/06-time-conversion.swift | 1 | 1210 | #!/usr/bin/swift
/*
https://github.com/singledev/swift-hacker-rank
06-time-conversion.swift
https://www.hackerrank.com/challenges/time-conversion
Created by Fernando Fernandes on 2/27/16.
Copyright © 2016 SINGLEDEV. All rights reserved.
http://stackoverflow.com/users/584548/singledev
Instructions:
$ chmod a+x 06-time-conversion.swift
$ ./06-time-conversion.swift
*/
import Foundation
var amPmTime = ""
var militaryTime: [String] = [String]()
func convertToMilitaryTime() {
// Remove ":"
militaryTime = amPmTime.characters.split(":").map(String.init)
// Logic for "PM"
if (militaryTime[2].containsString("P")) {
if (Int(militaryTime[0]) != 12) {
militaryTime[0] = String(Int(militaryTime[0])! + 12)
}
// Logic for "AM"
} else {
if (Int(militaryTime[0]) == 12) {
militaryTime[0] = "00"
}
}
// Remove "AM" or "PM"
militaryTime[2] = militaryTime[2].substringToIndex(militaryTime[2].startIndex.advancedBy(2))
}
print("Type the time in AM/PM format (e.g.: 07:05:45PM), then press ENTER")
amPmTime = readLine()!
convertToMilitaryTime()
print(militaryTime.joinWithSeparator(":"))
| mit | cc93cee1e4fd58bd3073046782b369e5 | 22.705882 | 96 | 0.643507 | 3.267568 | false | false | false | false |
SoneeJohn/WWDC | ThrowBack/TBUserDataMigrator.swift | 1 | 4949 | //
// TBUserDataMigrator.swift
// WWDC
//
// Created by Guilherme Rambo on 13/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
import RealmSwift
import ConfCore
private struct TBConstants {
static let legacySchemaVersion: UInt64 = 6
static let migratedSchemaVersion: UInt64 = 2017
}
public enum TBMigrationError: Error {
case realm(Error)
public var localizedDescription: String {
switch self {
case .realm(let underlyingError):
return "A Realm error occurred: \(underlyingError.localizedDescription)"
}
}
}
public enum TBMigrationResult {
case success
case failed(TBMigrationError)
}
public final class TBUserDataMigrator {
private let fileURL: URL
private var realm: Realm!
private weak var newRealm: Realm!
public var isPerformingMigration = false
public static var presentedMigrationPrompt: Bool {
get {
if ProcessInfo.processInfo.arguments.contains("--force-migration") {
return false
}
return TBPreferences.shared.presentedVersionFiveMigrationPrompt
}
set {
TBPreferences.shared.presentedVersionFiveMigrationPrompt = newValue
}
}
public init(legacyDatabaseFileURL: URL, newRealm: Realm) {
fileURL = legacyDatabaseFileURL
self.newRealm = newRealm
}
public var needsMigration: Bool {
// the old database file is renamed after migration, if the file exists, migration is needed
return FileManager.default.fileExists(atPath: fileURL.path)
}
public func performMigration(completion: @escaping (TBMigrationResult) -> Void) {
guard !isPerformingMigration else { return }
isPerformingMigration = true
defer { isPerformingMigration = false }
var legacyConfig = Realm.Configuration(fileURL: fileURL,
schemaVersion: TBConstants.legacySchemaVersion,
objectTypes: [])
legacyConfig.schemaVersion = TBConstants.migratedSchemaVersion
legacyConfig.migrationBlock = migrationBlock
do {
realm = try Realm(configuration: legacyConfig)
completion(.success)
} catch {
completion(.failed(.realm(error)))
}
}
private func migrationBlock(migration: Migration, version: UInt64) {
newRealm.beginWrite()
migration.enumerateObjects(ofType: "Session") { legacySession, _ in
guard let migrationSession = TBSession(legacySession) else { return }
guard let newSession = newRealm.object(ofType: Session.self, forPrimaryKey: migrationSession.identifier) else { return }
if migrationSession.isFavorite {
newSession.favorites.append(Favorite())
}
if !migrationSession.position.isZero || !migrationSession.relativePosition.isZero {
let progress = SessionProgress()
progress.currentPosition = migrationSession.position
progress.relativePosition = migrationSession.relativePosition
newSession.progresses.append(progress)
}
if let asset = newSession.assets.filter("rawAssetType == %@", SessionAssetType.hdVideo.rawValue).first {
let basePath = TBPreferences.shared.localVideoStoragePath
let newLocalFileURL = URL(fileURLWithPath: basePath + "/" + asset.relativeLocalURL)
let localDirectoryURL = newLocalFileURL.deletingLastPathComponent()
let originalLocalFileURL = URL(fileURLWithPath: basePath + "/" + newLocalFileURL.lastPathComponent)
if FileManager.default.fileExists(atPath: originalLocalFileURL.path) {
do {
if !FileManager.default.fileExists(atPath: localDirectoryURL.path) {
try FileManager.default.createDirectory(at: localDirectoryURL, withIntermediateDirectories: true, attributes: nil)
}
try FileManager.default.moveItem(at: originalLocalFileURL, to: newLocalFileURL)
newSession.isDownloaded = true
} catch {
NSLog("Error moving downloaded file from \(originalLocalFileURL) to \(newLocalFileURL): \(error)")
}
}
}
}
do {
try newRealm.commitWrite()
} catch {
NSLog("Error saving migrated realm data: \(error)")
}
let backupFileURL = fileURL.deletingPathExtension().appendingPathExtension("backup")
do {
try FileManager.default.moveItem(at: fileURL, to: backupFileURL)
} catch {
NSLog("Error moving backup file to \(backupFileURL)")
}
}
}
| bsd-2-clause | 913642abb15fa8edcdac68a22c64bf56 | 32.890411 | 142 | 0.625505 | 5.467403 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Scene/GlobeSurfaceShaderSet.swift | 1 | 13266 | //
// GlobeSurfaceShaderSet.swift
// CesiumKit
//
// Created by Ryan Walklin on 15/06/14.
// Copyright (c) 2014 Test Toast. All rights reserved.
//
import Foundation
struct GlobeSurfacePipeline {
var numberOfDayTextures: Int
var flags: Int
var pipeline: RenderPipeline
}
/**
* Manages the shaders used to shade the surface of a {@link Globe}.
*
* @alias GlobeSurfaceShaderSet
* @private
*/
class GlobeSurfaceShaderSet {
let baseVertexShaderSource: ShaderSource
let baseFragmentShaderSource: ShaderSource
fileprivate var _pipelinesByTexturesFlags = [Int: [Int: GlobeSurfacePipeline]]()
fileprivate var _pickPipelines = [Int: RenderPipeline]()
init (
baseVertexShaderSource: ShaderSource,
baseFragmentShaderSource: ShaderSource) {
self.baseVertexShaderSource = baseVertexShaderSource
self.baseFragmentShaderSource = baseFragmentShaderSource
}
fileprivate func getPositionMode(_ sceneMode: SceneMode) -> String {
let getPosition3DMode = "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPosition3DMode(position, height, textureCoordinates); }"
let getPosition2DMode = "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPosition2DMode(position, height, textureCoordinates); }"
let getPositionColumbusViewMode = "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPositionColumbusViewMode(position, height, textureCoordinates); }"
let getPositionMorphingMode = "vec4 getPosition(vec3 position, float height, vec2 textureCoordinates) { return getPositionMorphingMode(position, height, textureCoordinates); }"
let positionMode: String
switch sceneMode {
case SceneMode.scene3D:
positionMode = getPosition3DMode
case SceneMode.scene2D:
positionMode = getPosition2DMode
case SceneMode.columbusView:
positionMode = getPositionColumbusViewMode
case SceneMode.morphing:
positionMode = getPositionMorphingMode
}
return positionMode
}
func get2DYPositionFraction(_ useWebMercatorProjection: Bool) -> String {
let get2DYPositionFractionGeographicProjection = "float get2DYPositionFraction(vec2 textureCoordinates) { return get2DGeographicYPositionFraction(textureCoordinates); }"
let get2DYPositionFractionMercatorProjection = "float get2DYPositionFraction(vec2 textureCoordinates) { return get2DMercatorYPositionFraction(textureCoordinates); }"
return useWebMercatorProjection ? get2DYPositionFractionMercatorProjection : get2DYPositionFractionGeographicProjection
}
fileprivate let uniformStructString = "struct xlatMtlShaderUniform {\n float4 u_dayTextureTexCoordsRectangle [31];\n float4 u_dayTextureTranslationAndScale [31];\n float u_dayTextureAlpha [31];\n float u_dayTextureBrightness [31];\n float u_dayTextureContrast [31];\n float u_dayTextureHue [31];\n float u_dayTextureSaturation [31];\n float u_dayTextureOneOverGamma [31];\n float2 u_minMaxHeight;\n float4x4 u_scaleAndBias;\n float4 u_waterMaskTranslationAndScale;\n float4 u_initialColor;\n float4 u_tileRectangle;\n float4x4 u_modifiedModelView;\n float3 u_center3D;\n float2 u_southMercatorYAndOneOverHeight;\n float2 u_southAndNorthLatitude;\n float2 u_lightingFadeDistance;\n float u_zoomedOutOceanSpecularIntensity;\n};\n"
func getRenderPipeline (
frameState: FrameState,
surfaceTile: GlobeSurfaceTile,
numberOfDayTextures: Int,
applyBrightness: Bool,
applyContrast: Bool,
applyHue: Bool,
applySaturation: Bool,
applyGamma: Bool,
applyAlpha: Bool,
showReflectiveOcean: Bool,
showOceanWaves: Bool,
enableLighting: Bool,
hasVertexNormals: Bool,
useWebMercatorProjection: Bool,
enableFog: Bool
) -> RenderPipeline
{
let terrainEncoding = surfaceTile.pickTerrain!.mesh!.encoding
let quantizationMode = terrainEncoding.quantization
let quantization = quantizationMode.enabled
let quantizationDefine = quantizationMode.define
let sceneMode = frameState.mode
var flags = Int(sceneMode.rawValue)
flags = flags | Int(applyBrightness) << 2
flags = flags |
Int(applyContrast) << 3 |
Int(applyHue) << 4
flags = flags |
Int(applySaturation) << 5 |
Int(applyGamma) << 6
flags = flags |
Int(applyAlpha) << 7 |
(Int(showReflectiveOcean) << 8)
flags = flags |
(Int(showOceanWaves) << 9) |
(Int(enableLighting) << 10)
flags = flags |
(Int(hasVertexNormals) << 11) |
(Int(useWebMercatorProjection) << 12)
flags = flags |
(Int(enableFog) << 13) |
(Int(quantization) << 14)
var surfacePipeline = surfaceTile.surfacePipeline
if surfacePipeline != nil && surfacePipeline!.numberOfDayTextures == numberOfDayTextures && surfacePipeline!.flags == flags {
return surfacePipeline!.pipeline
}
// New tile, or tile changed number of textures or flags.
var pipelinesByFlags = _pipelinesByTexturesFlags[numberOfDayTextures]
if pipelinesByFlags == nil {
_pipelinesByTexturesFlags[numberOfDayTextures] = [Int: GlobeSurfacePipeline]()
pipelinesByFlags = _pipelinesByTexturesFlags[numberOfDayTextures]
}
surfacePipeline = pipelinesByFlags![flags]
if surfacePipeline == nil {
// Cache miss - we've never seen this combination of numberOfDayTextures and flags before.
var vs = baseVertexShaderSource
var fs = baseFragmentShaderSource
vs.defines.append(quantizationDefine)
fs.defines.append("TEXTURE_UNITS \(numberOfDayTextures)")
// Account for Metal not supporting sampler arrays
if numberOfDayTextures > 0 {
var textureArrayDefines = "\n"
for i in 0..<numberOfDayTextures {
textureArrayDefines += "uniform sampler2D u_dayTexture\(i);\n"
}
textureArrayDefines += "uniform vec4 u_dayTextureTranslationAndScale[TEXTURE_UNITS];\nuniform float u_dayTextureAlpha[TEXTURE_UNITS];\nuniform float u_dayTextureBrightness[TEXTURE_UNITS];\nuniform float u_dayTextureContrast[TEXTURE_UNITS];\nuniform float u_dayTextureHue[TEXTURE_UNITS];\nuniform float u_dayTextureSaturation[TEXTURE_UNITS];\nuniform float u_dayTextureOneOverGamma[TEXTURE_UNITS];\nuniform vec4 u_dayTextureTexCoordsRectangle[TEXTURE_UNITS];\n"
fs.sources.insert(textureArrayDefines, at: 0)
}
if applyBrightness {
fs.defines.append("APPLY_BRIGHTNESS")
}
if applyContrast {
fs.defines.append("APPLY_CONTRAST")
}
if applyHue {
fs.defines.append("APPLY_HUE")
}
if applySaturation {
fs.defines.append("APPLY_SATURATION")
}
if applyGamma {
fs.defines.append("APPLY_GAMMA")
}
if applyAlpha {
fs.defines.append("APPLY_ALPHA")
}
if showReflectiveOcean {
fs.defines.append("SHOW_REFLECTIVE_OCEAN")
vs.defines.append("SHOW_REFLECTIVE_OCEAN")
}
if showOceanWaves {
fs.defines.append("SHOW_OCEAN_WAVES")
}
if enableLighting {
if hasVertexNormals {
vs.defines.append("ENABLE_VERTEX_LIGHTING")
fs.defines.append("ENABLE_VERTEX_LIGHTING")
} else {
vs.defines.append("ENABLE_DAYNIGHT_SHADING")
fs.defines.append("ENABLE_DAYNIGHT_SHADING")
}
}
if enableFog {
vs.defines.append("FOG")
fs.defines.append("FOG")
}
var computeDayColor = "vec4 computeDayColor(vec4 initialColor, vec2 textureCoordinates)\n{ \nvec4 color = initialColor;\n"
for i in 0..<numberOfDayTextures {
computeDayColor += "color = sampleAndBlend(\ncolor,\nu_dayTexture\(i),\n"
computeDayColor += "textureCoordinates,\n"
computeDayColor += "u_dayTextureTexCoordsRectangle[\(i)],\n"
computeDayColor += "u_dayTextureTranslationAndScale[\(i)],\n"
computeDayColor += (applyAlpha ? "u_dayTextureAlpha[\(i)]" : "1.0") + ",\n"
computeDayColor += (applyBrightness ? "u_dayTextureBrightness[\(i)]" : "0.0") + ",\n"
computeDayColor += (applyContrast ? "u_dayTextureContrast[\(i)]" : "0.0") + ",\n"
computeDayColor += (applyHue ? "u_dayTextureHue[\(i)]" : "0.0") + ",\n"
computeDayColor += (applySaturation ? "u_dayTextureSaturation[\(i)]" : "0.0") + ",\n"
computeDayColor += (applyGamma ? "u_dayTextureOneOverGamma[\(i)]" : "0.0") + "\n"
computeDayColor += ");\n"
/* computeDayColor += "color = sampleAndBlend(\ncolor,\nu_dayTexture\(i),\n" +
"textureCoordinates,\n" +
"u_dayTextureTexCoordsRectangle[\(i)],\n" +
"u_dayTextureTranslationAndScale[\(i)],\n" +
(applyAlpha ? "u_dayTextureAlpha[\(i)]" : "1.0") + ",\n" +
(applyBrightness ? "u_dayTextureBrightness[\(i)]" : "0.0") + ",\n" +
(applyContrast ? "u_dayTextureContrast[\(i)]" : "0.0") + ",\n" +
(applyHue ? "u_dayTextureHue[\(i)]" : "0.0") + ",\n" +
(applySaturation ? "u_dayTextureSaturation[\(i)]" : "0.0") + ",\n" +
(applyGamma ? "u_dayTextureOneOverGamma[\(i)]" : "0.0") + "\n" +
");\n"*/
}
computeDayColor += "return color;\n}"
fs.sources.append(computeDayColor)
vs.sources.append(getPositionMode(sceneMode))
vs.sources.append(get2DYPositionFraction(useWebMercatorProjection))
let pipeline = RenderPipeline.fromCache(
context: frameState.context,
vertexShaderSource: vs,
fragmentShaderSource: fs,
vertexDescriptor: VertexDescriptor(attributes: terrainEncoding.vertexAttributes),
colorMask: nil,
depthStencil: frameState.context.depthTexture,
manualUniformStruct: uniformStructString,
uniformStructSize: MemoryLayout<TileUniformStruct>.size
)
pipelinesByFlags![flags] = GlobeSurfacePipeline(numberOfDayTextures: numberOfDayTextures, flags: flags, pipeline: pipeline)
surfacePipeline = pipelinesByFlags![flags]
}
_pipelinesByTexturesFlags[numberOfDayTextures] = pipelinesByFlags!
surfaceTile.surfacePipeline = surfacePipeline
return surfacePipeline!.pipeline
}
func getPickRenderPipeline(_ frameState: FrameState, surfaceTile: GlobeSurfaceTile, useWebMercatorProjection: Bool) -> RenderPipeline {
let terrainEncoding = surfaceTile.pickTerrain!.mesh!.encoding
let quantizationMode = terrainEncoding.quantization
let quantization = quantizationMode.enabled
let quantizationDefine = quantizationMode.define
let sceneMode = frameState.mode
let flags = sceneMode.rawValue | (Int(useWebMercatorProjection) << 2) | (Int(quantization) << 3)
var pickShader: RenderPipeline! = _pickPipelines[flags]
if pickShader == nil {
var vs = baseVertexShaderSource
vs.defines.append(quantizationDefine)
vs.sources.append(getPositionMode(sceneMode))
vs.sources.append(get2DYPositionFraction(useWebMercatorProjection))
// pass through fragment shader. only depth is rendered for the globe on a pick pass
let fs = ShaderSource(sources: [
"void main()\n" +
"{\n" +
" gl_FragColor = vec4(1.0, 1.0, 0.0, 1.0);\n" +
"}\n"
])
pickShader = RenderPipeline.fromCache(
context : frameState.context,
vertexShaderSource : vs,
fragmentShaderSource : fs,
vertexDescriptor: VertexDescriptor(attributes: terrainEncoding.vertexAttributes),
colorMask: ColorMask(
red : false,
green : false,
blue : false,
alpha : false
),
depthStencil: true
)
_pickPipelines[flags] = pickShader
}
return pickShader
}
deinit {
// ARC should deinit shaders
}
}
| apache-2.0 | f47e40f02fcc02bf7080f42041ac8544 | 44.276451 | 789 | 0.612468 | 4.460659 | false | false | false | false |
danielmartinprieto/AudioPlayer | AudioPlayer/AudioPlayer/utils/BackgroundHandler.swift | 2 | 4043 | //
// BackgroundHandler.swift
// AudioPlayer
//
// Created by Kevin DELANNOY on 22/03/16.
// Copyright © 2016 Kevin Delannoy. All rights reserved.
//
#if os(OSX)
import Foundation
#else
import UIKit
/// A `BackgroundTaskCreator` serves the purpose of creating background tasks.
protocol BackgroundTaskCreator: class {
/// Marks the beginning of a new long-running background task.
///
/// - Parameter handler: A handler to be called shortly before the app’s remaining background time reaches 0.
/// You should use this handler to clean up and mark the end of the background task. Failure to end the task
/// explicitly will result in the termination of the app. The handler is called synchronously on the main
/// thread, blocking the app’s suspension momentarily while the app is notified.
/// - Returns: A unique identifier for the new background task. You must pass this value to the
/// `endBackgroundTask:` method to mark the end of this task. This method returns `UIBackgroundTaskInvalid`
/// if running in the background is not possible.
func beginBackgroundTask(expirationHandler handler: (() -> Void)?) -> UIBackgroundTaskIdentifier
/// Marks the end of a specific long-running background task.
///
/// You must call this method to end a task that was started using the `beginBackgroundTask(expirationHandler:)`
/// method. If you do not, the system may kill your app.
///
/// This method can be safely called on a non-main thread.
///
/// - Parameter identifier: An identifier returned by the `beginBackgroundTask(expirationHandler:)` method.
func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier)
}
extension UIApplication: BackgroundTaskCreator {}
#endif
/// A `BackgroundHandler` handles background.
class BackgroundHandler: NSObject {
#if !os(OSX)
/// The background task creator
var backgroundTaskCreator: BackgroundTaskCreator = UIApplication.shared
/// The backround task identifier if a background task started. Nil if not.
private var taskIdentifier: UIBackgroundTaskIdentifier?
#else
private var taskIdentifier: Int?
#endif
/// The number of background request received. When this counter hits 0, the background task, if any, will be
/// terminated.
private var counter = 0
/// Ends background task if any on deinitialization.
deinit {
endBackgroundTask()
}
/// Starts a background task if there isn't already one.
///
/// - Returns: A boolean value indicating whether a background task was created or not.
@discardableResult
func beginBackgroundTask() -> Bool {
#if os(OSX)
return false
#else
counter += 1
guard taskIdentifier == nil else {
return false
}
taskIdentifier = backgroundTaskCreator.beginBackgroundTask { [weak self] in
if let taskIdentifier = self?.taskIdentifier {
self?.backgroundTaskCreator.endBackgroundTask(taskIdentifier)
}
self?.taskIdentifier = nil
}
return true
#endif
}
/// Ends the background task if there is one.
///
/// - Returns: A boolean value indicating whether a background task was ended or not.
@discardableResult
func endBackgroundTask() -> Bool {
#if os(OSX)
return false
#else
guard let taskIdentifier = taskIdentifier else {
return false
}
counter -= 1
guard counter == 0 else {
return false
}
if taskIdentifier != UIBackgroundTaskIdentifier.invalid {
backgroundTaskCreator.endBackgroundTask(taskIdentifier)
}
self.taskIdentifier = nil
return true
#endif
}
}
| mit | 01e16aa25709a2ee1f297a564d779f61 | 35.709091 | 120 | 0.63472 | 5.471545 | false | false | false | false |
qiuxiang/react-native-amap3d | lib/ios/MapView/CircleManager.swift | 1 | 1019 | @objc(AMapCircleManager)
class AMapCircleManager: RCTViewManager {
override class func requiresMainQueueSetup() -> Bool { false }
override func view() -> UIView { Circle() }
}
class Circle: UIView, Overlay {
var overlay = MACircle()
var renderer: MACircleRenderer?
@objc var radius = 0.0 { didSet { overlay.radius = radius } }
@objc var strokeWidth = 1.0 { didSet { renderer?.lineWidth = strokeWidth } }
@objc var strokeColor = UIColor.black { didSet { renderer?.strokeColor = strokeColor } }
@objc var fillColor = UIColor.white { didSet { renderer?.fillColor = fillColor } }
@objc func setCircleCenter(_ center: CLLocationCoordinate2D) {
overlay.coordinate = center
}
func getOverlay() -> MABaseOverlay { overlay }
func getRenderer() -> MAOverlayRenderer {
if renderer == nil {
renderer = MACircleRenderer(circle: overlay)
renderer?.fillColor = fillColor
renderer?.strokeColor = strokeColor
renderer?.lineWidth = strokeWidth
}
return renderer!
}
}
| mit | 0923f4422d967260b45a1b0d8ff900f9 | 32.966667 | 90 | 0.696762 | 4.373391 | false | false | false | false |
arinjoy/Landmark-Remark | LandmarkRemark/LandmarksViewController.swift | 1 | 30511 | //
// LandmarksViewController.swift
// LandmarkRemark
//
// Created by Arinjoy Biswas on 6/06/2016.
// Copyright © 2016 Arinjoy Biswas. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
// The view controller for the main page with the map view
class LandmarksViewController: UIViewController, LandmarksViewModelDelegate {
// outlet connections from storyboard
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var searchControllerHolderView: UIView!
@IBOutlet weak var logoutButton: UIBarButtonItem!
@IBOutlet weak var currentLocationToggleButton: UIButton!
@IBOutlet weak var boundarySegmentedControl: UISegmentedControl!
@IBOutlet weak var mapViewHeightConstraint: NSLayoutConstraint!
// location manger to cotantly update user location
var locationManager: CLLocationManager!
// to indicate whether currently updating location
var currentlyUpdatingLocation: Bool = true
// activity spinner
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
// search controller for searching landmarks
let searchController = UISearchController(searchResultsController: nil)
// the view-model
var viewModel: LandmarksViewModel!
//------------------------------------------------------------------------------------------------
// MARK: - View controller life cycle methods
//------------------------------------------------------------------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
userNameLabel.alpha = 0.0
self.extendedLayoutIncludesOpaqueBars = true
self.definesPresentationContext = true
// Setup the Search Controller
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
// Setup the search bar
searchController.searchBar.scopeButtonTitles = ["All", "Mine", "Others"]
searchController.searchBar.searchBarStyle = .Prominent
searchController.searchBar.barTintColor = Color.veryLightGreenColor
searchController.searchBar.keyboardType = .Default
searchController.searchBar.autocorrectionType = .No
searchController.searchBar.autocapitalizationType = .None
// add the search controller to its holding view
searchControllerHolderView.addSubview(self.searchController.searchBar)
// check for device type and adjust the UI to make it adaptive for all iOS devices (iPhone /iPad)
if UIDevice.currentDevice().getDeviceType() == .iPhone4 {
mapViewHeightConstraint.constant = -20.0
}
else if UIDevice.currentDevice().getDeviceType() == .iPhone5 {
mapViewHeightConstraint.constant = 25.0
}
else if UIDevice.currentDevice().getDeviceType() == .iPhone6 {
mapViewHeightConstraint.constant = 70.0
}
else {
mapViewHeightConstraint.constant = 100.0
}
if UIDevice.currentDevice().isDeviceiPad() {
mapViewHeightConstraint.constant = 200.0
}
// setting up the location manager to constatnly update location
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
// by deafult location is always being updated and the blue arrow button is enabled to indicate this
currentlyUpdatingLocation = true
currentLocationToggleButton.setImage(Icon.updateLocationEnabledImage, forState: UIControlState.Normal)
// setting up mapview delegate
mapView.delegate = self
// intialize the view-model
viewModel = LandmarksViewModel(delegate: self)
/* Checking whether user has changed bounadry selection preference previously.
By default the entire planet is being searched for landmarks and they are sorted geo-spatially from the nearest to farthest.
Therefore, if a user searches for a landmarks based on keywords, the reesult set would have all matchig landmarks based on the text in user name or note.
An Australian user may see results from American users too. This could be inconvenient to zoom out and zoom in to another country and that might not be necessary at all.
If the user is only concerend with landmarks within a sepcific boundary, he can choose either 1km, 10km, 100km radius. In that case, the geo-spatial searches would
checking for that boundary only to help/guide the user with relevant landamarks only (not too many irrelevant ones which are too far from the user)
*/
let preferences = NSUserDefaults.standardUserDefaults()
if preferences.objectForKey("BOUNDARY_PREFERENCE") == nil {
// default search strategy is the entire planet
boundarySegmentedControl.selectedSegmentIndex = 3
preferences.setInteger(2, forKey: "BOUNDARY_PREFERENCE")
preferences.synchronize()
}
else {
let savedValue = preferences.integerForKey("BOUNDARY_PREFERENCE")
boundarySegmentedControl.selectedSegmentIndex = savedValue
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// display the logged-in user name at the bottom of the UI
userNameLabel.text = viewModel.currentUserName
switch boundarySegmentedControl.selectedSegmentIndex {
case 0: viewModel.selectedBoundary = .ONE_KM
case 1: viewModel.selectedBoundary = .TEN_KM
case 2: viewModel.selectedBoundary = .HUNDRED_KM
case 3: viewModel.selectedBoundary = .ENTIRE_PLANET
default: break
}
// if for some reason location service setting was turned off (denied) by the user from the app settings, prompt the user that the usgae of location service is manadatory
if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.NotDetermined &&
(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Denied || CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Restricted) {
let alert = Utils.createCustomAlert("Warning", message: "Access to Location Service has been denied or restricted. Please go to settings and change permission.")
let settingsAction: UIAlertAction = UIAlertAction(title: "Settings", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
})
alert.addAction(settingsAction)
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
// animate the alpha value of user name hint
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.userNameLabel.alpha = 1.0
}, completion: nil)
}
// --------------------------------------------
// MARK :- Misclaneous view controller methods
// --------------------------------------------
// status bar preference
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
// -------------------------------
// MARK :- user Actions on the UI
// -------------------------------
@IBAction func refreshLandmarksAction(sender: AnyObject) {
showActivityLoader()
// ask the view-model to load the landmarks
viewModel.getAllLandmarks()
}
@IBAction func logoutAction(sender: AnyObject) {
let alertMenu = Utils.createCustomActionSheetAlert("", message: "Are you sure that you want to log out?")
let okAction = UIAlertAction(title: "Confirm", style: .Destructive) {
(action: UIAlertAction!) -> Void in
self.showActivityLoader()
self.viewModel.logout()
}
alertMenu.addAction(okAction)
alertMenu.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
if UIDevice.currentDevice().isDeviceiPad() {
alertMenu.popoverPresentationController?.barButtonItem = logoutButton
}
self.presentViewController(alertMenu, animated: true, completion: nil)
}
// user can temporarily turn off location update to be able to zoom in the search results, becuase cosntant location update always zoom out the map
// to 500 m ter boundary, and user might feel difficulty while he is not static and onteh move but also trying to zoom in some section of the map
// the blue arrorw head o the bottom-right side of the map is used for this purpose
@IBAction func toggleUpdateCurrentLocation(sender: AnyObject) {
currentlyUpdatingLocation = !self.currentlyUpdatingLocation
if currentlyUpdatingLocation {
startUpdatingCurrentLocation()
}
else {
stopUpdatingCurrentLocation()
}
}
@IBAction func boundaryChangeAction(sender: AnyObject) {
// user is chnaging boundary preference
switch self.boundarySegmentedControl.selectedSegmentIndex {
case 0 : viewModel.selectedBoundary = BoundaryRange.ONE_KM
case 1 : viewModel.selectedBoundary = BoundaryRange.TEN_KM
case 2 : viewModel.selectedBoundary = BoundaryRange.HUNDRED_KM
case 3 : viewModel.selectedBoundary = BoundaryRange.ENTIRE_PLANET
default: break
}
// save the user preference, see comment above at teh bottom of the viewDidLoad mehtod
let preferences = NSUserDefaults.standardUserDefaults()
preferences.setInteger(self.boundarySegmentedControl.selectedSegmentIndex, forKey: "BOUNDARY_PREFERENCE")
preferences.synchronize()
self.displayAlert("Information", message: "Landmarks data will be confined within your selected boundary radius when you perform a network refresh using the top-left refresh button.")
}
@IBAction func saveLandmarkAction(sender: AnyObject) {
self.performSaveLandmarkWithAlert("Saving a Landmark?", message: "\nYou're going to add a landmark at your current location. \n\nPlease enter a short note.", isUpdating: false)
}
// ------------------------------------
// MARK :- Helper methods
// ------------------------------------
func stopUpdatingCurrentLocation() {
currentlyUpdatingLocation = false
currentLocationToggleButton.setImage(Icon.updateLocationDisabledImage, forState: UIControlState.Normal)
locationManager.stopUpdatingLocation()
mapView.showsUserLocation = false
}
func startUpdatingCurrentLocation() {
currentlyUpdatingLocation = true
currentLocationToggleButton.setImage(Icon.updateLocationEnabledImage, forState: UIControlState.Normal)
locationManager.startUpdatingLocation()
// as soon as location update is happening zoom into the region
setMapRegion(viewModel.latestUpdatedLocation.coordinate, distance: 500)
mapView.showsUserLocation = true
}
func setMapRegion(location: CLLocationCoordinate2D, distance: CLLocationDistance) {
let region:MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(location, distance, distance)
mapView.setRegion(mapView.regionThatFits(region), animated: true)
}
/**
To show an alert with user input field for saving/editing a landmark
- parameter title: The title of the alert
- parameter message: The message to show in the alert
- parameter isUpdating: To indicate whther it is an update
- parameter updatinglandMarkId: If being updated, the landmark Id is necessary
*/
func performSaveLandmarkWithAlert(title: String, message: String, isUpdating: Bool = false, updatinglandMarkId: String = "") {
// inactivate the search controller UI
searchController.searchBar.resignFirstResponder()
searchController.searchBar.selectedScopeButtonIndex = 0
searchController.active = false
let alertController = Utils.createCustomAlert(title, message: message)
let saveAction = UIAlertAction(title: "Save", style: .Default) { (_) in
let noteTextField = alertController.textFields![0] as UITextField
self.showActivityLoader()
if isUpdating {
self.viewModel.updateRemarkForLandmark(updatinglandMarkId, newNote: (noteTextField.text?.trim().condenseWhitespace())!)
}
else {
self.viewModel.saveLandmarkWithRemark((noteTextField.text?.trim().condenseWhitespace())!)
}
}
// by default save button action is disbaled util the user types 3 or kore characters
saveAction.enabled = false
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }
alertController.addTextFieldWithConfigurationHandler { (textField) in
// customize the text field
textField.placeholder = isUpdating ? "Update your note here..." : "Type your note here..."
textField.keyboardType = .Default
textField.autocorrectionType = .Yes
textField.autocapitalizationType = .Sentences
textField.returnKeyType = .Done
textField.clearButtonMode = .WhileEditing
// bind the text chnage observer and enable the action abutton
NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: textField, queue: NSOperationQueue.mainQueue()) { (notification) in
saveAction.enabled = textField.text!.trim().condenseWhitespace().characters.count >= 3
}
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func showActivityLoader() {
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
activityIndicator.backgroundColor = UIColor(white: 0.3, alpha: 0.7)
activityIndicator.center = CGPointMake(self.view.center.x, (self.view.center.y - 0))
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
self.view.addSubview(activityIndicator)
self.view.bringSubviewToFront(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
func stopActivityLoader() {
activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
func displayAlert(title:String, message:String) {
let alert = Utils.createCustomAlert(title, message: message)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
/**
To calculate the recently updated current user human icon annotation
*/
func calculateRecentlyUpdatedHumanAnnotation() -> [MKAnnotation] {
// filter out the human indicator
let recentlyAddedHumanAnnotations = mapView.annotations.filter({ (item) -> Bool in
if item is MKUserLocation {
return false
}
else {
let annotation = item as! AnnotationViewModel
return annotation.isCurrentUserIndicator && item.coordinate.latitude == viewModel.latestUpdatedLocation.coordinate.latitude && item.coordinate.longitude == viewModel.latestUpdatedLocation.coordinate.longitude
}
})
return recentlyAddedHumanAnnotations
}
/**
To calculate all te real annotations saved from netowrk. i.e. everything except for current user Dot and human indicator
*/
func calculateAllNetworkSavedAnnotations() -> [MKAnnotation] {
// filter out any abnnotation that is not teh Dot or the human indicator
return mapView.annotations.filter({ (item) -> Bool in
if item is MKUserLocation {
return false
}
else {
let annotation = item as! AnnotationViewModel
if annotation.isCurrentUserIndicator && item.coordinate.latitude == viewModel.latestUpdatedLocation.coordinate.latitude && item.coordinate.longitude == viewModel.latestUpdatedLocation.coordinate.longitude {
return false
}
else {
return true
}
}
})
}
// -----------------------------------------------------------------------------------------------------
// MARK :- LandmarksViewModelDelegate method implementation, called by the view-model to notify anything
// -----------------------------------------------------------------------------------------------------
func logoutSuccess() {
Utils.delay(1.5) {
self.stopActivityLoader()
self.navigationController?.navigationBar.hidden = true
self.performSegueWithIdentifier("backToLoginScreenFromMapSegue", sender: self)
}
}
func landmarkSaveOrDeleteWithSuccess(message: String) {
Utils.delay(1.5) {
self.stopActivityLoader()
self.displayAlert("Success", message: message)
self.startUpdatingCurrentLocation()
}
}
func getAllLandmarkWithSuccess(count: Int) {
Utils.delay(1.5) {
self.stopActivityLoader()
// showing user a message about how many landmarks located based on the boundary preference
let countVal: String = count > 0 ? "\(count)" : "No"
var message = "\(countVal) landmarks located after searching globally everywhere."
if self.viewModel.selectedBoundary != .ENTIRE_PLANET {
var distance = "1 km"
switch self.viewModel.selectedBoundary {
case .ONE_KM : distance = "1 km"
case .TEN_KM : distance = "10 km"
case .HUNDRED_KM : distance = "100 km"
default: break
}
message = "\(countVal) landmarks located after searching \(distance) radius from your current location."
}
self.displayAlert("Information", message: message)
if count > 0 {
self.searchController.active = false
self.searchController.searchBar.text = ""
self.reloadAnnotations()
}
}
}
func operationFailureWithErrorMessage(title: String, message: String) {
Utils.delay(1.5) {
self.stopActivityLoader()
self.displayAlert(title, message: message)
}
}
func reloadAnnotations() {
if searchController.active {
stopUpdatingCurrentLocation()
}
// remove existing annotations
mapView.removeAnnotations(calculateAllNetworkSavedAnnotations())
// add back the annotations back taking into consideration of any search
let targetAnnotations = searchController.active ? viewModel.filteredLandmarkAnnotations : viewModel.landmarkAnnotations
mapView.addAnnotations(targetAnnotations)
// setting the map region 500 meters around the first search result, searched geo-spatially from the nearest to farthest
if targetAnnotations.count > 0 {
setMapRegion(targetAnnotations[0].coordinate, distance: 500)
}
}
}
//----------------------------------------------
// MARK: - CLLocationManagerDelegate
//----------------------------------------------
extension LandmarksViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0]
// ass soon as a location updated, pass this information to the other list view controller
NSNotificationCenter.defaultCenter().postNotificationName("UpdateLocation", object: userLocation)
// if a new location is received, update the location and relocate the human indicator
if viewModel.latestUpdatedLocation.coordinate.latitude != userLocation.coordinate.latitude || viewModel.latestUpdatedLocation.coordinate.longitude != userLocation.coordinate.longitude {
// set the region 500 meters
if currentlyUpdatingLocation {
setMapRegion(userLocation.coordinate, distance: 500)
}
// remove the existing human indicator
mapView.removeAnnotations(calculateRecentlyUpdatedHumanAnnotation())
// add the human indicator at the new location
let annotation = AnnotationViewModel(message: "I am here now.", username: viewModel.currentUserName, location: userLocation.coordinate, currentUserIndicator: true, currentLogedInUsername: viewModel.currentUserName)
mapView.addAnnotation(annotation)
// if the location update is happening for the first time after view load, call the delegate to fetch all the landmarks from backend
// by default (0, 0) location is used to start with before any location updates happen
if viewModel.latestUpdatedLocation.coordinate.latitude == 0 && viewModel.latestUpdatedLocation.coordinate.longitude == 0
{
viewModel.latestUpdatedLocation = userLocation
showActivityLoader()
viewModel.getAllLandmarks()
}
// always update the new location into the view-model property
viewModel.latestUpdatedLocation = userLocation
}
}
}
//---------------------------------------------------
// MARK: - UISearchBarDelegate
//---------------------------------------------------
extension LandmarksViewController: UISearchBarDelegate {
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
// as soon as the scope button selection chnaged ("All", "Mine", "Others"), ask te view model to search
viewModel.filterContentForSearchTextAndScope(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// as soon as the search cancel button hit, chnage the scpe back to "All", and start uodating the user location just
// in case user has turned it off to zoom into the map
searchBar.selectedScopeButtonIndex = 0
startUpdatingCurrentLocation()
}
}
//---------------------------------------------------
// MARK: - UISearchResultsUpdating
//---------------------------------------------------
extension LandmarksViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
// as soon as tthe text chnages on the search bar, ask te view model to search
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
viewModel.filterContentForSearchTextAndScope(searchController.searchBar.text!, scope: scope)
}
}
//---------------------------------------------------
// MARK: - MKMapViewDelegate
//---------------------------------------------------
extension LandmarksViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? AnnotationViewModel {
// There could be three types of annotation image
// - Current user location (human icon)
// - A red baloon/pin to indicate landmarks saved by other users
// - A purple baloon/pin to indicate the user's own landmark
var identifier = ""
var targetAnnotationImage: UIImage? = nil
// determine the pin image based on the conditions
// also calculate the right resuable view identifer depending on the pin type
if annotation.isCurrentUserIndicator {
identifier = "my_current_location"
targetAnnotationImage = Icon.myCurrentLocationAnnotaionImage
}
else if annotation.userName == viewModel.currentUserName {
identifier = "my_saved_landmark"
targetAnnotationImage = Icon.myLandmarkAnnotationImage
}
else {
identifier = "others_saved_landmark"
targetAnnotationImage = Icon.othersLandmarkAnnotationImage
}
var view: MKAnnotationView
// try to dequeue the view
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: 0, y: -5)
let disclosureButton = UIButton(frame: CGRectMake(0, 0, 33, 22))
disclosureButton.setImage(Icon.detailDisclosure, forState: UIControlState.Normal)
view.rightCalloutAccessoryView = disclosureButton as UIView
view.rightCalloutAccessoryView?.tintColor = Color.darkGreenColor
view.rightCalloutAccessoryView?.tintAdjustmentMode = .Normal
view.centerOffset = CGPointMake(0, -25)
// assign the correct annotation pin mage
view.image = targetAnnotationImage
}
return view
}
return nil
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let annotation = view.annotation as! AnnotationViewModel
// show call-out accessory view only if it's a network saved landmark
if annotation.isCurrentUserIndicator == false {
let alertTitle = (annotation.userName == viewModel.currentUserName) ? "Your Landmark" : "saved by: \(annotation.userName)"
let alertController = Utils.createCustomAlert(alertTitle, message: annotation.title!)
// To open up the Apple's Maps app with the location
let gotoMapAction = UIAlertAction(title: "Show in Maps", style: UIAlertActionStyle.Default) { (_) in
// open the Maps app to get the driving directions
let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]
annotation.mapItem().openInMapsWithLaunchOptions(launchOptions)
}
let cancelAction = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(gotoMapAction)
alertController.addAction(cancelAction)
// if this annotation/landmark is owned by the logged in user, then Edit & Delete options are enabled
if annotation.userName == viewModel.currentUserName {
// create the update action
let updateAction = UIAlertAction(title: "Edit", style: UIAlertActionStyle.Default) { (_) in
self.performSaveLandmarkWithAlert("Editing this landmark?", message: "Please change the existing note/remark.", isUpdating: true, updatinglandMarkId: annotation.landmarkId!)
}
alertController.addAction(updateAction)
// create the delete action
let deleteAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Destructive) { (_) in
self.searchController.searchBar.resignFirstResponder()
self.searchController.searchBar.selectedScopeButtonIndex = 0
self.searchController.active = false
self.showActivityLoader()
self.viewModel.deleteLandmark(annotation.landmarkId!)
}
alertController.addAction(deleteAction)
}
// show the controller when call-out was tapped
self.presentViewController(alertController, animated: true, completion: nil)
}
}
func mapView(mapView: MKMapView, didAddAnnotationViews views: [MKAnnotationView]) {
// apply some animation as soon as the annotation sare being added on the map
// alpha value chnages and a little jump happens
dispatch_async(dispatch_get_main_queue(), {
for annView in views {
let endFrame = annView.frame
annView.alpha = 0.0
annView.frame = CGRectOffset(endFrame, 0, -5)
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
annView.frame = endFrame
annView.alpha = 1.0
}, completion: nil)
}
})
}
}
| mit | 092464dd7287399d4ab1a34313b918e1 | 45.29742 | 226 | 0.635202 | 5.851554 | false | false | false | false |
lyft/SwiftLint | Source/swiftlint/Commands/AutoCorrectCommand.swift | 1 | 4755 | import Commandant
import Result
import SwiftLintFramework
struct AutoCorrectCommand: CommandProtocol {
let verb = "autocorrect"
let function = "Automatically correct warnings and errors"
func run(_ options: AutoCorrectOptions) -> Result<(), CommandantError<()>> {
let configuration = Configuration(options: options)
let cache = options.ignoreCache ? nil : LinterCache(configuration: configuration)
let indentWidth: Int
var useTabs: Bool
switch configuration.indentation {
case .tabs:
indentWidth = 4
useTabs = true
case .spaces(let count):
indentWidth = count
useTabs = false
}
if options.useTabs {
queuedPrintError("'use-tabs' is deprecated and will be completely removed" +
" in a future release. 'indentation' can now be defined in a configuration file.")
useTabs = options.useTabs
}
return configuration.visitLintableFiles(path: options.path, action: "Correcting",
quiet: options.quiet,
useScriptInputFiles: options.useScriptInputFiles,
forceExclude: options.forceExclude,
cache: cache, parallel: true) { linter in
let corrections = linter.correct()
if !corrections.isEmpty && !options.quiet {
let correctionLogs = corrections.map({ $0.consoleDescription })
queuedPrint(correctionLogs.joined(separator: "\n"))
}
if options.format {
let formattedContents = try? linter.file.format(trimmingTrailingWhitespace: true,
useTabs: useTabs,
indentWidth: indentWidth)
_ = try? formattedContents?
.write(toFile: linter.file.path!, atomically: true, encoding: .utf8)
}
}.flatMap { files in
if !options.quiet {
let pluralSuffix = { (collection: [Any]) -> String in
return collection.count != 1 ? "s" : ""
}
queuedPrintError("Done correcting \(files.count) file\(pluralSuffix(files))!")
}
return .success(())
}
}
}
struct AutoCorrectOptions: OptionsProtocol {
let path: String
let configurationFile: String
let useScriptInputFiles: Bool
let quiet: Bool
let forceExclude: Bool
let format: Bool
let cachePath: String
let ignoreCache: Bool
let useTabs: Bool
// swiftlint:disable line_length
static func create(_ path: String) -> (_ configurationFile: String) -> (_ useScriptInputFiles: Bool) -> (_ quiet: Bool) -> (_ forceExclude: Bool) -> (_ format: Bool) -> (_ cachePath: String) -> (_ ignoreCache: Bool) -> (_ useTabs: Bool) -> AutoCorrectOptions {
return { configurationFile in { useScriptInputFiles in { quiet in { forceExclude in { format in { cachePath in { ignoreCache in { useTabs in
self.init(path: path, configurationFile: configurationFile, useScriptInputFiles: useScriptInputFiles, quiet: quiet, forceExclude: forceExclude, format: format, cachePath: cachePath, ignoreCache: ignoreCache, useTabs: useTabs)
}}}}}}}}
}
static func evaluate(_ mode: CommandMode) -> Result<AutoCorrectOptions, CommandantError<CommandantError<()>>> {
// swiftlint:enable line_length
return create
<*> mode <| pathOption(action: "correct")
<*> mode <| configOption
<*> mode <| useScriptInputFilesOption
<*> mode <| quietOption(action: "correcting")
<*> mode <| Option(key: "force-exclude",
defaultValue: false,
usage: "exclude files in config `excluded` even if their paths are explicitly specified")
<*> mode <| Option(key: "format",
defaultValue: false,
usage: "should reformat the Swift files")
<*> mode <| Option(key: "cache-path", defaultValue: "",
usage: "the directory of the cache used when correcting")
<*> mode <| Option(key: "no-cache", defaultValue: false,
usage: "ignore cache when correcting")
<*> mode <| Option(key: "use-tabs",
defaultValue: false,
usage: "should use tabs over spaces when reformatting. Deprecated.")
}
}
| mit | c711fbca5aa67d6e559a91abf09af1fa | 47.520408 | 264 | 0.555415 | 5.366817 | false | true | false | false |
ScottLegrove/HoneyDueIOS | Honey Due/AppDelegate.swift | 1 | 6092 | //
// AppDelegate.swift
// Honey Due
//
// Created by Scott Legrove on 2016-03-29.
// Copyright © 2016 Scott Legrove. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "sl.Honey_Due" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Honey_Due", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
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 {
// Report any error we got.
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: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
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 {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | b77d626aa7862f9564d5c857d4680364 | 53.873874 | 291 | 0.719094 | 5.879344 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/NaturalLanguageUnderstandingV1/Models/SentimentOptions.swift | 1 | 2769 | /**
* (C) Copyright IBM Corp. 2017, 2021.
*
* 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
/**
Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze
sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`.
Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish.
*/
public struct SentimentOptions: Codable, Equatable {
/**
Set this to `false` to hide document-level sentiment results.
*/
public var document: Bool?
/**
Sentiment results will be returned for each target string that is found in the document.
*/
public var targets: [String]?
/**
(Beta) Enter a [custom
model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
ID to override the standard sentiment model for all sentiment analysis operations in the request, including
targeted sentiment for entities and keywords.
*/
public var model: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case document = "document"
case targets = "targets"
case model = "model"
}
/**
Initialize a `SentimentOptions` with member variables.
- parameter document: Set this to `false` to hide document-level sentiment results.
- parameter targets: Sentiment results will be returned for each target string that is found in the document.
- parameter model: (Beta) Enter a [custom
model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing)
ID to override the standard sentiment model for all sentiment analysis operations in the request, including
targeted sentiment for entities and keywords.
- returns: An initialized `SentimentOptions`.
*/
public init(
document: Bool? = nil,
targets: [String]? = nil,
model: String? = nil
)
{
self.document = document
self.targets = targets
self.model = model
}
}
| apache-2.0 | 5c780f09994fef1e19de46dcd8add2ec | 36.418919 | 122 | 0.70242 | 4.615 | false | false | false | false |
haskellswift/swift-package-manager | Sources/Utility/ProgressBar.swift | 2 | 3294 | /*
This source file is part of the Swift.org open source project
Copyright 2016 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
/// A protocol to operate on terminal based progress bars.
public protocol ProgressBarProtocol {
func update(percent: Int, text: String)
func complete()
}
/// Simple ProgressBar which shows the update text in new lines.
public final class SimpleProgressBar: ProgressBarProtocol {
private let header: String
private var isClear: Bool
private var stream: OutputByteStream
init(stream: OutputByteStream, header: String) {
self.stream = stream
self.header = header
self.isClear = true
}
public func update(percent: Int, text: String) {
if isClear {
stream <<< header
stream <<< "\n"
stream.flush()
isClear = false
}
stream <<< "\(percent)%: " <<< text
stream <<< "\n"
stream.flush()
}
public func complete() {
}
}
/// Three line progress bar with header, redraws on each update.
public final class ProgressBar: ProgressBarProtocol {
private let term: TerminalController
private let header: String
private var isClear: Bool // true if haven't drawn anything yet.
init(term: TerminalController, header: String) {
self.term = term
self.header = header
self.isClear = true
}
public func update(percent: Int, text: String) {
if isClear {
let spaceCount = (term.width/2 - header.utf8.count/2)
term.write(" ".repeating(n: spaceCount))
term.write(header, inColor: .cyan, bold: true)
term.endLine()
isClear = false
}
term.clearLine()
let percentString = percent < 10 ? " \(percent)" : "\(percent)"
let prefix = "\(percentString)% " + term.wrap("[", inColor: .green, bold: true)
term.write(prefix)
let barWidth = term.width - prefix.utf8.count
let n = Int(Double(barWidth) * Double(percent)/100.0)
term.write("=".repeating(n: n) + "-".repeating(n: barWidth - n), inColor: .green)
term.write("]", inColor: .green, bold: true)
term.endLine()
term.clearLine()
term.write(text)
term.moveCursor(y: 1)
}
public func complete() {
term.endLine()
}
}
/// Creates colored or simple progress bar based on the provided output stream.
public func createProgressBar(forStream stream: OutputByteStream, header: String) -> ProgressBarProtocol {
if let stdStream = stream as? LocalFileOutputByteStream, let term = TerminalController(stream: stdStream) {
return ProgressBar(term: term, header: header)
}
return SimpleProgressBar(stream: stream, header: header)
}
private extension String {
/// Repeats self n times. If n is less than zero, returns the same string.
func repeating(n: Int) -> String {
guard n > 0 else { return self }
var str = ""
for _ in 0..<n {
str = str + self
}
return str
}
}
| apache-2.0 | 2f0895d85e6a595bba115f8425e6574f | 28.945455 | 111 | 0.625076 | 4.289063 | false | false | false | false |
olimpias/Olimpo | olimpo/Olimpo.swift | 1 | 2674 | //
// Olimpo.swift
// olimpo
//
// Created by Cem Türker on 26/04/16.
// Copyright © 2016 Cem Türker. All rights reserved.
//
import Foundation
import UIKit
class Olimpo {
private let networkManager:NetworkManager;
private let mediaController:MediaController;
private static let sharedInstance:Olimpo = Olimpo();
static var MAX_CAPACITY_VALUE:Int = 30; //shouldnt be changed after calling load method...
private init() {
mediaController = MediaController();
networkManager = NetworkManager(networkCallback: mediaController);
}
//Creates new action with imageview
private func callNewAction(action:Action, imageView:UIImageView){
if action.url != nil {
if mediaController.isCacheContains(action){
mediaController.updateActionData(action);
mediaController.changeImageInImageView(imageView, key: action.url!);
}else{
if let url:NSURL = NSURL(string: action.url!) {
networkManager.downloadDataFromGivenUrl(url);
mediaController.addNewAction(action,imageView: imageView);
}
}
}
}
static func load(url:String) -> ActionBuilder {
let actionBuilder:ActionBuilder = ActionBuilder().build();
actionBuilder.url(url);
return actionBuilder;
}
class ActionBuilder {
private let action:Action;
init(){
action = Action();
}
func into(imageView:UIImageView) -> Void {
Olimpo.sharedInstance.callNewAction(action,imageView:imageView);
}
func placeHolder(placeHolder:UIImage) -> ActionBuilder {
action.placeHolder = placeHolder;
return self;
}
func error(error:UIImage) -> ActionBuilder {
action.error = error;
return self;
}
func contentMode(mode:UIViewContentMode) -> ActionBuilder {
action.imageViewContentMode = mode;
return self;
}
///Resize image.
///When reSize method is used, contentMode is recommmended to set , because you might not experience affects of resizing on image.
func reSize(height:CGFloat,width:CGFloat) -> ActionBuilder {
action.newSize = CGSize(width: width, height: height);
return self;
}
private func url(url:String) -> ActionBuilder {
action.url = url;
return self;
}
private func build() -> ActionBuilder {
return self;
}
}
}
| mit | b9cc5b7af706249cab77f482706c4d11 | 30.05814 | 138 | 0.591164 | 4.830018 | false | false | false | false |
quangvu1994/Exchange | Exchange/View Controllers/ExchangeSequenceViewController.swift | 1 | 5228 | //
// ExchangeSequenceViewController.swift
// Exchange
//
// Created by Quang Vu on 7/13/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
import FirebaseDatabase
class ExchangeSequenceViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
var posterItems = [Post]() {
didSet {
collectionView.reloadData()
}
}
var originalItem: Post?
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
guard let originalItem = originalItem else {
return
}
// fetch post
PostService.fetchPost(for: originalItem.poster.uid, completionHandler: { [unowned self] post in
self.posterItems = post.filter {
$0.requestedBy["\(User.currentUser.uid)"] != true && $0.availability == true
}
// Presect the original item
for post in self.posterItems {
if post.key == originalItem.key {
post.selected = true
}
}
})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifer = segue.identifier {
if identifer == "Finish Selecting Their Items" {
let selectedItems = posterItems.filter { $0.selected == true }
let stepTwoViewController = segue.destination as! SelectingMyItemsViewController
stepTwoViewController.posterItems = selectedItems
}
}
}
@IBAction func addItemAction(_ sender: UIButton) {
// Only continue if the user has selected at least one item
let selectedItems = posterItems.filter { $0.selected == true }
if !selectedItems.isEmpty {
self.performSegue(withIdentifier: "Finish Selecting Their Items", sender: nil)
} else {
self.displayWarningMessage(message: "Please select at least one item")
}
}
@IBAction func unwindFromStepTwo(_ sender: UIStoryboardSegue) {
print("Back")
}
}
extension ExchangeSequenceViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return posterItems.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Item Cell", for: indexPath) as! EXCollectionViewCell
let imageURL = URL(string: posterItems[indexPath.row].imagesURL[0])
cell.checkMark.isHidden = !posterItems[indexPath.row].selected
if !cell.checkMark.isHidden {
cell.itemImage.alpha = 0.5
cell.imageSelected = true
}
cell.itemImage.kf.setImage(with: imageURL)
cell.delegate = self
cell.addTapGesture()
cell.index = indexPath.row
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard kind == UICollectionElementKindSectionHeader else {
fatalError("Undefined collection view kind")
}
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "EX Header", for: indexPath)
return header
}
}
extension ExchangeSequenceViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfRows: CGFloat = 3
let spacingWidth: CGFloat = 3
let totalHorizontalSpacing = (numberOfRows - 1) * spacingWidth
let cellWidth = (collectionView.bounds.width - totalHorizontalSpacing) / numberOfRows
let cellSize = CGSize(width: cellWidth, height: cellWidth)
return cellSize
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 3.0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 3
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 3
}
}
extension ExchangeSequenceViewController: ImageSelectHandler {
func storeSelectedImages(for selectedCell: EXCollectionViewCell) {
guard let index = selectedCell.index else {
print("This cell doesn't have an assigned index")
return
}
selectedCell.toggleSelectedCheckmark()
posterItems[index].selected = selectedCell.imageSelected
}
}
| mit | a8d92225693ad403880833bde6859b11 | 37.433824 | 175 | 0.663095 | 5.614393 | false | false | false | false |
CallMeMrAlex/DYTV | DYTV-AlexanderZ-Swift/DYTV-AlexanderZ-Swift/Classes/Main(主框架)/View/CollectionBaseCell.swift | 1 | 1033 | //
// CollectionBaseCell.swift
// DYTV-AlexanderZ-Swift
//
// Created by Alexander Zou on 16/9/30.
// Copyright © 2016年 Alexander Zou. All rights reserved.
//
import UIKit
class CollectionBaseCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var onlineBtn: UIButton!
@IBOutlet weak var nickNameLabel: UILabel!
var anchor : AnchorModel? {
didSet {
guard let anchor = anchor else { return }
var onlineString : String = ""
if anchor.online >= 10000 {
onlineString = "\(Int(anchor.online / 10000))万在线"
} else {
onlineString = "\(anchor.online)人在线"
}
onlineBtn.setTitle(onlineString, for: .normal)
nickNameLabel.text = anchor.nickname
guard let iconURL = URL(string: anchor.vertical_src) else { return }
iconImageView.kf.setImage(with: iconURL)
}
}
}
| mit | 3c0e23180987b3735c94572320f645c3 | 22.674419 | 80 | 0.578585 | 4.779343 | false | false | false | false |
google/JacquardSDKiOS | Example/JacquardSDK/IMUDataCollectionView/IMUSessionDetailTableViewCell.swift | 1 | 1113 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import JacquardSDK
import UIKit
class IMUSessionDetailTableViewCell: UITableViewCell {
@IBOutlet private weak var title: UILabel!
static let reuseIdentifier = "IMUSessionDetailTableViewCell"
func configureCell(model: IMUSample) {
let accelation = model.acceleration
let gyro = model.gyro
let accString = "Accx: \(accelation.x), AccY: \(accelation.y), AccZ: \(accelation.x), "
let gyroString = "GyroRoll: \(gyro.x), GyroPitch: \(gyro.y), GyroYaw: \(gyro.x)"
title.text = accString + gyroString
}
}
| apache-2.0 | 34d6c7d89971dff72cf7cbc5bbe39dca | 34.903226 | 91 | 0.733154 | 3.864583 | false | false | false | false |
Polant/AppServer | Sources/App/Controllers/Merchant/MenuController.swift | 1 | 9144 | //
// MenuController.swift
// AppServer
//
// Created by Anton Poltoratskyi on 27.11.16.
//
//
import Foundation
import Vapor
import HTTP
class MenuController: DropletConfigurable {
weak var drop: Droplet?
required init(droplet: Droplet) {
self.drop = droplet
}
//MARK: - Setup
func setup() {
guard drop != nil else {
debugPrint("Drop is nil")
return
}
setupRoutes()
}
private func setupRoutes() {
guard let drop = drop else {
debugPrint("Drop is nil")
return
}
let merchantAuth = AuthMiddlewareFactory.shared.merchantAuthMiddleware
let menuGroup = drop.grouped("merchant")
.grouped(merchantAuth)
.grouped(AuthenticationMiddleware())
.grouped("menu")
let categoryGroup = menuGroup.grouped("category")
categoryGroup.post("list", handler: categoriesList)
categoryGroup.post("items", ":category_id", handler: categoryItemsList)
categoryGroup.post("create", handler: createCategory)
categoryGroup.post("edit", handler: editCategory)
categoryGroup.post("delete", handler: deleteCategory)
let menuItemsGroup = menuGroup.grouped("item")
menuItemsGroup.post("create", handler: createItem)
menuItemsGroup.post("edit", handler: editItem)
menuItemsGroup.post("delete", handler: deleteItem)
let customerAuth = AuthMiddlewareFactory.shared.customerAuthMiddleware
let infoGroup = drop.grouped("customer")
.grouped(customerAuth)
.grouped(AuthenticationMiddleware())
.grouped("menu")
infoGroup.post("items", handler: orderItemsSet)
}
//MARK: Menu List
func categoriesList(_ req: Request) throws -> ResponseRepresentable {
let merchant = try req.merchant()
var responseNodes = [Node]()
for category in try merchant.menuCategories().all() {
responseNodes.append(try category.makeNode())
}
return try JSON(node: ["error": false,
"menu_categories": Node.array(responseNodes)])
}
func categoryItemsList(_ req: Request) throws -> ResponseRepresentable {
guard let categoryId = req.parameters["category_id"]?.string,
let category = try MenuCategory.find(categoryId) else {
throw Abort.custom(status: .badRequest, message: "Category id required")
}
var responseNodes = [Node]()
for menuItem in try category.menuItems().all() {
responseNodes.append(try menuItem.makeNode())
}
return try JSON(node: ["error": false,
"menu_items": Node.array(responseNodes)])
}
//MARK: - Menu Items by array of identifiers
func orderItemsSet(_ req: Request) throws -> ResponseRepresentable {
guard let items = req.data["items"]?.array else {
throw Abort.badRequest
}
var ids = [NodeRepresentable]()
for jsonItem in items {
guard let object = jsonItem.object else { continue }
let menuItemId = object["id"]!.string!
ids.append(menuItemId)
}
var menuItems = [MenuItem]()
for id in ids {
guard let item = try MenuItem.find(id) else {
throw Abort.custom(status: .badRequest,
message: "Menu item with id=\(id) not found")
}
menuItems.append(item)
}
// let menuItems = try MenuItem.query().filter(MenuItem.self, "_id", .in, ids).all()
var result = [Node]()
for menuItem in menuItems {
result.append(try menuItem.makeNode())
}
return try JSON(node: ["error": false,
"order": Node.array(result)])
}
//MARK: - Category
func createCategory(_ req: Request) throws -> ResponseRepresentable {
let merchant = try req.merchant()
guard let categoryName = req.data["category_name"]?.string else {
throw Abort.custom(status: .badRequest, message: "Category name required")
}
guard let description = req.data["category_description"]?.string else {
throw Abort.custom(status: .badRequest, message: "Category description required")
}
let photoUrl = req.data["photo_url"]?.string
var menuCategory = MenuCategory(name: categoryName,
description: description,
merchantId: merchant.id!,
photoUrl: photoUrl)
try menuCategory.save()
return try JSON(node: ["error": false,
"message": "Category added",
"category" : menuCategory.makeJSON()])
}
func editCategory(_ req: Request) throws -> ResponseRepresentable {
var menuCategory = try req.menuCategory()
var isChanged = false
if let categoryName = req.data["category_name"]?.string {
menuCategory.name = categoryName
isChanged = true
}
if let categoryDescription = req.data["category_description"]?.string {
menuCategory.description = categoryDescription
isChanged = true
}
if let photo = req.data["photo_url"]?.string {
menuCategory.photoUrl = photo
isChanged = true
}
if isChanged {
try menuCategory.save()
return try JSON(node: ["error": false,
"message": "Category edited",
"category" : menuCategory.makeJSON()])
}
throw Abort.custom(status: .badRequest, message: "No parameters")
}
func deleteCategory(_ req: Request) throws -> ResponseRepresentable {
let menuCategory = try req.menuCategory()
try DataManager.shared.deleteMenuCategory(menuCategory)
return try JSON(node: ["error": false,
"message": "Category deleted"])
}
//MARK: - Menu Items
func createItem(_ req: Request) throws -> ResponseRepresentable {
let menuCategory = try req.menuCategory()
guard let name = req.data["name"]?.string else {
throw Abort.custom(status: .badRequest, message: "Menu item name required")
}
guard let description = req.data["description"]?.string else {
throw Abort.custom(status: .badRequest, message: "Menu item description required")
}
guard let price = req.data["price"]?.double else {
throw Abort.custom(status: .badRequest, message: "Menu item price required")
}
let photoUrl = req.data["photo_url"]?.string
var menuItem = MenuItem(name: name,
description: description,
photoUrl: photoUrl,
price: price,
menuCategoryId: menuCategory.id!)
try menuItem.save()
return try JSON(node: ["error": false,
"message": "Menu item added",
"menu_item" : menuItem.makeJSON()])
}
func editItem(_ req: Request) throws -> ResponseRepresentable {
var menuItem = try req.menuItem()
var isChanged = false
if let name = req.data["name"]?.string {
menuItem.name = name
isChanged = true
}
if let categoryDescription = req.data["description"]?.string {
menuItem.description = categoryDescription
isChanged = true
}
if let photo = req.data["photo_url"]?.string {
menuItem.photoUrl = photo
isChanged = true
}
if let photo = req.data["price"]?.double {
menuItem.price = photo
isChanged = true
}
if isChanged {
try menuItem.save()
return try JSON(node: ["error": false,
"message": "Menu item edited",
"menu_item" : menuItem.makeJSON()])
}
throw Abort.custom(status: .badRequest, message: "No parameters")
}
func deleteItem(_ req: Request) throws -> ResponseRepresentable {
let menuItem = try req.menuItem()
try menuItem.delete()
return try JSON(node: ["error": false,
"message": "Menu item deleted"])
}
}
| mit | 6defa7f6f289fa66b79cf34c1d247ce1 | 32.250909 | 94 | 0.528762 | 5.344243 | false | false | false | false |
combes/audio-weather | AudioWeather/AudioWeather/WeatherModel.swift | 1 | 3373 | //
// WeatherModel.swift
// AudioWeather
//
// Created by Christopher Combes on 6/17/17.
// Copyright © 2017 Christopher Combes. All rights reserved.
//
import SwiftyJSON
class WeatherModel: WeatherModelProtocol, CustomDebugStringConvertible {
// Title
var title = ""
// Location
var city = ""
// Condition
var code = 0
var date = ""
var temperature = ""
var conditionText = ""
// Wind
var windChill = ""
var windDirection = ""
var windSpeed = ""
// Astronomy
var sunrise = ""
var sunset = ""
var forecast = [ForecastModel]()
var debugDescription: String {
var description = ""
description += "Title(\"\(title)\")\n"
description += "City(\"\(city)\")\n"
description += "Condition(code: \(code), date: \(date), temperature: \(temperature), text: \(conditionText))\n"
description += "Wind(chill: \(windChill), direction: \(windDirection), speed: \(windSpeed))\n"
description += "Astronomy(sunrise: \(sunrise), sunset: \(sunset))\n"
description += "Forecast:\n"
for day in forecast {
description += day.debugDescription
}
return description
}
required init(json: JSON) {
// Start of relevant JSON
if json == JSON.null {
return
}
// Must have JSON to parse
let count = json[WeatherFields.query.rawValue][WeatherFields.count.rawValue].int
if count == 0 {
return
}
// Parse Channel
var channel = json[WeatherFields.query.rawValue][WeatherFields.results.rawValue][WeatherFields.channel.rawValue]
// Parse units
let units = channel[UnitFields.units.rawValue]
_ = UnitsModel(json: units)
// Parse title
title = channel[WeatherFields.title.rawValue].string ?? ""
// Parse city
city = channel[LocationFields.location.rawValue][LocationFields.city.rawValue].string ?? ""
// Parse wind
var wind = channel[WindFields.wind.rawValue]
windChill = wind[WindFields.chill.rawValue].string ?? ""
windDirection = wind[WindFields.direction.rawValue].string ?? ""
windSpeed = wind[WindFields.speed.rawValue].string ?? ""
// Parse astronomy
var astronomy = channel[AstronomyFields.astronomy.rawValue]
sunrise = astronomy[AstronomyFields.sunrise.rawValue].string ?? ""
sunset = astronomy[AstronomyFields.sunset.rawValue].string ?? ""
// Parse item with conditions
var item = channel[WeatherFields.item.rawValue]
var condition = item[ConditionFields.condition.rawValue]
if let codeText = condition[ConditionFields.code.rawValue].string {
code = Int(codeText) ?? 0
}
date = condition[ConditionFields.date.rawValue].string ?? ""
temperature = condition[ConditionFields.temperature.rawValue].string ?? ""
conditionText = condition[ConditionFields.text.rawValue].string ?? ""
// Parse forecast
let forecastDays = item[ForecastFields.forecast.rawValue]
for (_, day):(String, JSON) in forecastDays {
forecast.append(ForecastModel(json: day))
}
}
}
| mit | 3ccbdb50ea93b20c6673a82b087a54f1 | 32.058824 | 120 | 0.594603 | 4.600273 | false | false | false | false |
srn214/Floral | Floral/Pods/SwiftyUserDefaults/Sources/DefaultsBridges.swift | 2 | 10647 | //
// SwiftyUserDefaults
//
// Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz
//
// 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
/// Class important for saving and getting values from UserDefaults. Be careful when you
/// subclass your own!
open class DefaultsBridge<T> {
public init() {}
/// This method provides a way of saving your data in UserDefaults. Usually needed
/// when you want to create your custom Bridge, so you'll have to override it.
open func save(key: String, value: T?, userDefaults: UserDefaults) {
fatalError("This Bridge wasn't subclassed! Please do so before using it in your type.")
}
/// This method provides a way of saving your data in UserDefaults. Usually needed
/// when you want to create your custom Bridge, so you'll have to override it.
open func get(key: String, userDefaults: UserDefaults) -> T? {
fatalError("This Bridge wasn't subclassed! Please do so before using it in your type.")
}
/// Override this function if your data is represented differently in UserDefaults
/// and you map it in save/get methods.
///
/// For instance, if you store it as Data in UserDefaults, but your type is not Data in your
/// defaults key, then you need to `return true` here and provide `deserialize(_:)` method as well.
///
/// Similar if you store your array of type as e.g. `[String]` but the type you use is actually `[SomeClassThatHasOnlyOneStringProperty]`.
///
/// See `DefaultsRawRepresentableBridge` or `DefaultsCodableBridge` for examples.
open func isSerialized() -> Bool {
return false
}
/// Override this function if you've returned `true` in `isSerialized()` method.
///
/// See `isSerialized()` method description for more details.
open func deserialize(_ object: Any) -> T? {
fatalError("You set `isSerialized` to true, now you have to implement `deserialize` method.")
}
}
open class DefaultsObjectBridge<T>: DefaultsBridge<T> {
open override func save(key: String, value: T?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> T? {
return userDefaults.object(forKey: key) as? T
}
}
open class DefaultsArrayBridge<T: Collection>: DefaultsBridge<T> {
open override func save(key: String, value: T?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> T? {
return userDefaults.array(forKey: key) as? T
}
}
open class DefaultsStringBridge: DefaultsBridge<String> {
open override func save(key: String, value: String?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> String? {
return userDefaults.string(forKey: key)
}
}
open class DefaultsIntBridge: DefaultsBridge<Int> {
open override func save(key: String, value: Int?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> Int? {
if let int = userDefaults.number(forKey: key)?.intValue {
return int
}
// Fallback for launch arguments
if let string = userDefaults.object(forKey: key) as? String,
let int = Int(string) {
return int
}
return nil
}
}
open class DefaultsDoubleBridge: DefaultsBridge<Double> {
open override func save(key: String, value: Double?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> Double? {
if let double = userDefaults.number(forKey: key)?.doubleValue {
return double
}
// Fallback for launch arguments
if let string = userDefaults.object(forKey: key) as? String,
let double = Double(string) {
return double
}
return nil
}
}
open class DefaultsBoolBridge: DefaultsBridge<Bool> {
open override func save(key: String, value: Bool?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> Bool? {
// @warning we use number(forKey:) instead of bool(forKey:), because
// bool(forKey:) will always return value, even if it's not set
//
// Now, let's see if there is value in defaults that converts to Bool first:
if let bool = userDefaults.number(forKey: key)?.boolValue {
return bool
}
// If not, fallback for values saved in a plist (e.g. for testing)
// For instance, few of the string("YES", "true", "NO", "false") convert to Bool from a property list
return (userDefaults.object(forKey: key) as? String)?.bool
}
}
open class DefaultsDataBridge: DefaultsBridge<Data> {
open override func save(key: String, value: Data?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> Data? {
return userDefaults.data(forKey: key)
}
}
open class DefaultsUrlBridge: DefaultsBridge<URL> {
open override func save(key: String, value: URL?, userDefaults: UserDefaults) {
userDefaults.set(value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> URL? {
return userDefaults.url(forKey: key)
}
open override func isSerialized() -> Bool {
return true
}
open override func deserialize(_ object: Any) -> URL? {
if let object = object as? URL {
return object
}
if let object = object as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: object) as? URL
}
if let object = object as? NSString {
let path = object.expandingTildeInPath
return URL(fileURLWithPath: path)
}
return nil
}
}
open class DefaultsCodableBridge<T: Codable>: DefaultsBridge<T> {
open override func save(key: String, value: T?, userDefaults: UserDefaults) {
guard let value = value else {
userDefaults.removeObject(forKey: key)
return
}
userDefaults.set(encodable: value, forKey: key)
}
open override func get(key: String, userDefaults: UserDefaults) -> T? {
guard let data = userDefaults.data(forKey: key) else {
return nil
}
return deserialize(data)
}
open override func isSerialized() -> Bool {
return true
}
open override func deserialize(_ object: Any) -> T? {
guard let data = object as? Data else { return nil }
return try? JSONDecoder().decode(T.self, from: data)
}
}
open class DefaultsKeyedArchiverBridge<T>: DefaultsBridge<T> {
open override func get(key: String, userDefaults: UserDefaults) -> T? {
guard let data = userDefaults.data(forKey: key) else {
return nil
}
return deserialize(data)
}
open override func save(key: String, value: T?, userDefaults: UserDefaults) {
guard let value = value else {
userDefaults.removeObject(forKey: key)
return
}
// Needed because Quick/Nimble have min target 10.10...
if #available(OSX 10.11, *) {
userDefaults.set(NSKeyedArchiver.archivedData(withRootObject: value), forKey: key)
} else {
fatalError("Shouldn't really happen. We do not support macOS 10.10, if it happened to you please report your use-case on GitHub issues.")
}
}
open override func isSerialized() -> Bool {
return true
}
open override func deserialize(_ object: Any) -> T? {
guard let data = object as? Data else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: data) as? T
}
}
open class DefaultsRawRepresentableBridge<T: RawRepresentable>: DefaultsBridge<T> {
open override func get(key: String, userDefaults: UserDefaults) -> T? {
guard let object = userDefaults.object(forKey: key) else { return nil }
return deserialize(object)
}
open override func save(key: String, value: T?, userDefaults: UserDefaults) {
userDefaults.set(value?.rawValue, forKey: key)
}
open override func isSerialized() -> Bool {
return true
}
open override func deserialize(_ object: Any) -> T? {
guard let rawValue = object as? T.RawValue else { return nil }
return T(rawValue: rawValue)
}
}
open class DefaultsRawRepresentableArrayBridge<T: Collection>: DefaultsBridge<T> where T.Element: RawRepresentable {
open override func get(key: String, userDefaults: UserDefaults) -> T? {
guard let object = userDefaults.array(forKey: key) else { return nil }
return deserialize(object)
}
open override func save(key: String, value: T?, userDefaults: UserDefaults) {
let raw = value?.map { $0.rawValue }
userDefaults.set(raw, forKey: key)
}
open override func isSerialized() -> Bool {
return true
}
open override func deserialize(_ object: Any) -> T? {
guard let rawValue = object as? [T.Element.RawValue] else { return nil }
return rawValue.compactMap { T.Element(rawValue: $0) } as? T
}
}
| mit | 988f894804f04730e8f8922269fc31bb | 33.898361 | 149 | 0.657835 | 4.455421 | false | false | false | false |
testpress/ios-app | ios-app/UI/ContentsTableViewController.swift | 1 | 2994 | //
// ContentsTableViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
protocol ContentAttemptCreationDelegate {
func newAttemptCreated()
}
class ContentsTableViewController: BaseDBTableViewControllerV2<ContentsListResponse, Content>,
ContentAttemptCreationDelegate {
@IBOutlet weak var navigationBarItem: UINavigationItem!
var contentsUrl: String!
var chapterId: Int!
required init?(coder aDecoder: NSCoder) {
super.init(pager: ContentPager(), coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationBarItem.title = title
(pager as! ContentPager).url = contentsUrl
}
// MARK: - Table view data source
override func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.CONTENT_TABLE_VIEW_CELL,
for: indexPath) as! ContentsTableViewCell
cell.initCell(position: indexPath.row, viewController: self)
return cell
}
override func onLoadFinished(items: [Content]) {
super.onLoadFinished(items: items.sorted(by: { $0.order < $1.order }))
}
override func getItemsFromDb() -> [Content] {
let filterQuery = String(format: "chapterId=%d", chapterId)
return DBManager<Content>().getItemsFromDB(filteredBy: filterQuery, byKeyPath: "order")
}
func newAttemptCreated() {
items.removeAll()
}
override func setEmptyText() {
emptyView.setValues(image: Images.LearnFlatIcon.image, title: Strings.NO_ITEMS_EXIST,
description: Strings.NO_CONTENT_DESCRIPTION)
}
@IBAction func back() {
dismiss(animated: true, completion: nil)
}
}
| mit | 595bd240eb4aeeb3b7b885d8e4915ccf | 35.950617 | 99 | 0.688273 | 4.61171 | false | false | false | false |
jeffreybergier/Hipstapaper | Hipstapaper/Packages/V3Store/Sources/V3Store/PropertyWrappers/TagSystemListQuery.swift | 1 | 1919 | //
// Created by Jeffrey Bergier on 2022/06/17.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// 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 SwiftUI
import V3Model
@propertyWrapper
public struct TagSystemListQuery: DynamicProperty {
public init() {}
public var wrappedValue: some RandomAccessCollection<Tag> {
[
Tag(id: .systemUnread),
Tag(id: .systemAll),
]
}
}
extension Tag.Identifier {
public static let `default`: Tag.Identifier = .systemUnread
internal static let systemAll = Tag.Identifier("hipstapaper://tag/system/all", kind: .systemAll)
internal static let systemUnread = Tag.Identifier("hipstapaper://tag/system/unread", kind: .systemUnread)
public var isSystem: Bool {
self == type(of: self).systemAll || self == type(of: self).systemUnread
}
}
| mit | 01b5d9379ba4dbdd6c8bcbe546cea012 | 37.38 | 109 | 0.714956 | 4.208333 | false | false | false | false |
AtharvaVaidya/Expression | Expression/Classes/AVExpression.swift | 1 | 6844 |
import Foundation
// Credits to Ali Hafizji on GitHub.
// https://github.com/raywenderlich/swift-algorithm-club/tree/master/Shunting%20Yard
internal enum OperatorAssociativity {
case LeftAssociative
case RightAssociative
}
open class Expression {
private var expression: String
private var result: Double
public init(string: String) {
expression = string
.replacingOccurrences(of: "﹢", with: "+")
.replacingOccurrences(of: "﹣", with: "-")
.replacingOccurrences(of: "×", with: "*")
.replacingOccurrences(of: "÷", with: "/")
.replacingOccurrences(of: " ", with: "")
result = 0
}
// Follows the PEMDAS rule.
public func expressionResult() -> Double? {
if isValidExpression() {
return computeExpression()
} else {
return nil
}
}
private func parseIntoTokens(from string: String) -> [Token] {
var stack = [Token]()
var numberString = ""
for (index, character) in string.unicodeScalars.enumerated() {
if character.isDigit() || character.isDot() {
numberString += "\(character)"
} else if character.isOperator() {
if let number = Double(numberString) {
stack.append(Token(operand: number))
numberString = ""
}
stack.append(Token(operatorType: OperatorType(rawValue: "\(character)")!))
} else if character.isParanthesis() {
if let number = Double(numberString) {
stack.append(Token(operand: number))
numberString = ""
}
stack.append(Token(tokenType: character == "(" ? .openBracket : .closeBracket))
}
if index == string.unicodeScalars.count - 1 {
if let number = Double(numberString) {
stack.append(Token(operand: number))
numberString = ""
}
}
}
return stack
}
private func parseIntoNumbersAndOperators(from string: String) -> ([Double], [OperatorType]) {
var numbers: [Double] = []
var operators: [OperatorType] = []
var number: String = ""
for (index, character) in string.unicodeScalars.enumerated() {
if character.isDigit() || character.isDot() {
number.append("\(character)")
} else if character.isOperator() {
if index != 0, !string.unicodeScalars[index - 1].isOperator() {
numbers.append(Double(number)!)
number = ""
operators.append(OperatorType(rawValue: "\(character)")!)
} else {
number = ""
}
}
}
numbers.append(Double(number)!)
return (numbers, operators)
}
// private func parseNumber(from string: String
func resultFrom(operating operater: OperatorType, on numbers: [Double]) -> Double {
let n1 = numbers[0], n2 = numbers[1]
switch operater {
case .add: return n1 + n2
case .subtract: return n2 - n1
case .multiply: return n1 * n2
case .divide: return n2 / n1
case .exponent: return pow(n2, n1)
case .percent: return n2.truncatingRemainder(dividingBy: n1)
}
}
func resultFrom(operating operater: String, on numbers: [Double]) -> Double {
let n1 = numbers[0], n2 = numbers[1]
switch operater {
case OperatorType.add.rawValue: return n1 + n2
case OperatorType.subtract.rawValue: return n2 - n1
case OperatorType.multiply.rawValue: return n1 * n2
case OperatorType.divide.rawValue: return n2 / n1
case OperatorType.exponent.rawValue: return pow(n2, n1)
case OperatorType.percent.rawValue: return n2.truncatingRemainder(dividingBy: n1)
default: fatalError("\(operater.unicodeScalars[0].value)")
}
}
private func computeExpression() -> Double {
let expressionBuilder = InfixExpressionBuilder()
let tokenStack = parseIntoTokens(from: expression)
for token in tokenStack {
switch token.tokenType {
case .openBracket:
expressionBuilder.addOpenBracket()
case .closeBracket:
expressionBuilder.addCloseBracket()
case .operand(let operand):
expressionBuilder.addOperand(operand: operand)
case .operatorToken(let operatorToken):
expressionBuilder.addOperator(operatorType: operatorToken.operatorType)
}
}
let (_, tokens) = reversePolishNotation(expression: expressionBuilder.build())
var stack = Stack<Token>()
var tokenCounter = 0
for token in tokens {
if token.isOperand { stack.push(token) }
else {
guard let number1Description = stack.pop()?.description, let number2Description = stack.pop()?.description, let number1 = Double(number1Description), let number2 = Double(number2Description) else {
continue
}
let numbers = [number1, number2]
stack.push(Token(operand: resultFrom(operating: token.tokenType.description, on: numbers)))
}
tokenCounter += 1
}
if let description = stack.pop()?.description, let result = Double(description) {
return result
} else {
return 0
}
}
func isValidExpression() -> Bool {
// If you're on first or last then check if not operator
if !(expression.unicodeScalars.last!.isDigit()), !(expression.unicodeScalars.last!.isParanthesis()) { return false }
// If number of left brackets doesn't equal number of right brackets return false
if expression.components(separatedBy: "(").count != expression.components(separatedBy: ")").count { return false }
if expression.unicodeScalars.map({ $0.isDigit() }) == [Bool](repeating: false, count: expression.unicodeScalars.count) { return false }
for (index, character) in expression.unicodeScalars.enumerated() {
// Logic: If current char is operator then check if next is an operator and the one after that is not an operator.
// Edge case: if
if character.isOperator(), index + 2 < expression.unicodeScalars.count, expression.unicodeScalars[index + 1 ... index + 2].map({ $0.isOperator() }) == [true, true] {
return false
}
}
return true
}
}
| mit | be30f14189a71cf3b5b808ec84346adf | 36.988889 | 213 | 0.567856 | 4.887777 | false | false | false | false |
wess/Appendix | Sources/shared/Dictionary+Appendix.swift | 1 | 2808 | //
// Dictionary+Appendix.swift
// Appendix
//
// Created by Wesley Cope on 7/28/15.
// Copyright © 2015 Wess Cope. All rights reserved.
//
import Foundation
import Swift
public extension Dictionary {
public var jsonData:Data? {
guard JSONSerialization.isValidJSONObject(self) else { return nil}
return try? JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions())
}
public var jsonString:String? {
guard let data = self.jsonData else { return nil }
return String(data: data, encoding: .utf8)
}
public var httpQueryString:String {
return self.reduce([String]()) {
return $0 + ["\($1.key)=\($1.value)"]
}.joined(separator: "&")
}
public init(json string:String) {
guard let data = string.data(using: .utf8) else {
self = [:]
return
}
self = Dictionary(json: data)
}
public init(json data:Data) {
do {
self = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0)) as! [Key:Value]
}
catch let error as NSError {
fatalError(error.description)
}
self = [:]
}
public func filter(handler:(_ key:Key, _ value:Value) -> Bool) -> Dictionary {
var result = Dictionary()
for(key, val) in self {
if handler(key, val) {
result[key] = val
}
}
return result
}
public func has(key:Key) -> Bool {
return index(forKey: key) != nil
}
public func difference<Val:Equatable>(collection:[Key:Val]...) -> [Key:Val] {
var result = [Key:Val]()
for (k,v) in self {
if let item = v as? Val {
result[k] = item
}
}
for dict in collection {
for(key, val) in dict {
if result.has(key: key) && result[key] == val {
result.removeValue(forKey: key)
}
}
}
return result
}
public func merge(_ dict:Dictionary) -> Dictionary {
var this = self
for (k,v) in dict {
this.updateValue(v, forKey: k)
}
return this
}
}
extension Dictionary /* Safe typed getters */ {
public func string(for key:String) -> String? {
return value(for: key)
}
public func int(for key:String) -> Int? {
return value(for: key)
}
public func value<T>(for key:String) -> T? {
guard let v = (self as NSDictionary).value(forKey: key), type(of: v) == T.self else { return nil }
return v as? T
}
}
public func - <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] {
return first.difference(collection: second)
}
public func += <K, V>( lhs:inout [K:V], rhs:[K:V]) {
for (k,v) in rhs {
lhs.updateValue(v, forKey: k)
}
}
func + <K,V>(lhs:[K:V], rhs:[K:V]) -> [K:V] {
return lhs.merge(rhs)
}
| mit | 4f74d390f59f04bca5d55411bc0eb657 | 20.427481 | 129 | 0.582116 | 3.544192 | false | false | false | false |
SSU-CS-Department/ssumobile-ios | SSUMobile/Modules/Radio/SSURadioModule.swift | 1 | 1772 | //
// SSURadioModule.swift
// SSUMobile
//
// Created by Eric Amorde on 4/8/17.
// Copyright © 2017 Sonoma State University Department of Computer Science. All rights reserved.
//
import Foundation
import UIKit
class SSURadioModule: SSUModuleBase, SSUModuleUI {
@objc(sharedInstance)
static let instance = SSURadioModule()
@objc
var radioScheduleURL: URL? {
if let urlString = SSUConfiguration.instance.string(forKey: SSURadioScheduleURLKey) {
return URL(string: urlString)
}
return nil
}
// MARK: SSUModule
var title: String {
return NSLocalizedString("Radio", comment: "The campus online radio status - KSUN Radio")
}
var identifier: String {
return "radio"
}
func setup() {
}
// MARK: SSUModuleUI
func imageForHomeScreen() -> UIImage? {
return UIImage(named: "radio_icon")
}
func initialViewController() -> UIViewController {
let storyboard = UIStoryboard(name: "Radio_iPhone", bundle: Bundle(for: type(of: self)))
return storyboard.instantiateInitialViewController()!
}
func shouldNavigateToModule() -> Bool {
if !SSUConfiguration.instance.bool(forKey: SSURadioStreamEnabledKey) {
let message = SSUConfiguration.instance.string(forKey: SSURadioStreamDisabledMessageKey)
let alert = UIAlertController(title: "Radio Unavailable", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Done", style: .default, handler: nil))
SSUGlobalNavigationController.instance?.present(alert, animated: true, completion: nil)
return false
}
return true
}
}
| apache-2.0 | 4acfedbd9fce89705b96ba514bbcb511 | 28.516667 | 111 | 0.644833 | 4.460957 | false | false | false | false |
zarghol/documentation-provider | Sources/DocumentationProvider/EmptyTag.swift | 1 | 2146 | //
// EmptyTag.swift
// Checkout
//
// Created by Clément Nonn on 15/12/2016.
//
//
import Foundation
import Vapor
import Leaf
class Empty: BasicTag {
public enum Error: Swift.Error {
case expected1Argument
}
let name = "empty"
public func run(arguments: ArgumentList) throws -> Node? {
guard arguments.count == 1 else { throw Error.expected1Argument }
return nil
}
public func shouldRender(
tagTemplate: TagTemplate,
arguments: ArgumentList,
value: Node?
) -> Bool {
guard let arg = arguments.first else {
return true
}
if let array = arg.array, array.count == 0 {
return true
}
if let dico = arg.object, dico.count == 0 {
return true
}
return arg.isNull
}
}
//
//class NamedIndex: BasicTag {
// let name = "namedIndex"
//
// func run(arguments: [Argument]) throws -> Node? {
// guard
// arguments.count == 3,
// let array = arguments[0].value?.nodeArray,
// let index = arguments[1].value?.int,
// let name = arguments[2].value?.string,
// index < array.count
// else { return nil }
// return .object([name: array[index]])
// }
//
// public func render(
// stem: Stem,
// context: LeafContext,
// value: Node?,
// leaf: Leaf
// ) throws -> Bytes {
// guard let value = value else { fatalError("Value must not be nil") }
// context.push(value)
// let rendered = try stem.render(leaf, with: context)
// context.pop()
//
// return rendered + [.newLine]
// }
//}
//
//class CountEqual: BasicTag {
// let name = "countEqual"
//
// func run(arguments: [Argument]) throws -> Node? {
// guard arguments.count == 2,
// let array = arguments[0].value?.nodeArray,
// let expectedCount = arguments[1].value?.int,
// array.count == expectedCount else {
// return nil
// }
//
// return Node("ok")
// }
//}
| mit | 856eed6c99fc009381c79ee39d74fb69 | 23.101124 | 78 | 0.524009 | 3.837209 | false | false | false | false |
AshuMishra/BMSLocationFinder | BMSLocationFinder/BMSLocationFinder/Model Classes/DataModel.swift | 1 | 3346 | //
// DataModel.swift
// BMSLocationFinder
//
// Created by Ashutosh on 05/04/2015.
// Copyright (c) 2015 Ashutosh. All rights reserved.
//
//Class to handle CoreData related task
import UIKit
class DataModel : NSObject {
//Singlton class object
class var sharedModel: DataModel {
struct Static {
static var instance: DataModel?
static var token: dispatch_once_t = 0
}
//To initialize the object only once
dispatch_once(&Static.token) {
Static.instance = DataModel()
}
return Static.instance!
}
//Fetch favorite places
func fetchFavoritePlaces()-> NSArray {
var newPlaceArray = NSMutableArray()
let fetchRequest = NSFetchRequest(entityName: "FavoritePlace")
if let fetchResults = CoreDataManager.sharedManager.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [FavoritePlace] {
if (fetchResults.count > 0) {
for i in 0...fetchResults.count - 1 {
var favoritePlace = fetchResults[i] as FavoritePlace
var place = Place(favoritePlace: favoritePlace)
newPlaceArray.addObject(place)
}
}
}
//Sort array according to it's distance
var descriptor: NSSortDescriptor? = NSSortDescriptor(key: "distance", ascending: true)
var sortedResults: NSArray = newPlaceArray.sortedArrayUsingDescriptors(NSArray(object: descriptor!))
return sortedResults
}
func addPlaceToFavorites(currentPlace:Place) {
var favoritePlace: NSManagedObject? = self.fetchFavoritePlacesForId(currentPlace.placeId)
//If object is not in DB, then add it into DB to make it favorite and skip duplicacy.
if (favoritePlace == nil) {
let favoritePlace = NSEntityDescription.insertNewObjectForEntityForName("FavoritePlace", inManagedObjectContext: CoreDataManager.sharedManager.managedObjectContext!) as FavoritePlace
favoritePlace.placeName = currentPlace.placeName
favoritePlace.placeId = currentPlace.placeId
favoritePlace.placeImageUrl = currentPlace.iconUrl
favoritePlace.placeLatitude = currentPlace.latitude
favoritePlace.placeLongitude = currentPlace.longitude
favoritePlace.placeImagePhotoReference = currentPlace.photoReference
CoreDataManager.sharedManager.saveContext()
}
}
func removePlaceFromFavorites(currentPlace:Place) {
//Remove Object from favorite
var favoritePlace = self.fetchFavoritePlacesForId(currentPlace.placeId)
CoreDataManager.sharedManager.managedObjectContext?.deleteObject(favoritePlace!)
CoreDataManager.sharedManager.saveContext()
}
func fetchFavoritePlacesForId(placeId: String)-> FavoritePlace? {
var favoritePlace: FavoritePlace?
let fetchRequest = NSFetchRequest(entityName: "FavoritePlace")
fetchRequest.predicate = NSPredicate(format: "SELF.placeId = %@",placeId)
if let fetchResults = CoreDataManager.sharedManager.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [FavoritePlace] {
favoritePlace = fetchResults.first
}
return favoritePlace
}
}
| mit | 9522b11a796eeb68ff95e1f894975cc5 | 41.35443 | 194 | 0.678422 | 5.16358 | false | false | false | false |
Cleverlance/Pyramid | Sources/Common/Core/DataAccess/ResourceCachingOperationImpl.swift | 1 | 890 | //
// Copyright © 2016 Cleverlance. All rights reserved.
//
public class ResultCachingOperationImpl<
ItemType, Repository: RepositoryProtocol, Operation: OperationProtocol, Tag
>: TaggedOperation<Empty, ItemType, Tag>
where
Operation.Input == Empty, Operation.Output == ItemType,
Repository.Model == ItemType {
private var loadOperation: Operation
private var repository: Repository
public init(
loadOperation: Operation,
repository: Repository
) {
self.loadOperation = loadOperation
self.repository = repository
}
public override func execute(with _: Empty) throws -> ItemType {
if let item = (try? repository.load()) ?? nil {
return item
} else {
let item = try loadOperation.execute()
ignoreError { try repository.save(item) }
return item
}
}
}
| mit | 6523f2fb47a8734edf8cd34fe5a6fb83 | 26.78125 | 79 | 0.646794 | 4.911602 | false | false | false | false |
iStig/Uther_Swift | Uther_Swift/General/Transition/WelcomeTransitionManager.swift | 1 | 2012 | //
// WelcomeTransitionManager.swift
// Uther_Swift
//
// Created by iStig on 15/9/7.
// Copyright (c) 2015年 iStig. All rights reserved.
//
import UIKit
class WelcomeTransitionManager: NSObject,UIViewControllerAnimatedTransitioning,UIViewControllerTransitioningDelegate {
// MARK: UIViewControllerAnimatedTransitioning
func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval {
return 0.5
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView()
let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
container.addSubview(toView)
container.addSubview(fromView)
let fromAvatar = fromView.viewWithTag(1001)!
let toAvatar = toView.viewWithTag(1002)!
let snapshotAvatar = fromAvatar.snapshotViewAfterScreenUpdates(true)
snapshotAvatar.frame = fromAvatar.frame
container.addSubview(snapshotAvatar)
fromAvatar.alpha = 0
toAvatar.alpha = 0
UIView.animateWithDuration(self.transitionDuration(transitionContext), animations: {
fromView.alpha = 0
snapshotAvatar.frame = toAvatar.frame //将快照的头像位置从中间移动到左上角
},
completion: { finished in
toAvatar.alpha = 1
snapshotAvatar.removeFromSuperview()
transitionContext.completeTransition(true)
}
)
}
// MARK: UIViewControllerTransitioningDelegate
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return self
}
}
| mit | 6faeacf66fa163644e87d7765e72efc1 | 34.927273 | 217 | 0.691802 | 6.194357 | false | false | false | false |
openHPI/xikolo-ios | iOS/ViewControllers/Account/DownloadSettingsViewController.swift | 1 | 4077 | //
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Foundation
import UIKit
class DownloadSettingsViewController: UITableViewController {
// data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return VideoQuality.orderedValues.count
case 1:
return CourseItemContentPreloadSetting.orderedValues.count
default:
return 0
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return NSLocalizedString("settings.video-quality.section-header.download quality",
comment: "section title for download quality")
case 1:
return NSLocalizedString("settings.course-item-content-preload.section-header.course content",
comment: "section header for preload setting for course content")
default:
return nil
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
switch section {
case 1:
return NSLocalizedString("settings.course-item-content-preload.section-footer",
comment: "section footer for preload setting for course content")
default:
return nil
}
}
// delegate
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SettingsOptionBasicCell", for: indexPath)
switch indexPath.section {
case 0:
let videoQuality = VideoQuality.orderedValues[indexPath.row]
cell.textLabel?.text = videoQuality.description
cell.accessoryType = videoQuality == UserDefaults.standard.videoQualityForDownload ? .checkmark : .none
case 1:
let preloadOption = CourseItemContentPreloadSetting.orderedValues[indexPath.row]
cell.textLabel?.text = preloadOption.description
cell.accessoryType = preloadOption == UserDefaults.standard.contentPreloadSetting ? .checkmark : .none
default:
break
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var oldRow: Int?
switch indexPath.section {
case 0:
let oldVideoQuality = UserDefaults.standard.videoQualityForDownload
let newVideoQuality = VideoQuality.orderedValues[indexPath.row]
if oldVideoQuality != newVideoQuality {
UserDefaults.standard.videoQualityForDownload = newVideoQuality
oldRow = VideoQuality.orderedValues.firstIndex(of: oldVideoQuality)
}
case 1:
let oldPreloadOption = UserDefaults.standard.contentPreloadSetting
let newPreloadOption = CourseItemContentPreloadSetting.orderedValues[indexPath.row]
if oldPreloadOption != newPreloadOption {
UserDefaults.standard.contentPreloadSetting = newPreloadOption
oldRow = CourseItemContentPreloadSetting.orderedValues.firstIndex(of: oldPreloadOption)
}
default:
break
}
self.switchSelectedSettingsCell(at: indexPath, to: oldRow)
}
private func switchSelectedSettingsCell(at indexPath: IndexPath, to row: Int?) {
if let row = row {
let oldRow = IndexPath(row: row, section: indexPath.section)
tableView.reloadRows(at: [oldRow, indexPath], with: .none)
} else {
let indexSet = IndexSet(integer: indexPath.section)
tableView.reloadSections(indexSet, with: .none)
}
}
}
| gpl-3.0 | 63b9133af0b4855042c3c18e53e3e112 | 37.45283 | 115 | 0.643032 | 5.434667 | false | false | false | false |
milseman/swift | test/type/subclass_composition.swift | 4 | 20098 | // RUN: %target-typecheck-verify-swift
protocol P1 {
typealias DependentInConcreteConformance = Self
}
class Base<T> : P1 {
typealias DependentClass = T
required init(classInit: ()) {}
func classSelfReturn() -> Self {}
}
protocol P2 {
typealias FullyConcrete = Int
typealias DependentProtocol = Self
init(protocolInit: ())
func protocolSelfReturn() -> Self
}
typealias BaseAndP2<T> = Base<T> & P2
typealias BaseIntAndP2 = BaseAndP2<Int>
class Derived : Base<Int>, P2 {
required init(protocolInit: ()) {
super.init(classInit: ())
}
required init(classInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self {}
}
class Other : Base<Int> {}
typealias OtherAndP2 = Other & P2
protocol P3 : class {}
struct Unrelated {}
//
// If a class conforms to a protocol concretely, the resulting protocol
// composition type should be equivalent to the class type.
//
// FIXME: Not implemented yet.
//
func alreadyConforms<T>(_: Base<T>) {} // expected-note {{'alreadyConforms' previously declared here}}
func alreadyConforms<T>(_: Base<T> & P1) {} // expected-note {{'alreadyConforms' previously declared here}}
func alreadyConforms<T>(_: Base<T> & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}}
func alreadyConforms<T>(_: Base<T> & P1 & AnyObject) {} // expected-error {{invalid redeclaration of 'alreadyConforms'}}
func alreadyConforms(_: P3) {}
func alreadyConforms(_: P3 & AnyObject) {}
// SE-0156 stipulates that a composition can contain multiple classes, as long
// as they are all the same.
func basicDiagnostics(
_: Base<Int> & Base<Int>,
_: Base<Int> & Derived, // expected-error{{protocol-constrained type cannot contain class 'Derived' because it already contains class 'Base<Int>'}}
// Invalid typealias case
_: Derived & OtherAndP2, // expected-error{{protocol-constrained type cannot contain class 'Other' because it already contains class 'Derived'}}
// Valid typealias case
_: OtherAndP2 & P3) {}
// A composition containing only a single class is actually identical to
// the class type itself.
struct Box<T : Base<Int>> {}
func takesBox(_: Box<Base<Int>>) {}
func passesBox(_ b: Box<Base<Int> & Base<Int>>) {
takesBox(b)
}
// Test that subtyping behaves as you would expect.
func basicSubtyping(
base: Base<Int>,
baseAndP1: Base<Int> & P1,
baseAndP2: Base<Int> & P2,
baseAndP2AndAnyObject: Base<Int> & P2 & AnyObject,
baseAndAnyObject: Base<Int> & AnyObject,
derived: Derived,
derivedAndP2: Derived & P2,
derivedAndP3: Derived & P3,
derivedAndAnyObject: Derived & AnyObject,
p1AndAnyObject: P1 & AnyObject,
p2AndAnyObject: P2 & AnyObject,
anyObject: AnyObject) {
// Errors
let _: Base & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'Base & P2'}}
let _: Base<Int> & P2 = base // expected-error {{value of type 'Base<Int>' does not conform to specified type 'Base<Int> & P2'}}
let _: P3 = baseAndP1 // expected-error {{value of type 'Base<Int> & P1' does not conform to specified type 'P3'}}
let _: P3 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'P3'}}
let _: Derived = baseAndP1 // expected-error {{cannot convert value of type 'Base<Int> & P1' to specified type 'Derived'}}
let _: Derived = baseAndP2 // expected-error {{cannot convert value of type 'Base<Int> & P2' to specified type 'Derived'}}
let _: Derived & P2 = baseAndP2 // expected-error {{value of type 'Base<Int> & P2' does not conform to specified type 'Derived & P2'}}
let _ = Unrelated() as Derived & P2 // expected-error {{value of type 'Unrelated' does not conform to 'Derived & P2' in coercion}}
let _ = Unrelated() as? Derived & P2 // expected-warning {{always fails}}
let _ = baseAndP2 as Unrelated // expected-error {{cannot convert value of type 'Base<Int> & P2' to type 'Unrelated' in coercion}}
let _ = baseAndP2 as? Unrelated // expected-warning {{always fails}}
// Different behavior on Linux vs Darwin because of id-as-Any.
// let _ = Unrelated() as AnyObject
// let _ = Unrelated() as? AnyObject
let _ = anyObject as Unrelated // expected-error {{'AnyObject' is not convertible to 'Unrelated'; did you mean to use 'as!' to force downcast?}}
let _ = anyObject as? Unrelated
// No-ops
let _: Base & P1 = base
let _: Base<Int> & P1 = base
let _: Base & AnyObject = base
let _: Base<Int> & AnyObject = base
let _: Derived & AnyObject = derived
let _ = base as Base<Int> & P1
let _ = base as Base<Int> & AnyObject
let _ = derived as Derived & AnyObject
let _ = base as? Base<Int> & P1 // expected-warning {{always succeeds}}
let _ = base as? Base<Int> & AnyObject // expected-warning {{always succeeds}}
let _ = derived as? Derived & AnyObject // expected-warning {{always succeeds}}
// Erasing superclass constraint
let _: P1 = baseAndP1
let _: P1 & AnyObject = baseAndP1
let _: P1 = derived
let _: P1 & AnyObject = derived
let _: AnyObject = baseAndP1
let _: AnyObject = baseAndP2
let _: AnyObject = derived
let _: AnyObject = derivedAndP2
let _: AnyObject = derivedAndP3
let _: AnyObject = derivedAndAnyObject
let _ = baseAndP1 as P1
let _ = baseAndP1 as P1 & AnyObject
let _ = derived as P1
let _ = derived as P1 & AnyObject
let _ = baseAndP1 as AnyObject
let _ = derivedAndAnyObject as AnyObject
let _ = baseAndP1 as? P1 // expected-warning {{always succeeds}}
let _ = baseAndP1 as? P1 & AnyObject // expected-warning {{always succeeds}}
let _ = derived as? P1 // expected-warning {{always succeeds}}
let _ = derived as? P1 & AnyObject // expected-warning {{always succeeds}}
let _ = baseAndP1 as? AnyObject // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? AnyObject // expected-warning {{always succeeds}}
// Erasing conformance constraint
let _: Base = baseAndP1
let _: Base<Int> = baseAndP1
let _: Base = derivedAndP3
let _: Base<Int> = derivedAndP3
let _: Derived = derivedAndP2
let _: Derived = derivedAndAnyObject
let _ = baseAndP1 as Base<Int>
let _ = derivedAndP3 as Base<Int>
let _ = derivedAndP2 as Derived
let _ = derivedAndAnyObject as Derived
let _ = baseAndP1 as? Base<Int> // expected-warning {{always succeeds}}
let _ = derivedAndP3 as? Base<Int> // expected-warning {{always succeeds}}
let _ = derivedAndP2 as? Derived // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? Derived // expected-warning {{always succeeds}}
// Upcasts
let _: Base & P2 = derived
let _: Base<Int> & P2 = derived
let _: Base & P2 & AnyObject = derived
let _: Base<Int> & P2 & AnyObject = derived
let _: Base & P3 = derivedAndP3
let _: Base<Int> & P3 = derivedAndP3
let _ = derived as Base<Int> & P2
let _ = derived as Base<Int> & P2 & AnyObject
let _ = derivedAndP3 as Base<Int> & P3
let _ = derived as? Base<Int> & P2 // expected-warning {{always succeeds}}
let _ = derived as? Base<Int> & P2 & AnyObject // expected-warning {{always succeeds}}
let _ = derivedAndP3 as? Base<Int> & P3 // expected-warning {{always succeeds}}
// Calling methods with Self return
let _: Base & P2 = baseAndP2.classSelfReturn()
let _: Base<Int> & P2 = baseAndP2.classSelfReturn()
let _: Base & P2 = baseAndP2.protocolSelfReturn()
let _: Base<Int> & P2 = baseAndP2.protocolSelfReturn()
// Downcasts
let _ = baseAndP2 as Derived // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = baseAndP2 as? Derived
let _ = baseAndP2 as Derived & P3 // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = baseAndP2 as? Derived & P3
let _ = base as Derived & P2 // expected-error {{did you mean to use 'as!' to force downcast?}}
let _ = base as? Derived & P2
// Invalid cases
let _ = derived as Other & P2 // expected-error {{value of type 'Derived' does not conform to 'Other & P2' in coercion}}
let _ = derived as? Other & P2 // expected-warning {{always fails}}
let _ = derivedAndP3 as Other // expected-error {{cannot convert value of type 'Derived & P3' to type 'Other' in coercion}}
let _ = derivedAndP3 as? Other // expected-warning {{always fails}}
let _ = derivedAndP3 as Other & P3 // expected-error {{value of type 'Derived & P3' does not conform to 'Other & P3' in coercion}}
let _ = derivedAndP3 as? Other & P3 // expected-warning {{always fails}}
let _ = derived as Other // expected-error {{cannot convert value of type 'Derived' to type 'Other' in coercion}}
let _ = derived as? Other // expected-warning {{always fails}}
}
// Test conversions in return statements
func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int> {
return baseAndP2
}
func eraseProtocolInReturn(baseAndP2: (Base<Int> & P2)!) -> Base<Int> {
return baseAndP2
}
func eraseProtocolInReturn(baseAndP2: Base<Int> & P2) -> Base<Int>? {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2 {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: (Base<Int> & P2)!) -> P2 {
return baseAndP2
}
func eraseClassInReturn(baseAndP2: Base<Int> & P2) -> P2? {
return baseAndP2
}
func upcastToExistentialInReturn(derived: Derived) -> Base<Int> & P2 {
return derived
}
func upcastToExistentialInReturn(derived: Derived!) -> Base<Int> & P2 {
return derived
}
func upcastToExistentialInReturn(derived: Derived) -> (Base<Int> & P2)? {
return derived
}
func takesBase<T>(_: Base<T>) {}
func takesP2(_: P2) {}
func takesBaseMetatype<T>(_: Base<T>.Type) {}
func takesP2Metatype(_: P2.Type) {}
func takesBaseIntAndP2(_ x: Base<Int> & P2) {
takesBase(x)
takesP2(x)
}
func takesBaseIntAndP2Metatype(_ x: (Base<Int> & P2).Type) {
takesBaseMetatype(x)
takesP2Metatype(x)
}
func takesDerived(x: Derived) {
takesBaseIntAndP2(x)
}
func takesDerivedMetatype(x: Derived.Type) {
takesBaseIntAndP2Metatype(x)
}
//
// Looking up member types of subclass existentials.
//
func dependentMemberTypes<T : BaseIntAndP2>(
_: T.DependentInConcreteConformance,
_: T.DependentProtocol,
_: T.DependentClass,
_: T.FullyConcrete,
_: BaseIntAndP2.DependentInConcreteConformance, // FIXME expected-error {{}}
_: BaseIntAndP2.DependentProtocol, // expected-error {{type alias 'DependentProtocol' can only be used with a concrete type or generic parameter base}}
_: BaseIntAndP2.DependentClass,
_: BaseIntAndP2.FullyConcrete) {}
func conformsToAnyObject<T : AnyObject>(_: T) {}
func conformsToP1<T : P1>(_: T) {}
func conformsToP2<T : P2>(_: T) {}
func conformsToBaseIntAndP2<T : Base<Int> & P2>(_: T) {}
// expected-note@-1 4 {{in call to function 'conformsToBaseIntAndP2'}}
func conformsToBaseIntAndP2WithWhereClause<T>(_: T) where T : Base<Int> & P2 {}
// expected-note@-1 2 {{in call to function 'conformsToBaseIntAndP2WithWhereClause'}}
class FakeDerived : Base<String>, P2 {
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
}
//
// Metatype subtyping.
//
func metatypeSubtyping(
base: Base<Int>.Type,
derived: Derived.Type,
derivedAndAnyObject: (Derived & AnyObject).Type,
baseIntAndP2: (Base<Int> & P2).Type,
baseIntAndP2AndAnyObject: (Base<Int> & P2 & AnyObject).Type) {
// Erasing conformance constraint
let _: Base<Int>.Type = baseIntAndP2
let _: Base<Int>.Type = baseIntAndP2AndAnyObject
let _: Derived.Type = derivedAndAnyObject
let _: BaseAndP2<Int>.Type = baseIntAndP2AndAnyObject
let _ = baseIntAndP2 as Base<Int>.Type
let _ = baseIntAndP2AndAnyObject as Base<Int>.Type
let _ = derivedAndAnyObject as Derived.Type
let _ = baseIntAndP2AndAnyObject as BaseAndP2<Int>.Type
let _ = baseIntAndP2 as? Base<Int>.Type // expected-warning {{always succeeds}}
let _ = baseIntAndP2AndAnyObject as? Base<Int>.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? Derived.Type // expected-warning {{always succeeds}}
let _ = baseIntAndP2AndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
// Upcast
let _: BaseAndP2<Int>.Type = derived
let _: BaseAndP2<Int>.Type = derivedAndAnyObject
let _ = derived as BaseAndP2<Int>.Type
let _ = derivedAndAnyObject as BaseAndP2<Int>.Type
let _ = derived as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? BaseAndP2<Int>.Type // expected-warning {{always succeeds}}
// Erasing superclass constraint
let _: P2.Type = baseIntAndP2
let _: P2.Type = derived
let _: P2.Type = derivedAndAnyObject
let _: (P2 & AnyObject).Type = derived
let _: (P2 & AnyObject).Type = derivedAndAnyObject
let _ = baseIntAndP2 as P2.Type
let _ = derived as P2.Type
let _ = derivedAndAnyObject as P2.Type
let _ = derived as (P2 & AnyObject).Type
let _ = derivedAndAnyObject as (P2 & AnyObject).Type
let _ = baseIntAndP2 as? P2.Type // expected-warning {{always succeeds}}
let _ = derived as? P2.Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? P2.Type // expected-warning {{always succeeds}}
let _ = derived as? (P2 & AnyObject).Type // expected-warning {{always succeeds}}
let _ = derivedAndAnyObject as? (P2 & AnyObject).Type // expected-warning {{always succeeds}}
// Initializers
let _: Base<Int> & P2 = baseIntAndP2.init(classInit: ())
let _: Base<Int> & P2 = baseIntAndP2.init(protocolInit: ())
let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(classInit: ())
let _: Base<Int> & P2 & AnyObject = baseIntAndP2AndAnyObject.init(protocolInit: ())
let _: Derived = derived.init(classInit: ())
let _: Derived = derived.init(protocolInit: ())
let _: Derived & AnyObject = derivedAndAnyObject.init(classInit: ())
let _: Derived & AnyObject = derivedAndAnyObject.init(protocolInit: ())
}
//
// Conformance relation.
//
func conformsTo<T1 : P2, T2 : Base<Int> & P2>(
anyObject: AnyObject,
p1: P1,
p2: P2,
p3: P3,
base: Base<Int>,
badBase: Base<String>,
derived: Derived,
fakeDerived: FakeDerived,
p2Archetype: T1,
baseAndP2Archetype: T2) {
// FIXME: Uninformative diagnostics
// Errors
conformsToAnyObject(p1)
// expected-error@-1 {{cannot invoke 'conformsToAnyObject' with an argument list of type '(P1)'}}
// expected-note@-2 {{expected an argument list of type '(T)'}}
conformsToP1(p1)
// expected-error@-1 {{cannot invoke 'conformsToP1' with an argument list of type '(P1)'}}
// expected-note@-2 {{expected an argument list of type '(T)'}}
conformsToBaseIntAndP2(base)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
conformsToBaseIntAndP2(badBase)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
conformsToBaseIntAndP2(fakeDerived)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
conformsToBaseIntAndP2WithWhereClause(fakeDerived)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
conformsToBaseIntAndP2(p2Archetype)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
conformsToBaseIntAndP2WithWhereClause(p2Archetype)
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// Good
conformsToAnyObject(anyObject)
conformsToAnyObject(baseAndP2Archetype)
conformsToP1(derived)
conformsToP1(baseAndP2Archetype)
conformsToP2(derived)
conformsToP2(baseAndP2Archetype)
conformsToBaseIntAndP2(derived)
conformsToBaseIntAndP2(baseAndP2Archetype)
conformsToBaseIntAndP2WithWhereClause(derived)
conformsToBaseIntAndP2WithWhereClause(baseAndP2Archetype)
}
//
// Protocols with superclass-constrained Self -- not supported yet.
//
protocol ProtoConstraintsSelfToClass where Self : Base<Int> {}
protocol ProtoRefinesClass : Base<Int> {} // FIXME expected-error {{}}
protocol ProtoRefinesClassAndProtocolAlias : BaseIntAndP2 {}
protocol ProtoRefinesClassAndProtocolDirect : Base<Int> & P2 {} // FIXME expected-error 2 {{}}
protocol ProtoRefinesClassAndProtocolExpanded : Base<Int>, P2 {} // FIXME expected-error {{}}
class ClassConformsToClassProtocolBad1 : ProtoConstraintsSelfToClass {}
// expected-error@-1 {{'ProtoConstraintsSelfToClass' requires that 'ClassConformsToClassProtocolBad1' inherit from 'Base<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Base<Int>' [with Self = ClassConformsToClassProtocolBad1]}}
class ClassConformsToClassProtocolGood1 : Derived, ProtoConstraintsSelfToClass {}
class ClassConformsToClassProtocolBad2 : ProtoRefinesClass {}
// expected-error@-1 {{'ProtoRefinesClass' requires that 'ClassConformsToClassProtocolBad2' inherit from 'Base<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Base<Int>' [with Self = ClassConformsToClassProtocolBad2]}}
class ClassConformsToClassProtocolGood2 : Derived, ProtoRefinesClass {}
// Subclass existentials inside inheritance clauses
class CompositionInClassInheritanceClauseAlias : BaseIntAndP2 { // FIXME: expected-error {{}}
required init(classInit: ()) {
super.init(classInit: ()) // FIXME: expected-error {{}}
}
required init(protocolInit: ()) {
super.init(classInit: ()) // FIXME: expected-error {{}}
}
func protocolSelfReturn() -> Self { return self }
func asBase() -> Base<Int> { return self }
// FIXME expected-error@-1 {{}}
}
class CompositionInClassInheritanceClauseDirect : Base<Int> & P2 {
// expected-error@-1 {{protocol-constrained type is neither allowed nor needed here}}
required init(classInit: ()) {
super.init(classInit: ())
}
required init(protocolInit: ()) {
super.init(classInit: ())
}
func protocolSelfReturn() -> Self { return self }
func asBase() -> Base<Int> { return self }
}
protocol CompositionInAssociatedTypeInheritanceClause {
associatedtype A : BaseIntAndP2
}
// Members of metatypes and existential metatypes
protocol ProtocolWithStaticMember {
static func staticProtocolMember()
func instanceProtocolMember()
}
class ClassWithStaticMember {
static func staticClassMember() {}
func instanceClassMember() {}
}
func staticMembers(
m1: (ProtocolWithStaticMember & ClassWithStaticMember).Protocol,
m2: (ProtocolWithStaticMember & ClassWithStaticMember).Type) {
_ = m1.staticProtocolMember() // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticProtocolMember // expected-error {{static member 'staticProtocolMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticClassMember() // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.staticClassMember // expected-error {{static member 'staticClassMember' cannot be used on protocol metatype '(ClassWithStaticMember & ProtocolWithStaticMember).Protocol'}}
_ = m1.instanceProtocolMember
_ = m1.instanceClassMember
_ = m2.staticProtocolMember()
_ = m2.staticProtocolMember
_ = m2.staticClassMember()
_ = m2.staticClassMember
_ = m2.instanceProtocolMember // expected-error {{instance member 'instanceProtocolMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}}
_ = m2.instanceClassMember // expected-error {{instance member 'instanceClassMember' cannot be used on type 'ClassWithStaticMember & ProtocolWithStaticMember'}}
}
// Make sure we correctly form subclass existentials in expression context.
func takesBaseIntAndPArray(_: [Base<Int> & P2]) {}
func passesBaseIntAndPArray() {
takesBaseIntAndPArray([Base<Int> & P2]())
}
//
// Superclass constrained generic parameters
//
struct DerivedBox<T : Derived> {}
// expected-note@-1 {{requirement specified as 'T' : 'Derived' [with T = Derived & P3]}}
func takesBoxWithP3(_: DerivedBox<Derived & P3>) {}
// expected-error@-1 {{'DerivedBox' requires that 'Derived & P3' inherit from 'Derived'}}
| apache-2.0 | d318d95d91ad172f1880eae7791fdc22 | 35.541818 | 188 | 0.705543 | 3.681627 | false | false | false | false |
dvidlui/iOS8-day-by-day | 21-alerts-and-popovers/AppAlert/AppAlert/ViewController.swift | 1 | 3573 | //
// Copyright 2014 Scott Logic
//
// 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 UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func handlePopoverPressed(sender: UIView) {
let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("codePopover") as UIViewController
popoverVC.modalPresentationStyle = .Popover
if let popoverController = popoverVC.popoverPresentationController {
popoverController.sourceView = sender
popoverController.sourceRect = sender.bounds
popoverController.permittedArrowDirections = .Any
popoverController.delegate = self
}
presentViewController(popoverVC, animated: true, completion: nil)
}
@IBAction func handleAlertPressed(sender: AnyObject) {
let alert = UIAlertController(title: "Alert", message: "Using the alert controller", preferredStyle: .Alert)
let dismissHandler = {
(action: UIAlertAction!) in
self.dismissViewControllerAnimated(true, completion: nil)
}
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: dismissHandler))
alert.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: dismissHandler))
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: dismissHandler))
alert.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = "Sample text field"
}
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func handleActionSheetPressed(sender: UIView) {
let actionSheet = UIAlertController(title: "Action Sheet", message: "Using the alert controller", preferredStyle: .ActionSheet)
if let presentationController = actionSheet.popoverPresentationController {
presentationController.sourceView = sender
presentationController.sourceRect = sender.bounds
}
let dismissHandler = {
(action: UIAlertAction!) in
self.dismissViewControllerAnimated(true, completion: nil)
}
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: dismissHandler))
actionSheet.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: dismissHandler))
actionSheet.addAction(UIAlertAction(title: "OK", style: .Default, handler: dismissHandler))
presentViewController(actionSheet, animated: true, completion: nil)
}
// MARK: - UIPopoverPresentationControllerDelegate
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
return .FullScreen
}
func presentationController(controller: UIPresentationController!, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController! {
return UINavigationController(rootViewController: controller.presentedViewController)
}
}
| apache-2.0 | a69284b352a109b96f9d8ed13a9fe94f | 42.048193 | 167 | 0.752589 | 5.496923 | false | false | false | false |
lkzhao/Hero | Sources/Preprocessors/IgnoreSubviewModifiersPreprocessor.swift | 1 | 2025 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(UIKit)
import UIKit
class IgnoreSubviewModifiersPreprocessor: BasePreprocessor {
override func process(fromViews: [UIView], toViews: [UIView]) {
process(views: fromViews)
process(views: toViews)
}
func process(views: [UIView]) {
for view in views {
guard let recursive = context[view]?.ignoreSubviewModifiers else { continue }
var parentView = view
if view is UITableView, let wrapperView = view.subviews.get(0) {
parentView = wrapperView
}
if recursive {
cleanSubviewModifiers(parentView)
} else {
for subview in parentView.subviews {
context[subview] = nil
}
}
}
}
private func cleanSubviewModifiers(_ parentView: UIView) {
for view in parentView.subviews {
context[view] = nil
cleanSubviewModifiers(view)
}
}
}
#endif
| mit | 00a63116c2d775b72237527e4cfb3723 | 33.322034 | 83 | 0.711605 | 4.460352 | false | false | false | false |
BenYeh16/SoundMapiOS | SoundMap/ProfileViewController.swift | 1 | 6484 | //
// ProfileViewController.swift
// SoundMap
//
// Created by mhci on 2017/6/7.
// Copyright © 2017年 cnl4. All rights reserved.
//
import UIKit
import AVFoundation
class ProfileViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var profileImage: UIImageView!
@IBOutlet weak var uploadButton: UIButton!
@IBOutlet weak var audioCurrent: UILabel!
@IBOutlet weak var playButton: UIButton!
var player:AVAudioPlayer = AVAudioPlayer();
var remotePlayer:AVPlayer = AVPlayer();
var isPaused:BooleanLiteralType = false;
var timer: Timer!
let picker = UIImagePickerController()
let catPictureURL = URL(string: "http://140.112.90.200:2096/")!
let data = SharedData()
func loadProfilePic(){
let url = data.getUserPhoto(id: data.getUserId());
if ( url.isEmpty ) {
print("url is empty");
} else {
let session = URLSession(configuration: .default);
let getUserPhotoSession = session.dataTask(with: URL(string: url)!) { (data, response, error) in
if let e = error {
print("Error getting user photo: \(e)")
} else {
if let res = response as? HTTPURLResponse {
print("Check if get user photo success \(res.statusCode)")
let image = UIImage(data: data!)
self.profileImage.image = image
} else {
print("Couldn't get response code for some reason")
}
}
}
getUserPhotoSession.resume();
}
}
func loadProfileAudio(){
let url = data.getUserAudio(id: data.getUserId());
let playerItem = AVPlayerItem(url: URL(string: url)!)
do {
try remotePlayer = AVPlayer(playerItem: playerItem)
self.remotePlayer.volume = 1.0
} catch {
print ("Can't load user audio")
}
}
//func uploadProfilePhoto(UIImage: image){
//let url = data.get
//}
override func viewDidLoad() {
super.viewDidLoad()
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
self.picker.delegate = self
// Get user name
self.userName.font = self.userName.font?.withSize(30)
// TODO: get userID
// Set image to circle
self.profileImage.frame = CGRect(x: 85, y: 124, width: 150, height: 150) ; // set as you want
self.profileImage.layer.cornerRadius = self.profileImage.frame.height / 2
self.profileImage.layer.masksToBounds = true
self.profileImage.layer.borderWidth = 2
self.profileImage.layer.borderColor = UIColor(red: 86/255, green: 86/255, blue: 1/255, alpha: 1).cgColor
// 1. Load Profile Picture
loadProfilePic();
// 2. Load User Name
userName.text = data.getUserId()
// 3. Load Profile Audio
loadProfileAudio();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/****** Audio ******/
@IBAction func playAudioPressed(_ sender: Any) {
if ( self.isPaused == false ) {
remotePlayer.play()
playButton.setImage(UIImage(named: "music-pause"), for: .normal)
self.isPaused = true
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .commonModes)
} else {
remotePlayer.pause()
playButton.setImage(UIImage(named: "music-play"), for: .normal)
self.isPaused = false
timer.invalidate()
}
}
func stringFromTimeInterval(interval: TimeInterval) -> String {
let interval = Int(interval)
let seconds = interval % 60
let minutes = (interval / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
func stringFromFloatCMTime(time: Double) -> String {
let intTime = Int(time)
let seconds = intTime % 60
let minutes = (intTime / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
func updateTime(_ timer: Timer) {
let currentTimeInSeconds = CMTimeGetSeconds((remotePlayer.currentItem?.currentTime())!)
audioCurrent.text = stringFromFloatCMTime(time: currentTimeInSeconds)
}
/****** Photo ******/
// Upload photo from library
@IBAction func uploadPhoto(_ sender: Any) {
self.picker.allowsEditing = false
self.picker.sourceType = .photoLibrary
self.picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
self.picker.modalPresentationStyle = .popover
present(self.picker, animated: true, completion: nil)
self.picker.popoverPresentationController?.sourceView = uploadButton!
}
// Pick image
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any])
{
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //2
profileImage.contentMode = .scaleAspectFill //3
profileImage.image = chosenImage //4
// Upload Image
//uploadProfileImage(chosenImage: UIImage);
dismiss(animated:true, completion: nil) //5
}
// Cancel picking from library
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true, completion: nil)
}
// Alert if no camera
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
}
| gpl-3.0 | d921dea71faa4050f6ccabd643366569 | 32.235897 | 126 | 0.586021 | 5.020139 | false | false | false | false |
cornerAnt/PilesSugar | PilesSugar/PilesSugar/Module/Club/ClubHot/View/ClubHotCell.swift | 1 | 1586 | //
// ClubHotCell.swift
// PilesSugar
//
// Created by SoloKM on 16/1/13.
// Copyright © 2016年 SoloKM. All rights reserved.
//
import UIKit
class ClubHotCell: UITableViewCell {
/*
comment_count = 0
content = ""
avatar = ""
name = ""
username = ""
active_time = 0
add_datetime_ts = 0
*/
var clubHotModel : ClubHotModel!{
didSet{
var count = clubHotModel.comment_count!
var tempStr = ""
if count > 999 {
count = count / 1000
tempStr = "\(count)" + "k"
}else{
tempStr = "\(count)"
}
comment_countButton.setTitle(tempStr , forState: UIControlState.Normal)
photoImageView.yy_imageURL = NSURL(string: clubHotModel.path!)
contentLabel.text = clubHotModel.content
userInfoLabel.text = clubHotModel.name! + " - " + clubHotModel.username!
}
}
@IBOutlet weak private var comment_countButton: UIButton!
@IBOutlet weak private var photoImageView: UIImageView!
@IBOutlet weak private var contentLabel: UILabel!
@IBOutlet weak private var userInfoLabel: UILabel!
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
}
}
| apache-2.0 | 57494fb4e215def91cc8a994ae8d43d9 | 22.984848 | 84 | 0.554011 | 4.739521 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/HDWallet/Sources/HDWalletKit/Models/HDKeyPath.swift | 1 | 4442 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Parsing
import ToolKit
public enum HDKeyPathError: Error, Equatable {
case invalidIndex
case parsingError(Error)
public static func == (lhs: HDKeyPathError, rhs: HDKeyPathError) -> Bool {
switch (lhs, rhs) {
case (.parsingError(let lhsError), .parsingError(let rhsError)):
return lhsError.localizedDescription == rhsError.localizedDescription
case (.invalidIndex, .invalidIndex):
return true
default:
return false
}
}
}
public enum DerivationComponent: Equatable {
case normal(UInt32)
case hardened(UInt32)
var description: String {
switch self {
case .hardened(let index):
return "\(index)'"
case .normal(let index):
return "\(index)"
}
}
var isHardened: Bool {
switch self {
case .normal:
return false
case .hardened:
return true
}
}
static func normal(intValue: Int) -> Self {
.normal(UInt32(intValue))
}
static func hardened(intValue: Int) -> Self {
.hardened(UInt32(intValue))
}
}
extension Array where Element == DerivationComponent {
func with(normal index: UInt32) -> Self {
self + [.normal(index)]
}
func with(hardened index: UInt32) -> Self {
self + [.hardened(index)]
}
}
public struct HDKeyPath: LosslessStringConvertible, Equatable {
public var description: String {
components
.map(\.description)
.reduce(into: "m") { acc, item in
acc += "/" + item
}
}
public let components: [DerivationComponent]
init(component: DerivationComponent) {
self.init(components: [component])
}
public init(index: Int, hardened: Bool) {
switch hardened {
case false:
self.init(components: [.normal(UInt32(index))])
case true:
self.init(components: [.hardened(UInt32(index))])
}
}
public init(components: [DerivationComponent]) {
self.components = components
}
public init?(_ description: String) {
guard let hdKeyPath = try? Self.from(string: description).get() else {
return nil
}
components = hdKeyPath.components
}
}
extension HDKeyPath {
public static func from(string: String) -> Result<Self, HDKeyPathError> {
let indexParser = Parse {
"/"
Int.parser()
}
.flatMap { value in
if value <= Int32.max {
Always(value)
} else {
Parsing.Fail<Substring, Int>(throwing: HDKeyPathError.invalidIndex)
}
}
let normalDerivationIndexParser = indexParser
.map(DerivationComponent.normal(intValue:))
let hardenedDerivationIndexParser = Parse {
indexParser
OneOf {
"'"
"h"
"H"
}
}
.map(DerivationComponent.hardened(intValue:))
let derivationIndexParser = OneOf {
hardenedDerivationIndexParser
normalDerivationIndexParser
}
let pathComponentsParser = Parse {
OneOf {
"M"
"m"
}
Many { derivationIndexParser }
Optionally { "/" }
}
.map(\.0)
return Result { try pathComponentsParser.parse(string) }
.mapError(HDKeyPathError.parsingError)
.map(HDKeyPath.from(components:))
}
}
extension HDKeyPath {
static func from(components: [DerivationComponent]) -> Self {
Self(components: components)
}
}
extension HDKeyPath {
func with(normal index: UInt32) -> Self {
HDKeyPath(components: components + [.normal(index)])
}
func with(hardened index: UInt32) -> Self {
HDKeyPath(components: components + [.hardened(index)])
}
}
extension Result where Success == HDKeyPath {
func with(normal index: UInt32) -> Result<Success, Failure> {
map { path -> Success in
path.with(normal: index)
}
}
func with(hardened index: UInt32) -> Result<Success, Failure> {
map { path -> Success in
path.with(hardened: index)
}
}
}
| lgpl-3.0 | 849ba3e7912bdb3c6326f9b55124395f | 23.401099 | 83 | 0.560009 | 4.517803 | false | false | false | false |
huonw/swift | validation-test/compiler_crashers_fixed/00194-swift-parser-parseexprsequence.swift | 65 | 1369 | // 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
protocol A {
typealias E
}
struct B<T : A> {
let h -> g {
d j d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}
class d: f{ class func i {}
struct d<f : e,e where g.h == f.h> {
}
protocolias h
}
func some<S: Sequence, T where Optional<T> == S.Iterator.Element>(xs : S) -> T? {
for (mx : T?) in xs {
if let x = mx {
return x
}
}
return nil
}
let xs : [Int?] = [nil, 4, nil]
print(some(xs))
fuotocol A {
typealias B
}return []
}
func i(c: () -> ()) {
}
cnc c<d {
enum c {
func e
var _ = e
}
}
class A<T : A> {
}
func some<C -> b = b
}
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
var x1 = 1
var f1: Int -> Int = {
return $0
}
let su a(2, 3)))
| apache-2.0 | b5ff2a3342ce830b1290208c64bbbc69 | 17.013158 | 81 | 0.549306 | 2.870021 | false | false | false | false |
doertydoerk/offtube | Offtube/MainViewController.swift | 1 | 3069 | //
// MainTableVC.swift
// Offtube
//
// Created by Dirk Gerretz on 05/12/2016.
// Copyright © 2016 [code2 app];. All rights reserved.
//
import UIKit
protocol MainViewControllerProtocol: class {
func requestVideo(url: String)
func reloadVideo(index: Int)
}
class MainViewController: UITableViewController {
// MARK: - Properties
var model = MainViewModel()
@IBOutlet weak var searchBar: UISearchBar!
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
// The viewModel has already been initialized as the Datasoure via the Stroryboard
tableView.dataSource = model
tableView.delegate = self
model.viewController = self
clearsSelectionOnViewWillAppear = true
setupNavBarItems()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
func setupNavBarItems(){
navigationItem.rightBarButtonItem = editButtonItem
navigationItem.rightBarButtonItem?.tintColor = .white
navigationController?.navigationBar.barTintColor = UIColor(red: 0.87, green: 0.18, blue: 0.19, alpha: 1.00)
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
// MARK: Actions
@IBAction func deleteAllTapped(_: UIBarButtonItem) {
model.deleteAllVideos()
}
// MARK: - Segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toVideoPlayer" {
let cell = sender as? VideoCell
let row = (tableView.indexPath(for: cell!))?.row
let video = model.videos?[row!]
let playerView = segue.destination as? VideoViewController
playerView?.video = video
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "toVideoPlayer" {
let cell = sender as? VideoCell
let row = (tableView.indexPath(for: cell!))?.row
let video = model.videos?[row!]
if !(VideoManager.fileExists(url: URL(string: (video?.fileLocation)!)!)) {
let indexPAth = IndexPath(row: row!, section: 0)
tableView.deselectRow(at: indexPAth, animated: true)
return false
}
}
return true
}
// MARK: Misc.
static func displayNetworkIndicator(_ on: Bool) {
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = on
}
}
override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
model.reloadVideo(index: indexPath.row)
}
}
extension MainViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
if let url = searchBar.text {
model.requestVideo(url: url)
}
}
}
| mit | 2a5c4dc8978e96f3f9621650eb0ec06d | 29.376238 | 109 | 0.65189 | 4.877583 | false | false | false | false |
adambailey-/SwiftSoundManager | SwiftSoundManager/SoundTableViewController.swift | 1 | 2702 | //
// SoundTableViewController.swift
// SwiftSoundManager
//
// Created by Adam Bailey on 1/6/15.
// Copyright (c) 2015 Adam Bailey. All rights reserved.
//
import UIKit
import AudioToolbox
class SoundTableViewController: UITableViewController {
var soundManager: SoundManager = SoundManager()
var lastSelected: NSIndexPath! = nil
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor().mainBackgroundColor()
view.tintColor = UIColor().primaryTintColor()
tableView.backgroundColor = UIColor().mainBackgroundColor()
tableView.separatorColor = UIColor().secondaryBorderColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let row = soundManager.rowForSoundName(SwiftSoundManagerDefaults.sharedInstance.alertChosen)
if row >= 0 {
lastSelected = NSIndexPath(forRow: row, inSection: 0)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return self.soundManager.sounds!.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("soundCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel!.text = soundManager.sounds![indexPath.row].displayName
cell.backgroundColor = UIColor().tableCellBackgroundColor()
cell.textLabel!.textColor = UIColor().primaryTextColor()
if lastSelected != nil && lastSelected! == indexPath {
cell.accessoryType = .Checkmark
} else {
cell.accessoryType = .None
}
return cell
}
// MARK: - Table view data delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let audioID: SystemSoundID = self.soundManager.sounds![indexPath.row].audioID
soundManager.playSystemSound(audioID)
// keep track of the last selected cell
lastSelected = indexPath
tableView.reloadData()
SwiftSoundManagerDefaults.sharedInstance.alertChosen = soundManager.sounds![indexPath.row].soundName
}
}
| mit | 588ffaa57183de0817f96bcf545bd386 | 32.358025 | 136 | 0.674315 | 5.447581 | false | false | false | false |
linebounce/HLT-Challenge | HLTChallenge/FlickrPhotoMetadata.swift | 1 | 2043 | //
// FlickrImage.swift
// HLTChallenge
//
// Created by Key Hoffman on 10/5/16.
// Copyright © 2016 Key Hoffman. All rights reserved.
//
import UIKit
// MARK: - FlickrPhotoMetadata
struct FlickrPhotoMetadata: FlickrCollectionElement {
let id: String
let url: String
let title: String
let ownerID: String
let ownerName: String
}
// MARK: - FlickrAPIGetable Conformance
extension FlickrPhotoMetadata {
static func create(from dict: JSONDictionary) -> Result<FlickrPhotoMetadata> {
guard let id = dict[FlickrConstants.Response.Keys.Metadata.id] >>- JSONString,
let url = dict[FlickrConstants.Response.Keys.Metadata.url] >>- JSONString,
let title = dict[FlickrConstants.Response.Keys.Metadata.title] >>- JSONString,
let ownerId = dict[FlickrConstants.Response.Keys.Metadata.ownerID] >>- JSONString,
let ownerName = dict[FlickrConstants.Response.Keys.Metadata.ownerName] >>- JSONString else { return Result(CreationError.Flickr.metadata) }
return Result.init <| FlickrPhotoMetadata(id: id, url: url, title: title, ownerID: ownerId, ownerName: ownerName)
}
}
// MARK: - Module Instance API
extension FlickrPhotoMetadata {
var commentParameter: URLParameters {
// return [FlickrConstants.Parameters.Keys.PhotoCommentCollection.photoID: id]
return [FlickrConstants.Parameters.Keys.CommentCollection.photoID: "29466047852"]
}
func getFlickrPhoto(withBlock block: @escaping ResultBlock<FlickrPhoto>) { // FIXME: HANDLE ERROR AND CLEAN THIS UP!!!!!!
DispatchQueue.global(qos: .userInitiated).async {
let data = URL(string: self.url).flatMap { try? Data(contentsOf:$0) }
DispatchQueue.main.async {
(data >>- UIImage.init).toResult <| CreationError.Flickr.photo(forURL: self.url) <^> { downloadedImage in (downloadedImage, self) |> (FlickrPhoto.init |>> Result.init |>> block) }
}
}
}
}
| mit | 793b434eb7182f49f5343f7c939dcb90 | 38.269231 | 195 | 0.666503 | 4.263048 | false | false | false | false |
externl/ice | swift/test/Ice/facets/AllTests.swift | 4 | 7284 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import PromiseKit
import TestCommon
class EmptyI: Empty {}
func allTests(_ helper: TestHelper) throws -> GPrx {
func test(_ value: Bool, file: String = #file, line: Int = #line) throws {
try helper.test(value, file: file, line: line)
}
let output = helper.getWriter()
let communicator = helper.communicator()
output.write("testing Ice.Admin.Facets property... ")
try test(communicator.getProperties().getPropertyAsList("Ice.Admin.Facets").count == 0)
communicator.getProperties().setProperty(key: "Ice.Admin.Facets", value: "foobar")
var facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets")
try test(facetFilter == ["foobar"])
communicator.getProperties().setProperty(key: "Ice.Admin.Facets", value: "foo\\'bar")
facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets")
try test(facetFilter == ["foo'bar"])
communicator.getProperties().setProperty(key: "Ice.Admin.Facets", value: "'foo bar' toto 'titi'")
facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets")
try test(facetFilter == ["foo bar", "toto", "titi"])
communicator.getProperties().setProperty(key: "Ice.Admin.Facets", value: "'foo bar\\' toto' 'titi'")
facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets")
try test(facetFilter == ["foo bar' toto", "titi"])
// communicator.getProperties().setProperty("Ice.Admin.Facets", "'foo bar' 'toto titi");
// facetFilter = communicator.getProperties().getPropertyAsList("Ice.Admin.Facets");
// test(facetFilter.Length == 0);
communicator.getProperties().setProperty(key: "Ice.Admin.Facets", value: "")
output.writeLine("ok")
output.write("testing facet registration exceptions... ")
communicator.getProperties().setProperty(key: "FacetExceptionTestAdapter.Endpoints", value: "tcp -h *")
let adapter = try communicator.createObjectAdapter("FacetExceptionTestAdapter")
let obj = EmptyI()
_ = try adapter.add(servant: EmptyDisp(obj), id: Ice.stringToIdentity("d"))
_ = try adapter.addFacet(servant: EmptyDisp(obj), id: Ice.stringToIdentity("d"), facet: "facetABCD")
do {
_ = try adapter.addFacet(servant: EmptyDisp(obj), id: Ice.stringToIdentity("d"), facet: "facetABCD")
try test(false)
} catch is Ice.AlreadyRegisteredException {}
_ = try adapter.removeFacet(id: Ice.stringToIdentity("d"), facet: "facetABCD")
do {
_ = try adapter.removeFacet(id: Ice.stringToIdentity("d"), facet: "facetABCD")
try test(false)
} catch is Ice.NotRegisteredException {}
output.writeLine("ok")
output.write("testing removeAllFacets... ")
let obj1 = EmptyI()
let obj2 = EmptyI()
_ = try adapter.addFacet(servant: EmptyDisp(obj1), id: Ice.stringToIdentity("id1"), facet: "f1")
_ = try adapter.addFacet(servant: EmptyDisp(obj2), id: Ice.stringToIdentity("id1"), facet: "f2")
let obj3 = EmptyI()
_ = try adapter.addFacet(servant: EmptyDisp(obj1), id: Ice.stringToIdentity("id2"), facet: "f1")
_ = try adapter.addFacet(servant: EmptyDisp(obj2), id: Ice.stringToIdentity("id2"), facet: "f2")
_ = try adapter.addFacet(servant: EmptyDisp(obj3), id: Ice.stringToIdentity("id2"), facet: "")
var fm = try adapter.removeAllFacets(Ice.stringToIdentity("id1"))
try test(fm.count == 2)
try test((fm["f1"] as! EmptyDisp).servant as? EmptyI === obj1)
try test((fm["f2"] as! EmptyDisp).servant as? EmptyI === obj2)
do {
_ = try adapter.removeAllFacets(Ice.stringToIdentity("id1"))
try test(false)
} catch is Ice.NotRegisteredException {}
fm = try adapter.removeAllFacets(Ice.stringToIdentity("id2"))
try test(fm.count == 3)
try test((fm["f1"] as! EmptyDisp).servant as? EmptyI === obj1)
try test((fm["f2"] as! EmptyDisp).servant as? EmptyI === obj2)
try test((fm[""] as! EmptyDisp).servant as? EmptyI === obj3)
output.writeLine("ok")
adapter.deactivate()
output.write("testing stringToProxy... ")
let db = try communicator.stringToProxy("d:\(helper.getTestEndpoint(num: 0))")!
output.writeLine("ok")
output.write("testing unchecked cast... ")
var prx = uncheckedCast(prx: db, type: ObjectPrx.self)
try test(prx.ice_getFacet() == "")
prx = uncheckedCast(prx: db, type: ObjectPrx.self, facet: "facetABCD")
try test(prx.ice_getFacet() == "facetABCD")
var prx2 = uncheckedCast(prx: prx, type: ObjectPrx.self)
try test(prx2.ice_getFacet() == "facetABCD")
var prx3 = uncheckedCast(prx: prx, type: ObjectPrx.self, facet: "")
try test(prx3.ice_getFacet() == "")
var d = uncheckedCast(prx: db, type: DPrx.self)
try test(d.ice_getFacet() == "")
var df = uncheckedCast(prx: db, type: DPrx.self, facet: "facetABCD")
try test(df.ice_getFacet() == "facetABCD")
var df2 = uncheckedCast(prx: df, type: DPrx.self)
try test(df2.ice_getFacet() == "facetABCD")
var df3 = uncheckedCast(prx: df, type: DPrx.self, facet: "")
try test(df3.ice_getFacet() == "")
output.writeLine("ok")
output.write("testing checked cast... ")
prx = try checkedCast(prx: db, type: ObjectPrx.self)!
try test(prx.ice_getFacet() == "")
prx = try checkedCast(prx: db, type: ObjectPrx.self, facet: "facetABCD")!
try test(prx.ice_getFacet() == "facetABCD")
prx2 = try checkedCast(prx: prx, type: ObjectPrx.self)!
try test(prx2.ice_getFacet() == "facetABCD")
prx3 = try checkedCast(prx: prx, type: ObjectPrx.self, facet: "")!
try test(prx3.ice_getFacet() == "")
d = try checkedCast(prx: db, type: DPrx.self)!
try test(d.ice_getFacet() == "")
df = try checkedCast(prx: db, type: DPrx.self, facet: "facetABCD")!
try test(df.ice_getFacet() == "facetABCD")
df2 = try checkedCast(prx: df, type: DPrx.self)!
try test(df2.ice_getFacet() == "facetABCD")
df3 = try checkedCast(prx: df, type: DPrx.self, facet: "")!
try test(df3.ice_getFacet() == "")
output.writeLine("ok")
output.write("testing non-facets A, B, C, and D... ")
d = try checkedCast(prx: db, type: DPrx.self)!
try test(d == db)
try test(d.callA() == "A")
try test(d.callB() == "B")
try test(d.callC() == "C")
try test(d.callD() == "D")
output.writeLine("ok")
output.write("testing facets A, B, C, and D... ")
df = try checkedCast(prx: d, type: DPrx.self, facet: "facetABCD")!
try test(df.callA() == "A")
try test(df.callB() == "B")
try test(df.callC() == "C")
try test(df.callD() == "D")
output.writeLine("ok")
output.write("testing facets E and F... ")
let ff = try checkedCast(prx: d, type: FPrx.self, facet: "facetEF")!
try test(ff.callE() == "E")
try test(ff.callF() == "F")
output.writeLine("ok")
output.write("testing facet G... ")
let gf = try checkedCast(prx: ff, type: GPrx.self, facet: "facetGH")!
try test(gf.callG() == "G")
output.writeLine("ok")
output.write("testing whether casting preserves the facet... ")
let hf = try checkedCast(prx: gf, type: HPrx.self)!
try test(hf.callG() == "G")
try test(hf.callH() == "H")
output.writeLine("ok")
return gf
}
| gpl-2.0 | 6e7c48de0bcb8ced656a359a58029859 | 44.525 | 108 | 0.648545 | 3.413308 | false | true | false | false |
beeth0ven/BNKit | BNKit/Source/UIKit+/RegularExpression/PlaceholderTextView.swift | 1 | 1560 | //
// PlaceholderTextView.swift
// SelfSizeTextView
//
// Created by luojie on 16/5/12.
// Copyright © 2016年 LuoJie. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
open class PlaceholderTextView: UITextView {
@IBInspectable
open var placeholder: NSString? {
didSet { setNeedsDisplay()
}
}
@IBInspectable
open var placeholderColor: UIColor = .lightGray {
didSet { setNeedsDisplay() }
}
override open var text: String! {
didSet { setNeedsDisplay() }
}
override open func awakeFromNib() {
super.awakeFromNib()
setup()
}
fileprivate func setup() {
observe(forNotification: .UITextViewTextDidChange, sender: self) { [unowned self] _ in
self.setNeedsDisplay()
}
}
override open func draw(_ rect: CGRect) {
super.draw(rect)
guard let placeholder = placeholder, text.isEmpty else { return }
var placeholderAttributes = [String: AnyObject]()
placeholderAttributes[NSFontAttributeName] = font ?? UIFont.systemFont(ofSize: UIFont.systemFontSize)
placeholderAttributes[NSForegroundColorAttributeName] = placeholderColor
let placeholderRect = rect.insetBy(
dx: contentInset.left + textContainerInset.left + textContainer.lineFragmentPadding,
dy: contentInset.top + textContainerInset.top
)
placeholder.draw(in: placeholderRect, withAttributes: placeholderAttributes)
}
}
| mit | 6d3b921481566f484b35742c7396c2b3 | 26.803571 | 109 | 0.643545 | 5.242424 | false | false | false | false |
apple/swift-nio-extras | Tests/NIOHTTPCompressionTests/HTTPRequestCompressorTest.swift | 1 | 17346 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import XCTest
import CNIOExtrasZlib
import NIOCore
import NIOEmbedded
import NIOHTTP1
@testable import NIOHTTPCompression
class HTTPRequestCompressorTest: XCTestCase {
func compressionChannel(_ compression: NIOCompression.Algorithm = .gzip) throws -> EmbeddedChannel {
let channel = EmbeddedChannel()
//XCTAssertNoThrow(try channel.pipeline.addHandler(HTTPRequestEncoder(), name: "encoder").wait())
XCTAssertNoThrow(try channel.pipeline.addHandler(NIOHTTPRequestCompressor(encoding: compression), name: "compressor").wait())
return channel
}
func write(body: [ByteBuffer], to channel: EmbeddedChannel) throws {
let requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/")
try write(head: requestHead, body: body, to: channel)
}
func write(head: HTTPRequestHead, body: [ByteBuffer], to channel: EmbeddedChannel) throws {
var promiseArray = PromiseArray(on: channel.eventLoop)
channel.pipeline.write(NIOAny(HTTPClientRequestPart.head(head)), promise: promiseArray.makePromise())
for bodyChunk in body {
channel.pipeline.write(NIOAny(HTTPClientRequestPart.body(.byteBuffer(bodyChunk))), promise: promiseArray.makePromise())
}
channel.pipeline.write(NIOAny(HTTPClientRequestPart.end(nil)), promise: promiseArray.makePromise())
channel.pipeline.flush()
try promiseArray.waitUntilComplete()
}
func writeWithIntermittantFlush(body: [ByteBuffer], to channel: EmbeddedChannel) throws {
let requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/")
try writeWithIntermittantFlush(head: requestHead, body: body, to: channel)
}
func writeWithIntermittantFlush(head: HTTPRequestHead, body: [ByteBuffer], to channel: EmbeddedChannel) throws {
var promiseArray = PromiseArray(on: channel.eventLoop)
var count = 3
channel.pipeline.write(NIOAny(HTTPClientRequestPart.head(head)), promise: promiseArray.makePromise())
for bodyChunk in body {
channel.pipeline.write(
NIOAny(HTTPClientRequestPart.body(.byteBuffer(bodyChunk))),
promise: promiseArray.makePromise()
)
count -= 1
if count == 0 {
channel.pipeline.flush()
count = 3
}
}
channel.pipeline.write(NIOAny(HTTPClientRequestPart.end(nil)), promise: promiseArray.makePromise())
channel.pipeline.flush()
try promiseArray.waitUntilComplete()
}
func read(from channel: EmbeddedChannel) throws -> (head: HTTPRequestHead, body: ByteBuffer) {
var requestHead: HTTPRequestHead!
var byteBuffer = channel.allocator.buffer(capacity: 0)
channel.pipeline.read()
loop: while let requestPart: HTTPClientRequestPart = try channel.readOutbound() {
switch requestPart {
case .head(let head):
requestHead = head
case .body(let data):
if case .byteBuffer(var buffer) = data {
byteBuffer.writeBuffer(&buffer)
}
case .end:
break loop
}
}
return (head: requestHead, body: byteBuffer)
}
func readVerifyPart(from channel: EmbeddedChannel, verify: (HTTPClientRequestPart)->()) throws {
channel.pipeline.read()
loop: while let requestPart: HTTPClientRequestPart = try channel.readOutbound() {
verify(requestPart)
}
}
func testGzipContentEncoding() throws {
let channel = try compressionChannel()
var buffer = ByteBufferAllocator().buffer(capacity: 0)
buffer.writeString("Test")
_ = try write(body: [buffer], to: channel)
try readVerifyPart(from: channel) { part in
if case .head(let head) = part {
XCTAssertEqual(head.headers["Content-Encoding"].first, "gzip")
}
}
}
func testDeflateContentEncoding() throws {
let channel = try compressionChannel(.deflate)
var buffer = ByteBufferAllocator().buffer(capacity: 0)
buffer.writeString("Test")
_ = try write(body: [buffer], to: channel)
try readVerifyPart(from: channel) { part in
if case .head(let head) = part {
XCTAssertEqual(head.headers["Content-Encoding"].first, "deflate")
}
}
}
func testOneBuffer() throws {
let channel = try compressionChannel()
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
_ = try write(body: [buffer], to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
}
func testMultipleBuffers() throws {
let channel = try compressionChannel()
var buffers: [ByteBuffer] = []
var buffersConcat = ByteBufferAllocator().buffer(capacity: 16 * 1024 * Int.bitWidth / 8)
for _ in 0..<16 {
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
buffers.append(buffer)
buffersConcat.writeBuffer(&buffer)
}
try write(body: buffers, to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffersConcat.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffersConcat, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
}
func testMultipleBuffersDeflate() throws {
let channel = try compressionChannel(.deflate)
var buffers: [ByteBuffer] = []
var buffersConcat = ByteBufferAllocator().buffer(capacity: 16 * 1024 * Int.bitWidth / 8)
for _ in 0..<16 {
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
buffers.append(buffer)
buffersConcat.writeBuffer(&buffer)
}
try write(body: buffers, to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffersConcat.readableBytes)
z_stream.decompressDeflate(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffersConcat, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "deflate")
}
func testMultipleBuffersWithFlushes() throws {
let channel = try compressionChannel()
var buffers: [ByteBuffer] = []
var buffersConcat = ByteBufferAllocator().buffer(capacity: 16 * 1024 * Int.bitWidth / 8)
for _ in 0..<16 {
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
buffers.append(buffer)
buffersConcat.writeBuffer(&buffer)
}
try writeWithIntermittantFlush(body: buffers, to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffersConcat.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffersConcat, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
XCTAssertEqual(result.head.headers["transfer-encoding"].first, "chunked")
XCTAssertNil(result.head.headers["content-size"].first)
}
func testFlushAfterHead() throws {
let channel = try compressionChannel()
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
let requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/")
var promiseArray = PromiseArray(on: channel.eventLoop)
channel.pipeline.write(NIOAny(HTTPClientRequestPart.head(requestHead)), promise: promiseArray.makePromise())
channel.pipeline.flush()
channel.pipeline.write(NIOAny(HTTPClientRequestPart.body(.byteBuffer(buffer))), promise: promiseArray.makePromise())
channel.pipeline.write(NIOAny(HTTPClientRequestPart.end(nil)), promise: promiseArray.makePromise())
channel.pipeline.flush()
try promiseArray.waitUntilComplete()
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
}
func testFlushBeforeEnd() throws {
let channel = try compressionChannel()
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
let requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/")
var promiseArray = PromiseArray(on: channel.eventLoop)
channel.pipeline.write(NIOAny(HTTPClientRequestPart.head(requestHead)), promise: promiseArray.makePromise())
channel.pipeline.write(NIOAny(HTTPClientRequestPart.body(.byteBuffer(buffer))), promise: promiseArray.makePromise())
channel.pipeline.flush()
channel.pipeline.write(NIOAny(HTTPClientRequestPart.end(nil)), promise: promiseArray.makePromise())
channel.pipeline.flush()
try promiseArray.waitUntilComplete()
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
}
func testDoubleFlush() throws {
let channel = try compressionChannel()
var buffer = ByteBufferAllocator().buffer(capacity: 1024 * Int.bitWidth / 8)
for _ in 0..<1024 {
buffer.writeInteger(Int.random(in: Int.min...Int.max))
}
let algo = NIOCompression.Algorithm.gzip
if algo == NIOCompression.Algorithm.deflate {
print("Hello")
}
let requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/")
var promiseArray = PromiseArray(on: channel.eventLoop)
channel.pipeline.write(NIOAny(HTTPClientRequestPart.head(requestHead)), promise: promiseArray.makePromise())
channel.pipeline.write(NIOAny(HTTPClientRequestPart.body(.byteBuffer(buffer))), promise: promiseArray.makePromise())
channel.pipeline.flush()
channel.pipeline.flush()
channel.pipeline.write(NIOAny(HTTPClientRequestPart.end(nil)), promise: promiseArray.makePromise())
channel.pipeline.flush()
try promiseArray.waitUntilComplete()
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
}
func testNoBody() throws {
let channel = try compressionChannel()
let requestHead = HTTPRequestHead(version: HTTPVersion(major: 1, minor: 1), method: .GET, uri: "/")
var promiseArray = PromiseArray(on: channel.eventLoop)
channel.pipeline.write(NIOAny(HTTPClientRequestPart.head(requestHead)), promise: promiseArray.makePromise())
channel.pipeline.write(NIOAny(HTTPClientRequestPart.end(nil)), promise: promiseArray.makePromise())
channel.pipeline.flush()
try promiseArray.waitUntilComplete()
try readVerifyPart(from: channel) { part in
switch part {
case .head(let head):
XCTAssertNil(head.headers["Content-Encoding"].first)
case.body:
XCTFail("Shouldn't return a body")
case .end:
break
}
}
}
}
struct PromiseArray {
var promises: [EventLoopPromise<Void>]
let eventLoop: EventLoop
init(on eventLoop: EventLoop) {
self.promises = []
self.eventLoop = eventLoop
}
mutating func makePromise() -> EventLoopPromise<Void> {
let promise: EventLoopPromise<Void> = eventLoop.makePromise()
self.promises.append(promise)
return promise
}
func waitUntilComplete() throws {
let resultFutures = promises.map { $0.futureResult }
_ = try EventLoopFuture.whenAllComplete(resultFutures, on: eventLoop).wait()
}
}
private extension ByteBuffer {
@discardableResult
mutating func withUnsafeMutableReadableUInt8Bytes<T>(_ body: (UnsafeMutableBufferPointer<UInt8>) throws -> T) rethrows -> T {
return try self.withUnsafeMutableReadableBytes { (ptr: UnsafeMutableRawBufferPointer) -> T in
let baseInputPointer = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self)
let inputBufferPointer = UnsafeMutableBufferPointer(start: baseInputPointer, count: ptr.count)
return try body(inputBufferPointer)
}
}
@discardableResult
mutating func writeWithUnsafeMutableUInt8Bytes(_ body: (UnsafeMutableBufferPointer<UInt8>) throws -> Int) rethrows -> Int {
return try self.writeWithUnsafeMutableBytes(minimumWritableBytes: 0) { (ptr: UnsafeMutableRawBufferPointer) -> Int in
let baseInputPointer = ptr.baseAddress?.assumingMemoryBound(to: UInt8.self)
let inputBufferPointer = UnsafeMutableBufferPointer(start: baseInputPointer, count: ptr.count)
return try body(inputBufferPointer)
}
}
}
private extension z_stream {
static func decompressDeflate(compressedBytes: inout ByteBuffer, outputBuffer: inout ByteBuffer) {
decompress(compressedBytes: &compressedBytes, outputBuffer: &outputBuffer, windowSize: 15)
}
static func decompressGzip(compressedBytes: inout ByteBuffer, outputBuffer: inout ByteBuffer) {
decompress(compressedBytes: &compressedBytes, outputBuffer: &outputBuffer, windowSize: 16 + 15)
}
private static func decompress(compressedBytes: inout ByteBuffer, outputBuffer: inout ByteBuffer, windowSize: Int32) {
compressedBytes.withUnsafeMutableReadableUInt8Bytes { inputPointer in
outputBuffer.writeWithUnsafeMutableUInt8Bytes { outputPointer -> Int in
var stream = z_stream()
// zlib requires we initialize next_in, avail_in, zalloc, zfree and opaque before calling inflateInit2.
stream.next_in = inputPointer.baseAddress!
stream.avail_in = UInt32(inputPointer.count)
stream.next_out = outputPointer.baseAddress!
stream.avail_out = UInt32(outputPointer.count)
stream.zalloc = nil
stream.zfree = nil
stream.opaque = nil
var rc = CNIOExtrasZlib_inflateInit2(&stream, windowSize)
precondition(rc == Z_OK)
rc = inflate(&stream, Z_FINISH)
XCTAssertEqual(rc, Z_STREAM_END)
XCTAssertEqual(stream.avail_in, 0)
rc = inflateEnd(&stream)
XCTAssertEqual(rc, Z_OK)
return outputPointer.count - Int(stream.avail_out)
}
}
}
}
| apache-2.0 | 64b2b4f68f97fa25a57233fffe321fe4 | 43.25 | 133 | 0.64672 | 4.799668 | false | false | false | false |
BBRick/wp | wp/Scenes/Share/RechageVC/RechargeListVC.swift | 1 | 5988 |
//
// RechargeListvc.swift
// wp
//
// Created by sum on 2017/1/5.
// Copyright © 2017年 com.yundian. All rights reserved.
//
import UIKit
class RechargeListVCCell: OEZTableViewCell {
@IBOutlet weak var weekLb: UILabel! // 姓名LbstatusLb
@IBOutlet weak var timeLb: UILabel! // 时间Lb
@IBOutlet weak var moneyCountLb: UILabel! // 充值金额Lb
@IBOutlet weak var statusLb: UILabel! // 状态Lb
@IBOutlet weak var minuteLb: UILabel! // 分秒
@IBOutlet weak var bankLogo: UIImageView! // 银行卡图片
@IBOutlet weak var withDrawto: UILabel! // 提现至
//MARK:--- 刷新cell
override func update(_ data: Any!) {
let model = data as! Model
self.moneyCountLb.text = "+" + " " + String.init(format: "%.2f", model.amount)
let timestr : Int = Date.stringToTimeStamp(stringTime: model.depositTime)
self.withDrawto.text = model.depositType == 1 ? "微信支付" :"银行卡"
self.weekLb.text = Date.yt_convertDateStrWithTimestempWithSecond(timestr, format: "yyyy")
self.statusLb.text = model.status == 1 ? "处理中" : (model.status == 2 ? "充值成功": "充值失败")
self.timeLb.text = Date.yt_convertDateStrWithTimestempWithSecond(timestr, format: "MM-dd")
self.minuteLb.text = Date.yt_convertDateStrWithTimestempWithSecond(timestr, format: "HH:mm:ss")
self.bankLogo.image = model.depositType == 1 ? UIImage.init(named: "weixinpay") : (UIImage.init(named: "unionPay"))
// 设置失败的cell的背景alpha 根据status 来判断 状态view
self.alpha = model.status == 2 ? 1 : (model.status == 1 ? 1 : 0.6)
}
}
class RechargeListVC: BasePageListTableViewController {
var contentoffset = CGFloat() //用来接收偏移量
var pageNumber : Int = 0 //用来判断刷新列表页第几页
var monthLb = UILabel() // 设置显示的月份的label
var dataModel = [Model]() //来接收全局的数组
override func viewDidLoad() {
super.viewDidLoad()
pageNumber = 0
title = "充值列表"
self.setIsLoadMore(true)
ShareModel.share().addObserver(self, forKeyPath: "selectMonth", options: .new, context: nil)
}
//MARK: 界面销毁删除监听
deinit {
ShareModel.share().removeObserver(self, forKeyPath: "selectMonth", context: nil)
}
//MARK: 监听键值对
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
if keyPath == "selectMonth" {
if let selectMonth = change? [NSKeyValueChangeKey.newKey] as? String {
self.tableView.isScrollEnabled = true
if selectMonth != "1000000" {
monthLb.text = "2017年" + " " + "\(selectMonth)" + "月"
}
}
}
}
//MARK: 网络请求列表
override func didRequest(_ pageIndex : Int) {
AppAPIHelper.user().creditlist(status: 0, pos: Int32((pageIndex - 1) * 10) , count: 10, complete: {[weak self] (result) -> ()? in
if let object = result {
let Model : RechargeListModel = object as! RechargeListModel
self?.didRequestComplete(Model.depositsinfo as AnyObject)
}else{
self?.didRequestComplete(nil)
}
return nil
}, error: errorBlockFunc())
}
// override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
// let headerView = UIView ()
// if section == 0 {
// let headerView : UIView = UIView.init(frame:CGRect.init(x: 0, y: 0, width:self.view.frame.size.width, height: 40))
// headerView.backgroundColor = UIColor.groupTableViewBackground
// monthLb = UILabel.init(frame: CGRect.init(x: 17, y: 0, width: self.view.frame.size.width, height: 40))
// monthLb.text = "2017年 1月"
// monthLb.textColor = UIColor.init(hexString: "333333")
// monthLb.font = UIFont.systemFont(ofSize: 16)
//
// headerView.addSubview(monthLb)
//
// let dateBtn :UIButton = UIButton.init(type: UIButtonType.custom)
//
// dateBtn.frame = CGRect.init(x: self.view.frame.size.width-60, y: 8, width: 23, height: 23)
//
// dateBtn.setBackgroundImage(UIImage.init(named: "calendar"), for: UIControlState.normal)
// dateBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//
// dateBtn.addTarget(self, action: #selector(selectDate), for: UIControlEvents.touchUpInside)
//
// headerView.addSubview(dateBtn)
// return headerView
//
// }
//
//
// return headerView
// }
//
// override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
//
// return 40
// }
// override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
//
// return 0.1
//
// }
//MARK: ---视图添加
func selectDate(){
let customer : CustomeAlertView = CustomeAlertView.init(frame: CGRect.init(x: 0, y: contentoffset, width: self.view.frame.size.width, height: self.view.frame.size.height))
self.tableView.isScrollEnabled = false
self.view.addSubview(customer)
}
override func scrollViewDidScroll(_ scrollView: UIScrollView){
contentoffset = scrollView.contentOffset.y
}
}
| apache-2.0 | 04d95dc2ea09f5aba547da7cd58ef208 | 39.160839 | 179 | 0.585234 | 4.052929 | false | false | false | false |
xiaoxionglaoshi/DNSwiftProject | DNSwiftProject/DNSwiftProject/Classes/Expend/DNExtensions/UIViewExtension.swift | 1 | 15525 | //
// UIViewExtension.swift
// DNSwiftProject
//
// Created by mainone on 16/12/20.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
// MARK: Frame
extension UIView {
// x
public var x: CGFloat {
get {
return self.frame.origin.x
} set(value) {
self.frame = CGRect(x: value, y: self.y, width: self.w, height: self.h)
}
}
// y
public var y: CGFloat {
get {
return self.frame.origin.y
} set(value) {
self.frame = CGRect(x: self.x, y: value, width: self.w, height: self.h)
}
}
// width
public var w: CGFloat {
get {
return self.frame.size.width
} set(value) {
self.frame = CGRect(x: self.x, y: self.y, width: value, height: self.h)
}
}
// height
public var h: CGFloat {
get {
return self.frame.size.height
} set(value) {
self.frame = CGRect(x: self.x, y: self.y, width: self.w, height: value)
}
}
// left
public var left: CGFloat {
get {
return self.x
} set(value) {
self.x = value
}
}
// right
public var right: CGFloat {
get {
return self.x + self.w
} set(value) {
self.x = value - self.w
}
}
// top
public var top: CGFloat {
get {
return self.y
} set(value) {
self.y = value
}
}
// bottom
public var bottom: CGFloat {
get {
return self.y + self.h
} set(value) {
self.y = value - self.h
}
}
// origin
public var origin: CGPoint {
get {
return self.frame.origin
} set(value) {
self.frame = CGRect(origin: value, size: self.frame.size)
}
}
// centerX
public var centerX: CGFloat {
get {
return self.center.x
} set(value) {
self.center.x = value
}
}
// centerY
public var centerY: CGFloat {
get {
return self.center.y
} set(value) {
self.center.y = value
}
}
// size
public var size: CGSize {
get {
return self.frame.size
} set(value) {
self.frame = CGRect(origin: self.frame.origin, size: value)
}
}
// leftOffset
public func leftOffset(_ offset: CGFloat) -> CGFloat {
return self.left - offset
}
// rightOffset
public func rightOffset(_ offset: CGFloat) -> CGFloat {
return self.right + offset
}
// topOffset
public func topOffset(_ offset: CGFloat) -> CGFloat {
return self.top - offset
}
// bottomOffset
public func bottomOffset(_ offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
// alignRight
public func alignRight(_ offset: CGFloat) -> CGFloat {
return self.w - offset
}
// 移除子视图
public func removeSubviews() {
self.subviews.forEach({$0.removeFromSuperview()})
}
}
// MARK: Transform
extension UIView {
// 以X轴旋转
public func setRotationX(_ x: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
self.layer.transform = transform
}
// 以Y轴旋转
public func setRotationY(_ y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
self.layer.transform = transform
}
// 以Z轴旋转
public func setRotationZ(_ z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
self.layer.transform = transform
}
// 旋转
public func setRotation(x: CGFloat, y: CGFloat, z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
self.layer.transform = transform
}
// 放大比例
public func setScale(x: CGFloat, y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, x, y, 1)
self.layer.transform = transform
}
}
// MARK: Layer
extension UIView {
// 设置圆角
public func setCornerRadius(radius: CGFloat) {
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
// 添加阴影
public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.shadowColor = color.cgColor
if let r = cornerRadius {
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath
}
}
// 加边框
public func addBorder(width: CGFloat, color: UIColor) {
layer.borderWidth = width
layer.borderColor = color.cgColor
layer.masksToBounds = true
}
// 添加上边框
public func addBorderTop(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
}
// 添加上边框 可设置两头空缺
public func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) {
addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color)
}
// 添加下边框
public func addBorderBottom(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
}
// 添加左边框
public func addBorderLeft(size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
}
// 添加右边框
public func addBorderRight(size: CGFloat, color: UIColor) {
addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
}
// 添加边界
fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
let border = CALayer()
border.backgroundColor = color.cgColor
border.frame = CGRect(x: x, y: y, width: width, height: height)
layer.addSublayer(border)
}
// 画圆 圆填充+边框颜色 + 边框宽度
public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = fillColor.cgColor
shapeLayer.strokeColor = strokeColor.cgColor
shapeLayer.lineWidth = strokeWidth
self.layer.addSublayer(shapeLayer)
}
// 画圆 边框颜色 + 边框宽度
public func drawStroke(width: CGFloat, color: UIColor) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer ()
shapeLayer.path = path.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = width
self.layer.addSublayer(shapeLayer)
}
}
private let UIViewAnimationDuration: TimeInterval = 1
private let UIViewAnimationSpringDamping: CGFloat = 0.5
private let UIViewAnimationSpringVelocity: CGFloat = 0.5
// MARK: Animation
extension UIView {
// 执行弹性动画
public func spring(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
spring(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
// 执行弹性动画
public func spring(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animate(
withDuration: UIViewAnimationDuration,
delay: 0,
usingSpringWithDamping: UIViewAnimationSpringDamping,
initialSpringVelocity: UIViewAnimationSpringVelocity,
options: UIViewAnimationOptions.allowAnimatedContent,
animations: animations,
completion: completion
)
}
// pop效果 size:放大比例 1...
public func pop(size: CGFloat) {
setScale(x: size, y: size)
spring(duration: 0.2, animations: { [unowned self] () -> Void in
self.setScale(x: 1, y: 1)
})
}
// 反向pop size: 0...1
public func reversePop(size: CGFloat) {
setScale(x: size, y: size)
UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { [weak self] Void in
self?.setScale(x: 1, y: 1)
}) { (bool) in }
}
}
// 渲染
extension UIView {
// View转换成Image
public func toImage () -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
drawHierarchy(in: bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
// 手势 Block是用是[weak self] (gesture), 可能造成的内存泄漏
extension UIView {
// 添加点击手势 可设置点击次数
public func addTapGesture(tapNumber: Int = 1, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
// 添加点击手势 Block回调
public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
isUserInteractionEnabled = true
}
// 添加滑动手势
public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) {
let swipe = UISwipeGestureRecognizer(target: target, action: action)
swipe.direction = direction
#if os(iOS)
swipe.numberOfTouchesRequired = numberOfTouches
#endif
addGestureRecognizer(swipe)
isUserInteractionEnabled = true
}
// 添加滑动手势 Block回调
public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> ())?) {
let swipe = BlockSwipe(direction: direction, fingerCount: numberOfTouches, action: action)
addGestureRecognizer(swipe)
isUserInteractionEnabled = true
}
// 添加拖拽手势
public func addPanGesture(target: AnyObject, action: Selector) {
let pan = UIPanGestureRecognizer(target: target, action: action)
addGestureRecognizer(pan)
isUserInteractionEnabled = true
}
// 添加拖拽手势 Block回调
public func addPanGesture(action: ((UIPanGestureRecognizer) -> ())?) {
let pan = BlockPan(action: action)
addGestureRecognizer(pan)
isUserInteractionEnabled = true
}
#if os(iOS)
// 添加捏合手势
public func addPinchGesture(target: AnyObject, action: Selector) {
let pinch = UIPinchGestureRecognizer(target: target, action: action)
addGestureRecognizer(pinch)
isUserInteractionEnabled = true
}
#endif
#if os(iOS)
// 添加捏合手势 Block回调
public func addPinchGesture(action: ((UIPinchGestureRecognizer) -> ())?) {
let pinch = BlockPinch(action: action)
addGestureRecognizer(pinch)
isUserInteractionEnabled = true
}
#endif
// 添加长按手势
public func addLongPressGesture(target: AnyObject, action: Selector) {
let longPress = UILongPressGestureRecognizer(target: target, action: action)
addGestureRecognizer(longPress)
isUserInteractionEnabled = true
}
// 添加长按手势 Block回调
public func addLongPressGesture(action: ((UILongPressGestureRecognizer) -> ())?) {
let longPress = BlockLongPress(action: action)
addGestureRecognizer(longPress)
isUserInteractionEnabled = true
}
// 移除全部手势
public func removeGestureRecognizers() {
gestureRecognizers?.forEach(removeGestureRecognizer)
}
}
extension UIView {
// 画圆角 [.bottomLeft, .topRight]
public func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
// 视图变圆
public func roundView() {
self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) / 2
}
}
extension UIView {
// 循环查找rootView
func rootView() -> UIView {
guard let parentView = superview else {
return self
}
return parentView.rootView()
}
}
private let UIViewDefaultFadeDuration: TimeInterval = 0.4
extension UIView {
// 视图淡入 持续时间+延时+Block回调
public func fadeIn(_ duration:TimeInterval? = UIViewDefaultFadeDuration, delay _delay:TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: _delay ?? 0.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: {
self.alpha = 1.0
}, completion:completion)
}
// 视图淡入 持续时间+延时+Block回调
public func fadeOut(_ duration:TimeInterval? = UIViewDefaultFadeDuration, delay _delay:TimeInterval? = 0.0, completion:((Bool) -> Void)? = nil) {
UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: _delay ?? 0.0, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: {
self.alpha = 0.0
}, completion:completion)
}
// 视图淡化 alpha = Value
public func fadeTo(_ value:CGFloat, duration _duration:TimeInterval? = UIViewDefaultFadeDuration, delay _delay:TimeInterval? = 0.0, completion:((Bool) -> Void)? = nil) {
UIView.animate(withDuration: _duration ?? UIViewDefaultFadeDuration, delay: _delay ?? UIViewDefaultFadeDuration, options: UIViewAnimationOptions(rawValue: UInt(0)), animations: {
self.alpha = value
}, completion:completion)
}
}
| apache-2.0 | e12caf1359f0fa0c88743be5bbaace94 | 30.742072 | 186 | 0.61376 | 4.346844 | false | false | false | false |
rbeeger/Nimble | NimbleTests/Matchers/RaisesExceptionTest.swift | 73 | 8890 | import XCTest
import Nimble
class RaisesExceptionTest: XCTestCase {
var exception = NSException(name: "laugh", reason: "Lulz", userInfo: ["key": "value"])
func testPositiveMatches() {
expect { self.exception.raise() }.to(raiseException())
expect { self.exception.raise() }.to(raiseException(named: "laugh"))
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz"))
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]))
}
func testPositiveMatchesWithClosures() {
expect { self.exception.raise() }.to(raiseException { exception in
expect(exception.name).to(equal("laugh"))
})
expect { self.exception.raise() }.to(raiseException(named: "laugh") { exception in
expect(exception.name).to(beginWith("lau"))
})
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { exception in
expect(exception.name).to(beginWith("lau"))
})
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { exception in
expect(exception.name).to(beginWith("lau"))
})
expect { self.exception.raise() }.to(raiseException(named: "laugh") { exception in
expect(exception.name).toNot(beginWith("as"))
})
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { exception in
expect(exception.name).toNot(beginWith("df"))
})
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { exception in
expect(exception.name).toNot(beginWith("as"))
})
}
func testNegativeMatches() {
failsWithErrorMessage("expected to raise exception with name <foo>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.to(raiseException(named: "foo"))
}
failsWithErrorMessage("expected to raise exception with name <laugh> with reason <bar>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "bar"))
}
failsWithErrorMessage(
"expected to raise exception with name <laugh> with reason <Lulz> with userInfo <{k = v;}>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["k": "v"]))
}
failsWithErrorMessage("expected to raise any exception, got no exception") {
expect { self.exception }.to(raiseException())
}
failsWithErrorMessage("expected to not raise any exception, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.toNot(raiseException())
}
failsWithErrorMessage("expected to raise exception with name <laugh> with reason <Lulz>, got no exception") {
expect { self.exception }.to(raiseException(named: "laugh", reason: "Lulz"))
}
failsWithErrorMessage("expected to raise exception with name <bar> with reason <Lulz>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.to(raiseException(named: "bar", reason: "Lulz"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.toNot(raiseException(named: "laugh"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh> with reason <Lulz>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz"))
}
failsWithErrorMessage("expected to not raise exception with name <laugh> with reason <Lulz> with userInfo <{key = value;}>, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.toNot(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]))
}
}
func testNegativeMatchesDoNotCallClosureWithoutException() {
failsWithErrorMessage("expected to raise exception that satisfies block, got no exception") {
expect { self.exception }.to(raiseException { exception in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> that satisfies block, got no exception") {
expect { self.exception }.to(raiseException(named: "foo") { exception in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> with reason <ha> that satisfies block, got no exception") {
expect { self.exception }.to(raiseException(named: "foo", reason: "ha") { exception in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to raise exception with name <foo> with reason <Lulz> with userInfo <{}> that satisfies block, got no exception") {
expect { self.exception }.to(raiseException(named: "foo", reason: "Lulz", userInfo: [:]) { exception in
expect(exception.name).to(equal("foo"))
})
}
failsWithErrorMessage("expected to not raise any exception, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.toNot(raiseException())
}
}
func testNegativeMatchesWithClosure() {
failsWithErrorMessage("expected to raise exception that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }") {
expect { self.exception.raise() }.to(raiseException { exception in
expect(exception.name).to(equal("foo"))
})
}
let innerFailureMessage = "expected to begin with <fo>, got <laugh>"
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.exception.raise() }.to(raiseException(named: "laugh") { exception in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.exception.raise() }.to(raiseException(named: "lol") { exception in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> with reason <Lulz> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz") { exception in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> with reason <wrong> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.exception.raise() }.to(raiseException(named: "lol", reason: "wrong") { exception in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <laugh> with reason <Lulz> with userInfo <{key = value;}> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.exception.raise() }.to(raiseException(named: "laugh", reason: "Lulz", userInfo: ["key": "value"]) { exception in
expect(exception.name).to(beginWith("fo"))
})
}
failsWithErrorMessage([innerFailureMessage, "expected to raise exception with name <lol> with reason <Lulz> with userInfo <{}> that satisfies block, got NSException { name=laugh, reason='Lulz', userInfo=[key: value] }"]) {
expect { self.exception.raise() }.to(raiseException(named: "lol", reason: "Lulz", userInfo: [:]) { exception in
expect(exception.name).to(beginWith("fo"))
})
}
}
}
| apache-2.0 | e92345257bf3d570850040506e911cc8 | 57.104575 | 244 | 0.628009 | 4.390123 | false | true | false | false |
SlayterDev/BSToast | BSToastDemo/BSToastDemo/ViewController.swift | 1 | 1160 | //
// ViewController.swift
// BSToastDemo
//
// Created by Bradley Slayter on 9/18/15.
// Copyright © 2015 Flipped Bit. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let toastWidth = UIScreen.mainScreen().bounds.width * 0.4
let toastHeight: CGFloat = 90.0
override func viewDidLoad() {
super.viewDidLoad()
// Create a button and add it to the screen
let btn = UIButton(type: .System)
btn.setTitle("Show", forState: .Normal)
btn.addTarget(self, action: "showToast:", forControlEvents: .PrimaryActionTriggered)
btn.frame = CGRectMake(0, 0, 200, 65)
btn.center = CGPointMake(self.view.center.x, self.view.center.y - (self.view.center.y/2))
self.view.addSubview(btn)
}
func showToast(sender: AnyObject) {
// Create a toast notification and show it
let toast = BSToast(frame: CGRectMake(0, 0, toastWidth, toastHeight),
text: "Here's a toast notification")
toast.center = self.view.center
toast.showInViewWithDuration(1.75, view: self.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 102d983df20242c36d79bcf20fc765f8 | 25.953488 | 91 | 0.715272 | 3.48048 | false | false | false | false |
blinker13/Signals | Tests/TimeTests.swift | 1 | 1932 |
import XCTest
@testable import Signal
class TimeTests: XCTestCase {
func test_init() {
let subject = Time()
XCTAssertEqual(subject.nano, 0)
}
func test_initWithZero() {
let subject = Time(0.0)
XCTAssertEqual(subject.nano, 0)
}
func test_initWithDouble() {
let subject = Time(13.0)
XCTAssertEqual(subject.nano, 13_000_000_000)
}
//MARK: -
func test_absolute_Now() {
let current = mach_absolute_time()
XCTAssertGreaterThan(Time.Now.absolute, current)
XCTAssertLessThan(Time.Now.absolute, mach_absolute_time())
}
func test_absolute_Forever() {
let subject = Time.Forever.absolute
XCTAssertEqual(subject, UInt64.max)
}
func test_absolute_Interval() {
let subject = Time.Interval(13.0).absolute
XCTAssertNotEqual(subject, 0)
}
//MARK: -
func test_nano_Now() {
XCTAssertEqual(Time.Now.nano, 0)
}
func test_nano_Forever() {
XCTAssertEqual(Time.Forever.nano, UInt64.max)
}
func test_nano_Interval() {
XCTAssertNotEqual(Time.Interval(13.0).nano, 0)
}
//MARK: -
func test_spec_Now() {
let subject = Time.Now.spec
XCTAssertEqual(subject.tv_sec, 0)
XCTAssertEqual(subject.tv_nsec, 0)
}
func test_spec_Forever() {
let subject = Time.Forever.spec
XCTAssertEqual(subject.tv_sec, UInt32.max)
XCTAssertEqual(subject.tv_nsec, Int32.max)
}
func test_spec_Interval() {
let subject = Time.Interval(3.987654321).spec
XCTAssertEqual(subject.tv_sec, 3)
XCTAssertEqual(subject.tv_nsec, 987654321)
}
//MARK: -
func test_description() {
XCTAssertEqual(Time.Now.description, "Now")
XCTAssertEqual(Time.Forever.description, "Forever")
XCTAssertEqual(Time.Interval(13.13).description, "13.13")
}
}
| mit | a8e1205ca4b2615c65573d729e766bee | 22.560976 | 66 | 0.611284 | 3.879518 | false | true | false | false |
damirstuhec/DSDynamicScrollView | Sample_Swift/DynamicScrollView/ExampleView.swift | 2 | 1731 | //
// ExampleView.swift
// DynamicScrollView
//
// Created by Damir Stuhec on 03/10/14.
// Copyright (c) 2014 damirstuhec. All rights reserved.
//
import UIKit
import Darwin
class ExampleView: DSDynamicView
{
var nameLabel: UILabel
var uniqueNumber: Int
var distance: Int
init(frame: CGRect, name: String)
{
nameLabel = UILabel(frame: frame)
nameLabel.autoresizingMask = .FlexibleHeight | .FlexibleWidth
nameLabel.textAlignment = .Center
nameLabel.text = name
nameLabel.textColor = UIColor.whiteColor()
uniqueNumber = 0
distance = 0
super.init(frame: frame)
var hue = CGFloat(Float(arc4random() % 256) / 256.0)
var saturation = CGFloat(Float(arc4random() % 128) / 256.0) + 0.5
var brightness = CGFloat(Float(arc4random() % 128) / 256.0) + 0.5
self.backgroundColor = UIColor(hue: CGFloat(hue), saturation: CGFloat(saturation), brightness: CGFloat(brightness), alpha: 1)
self.addSubview(nameLabel)
}
override func isEqual(object: AnyObject?) -> Bool
{
if let anotherView = object as? ExampleView
{
return self.uniqueNumber == anotherView.uniqueNumber
}
else
{
return false
}
}
override func compareToObject(object: AnyObject?) -> Bool
{
if let anotherView = object as? ExampleView
{
if self.distance > anotherView.distance
{
return false
}
else
{
return true
}
}
else
{
return true
}
}
}
| mit | daf63aae1ad9757cec9c04f69e61e899 | 24.086957 | 133 | 0.55517 | 4.543307 | false | false | false | false |
laszlokorte/reform-swift | ReformStage/ReformStage/GridSnapPoint.swift | 1 | 871 | //
// GridSnapPoint.swift
// ReformStage
//
// Created by Laszlo Korte on 01.10.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import ReformMath
import ReformCore
public struct GridSnapPoint : SnapPoint, Equatable {
public let position : Vec2d
let point : GridPoint
public init(position: Vec2d, point: GridPoint) {
self.position = position
self.point = point
}
public var label : String {
return String(format: "%.1%% Horizontally, %.1f%% Vertically", point.percent.x * 100, point.percent.y * 100)
}
public var runtimePoint : LabeledPoint {
return point
}
public func belongsTo(_ formId: FormIdentifier) -> Bool {
return false
}
}
public func ==(lhs: GridSnapPoint, rhs: GridSnapPoint) -> Bool {
return lhs.position == rhs.position && lhs.point == rhs.point
}
| mit | 96a6e33d023abe8640d0c089d5f62543 | 23.166667 | 116 | 0.650575 | 3.849558 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Search/Reverse geocode/ReverseGeocodeViewController.swift | 1 | 4829 | // Copyright 2016 Esri.
//
// 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 UIKit
import ArcGIS
class ReverseGeocodeViewController: UIViewController, AGSGeoViewTouchDelegate {
@IBOutlet weak var mapView: AGSMapView! {
didSet {
// Create an instance of a map with ESRI topographic basemap.
mapView.map = AGSMap(basemapStyle: .arcGISTopographic)
mapView.touchDelegate = self
// Add the graphics overlay.
mapView.graphicsOverlays.add(self.graphicsOverlay)
// Zoom to a specific extent.
mapView.setViewpoint(AGSViewpoint(center: AGSPoint(x: -117.195, y: 34.058, spatialReference: .wgs84()), scale: 5e4))
}
}
private let locatorTask = AGSLocatorTask(url: URL(string: "https://geocode-api.arcgis.com/arcgis/rest/services/World/GeocodeServer")!)
private var graphicsOverlay = AGSGraphicsOverlay()
private var cancelable: AGSCancelable!
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ReverseGeocodeViewController"]
}
private func reverseGeocode(_ point: AGSPoint) {
// Cancel previous request.
if self.cancelable != nil {
self.cancelable.cancel()
}
// Hide the callout.
self.mapView.callout.dismiss()
// Remove already existing graphics.
self.graphicsOverlay.graphics.removeAllObjects()
// Normalize point.
let normalizedPoint = AGSGeometryEngine.normalizeCentralMeridian(of: point) as! AGSPoint
let graphic = self.graphicForPoint(normalizedPoint)
self.graphicsOverlay.graphics.add(graphic)
// Initialize parameters.
let reverseGeocodeParameters = AGSReverseGeocodeParameters()
reverseGeocodeParameters.maxResults = 1
// Reverse geocode.
self.cancelable = self.locatorTask.reverseGeocode(withLocation: normalizedPoint, parameters: reverseGeocodeParameters) { [weak self] (results: [AGSGeocodeResult]?, error: Error?) in
if let error = error {
// Present user canceled error.
if (error as NSError).code != NSUserCancelledError {
self?.presentAlert(error: error)
}
} else if let result = results?.first {
graphic.attributes.addEntries(from: result.attributes!)
self?.showCalloutForGraphic(graphic, tapLocation: normalizedPoint)
return
} else {
self?.presentAlert(message: "No address found")
}
self?.graphicsOverlay.graphics.remove(graphic)
}
}
/// Method returns a graphic object for the specified point and attributes.
private func graphicForPoint(_ point: AGSPoint) -> AGSGraphic {
let markerImage = UIImage(named: "RedMarker")!
let symbol = AGSPictureMarkerSymbol(image: markerImage)
symbol.leaderOffsetY = markerImage.size.height / 2
symbol.offsetY = markerImage.size.height / 2
let graphic = AGSGraphic(geometry: point, symbol: symbol, attributes: [String: AnyObject]())
return graphic
}
/// Show callout for the graphic.
private func showCalloutForGraphic(_ graphic: AGSGraphic, tapLocation: AGSPoint) {
// Get the attributes from the graphic and populates the title and detail for the callout.
let cityString = graphic.attributes["City"] as? String ?? ""
let addressString = graphic.attributes["Address"] as? String ?? ""
let stateString = graphic.attributes["State"] as? String ?? ""
self.mapView.callout.title = addressString
self.mapView.callout.detail = "\(cityString) \(stateString)"
self.mapView.callout.isAccessoryButtonHidden = true
self.mapView.callout.show(for: graphic, tapLocation: tapLocation, animated: true)
}
// MARK: - AGSGeoViewTouchDelegate
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
self.reverseGeocode(mapPoint)
}
}
| apache-2.0 | 9c518b4a98796429e286648b111a3486 | 42.9 | 189 | 0.657693 | 4.942682 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Scenes/Distance composite symbol/DistanceCompositeSymbolViewController.swift | 1 | 3724 | //
// Copyright 2017 Esri.
//
// 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 UIKit
import ArcGIS
class DistanceCompositeSymbolViewController: UIViewController {
@IBOutlet var sceneView: AGSSceneView!
override func viewDidLoad() {
super.viewDidLoad()
// add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["DistanceCompositeSymbolViewController"]
// Initialize scene with imagery basemap style.
let scene = AGSScene(basemapStyle: .arcGISImagery)
// assign scene to the scene view
self.sceneView.scene = scene
// add base surface for elevation data
let surface = AGSSurface()
/// The url of the Terrain 3D ArcGIS REST Service.
let worldElevationServiceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")!
let elevationSource = AGSArcGISTiledElevationSource(url: worldElevationServiceURL)
surface.elevationSources.append(elevationSource)
scene.baseSurface = surface
let graphicsOverlay = AGSGraphicsOverlay()
graphicsOverlay.sceneProperties?.surfacePlacement = .relative
self.sceneView.graphicsOverlays.add(graphicsOverlay)
// set up the different symbols
let circleSymbol = AGSSimpleMarkerSymbol(style: .circle, color: .red, size: 10.0)
let coneSymbol = AGSSimpleMarkerSceneSymbol.cone(with: .red, diameter: 200, height: 600)
coneSymbol.pitch = -90.0
let modelSymbol = AGSModelSceneSymbol(name: "Bristol", extension: "dae", scale: 100.0)
modelSymbol.load { [weak self] (error) in
if let error = error {
self?.presentAlert(error: error)
return
}
// set up the distance composite symbol
let compositeSymbol = AGSDistanceCompositeSceneSymbol()
compositeSymbol.ranges.append(AGSDistanceSymbolRange(symbol: modelSymbol, minDistance: 0, maxDistance: 10000))
compositeSymbol.ranges.append(AGSDistanceSymbolRange(symbol: coneSymbol, minDistance: 10001, maxDistance: 30000))
compositeSymbol.ranges.append(AGSDistanceSymbolRange(symbol: circleSymbol, minDistance: 30001, maxDistance: 0))
// create graphic
let aircraftPosition = AGSPoint(x: -2.708471, y: 56.096575, z: 5000, spatialReference: .wgs84())
let aircraftGraphic = AGSGraphic(geometry: aircraftPosition, symbol: compositeSymbol, attributes: nil)
// add graphic to graphics overlay
graphicsOverlay.graphics.add(aircraftGraphic)
// add an orbit camera controller to lock the camera to the graphic
let cameraController = AGSOrbitGeoElementCameraController(targetGeoElement: aircraftGraphic, distance: 4000)
cameraController.cameraPitchOffset = 80
cameraController.cameraHeadingOffset = -30
self?.sceneView.cameraController = cameraController
}
}
}
| apache-2.0 | 81712b6da729425817ba542733d00299 | 46.139241 | 145 | 0.68072 | 4.887139 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.