repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
salimbraksa/SBSlideMenu
SBSlideMenu/SBSlideMenu.swift
1
21970
// // SBSlideMenu.swift // Shop // // Created by Braksa Salim on 10/6/15. // Copyright © 2015 Braksa Salim. All rights reserved. // import UIKit import Cartography // MARK: - Main Class public class SBSlideMenu: UIView { // MARK: Properties weak public var delegate: SBSlideMenuDelegate! var animator: Animator! private var currentIndex: Int = 0 { didSet { // If currentIndex didn't change then let's just cancel if currentIndex == oldValue { return } // Save previous index previousIndex = oldValue // Set direction if oldValue < currentIndex { direction = .Forward } else if oldValue == currentIndex { direction = .Static } else { direction = .Backward } } } private var previousIndex: Int? private var direction: Direction? // Animation index private var animationFromIndex: Int! private var animationToIndex: Int! // - Configurable Params public var enableBlurEffect: Bool = false public var bgColor: UIColor = UIColor.whiteColor() public var spacing: CGFloat = 10 public var animatedBarColor: UIColor = UIColor.blueColor() public var autoSpreadCategories: Bool = false public var spacerViewColor = UIColor.clearColor() // We're setting only leftMargin because it's equal to rightMargin anyways public var leftMargin: CGFloat = 20 public var rightMargin: CGFloat = 20 // - Subviews private var categories = [UIControl]() private var categoriesContainer: UIView! private var backgroundView: UIView! private var scrollView: UIScrollView! var animatedBar: UIView! // - Other private var animatedBarConstraints: ConstraintGroup! // MARK: Initialization public init(arrangedSubviews: [AnyObject]) { super.init(frame: CGRectZero) // Instantiate animator animator = Animator.sharedInstance animator.delegate = self // Set categories for (i, view) in arrangedSubviews.enumerate() { // Convert to control if let control = view as? UIControl { // Append control categories.append(control) } else { print("View of index \(i) is not of type UIControl") } } } func initializeTopBar() { // Initializing Subviews, and adding them // Background view, it's going to be opaque or transluent backgroundView = UIView() backgroundView.backgroundColor = UIColor.clearColor() if enableBlurEffect { // Add a blurView let blurEffect = UIBlurEffect(style: .ExtraLight) let blurView = UIVisualEffectView(effect: blurEffect) backgroundView.backgroundColor = UIColor.clearColor() backgroundView.addSubview(blurView) // Layout blurView constrain(blurView) { blurView in blurView.edges == blurView.superview!.edges } } addSubview(backgroundView) // A Scroll View, to scroll categories if there is a lot of them scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false backgroundView.addSubview(scrollView) // A container that is going to contain all the categories categoriesContainer = UIView() categoriesContainer.backgroundColor = UIColor.clearColor() scrollView.addSubview(categoriesContainer) // The categories themselves for (i, view) in categories.enumerate() { // Defer does the following: // Before leaving this function scope // Please execute this block defer { // Select only the first view // And Deselect the others let view = view as? CategoryControl if i == 0 { view?.didSelectCategory() } else { view?.didDeselectCategory() } } // Without this, shit happens categoriesContainer.autoresizesSubviews = false // Add target/control to view view.addTarget(self, action: "controlPressed:", forControlEvents: .TouchUpInside) // Disable user interaction view.subviews.first?.userInteractionEnabled = false // Add each view to superview categoriesContainer.addSubview(view) } // Add an animated bar animatedBar = UIView(frame: CGRect(x: leftMargin, y: 45, width: 45, height: 3)) animatedBar.backgroundColor = animatedBarColor categoriesContainer.addSubview(animatedBar) constrain(animatedBar) { animatedBar in animatedBar.height == 3 animatedBar.bottom == animatedBar.superview!.bottom } // Allocate animatedBarConstraints animatedBarConstraints = ConstraintGroup() // Constrain views constrainViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Lifecycle override public func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) initializeTopBar() } // MARK: User Interaction func moveToIndex(index: Int, fromIndex: Int, automatic: Bool) { // Animate prepareAnimationFromIndex(currentIndex, toIndex: index, startAutomatically: automatic) // Set currentIndex currentIndex = index } func controlPressed(control: UIControl) { // Get the index of superview guard let index = categories.indexOf(control) else { return } // Do nothing if currentIndex == index if index == currentIndex { return } // Move moveToIndex(index, fromIndex: currentIndex, automatic: true) // Call the delegate delegate?.didSelectButtonOfIndex(index) } // MARK: Layouting & Constraining private func constrainViews() { // Constrain backgroundView constrain(backgroundView) { backgroundView in backgroundView.edges == backgroundView.superview!.edges } // Constrain scrollView constrain(scrollView) { scrollView in scrollView.edges == scrollView.superview!.edges } // Constrain animatedBar updateAnimatedBarConstraints() // Constrain categories // Iterate through each category for (index, category) in categories.enumerate() { // Get the previous category and spacerView let previousCategory: UIControl? = index != 0 ? categories[index-1] : nil let previousSpacerView: UIView? = index != 0 ? categoriesContainer.subviews.last : nil // Get category width that cames directly from the nib ( or maybe programmatically ) let categoryWidth: CGFloat? = autoSpreadCategories == false ? category.bounds.width : nil // Common constraints for every category at any index constrain(category) { category in category.top == category.superview!.top category.bottom == category.superview!.bottom } // Adding a spacer view and constraining it at every index // Excepct the last one var spacerView: UIView! if index < categories.endIndex - 1 { // Create a spacer view spacerView = UIView() spacerView.backgroundColor = spacerViewColor categoriesContainer.addSubview(spacerView) // Common constraints for every spacerView at any index ( except the last one ) constrain(category, spacerView) { category, spacerView in spacerView.top == spacerView.superview!.top spacerView.bottom == spacerView.superview!.bottom category.right == spacerView.left autoSpreadCategories == true ? ( spacerView.width == spacing ~ 500 ) : ( category.width == categoryWidth! ~ 500 ) } } switch index { // Constrain the first category case 0: constrain(category) { category in category.left == category.superview!.left + leftMargin } case let i where i > 0 && i != categories.endIndex - 1: constrain(category, spacerView, previousCategory!, previousSpacerView!) { category, spacerView, previousCategory, previousSpacerView in autoSpreadCategories == true ? ( previousCategory.width == category.width ) : ( previousSpacerView.width == spacerView.width ) previousSpacerView.right == category.left } // Constrain the last category case categories.endIndex - 1: constrain(category, previousCategory!, previousSpacerView!) { category, previousCategory, previousSpacerView in category.right == category.superview!.right - rightMargin ~ 500 autoSpreadCategories == true ? ( previousCategory.width == category.width ) : ( category.width == categoryWidth! ~ 500 ) previousSpacerView.right == category.left } // Constrain views in the middle default: break } } } override public func layoutSubviews() { super.layoutSubviews() // (Re)Calculate the container size manually recalculateContainerSize() // Cancel all ongoing animations cancelAnimations() } private func updateAnimatedBarConstraints() { // Constrain animatedBar let firstView = categories[currentIndex] constrain(animatedBar, firstView, replace: animatedBarConstraints) { animatedBar, firstView in animatedBar.left == firstView.left animatedBar.right == firstView.right } } private func setAnimatedBarConstraintsForIndex(index: Int) { let category = categories[index] constrain(animatedBar, category, replace: animatedBarConstraints) { animatedBar, category in animatedBar.left == category.left animatedBar.right == category.right } } // MARK: Helpers private func recalculateContainerSize() { // If the autoSpreadCategories is activated // No need to calculate the container width let containerWidth: CGFloat if autoSpreadCategories == true { containerWidth = bounds.width } else { let numberOfViews = categories.count let totalWidth = categories.reduce(0) { $0 + $1.bounds.width } let totalWidthWithSpacing = rightMargin + leftMargin + CGFloat(numberOfViews-1) * spacing + totalWidth containerWidth = autoSpreadCategories == true ? bounds.width : max(totalWidthWithSpacing, bounds.width) } scrollView?.contentSize = CGSize(width: containerWidth, height: bounds.height) scrollView?.alwaysBounceHorizontal = containerWidth > bounds.width scrollView?.contentOffset.x = contentOffsetForControl(categories[currentIndex]).x categoriesContainer?.frame.size = CGSize(width: containerWidth ?? 0, height: bounds.height) } private func contentOffsetForControl(control: UIControl) -> CGPoint { // Maximum offset x of the scrollView let offsetXMaxValue = categoriesContainer.bounds.width - bounds.width // The center of this view let bgCenterX = center.x // The center of the selected button's superview let viewCenterX = control.center.x // The distance between them let distance = viewCenterX - bgCenterX // Calculate the the new offset return CGPoint(x: max(0, min(offsetXMaxValue, distance)), y: scrollView.contentOffset.y) } private func isValidIndex(index: Int!) -> Bool { // False if it's nill if index == nil { return false } // Index shouldn't exceed or preceed categories first index and last index return index >= 0 && index < categories.endIndex } } // MARK: - Animation Section extension SBSlideMenu: AnimatorDelegate { // MARK: Animation API public func prepareAnimationFromIndex(fromIndex: Int, toIndex: Int, startAutomatically automatic: Bool = false) { // The following two "if"s concern only categories // They handle some animation EDGE CASES // You may want to skip this step in order to understand // How these animations work // // 1. Understanding the first 'if' : // // - First of all it checks if the animationToIndex is a valid index // Check the isValidIndex: method below, it's not rocket science // N.B: animationToIndex here is not the actual toIndex param, animationToIndex // Is the previous toIndex // - Imagine the following scenario : // // [ Category 1 ] - [ Category 2 ] - [ Category 3 ] // // Here, assume we have 3 categories, Okey ? // The first "if" solves the problem that occurs // When the user does the following // --> Starts at [ Category 1 ] // --> Moves to [ Category 2 ] // --> But before he stops transitionning to [ Category 2 ] // He quickly moves to [ Category 3 ] // --> Again, before he stops transitionning to [ Category 3 ] // He quickly moves back to [ Category 1 ] ( YES IT CAN HAPPENS ) // // EXPECTATION: // [ Category 3 ]'s animations SHOULD be cancelled // // REALITY: // [ Category 3 ]'s animations ARE not cancelled if isValidIndex(animationToIndex) && fromIndex == animationFromIndex { let castedControl = categories[animationToIndex] as? SBAnimator let layers = castedControl?.animatedSublayers() ?? [] for layer in layers { animator.cancelLayerAnimationForKeys(layer, forKeys: layer.explicitAnimationKeys()) } } // 2. Understanding the second 'if': // // - Like the first 'if', we test if animationToIndex is a valid index // And the actual next index ( aka. toIndex param ) isn't // The previous animationFromIndex ( not the actual fromIndex param ) // N.B: animationFromIndex here is not the actual fromIndex param, animationFromIndex // Is the previous fromIndex // - Imagine the following scenario : // // [ Category 1 ] - [ Category 2 ] - [ Category 3 ] // // Here, assume we have 3 categories, Okey ? // The second "if" solves the problem that occurs // When the user does the following // --> Starts at [ Category 1 ] // --> Moves to [ Category 2 ] // --> But before he stops transitionning to [ Category 2 ] // He quickly moves to [ Category 3 ] // --> The user stops at [ Category 3 ] // // EXPECTATION: // [ Category 1 ]'s animations SHOULD be finished ( not cancelled this time ) // // REALITY: // [ Category 1 ]'s animations ARE not finished if isValidIndex(animationToIndex) && toIndex != animationFromIndex { let layers = (categories[animationFromIndex] as? SBAnimator)?.animatedSublayers() ?? [] for layer in layers { animator.resumeLayer(layer, fromCurrentTimeOffset: true) } } // Remember these indexes animationFromIndex = fromIndex animationToIndex = toIndex // Verify destination index ( toIndex ) // If toIndex isn't valid, then do not perform any animation if !isValidIndex(toIndex) { return } // Get the next control let nextControl = categories[toIndex] // The default duration depending if the animation // Should start automatically or manually let duration = automatic ? 0.25 : 0.90 // Animating the animatedBar position, and width // By setting it's constraints setAnimatedBarConstraintsForIndex(toIndex) categoriesContainer.layoutIfNeeded() let posAnimation = CABasicAnimation(keyPath: "position.x") let point = animatedBar.center posAnimation.toValue = NSNumber(double: Double(point.x)) let sizeAnimation = CABasicAnimation(keyPath: "bounds.size.width") let size = animatedBar.bounds.size sizeAnimation.toValue = NSNumber(double: Double(size.width)) // Groupe animatedBar's animations let animatedBarAnimationGroup = CAAnimationGroup() animatedBarAnimationGroup.duration = duration animatedBarAnimationGroup.animations = [posAnimation, sizeAnimation] // Animate scrollView's contentOffset // ( but since the layer has no contentOffset property, I use bounds ) let scrollAnimation = CABasicAnimation(keyPath: "bounds.origin.x") var bounds = scrollView.bounds bounds.origin.x = contentOffsetForControl(nextControl).x self.scrollView.bounds.origin.x = bounds.origin.x scrollAnimation.toValue = NSNumber(double: Double(bounds.origin.x)) // Group scrollView's animations let scrollViewAnimationGroup = CAAnimationGroup() scrollViewAnimationGroup.fillMode = kCAFillModeBackwards scrollViewAnimationGroup.duration = duration scrollViewAnimationGroup.animations = [scrollAnimation] // Add animations animator.addAnimation(animatedBarAnimationGroup, toLayer: animatedBar.layer, forKey: "Bar Animation", startAutomatically: automatic) animator.addAnimation(scrollViewAnimationGroup, toLayer: scrollView.layer, forKey: "ScrollView Animation", startAutomatically: automatic) // Categories animations animateCategoryForIndex(toIndex, reversed: false, automatic: automatic) animateCategoryForIndex(fromIndex, reversed: true, automatic: automatic) } public func moveProgressively(progress: Double) { // Handling possible errors if animationToIndex >= categories.count || animationToIndex < 0 { return } // Animate Progessively animator.animateLayerProgressively(animatedBar.layer, progress: progress) animator.animateLayerProgressively(scrollView.layer, progress: progress) let nextControlLayers = (categories[animationToIndex] as? SBAnimator)?.animatedSublayers() ?? [] let previousControlLayers = (categories[animationFromIndex] as? SBAnimator)?.animatedSublayers() ?? [] for layer in nextControlLayers { animator.animateLayerProgressively(layer, progress: progress) } for layer in previousControlLayers { animator.animateLayerProgressively(layer, progress: progress) } } // MARK: Animator Delegate internal func animationDidStop(animation: CAAnimation, forLayer layer: CALayer, finished: Bool) { // Set animated bar constraints to the previous category if : // + The layer is the animatedBar layer // + The animation is not finished // + There is no ongoing animation with the same animation.name let shouldSetBarConstraints = layer == animatedBar.layer && !finished && !(layer.explicitAnimationKeys()?.contains(animation.name ?? "") ?? false) shouldSetBarConstraints ? setAnimatedBarConstraintsForIndex(animationFromIndex) : () // Update currentIndex if the animation is finished finished ? ( currentIndex = animationToIndex ) : () } // MARK: Internal Helpers private func cancelAnimations() { // Cancel ongoing animations animator.cancelLayerAnimationForKeys(animatedBar.layer, forKeys: animatedBar.layer.explicitAnimationKeys()) animator.cancelLayerAnimationForKeys(scrollView.layer, forKeys: scrollView.layer.explicitAnimationKeys()) if isValidIndex(animationFromIndex) { // Get destination control layers let layers = (categories[animationFromIndex] as? SBAnimator)?.animatedSublayers() ?? [] let _ = layers.map { animator.cancelLayerAnimationForKeys($0, forKeys: $0.explicitAnimationKeys()) } } if isValidIndex(animationToIndex) { // Get destination control layers let layers = (categories[animationToIndex] as? SBAnimator)?.animatedSublayers() ?? [] let _ = layers.map { animator.cancelLayerAnimationForKeys($0, forKeys: $0.explicitAnimationKeys()) } } } private func animateCategoryForIndex(index: Int, reversed: Bool, automatic: Bool) { guard let category = categories[index] as? SBAnimator else { return } // Animate Next Control let categoryLayers = category.animatedSublayers() for layer in categoryLayers { // Get animations guard let animations = category.describeAnimationsForLayer(layer, reversed: reversed, automatic: automatic) else { return } for (index, animation) in animations.enumerate() { // Make key let key = index == 0 ? "Animation" : "Animation-\(index)" // Add Animation animator.addAnimation(animation, toLayer: layer, forKey: key, startAutomatically: automatic) } } } }
mit
4d11b665b3f86158d764a73941a8e2fb
34.239165
152
0.624379
5.298817
false
false
false
false
martinschilliger/SwissGrid
Pods/ObjectMapper/Sources/IntegerOperators.swift
1
3888
// // IntegerOperators.swift // ObjectMapper // // Created by Suyeol Jeon on 17/02/2017. // Copyright © 2017 hearst. All rights reserved. // import Foundation // MARK: - Signed Integer /// SignedInteger mapping public func <- <T: SignedInteger>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T = toSignedInteger(right.currentValue) ?? 0 FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } /// Optional SignedInteger mapping public func <- <T: SignedInteger>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T? = toSignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } /// ImplicitlyUnwrappedOptional SignedInteger mapping public func <- <T: SignedInteger>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T! = toSignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } // MARK: - Unsigned Integer /// UnsignedInteger mapping public func <- <T: UnsignedInteger>(left: inout T, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T = toUnsignedInteger(right.currentValue) ?? 0 FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } /// Optional UnsignedInteger mapping public func <- <T: UnsignedInteger>(left: inout T?, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T? = toUnsignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } /// ImplicitlyUnwrappedOptional UnsignedInteger mapping public func <- <T: UnsignedInteger>(left: inout T!, right: Map) { switch right.mappingType { case .fromJSON where right.isKeyPresent: let value: T! = toUnsignedInteger(right.currentValue) FromJSON.basicType(&left, object: value) case .toJSON: left >>> right default: () } } // MARK: - Casting Utils /// Convert any value to `SignedInteger`. private func toSignedInteger<T: SignedInteger>(_ value: Any?) -> T? { guard let value = value, case let number as NSNumber = value else { return nil } if T.self == Int.self, let x = Int(exactly: number.int64Value) { return T(x) } if T.self == Int8.self, let x = Int8(exactly: number.int64Value) { return T(x) } if T.self == Int16.self, let x = Int16(exactly: number.int64Value) { return T(x) } if T.self == Int32.self, let x = Int32(exactly: number.int64Value) { return T(x) } if T.self == Int64.self, let x = Int64(exactly: number.int64Value) { return T(x) } return nil } /// Convert any value to `UnsignedInteger`. private func toUnsignedInteger<T: UnsignedInteger>(_ value: Any?) -> T? { guard let value = value, case let number as NSNumber = value else { return nil } if T.self == UInt.self, let x = UInt(exactly: number.uint64Value) { return T(x) } if T.self == UInt8.self, let x = UInt8(exactly: number.uint64Value) { return T(x) } if T.self == UInt16.self, let x = UInt16(exactly: number.uint64Value) { return T(x) } if T.self == UInt32.self, let x = UInt32(exactly: number.uint64Value) { return T(x) } if T.self == UInt64.self, let x = UInt64(exactly: number.uint64Value) { return T(x) } return nil }
mit
986da327f678175ab99c83bc4d95f424
26.181818
75
0.622845
3.837117
false
false
false
false
Eonil/Editor
Editor4/MenuCommandShortcutKeyExtensions.swift
1
4440
// // MenuCommandShortcutKeys.swift // Editor4 // // Created by Hoon H. on 2016/05/25. // Copyright © 2016 Eonil. All rights reserved. // import AppKit extension MenuCommand { func getShortcutKey() -> MenuItemShortcutKey? { switch self { case .main(let command): return command.getShortcutKey() case .fileNavigator(let command): return command.getShortcutKey() } } func getKeyModifiersAndKeyEquivalentPair() -> (keyModifier: NSEventModifierFlags, keyEquivalent: String) { let shortcut = getShortcutKey() return (shortcut?.keyModifiers ?? [], shortcut?.keyEquivalent ?? "") } } private extension MainMenuCommand { private func getShortcutKey() -> MenuItemShortcutKey? { let Command = NSEventModifierFlags.CommandKeyMask let Option = NSEventModifierFlags.AlternateKeyMask let Control = NSEventModifierFlags.ControlKeyMask let Shift = NSEventModifierFlags.ShiftKeyMask let Return = "\r" let Delete = "\u{0008}" let F6 = String(UnicodeScalar(NSF6FunctionKey)) let F7 = String(UnicodeScalar(NSF7FunctionKey)) let F8 = String(UnicodeScalar(NSF8FunctionKey)) switch self { case .FileNewWorkspace: return Command + Control + "N" case .FileNewFolder: return Command + Option + "N" case .FileNewFile: return Command + "N" case .FileOpenWorkspace: return Command + Control + "O" case .FileOpenClearWorkspaceHistory: return nil case .FileCloseFile: return Command + Shift + "W" case .FileCloseWorkspace: return Command + "W" case .FileDelete: return Command + Delete case .FileShowInFinder: return nil case .FileShowInTerminal: return nil case .ViewEditor: return Command + Return case .ViewShowProjectNavigator: return Command + "1" case .ViewShowIssueNavigator: return Command + "2" case .ViewShowDebugNavigator: return Command + "3" case .ViewHideNavigator: return Command + "0" case .ViewConsole: return Command + Shift + "C" case .ViewFullScreen: return Command + Control + "F" case .EditorShowCompletions: return Command + " " case .ProductRun: return Command + "R" case .ProductBuild: return Command + "B" case .ProductClean: return Command + Shift + "K" case .ProductStop: return Command + "." case .DebugPause: return Command + Control + "Y" case .DebugResume: return Command + Control + "Y" case .DebugHalt: return nil case .DebugStepInto: return Command + F6 case .DebugStepOut: return Command + F7 case .DebugStepOver: return Command + F8 case .DebugClearConsole: return Command + "K" } } } private extension FileNavigatorMenuCommand { private func getShortcutKey() -> MenuItemShortcutKey? { return nil } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct MenuItemShortcutKey { var keyModifiers: NSEventModifierFlags var keyEquivalent: String } private func + (a: NSEventModifierFlags, b: NSEventModifierFlags) -> MenuItemShortcutKey { return MenuItemShortcutKey(keyModifiers: [a, b], keyEquivalent: "") } private func + (a: NSEventModifierFlags, b: String) -> MenuItemShortcutKey { return MenuItemShortcutKey(keyModifiers: a, keyEquivalent: b.lowercaseString) } private func + (a: MenuItemShortcutKey, b: String) -> MenuItemShortcutKey { return MenuItemShortcutKey(keyModifiers: a.keyModifiers, keyEquivalent: a.keyEquivalent + b.lowercaseString) }
mit
47eca04ceb34479dca66c2d5b64f7c59
45.239583
128
0.54314
5.102299
false
false
false
false
optimizely/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/DisplayTrigger.swift
2
1898
// // DisplayTrigger.swift // Mixpanel // // Created by Madhu Palani on 1/30/19. // Copyright © 2019 Mixpanel. All rights reserved. // import Foundation class DisplayTrigger { enum PayloadKey { static let event = "event" static let selector = "selector" } static let ANY_EVENT = "$any_event" let event: String? let selectorOpt: [String: Any]? init?(jsonObject: [String: Any]?) { guard let object = jsonObject else { Logger.error(message: "display trigger json object should not be nil") return nil } guard let event = object[PayloadKey.event] as? String else { Logger.error(message: "invalid event name type") return nil } guard let selector = object[PayloadKey.selector] as? [String: Any]? else { Logger.error(message: "invalid selector section") return nil } self.event = event self.selectorOpt = selector } func matchesEvent(eventName: String?, properties: InternalProperties) -> Bool { if let event = self.event { if (eventName == DisplayTrigger.ANY_EVENT || eventName == "" || eventName?.compare(event) == ComparisonResult.orderedSame) { if let selector = selectorOpt { if let value = SelectorEvaluator.evaluate(selector: selector, properties: properties) { return value } return false } return true } } return false } func payload() -> [String: AnyObject] { var payload = [String: AnyObject]() payload[PayloadKey.event] = event as AnyObject payload[PayloadKey.selector] = selectorOpt as AnyObject return payload } }
apache-2.0
a72cd6aaf225bd0b1e6bca874d6dde01
28.640625
136
0.556668
4.864103
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Settings/AdvanceAccountSettingViewController.swift
2
9214
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import SnapKit import Foundation import FxA import Account class AdvanceAccountSettingViewController: SettingsTableViewController { fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier" fileprivate var customSyncUrl: String? override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsAdvanceAccountSectionName self.customSyncUrl = self.profile.prefs.stringForKey(PrefsKeys.KeyCustomSyncWeb) } func clearCustomAccountPrefs() { self.profile.prefs.setBool(false, forKey: PrefsKeys.KeyUseCustomSyncService) self.profile.prefs.setString("", forKey: PrefsKeys.KeyCustomSyncToken) self.profile.prefs.setString("", forKey: PrefsKeys.KeyCustomSyncProfile) self.profile.prefs.setString("", forKey: PrefsKeys.KeyCustomSyncOauth) self.profile.prefs.setString("", forKey: PrefsKeys.KeyCustomSyncAuth) self.profile.prefs.setString("", forKey: PrefsKeys.KeyCustomSyncWeb) // To help prevent the account being in a strange state, we force it to // log out when user clears their custom server preferences. self.profile.removeAccount() } func setCustomAccountPrefs(_ data: Data, url: URL) { guard let settings = (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)) as? [String:Any], let customSyncToken = settings["sync_tokenserver_base_url"] as? String, let customSyncProfile = settings["profile_server_base_url"] as? String, let customSyncOauth = settings["oauth_server_base_url"] as? String, let customSyncAuth = settings["auth_server_base_url"] as? String else { return } self.profile.prefs.setBool(true, forKey: PrefsKeys.KeyUseCustomSyncService) self.profile.prefs.setString(customSyncToken, forKey: PrefsKeys.KeyCustomSyncToken) self.profile.prefs.setString(customSyncProfile, forKey: PrefsKeys.KeyCustomSyncProfile) self.profile.prefs.setString(customSyncOauth, forKey: PrefsKeys.KeyCustomSyncOauth) self.profile.prefs.setString(customSyncAuth, forKey: PrefsKeys.KeyCustomSyncAuth) self.profile.prefs.setString(url.absoluteString, forKey: PrefsKeys.KeyCustomSyncWeb) self.profile.removeAccount() self.displaySuccessAlert() } func setCustomAccountPrefs() { guard let urlString = self.customSyncUrl, let url = URL(string: urlString) else { // If the user attempts to set a nil url, clear all the custom service perferences // and use default FxA servers. self.displayNoServiceSetAlert() return } // FxA stores its server configuation under a well-known path. This attempts to download the configuration // and save it into the users preferences. let syncConfigureString = urlString + "/.well-known/fxa-client-configuration" guard let syncConfigureURL = URL(string: syncConfigureString) else { return } URLSession.shared.dataTask(with: syncConfigureURL, completionHandler: {(data, response, error) in guard let data = data, error == nil else { // Something went wrong while downloading or parsing the configuration. self.displayErrorAlert() return } self.setCustomAccountPrefs(data, url: url) }).resume() } func displaySuccessAlert() { let alertController = UIAlertController(title: "", message: Strings.SettingsAdvanceAccountUrlUpdatedAlertMessage, preferredStyle: .alert) let defaultAction = UIAlertAction(title: Strings.SettingsAdvanceAccountUrlUpdatedAlertOk, style: .default, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true) } func displayErrorAlert() { self.profile.prefs.setBool(false, forKey: PrefsKeys.KeyUseCustomSyncService) DispatchQueue.main.async { self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic) } let alertController = UIAlertController(title: Strings.SettingsAdvanceAccountUrlErrorAlertTitle, message: Strings.SettingsAdvanceAccountUrlErrorAlertMessage, preferredStyle: .alert) let defaultAction = UIAlertAction(title: Strings.SettingsAdvanceAccountUrlErrorAlertOk, style: .default, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true) } func displayNoServiceSetAlert() { self.profile.prefs.setBool(false, forKey: PrefsKeys.KeyUseCustomSyncService) DispatchQueue.main.async { self.tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic) } let alertController = UIAlertController(title: Strings.SettingsAdvanceAccountUrlErrorAlertTitle, message: Strings.SettingsAdvanceAccountEmptyUrlErrorAlertMessage, preferredStyle: .alert) let defaultAction = UIAlertAction(title: Strings.SettingsAdvanceAccountUrlUpdatedAlertOk, style: .default, handler: nil) alertController.addAction(defaultAction) self.present(alertController, animated: true) } override func generateSettings() -> [SettingSection] { let prefs = profile.prefs let customSyncSetting = CustomSyncWebPageSetting(prefs: prefs, prefKey: PrefsKeys.KeyCustomSyncWeb, placeholder: Strings.SettingsAdvanceAccountUrlPlaceholder, accessibilityIdentifier: "CustomSyncSetting", settingDidChange: { fieldText in self.customSyncUrl = fieldText if let customSyncUrl = self.customSyncUrl, customSyncUrl.isEmpty { self.clearCustomAccountPrefs() return } }) var basicSettings: [Setting] = [] basicSettings += [ CustomSyncEnableSetting( prefs: prefs, settingDidChange: { result in if result == true { // Reload the table data to ensure that the updated custom url is set self.tableView?.reloadData() self.setCustomAccountPrefs() } }), customSyncSetting ] let settings: [SettingSection] = [ SettingSection(title: NSAttributedString(string: ""), children: basicSettings), SettingSection(title: NSAttributedString(string: Strings.SettingsAdvanceAccountSectionFooter), children: []) ] return settings } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as! SettingsTableSectionHeaderFooterView let sectionSetting = settings[section] headerView.titleLabel.text = sectionSetting.title?.string switch section { // Hide the bottom border for the FxA custom server notes. case 1: headerView.titleAlignment = .top headerView.titleLabel.numberOfLines = 0 headerView.showBottomBorder = false default: return super.tableView(tableView, viewForHeaderInSection: section) } return headerView } } class CustomSyncEnableSetting: BoolSetting { init(prefs: Prefs, settingDidChange: ((Bool?) -> Void)? = nil) { super.init( prefs: prefs, prefKey: PrefsKeys.KeyUseCustomSyncService, defaultValue: false, attributedTitleText: NSAttributedString(string: Strings.SettingsAdvanceAccountUseCustomAccountsServiceTitle), settingDidChange: settingDidChange ) } } class CustomSyncWebPageSetting: WebPageSetting { override init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingDidChange: ((String?) -> Void)? = nil) { super.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, placeholder: placeholder, accessibilityIdentifier: accessibilityIdentifier, settingDidChange: settingDidChange) textField.clearButtonMode = UITextFieldViewMode.always } }
mpl-2.0
83fe7063dc1f0a33fd4098d359c421be
49.349727
194
0.644346
5.504182
false
false
false
false
wrengels/Amplify4
Amplify4/Amplify4/Amplify4/Document.swift
1
2229
// // Document.swift // Amplify4 // // Created by Bill Engels on 1/15/15. // Copyright (c) 2015 Bill Engels. All rights reserved. // import Cocoa class Document: NSDocument { var text = "" override init() { super.init() // Add your subclass-specific initialization here. } override func windowControllerDidLoadNib(aController: NSWindowController) { super.windowControllerDidLoadNib(aController) // Add any code here that needs to be executed once the windowController has loaded the document's window. } override class func autosavesInPlace() -> Bool { return true } override var windowNibName: String? { // Returns the nib file name of the document // If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead. return "Document" } override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { // Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil. // You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return nil } override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { // Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false. // You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead. // If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded. outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil) return false } }
gpl-2.0
d89533d14536cb3855b050efbefa53ea
40.277778
198
0.708389
4.866812
false
false
false
false
GlebRadchenko/MenuContainer
MenuContainer/MenuContainer/Sources/Container/ContainerView.swift
1
1023
// // ContainerView.swift // MenuContainer // // Created by GlebRadchenko on 2/8/17. // Copyright © 2017 Gleb Radchenko. All rights reserved. // import UIKit class ContainerView: UIView { var viewController: UIViewController! var filled: Bool { return viewController != nil } var active: Bool { set { newValue ? show() : hide() } get { return !isHidden } } func embed(_ vc: UIViewController) { if viewController != nil { clear() } viewController = vc vc.view.translatesAutoresizingMaskIntoConstraints = false addSubview(vc.view) bind(vc.view) } func clear() { subviews.forEach { $0.removeFromSuperview() } viewController?.removeFromParentViewController() viewController?.didMove(toParentViewController: nil) viewController = nil } func show() { isHidden = false } func hide() { isHidden = true } }
mit
179d356cd75f0e7621efb2d300e32ded
20.744681
65
0.579256
4.866667
false
false
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/Notifications/FitpayNotificationsManager.swift
1
8574
import Foundation open class FitpayNotificationsManager: NSObject, ClientModel { public static let sharedInstance = FitpayNotificationsManager() public typealias NotificationsPayload = [AnyHashable: Any] /// NotificationsEventBlockHandler /// /// - parameter event: Provides event with payload in eventData property public typealias NotificationsEventBlockHandler = (_ event: FitpayEvent) -> Void var notificationToken: String = "" var client: RestClient? private let eventsDispatcher = FitpayEventDispatcher() private var syncCompletedBinding: FitpayEventBinding? private var syncFailedBinding: FitpayEventBinding? private var notificationsQueue = [NotificationsPayload]() private var currentNotification: NotificationsPayload? private var noActivityTimer: Timer? // MARK: - Public Functions public func setRestClient(_ client: RestClient?) { self.client = client } /** Handle notification from Fitpay platform. It may call syncing process and other stuff. When all notifications processed we should receive AllNotificationsProcessed event. In completion (or in other place where handling of hotification completed) to this event you should call fetchCompletionHandler if this function was called from background. - parameter payload: payload of notification */ open func handleNotification(_ payload: NotificationsPayload) { log.verbose("NOTIFICATIONS_DATA: handling notification") let notificationDetail = self.notificationDetailFromNotification(payload) if (notificationDetail?.type?.lowercased() == "sync") { notificationDetail?.sendAckSync() } notificationsQueue.enqueue(payload) processNextNotificationIfAvailable() } /** Saves notification token after next sync process. - parameter token: notifications token which should be provided by Firebase */ open func updateNotificationsToken(_ token: String) { notificationToken = token } /** Binds to the event using NotificationsEventType and a block as callback. - parameter eventType: type of event which you want to bind to - parameter completion: completion handler which will be called */ open func bindToEvent(eventType: NotificationsEventType, completion: @escaping NotificationsEventBlockHandler) -> FitpayEventBinding? { return eventsDispatcher.addListenerToEvent(FitpayBlockEventListener(completion: completion), eventId: eventType) } /** Binds to the event using NotificationsEventType and a block as callback. - parameter eventType: type of event which you want to bind to - parameter completion: completion handler which will be called - parameter queue: queue in which completion will be called */ open func bindToEvent(eventType: NotificationsEventType, completion: @escaping NotificationsEventBlockHandler, queue: DispatchQueue) -> FitpayEventBinding? { return eventsDispatcher.addListenerToEvent(FitpayBlockEventListener(completion: completion, queue: queue), eventId: eventType) } /// Removes bind. open func removeSyncBinding(binding: FitpayEventBinding) { eventsDispatcher.removeBinding(binding) } /// Removes all synchronization bindings. open func removeAllSyncBindings() { eventsDispatcher.removeAllBindings() } open func updateRestClientForNotificationDetail(_ notificationDetail: NotificationDetail?) { if let notificationDetail = notificationDetail, notificationDetail.client == nil { notificationDetail.client = self.client } } /// Creates a notification detail from both old and new notification types public func notificationDetailFromNotification(_ notification: NotificationsPayload?) -> NotificationDetail? { var notificationDetail: NotificationDetail? if let fpField2 = notification?["fpField2"] as? String { notificationDetail = try? NotificationDetail(fpField2) } else if notification?["source"] as? String == "FitPay" { notificationDetail = try? NotificationDetail(notification?["payload"]) notificationDetail?.type = notification?["type"] as? String } notificationDetail?.client = self.client return notificationDetail } // MARK: - Private Functions private func processNextNotificationIfAvailable() { log.verbose("NOTIFICATIONS_DATA: Processing next notification if available.") guard currentNotification == nil else { log.verbose("NOTIFICATIONS_DATA: currentNotification was not nil returning.") return } if notificationsQueue.peekAtQueue() == nil { log.verbose("NOTIFICATIONS_DATA: peeked at queue and found nothing.") callAllNotificationProcessedCompletion() return } self.currentNotification = notificationsQueue.dequeue() guard let currentNotification = self.currentNotification else { return } var notificationType = NotificationType.withoutSync if (currentNotification["fpField1"] as? String)?.lowercased() == "sync" || (currentNotification["type"] as? String)?.lowercased() == "sync" { log.debug("NOTIFICATIONS_DATA: notification was of type sync.") notificationType = NotificationType.withSync } callReceivedCompletion(currentNotification, notificationType: notificationType) switch notificationType { case .withSync: let notificationDetail = notificationDetailFromNotification(currentNotification) guard let userId = notificationDetail?.userId else { log.error("NOTIFICATIONS_DATA: Recieved notification with no userId. Returning") return } client?.user(id: userId) { (user: User?, err: ErrorResponse?) in guard let user = user, err == nil else { log.error("NOTIFICATIONS_DATA: Failed to retrieve user with ID \(userId). Continuing to next notification. Error: \(err!.description)") self.currentNotification = nil self.noActivityTimer?.invalidate() self.processNextNotificationIfAvailable() return } SyncRequestQueue.sharedInstance.add(request: SyncRequest(notification: notificationDetail, initiator: .notification, user: user)) { (_, _) in self.currentNotification = nil self.noActivityTimer?.invalidate() self.noActivityTimer = nil self.processNextNotificationIfAvailable() } } noActivityTimer?.invalidate() noActivityTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(FitpayNotificationsManager.handleNoActiviy), userInfo: nil, repeats: false) case .withoutSync: // just call completion log.debug("NOTIFICATIONS_DATA: notification was non-sync.") self.currentNotification = nil processNextNotificationIfAvailable() } } private func callReceivedCompletion(_ payload: NotificationsPayload, notificationType: NotificationType) { var eventType: NotificationsEventType switch notificationType { case .withSync: eventType = .receivedSyncNotification case .withoutSync: eventType = .receivedSimpleNotification } eventsDispatcher.dispatchEvent(FitpayEvent(eventId: eventType, eventData: payload)) } private func callAllNotificationProcessedCompletion() { eventsDispatcher.dispatchEvent(FitpayEvent(eventId: NotificationsEventType.allNotificationsProcessed, eventData: [:])) } /// Clear current notification and process the next one if available if the current notification times out @objc private func handleNoActiviy() { log.verbose("NOTIFICATIONS_DATA: Notification Sync timed out. Sync Request Queue did not return in time, so we continue to the next notification.") currentNotification = nil processNextNotificationIfAvailable() } }
mit
69119fb978ad05e96edcbcfea66e0021
42.085427
178
0.671565
5.801083
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressTest/Classes/Stores/NoticeStoreTests.swift
2
5024
import WordPressFlux import XCTest @testable import WordPress class NoticeStoreTests: XCTestCase { private var dispatcher: ActionDispatcher! private var store: NoticeStore! override func setUp() { super.setUp() dispatcher = ActionDispatcher() store = NoticeStore(dispatcher: dispatcher) } override func tearDown() { dispatcher = nil store = nil super.tearDown() } func testPostActionSetsTheNoticeAsTheCurrent() { // Given precondition(store.currentNotice == nil) let notice = Notice(title: "Alpha") // When dispatch(.post(notice)) // Then XCTAssertEqual(notice, store.currentNotice) } func testPostActionQueuesTheNoticeIfThereIsACurrentNotice() { // Given let alpha = Notice(title: "Alpha") dispatch(.post(alpha)) precondition(store.currentNotice == alpha) // When dispatch(.post(Notice(title: "Bravo"))) // Then XCTAssertEqual(alpha, store.currentNotice) } func testDismissActionSetsTheNextNoticeInTheQueueAsTheCurrent() { // Given let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") dispatch(.post(alpha)) dispatch(.post(bravo)) precondition(store.currentNotice == alpha) // When dispatch(.dismiss) // Then XCTAssertEqual(bravo, store.currentNotice) } func testClearActionCanClearTheCurrentNotice() { // Given let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") dispatch(.post(alpha)) dispatch(.post(bravo)) precondition(store.currentNotice == alpha) // When dispatch(.clear(alpha)) // Then // Alpha was removed so the next in queue, Bravo, is set as the current XCTAssertEqual(bravo, store.currentNotice) } func testClearActionCanRemoveANoticeInTheQueue() { // Given let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") dispatch(.post(alpha)) dispatch(.post(bravo)) precondition(store.currentNotice == alpha) // When dispatch(.clear(bravo)) // Remove alpha dispatch(.dismiss) // Then // Since Bravo was removed from the queue, there should be no current XCTAssertNil(store.currentNotice) } func testClearWithTagActionRemovesNoticesWithTheMatchingTag() { // Given let tagToClear: Notice.Tag = "quae" let alpha = Notice(title: "Alpha", tag: tagToClear) let bravo = Notice(title: "Bravo") let charlie = Notice(title: "Charlie", tag: tagToClear) [alpha, bravo, charlie].forEach { dispatch(.post($0)) } precondition(store.currentNotice == alpha) // When dispatch(.clearWithTag(tagToClear)) // Then // Since Alpha was removed, Bravo is now the current Notice XCTAssertEqual(bravo, store.currentNotice) // Dismiss Bravo so that we can test that Charlie was removed too dispatch(.dismiss) XCTAssertNil(store.currentNotice) } func testEmptyActionClearsTheQueueButNotTheCurrentNotice() { // Given let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") let charlie = Notice(title: "Charlie") [alpha, bravo, charlie].forEach { dispatch(.post($0)) } precondition(store.currentNotice == alpha) // When dispatch(.empty) // Then XCTAssertEqual(alpha, store.currentNotice) // Dismiss Alpha so that we can test that everything else was removed dispatch(.dismiss) XCTAssertNil(store.currentNotice) } func testLockActionClearsTheNoticeThatIsShown() { let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") [alpha, bravo].forEach { dispatch(.post($0)) } XCTAssertEqual(alpha, store.currentNotice) dispatch(.lock) XCTAssertEqual(nil, store.currentNotice) } func testLockUnlockShowsEnqueuedNotices() { dispatch(.lock) let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") [alpha, bravo].forEach { dispatch(.post($0)) } dispatch(.unlock) XCTAssertEqual(alpha, store.currentNotice) } func testCanNotDismissNoticesOnLockedStore() { dispatch(.lock) let alpha = Notice(title: "Alpha") let bravo = Notice(title: "Bravo") [alpha, bravo].forEach { dispatch(.post($0)) } dispatch(.dismiss) // You can't dismiss notices in the locked store. Since that would removed notices without showing them to the user. dispatch(.unlock) XCTAssertEqual(alpha, store.currentNotice) } // MARK: - Helpers private func dispatch(_ action: NoticeAction) { dispatcher.dispatch(action) } }
gpl-2.0
52e62fce7d5dda746d56ecbf5fdf8411
26.604396
143
0.61465
4.485714
false
true
false
false
FlexMonkey/Filterpedia
Filterpedia/components/FilterNavigator.swift
1
7630
// // FilterNavigator.swift // Filterpedia // // Created by Simon Gladman on 29/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> import Foundation import UIKit class FilterNavigator: UIView { let filterCategories = [ CategoryCustomFilters, kCICategoryBlur, kCICategoryColorAdjustment, kCICategoryColorEffect, kCICategoryCompositeOperation, kCICategoryDistortionEffect, kCICategoryGenerator, kCICategoryGeometryAdjustment, kCICategoryGradient, kCICategoryHalftoneEffect, kCICategoryReduction, kCICategorySharpen, kCICategoryStylize, kCICategoryTileEffect, kCICategoryTransition, ].sort{ CIFilter.localizedNameForCategory($0) < CIFilter.localizedNameForCategory($1)} /// Filterpedia doesn't support code generators, color cube filters, filters that require NSValue let exclusions = ["CIQRCodeGenerator", "CIPDF417BarcodeGenerator", "CICode128BarcodeGenerator", "CIAztecCodeGenerator", "CIColorCubeWithColorSpace", "CIColorCube", "CIAffineTransform", "CIAffineClamp", "CIAffineTile", "CICrop"] // to do: fix CICrop! let segmentedControl = UISegmentedControl(items: [FilterNavigatorMode.Grouped.rawValue, FilterNavigatorMode.Flat.rawValue]) let tableView: UITableView = { let tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain) tableView.registerClass(UITableViewHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: "HeaderRenderer") tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "ItemRenderer") return tableView }() var mode: FilterNavigatorMode = .Grouped { didSet { tableView.reloadData() } } weak var delegate: FilterNavigatorDelegate? override init(frame: CGRect) { super.init(frame: frame) CustomFiltersVendor.registerFilters() tableView.dataSource = self tableView.delegate = self segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(FilterNavigator.segmentedControlChange), forControlEvents: UIControlEvents.ValueChanged) addSubview(tableView) addSubview(segmentedControl) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func segmentedControlChange() { mode = segmentedControl.selectedSegmentIndex == 0 ? .Grouped : .Flat } override func layoutSubviews() { let segmentedControlHeight = segmentedControl.intrinsicContentSize().height tableView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height - segmentedControlHeight) segmentedControl.frame = CGRect(x: 0, y: frame.height - segmentedControlHeight, width: frame.width, height: segmentedControlHeight) } } // MARK: UITableViewDelegate extension extension FilterNavigator: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let filterName: String switch mode { case .Grouped: filterName = supportedFilterNamesInCategory(filterCategories[indexPath.section]).sort()[indexPath.row] case .Flat: filterName = supportedFilterNamesInCategories(nil).sort { CIFilter.localizedNameForFilterName($0) ?? $0 < CIFilter.localizedNameForFilterName($1) ?? $1 }[indexPath.row] } delegate?.filterNavigator(self, didSelectFilterName: filterName) } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch mode { case .Grouped: return 40 case .Flat: return 0 } } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("HeaderRenderer")! as UITableViewHeaderFooterView switch mode { case .Grouped: cell.textLabel?.text = CIFilter.localizedNameForCategory(filterCategories[section]) case .Flat: cell.textLabel?.text = nil } return cell } func supportedFilterNamesInCategory(category: String?) -> [String] { return CIFilter.filterNamesInCategory(category).filter { !exclusions.contains($0) } } func supportedFilterNamesInCategories(categories: [String]?) -> [String] { return CIFilter.filterNamesInCategories(categories).filter { !exclusions.contains($0) } } } // MARK: UITableViewDataSource extension extension FilterNavigator: UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { switch mode { case .Grouped: return filterCategories.count case .Flat: return 1 } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch mode { case .Grouped: return supportedFilterNamesInCategory(filterCategories[section]).count case .Flat: return supportedFilterNamesInCategories(nil).count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ItemRenderer", forIndexPath: indexPath) let filterName: String switch mode { case .Grouped: filterName = supportedFilterNamesInCategory(filterCategories[indexPath.section]).sort()[indexPath.row] case .Flat: filterName = supportedFilterNamesInCategories(nil).sort { CIFilter.localizedNameForFilterName($0) ?? $0 < CIFilter.localizedNameForFilterName($1) ?? $1 }[indexPath.row] } cell.textLabel?.text = CIFilter.localizedNameForFilterName(filterName) ?? (CIFilter(name: filterName)?.attributes[kCIAttributeFilterDisplayName] as? String) ?? filterName return cell } } // MARK: Filter Navigator Modes enum FilterNavigatorMode: String { case Grouped case Flat } // MARK: FilterNavigatorDelegate protocol FilterNavigatorDelegate: class { func filterNavigator(filterNavigator: FilterNavigator, didSelectFilterName: String) }
gpl-3.0
6b9e8022b149e9d64b49c3c0db928923
28.684825
178
0.645432
5.261379
false
false
false
false
AlphaJian/PaperCalculator
PaperCalculator/PaperCalculator/Views/Review/QuestionTableViewCell.swift
1
5051
// // QuestionTableViewCell.swift // PaperCalculator // // Created by Jian Zhang on 9/28/16. // Copyright © 2016 apple. All rights reserved. // import UIKit class QuestionTableViewCell: UITableViewCell { var btnHandler : ReturnWithThreeParmsBlock! var multiBtnHandler : ReturnWithThreeParmsBlock! var nextPaperHandler : ButtonTouchUpBlock! var indexPath : IndexPath! var questionArr : [CellQuestionModel]! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override init(style : UITableViewCellStyle, reuseIdentifier : String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initLastCell (){ let btn = UIButton(type: .custom) btn.layer.cornerRadius = 10 btn.frame = CGRect(x: LCDW - 20 - 150, y: 0, width: 150, height: 60) btn.backgroundColor = darkBlue btn.titleLabel?.font = mediumFont btn.setTitle("批改下一个", for: .normal) btn.addTarget(self, action: #selector(QuestionTableViewCell.nextBtnTapped), for: .touchUpInside) self.contentView.addSubview(btn) } func nextBtnTapped() { let paperModelSave : PaperModel = DataManager.shareManager.paperModel.copySelf() DataManager.shareManager.papersArray.append(paperModelSave) DataManager.shareManager.paperModel = DataManager.shareManager.paperModelTemp.copySelf() if nextPaperHandler != nil { nextPaperHandler!() } } func initUI(arr : [CellQuestionModel], index : IndexPath){ questionArr = arr indexPath = index let padding = 20 let width = (LCDW - 3 * CGFloat(padding)) / 2 var originX = padding for i in 0 ... questionArr.count - 1 { let model = questionArr[i] let btn = UIButton(type: .custom) btn.layer.cornerRadius = 10 btn.frame = CGRect(x: originX, y: 0, width: Int(width), height: 60) let titleQuestionNo : String = "( \(model.questionNo!) )" let titleScore : String = " \(model.realScore!)" let totalTitle = titleQuestionNo + titleScore let title : NSMutableAttributedString = NSMutableAttributedString(string: totalTitle, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 25)]) title.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 10), range: NSRange.init(location: titleQuestionNo.characters.count, length: totalTitle.characters.count - titleQuestionNo.characters.count)) title.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSRange.init(location: 0, length: totalTitle.characters.count)) btn.setAttributedTitle(title , for: .normal) //btn.setTitle("( \(model.questionNo!) ) -- \(model.realScore!)", for: .normal) btn.titleLabel?.backgroundColor = UIColor.clear btn.titleLabel?.font = mediumFont btn.addTarget(self, action: #selector(QuestionTableViewCell.btnTapped(_:)), for: .touchUpInside) btn.tag = 10 + i originX = Int(btn.right()) + padding self.contentView.addSubview(btn) if model.realScore < model.score { btn.backgroundColor = lightRed } else { btn.backgroundColor = lightBlue } } } func btnTapped(_ sender: UIButton) { let model = questionArr[sender.tag - 10] as CellQuestionModel //Indexpath exchange if model.questionStyle == .yesOrNo { if model.score == model.realScore { model.realScore = 0 } else { model.realScore = model.score } if btnHandler != nil { let index = IndexPath(row: indexPath.row * 2 + sender.tag - 10, section: indexPath.section) btnHandler!(index as AnyObject, indexPath as AnyObject ,model) } } else { if multiBtnHandler != nil { let index = IndexPath(row: indexPath.row * 2 + sender.tag - 10, section: indexPath.section) multiBtnHandler!(index as AnyObject, indexPath as AnyObject ,model) } } } func clearCell(){ for view in self.contentView.subviews { view.removeFromSuperview() } } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
gpl-3.0
a923ccea051e90846dc63d626fcfdedf
31.307692
226
0.582738
4.878993
false
false
false
false
powerytg/Accented
Accented/UI/Home/Themes/Card/Layout/StreamCardLayoutSpec.swift
1
1746
// // StreamCardLayoutSpec.swift // Accented // // Created by Tiangong You on 5/20/16. // Copyright © 2016 Tiangong You. All rights reserved. // import UIKit class StreamCardLayoutSpec: NSObject { // Top padding static let topPadding : CGFloat = 3 // Bottom padding static let bottomPadding : CGFloat = 10 // Padding between the title and the subtitle static let titleVPadding : CGFloat = 5 // Title horizontal padding static let titleHPadding : CGFloat = 40 // Subtitle horizontal padding static let subtitleHPadding : CGFloat = 60 // Descriptions horizontal padding static let descHPadding : CGFloat = 10 // Padding between the photo and the subtitle, as well between the photo and the descriptions static let photoVPadding : CGFloat = 15 // Photo left padding static let photoLeftPadding : CGFloat = 3 // Photo right padding static let photoRightPadding : CGFloat = 3 // Max lines of title static let titleLabelLineCount = 2 // Max lines of subtitle(author / date) static let subtitleLineCount = 1 // Max lines of descriptions static let descLineCount = 10 // Footer decor height static let footerHeight : CGFloat = 12 // Footer top padding static let footerTopPadding : CGFloat = 22 // Footer bottom padding static let footerBottomPadding : CGFloat = 4 // Max height of photo static let maxPhotoHeight : CGFloat = 240 // Title font static let titleFont = UIFont(name: "AvenirNextCondensed-DemiBold", size: 17) // Subtitle font static let subtitleFont = UIFont(name: "AvenirNextCondensed-Regular", size: 15) }
mit
fd37e3f8a9123a04f794f3bda00dd39c
25.439394
97
0.664756
5.014368
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/HTML Parser/ExternalSourceViewElementCellViewModel.swift
1
2274
import KsApi import Prelude import ReactiveSwift public protocol ExternalSourceViewElementCellViewModelInputs { /// Call to configure with a `ExternalSourceViewElement` representing external source element. func configureWith(element: ExternalSourceViewElement) } public protocol ExternalSourceViewElementCellViewModelOutputs { /// Emits a text `String` representing the iframe tag's src attibute captured in the html parser. var htmlText: Signal<String, Never> { get } /// Emits an optional `Int` taken from iframe representing that embedded content's height in a webview. var contentHeight: Signal<Int, Never> { get } } public protocol ExternalSourceViewElementCellViewModelType { var inputs: ExternalSourceViewElementCellViewModelInputs { get } var outputs: ExternalSourceViewElementCellViewModelOutputs { get } } public final class ExternalSourceViewElementCellViewModel: ExternalSourceViewElementCellViewModelType, ExternalSourceViewElementCellViewModelInputs, ExternalSourceViewElementCellViewModelOutputs { // MARK: Initializers public init() { self.htmlText = self.externalSourceViewElement.signal.skipNil() .switchMap { element -> SignalProducer<String?, Never> in guard !element.embeddedURLString.isEmpty else { return SignalProducer(value: nil) } return SignalProducer(value: element.embeddedURLString) } .skipNil() self.contentHeight = self.externalSourceViewElement.signal.skipNil() .switchMap { element -> SignalProducer<Int?, Never> in guard let contentHeight = element.embeddedURLContentHeight, !element.embeddedURLString.isEmpty else { return SignalProducer(value: nil) } return SignalProducer(value: contentHeight) } .skipNil() } fileprivate let externalSourceViewElement = MutableProperty<ExternalSourceViewElement?>(nil) public func configureWith(element: ExternalSourceViewElement) { self.externalSourceViewElement.value = element } public let contentHeight: Signal<Int, Never> public let htmlText: Signal<String, Never> public var inputs: ExternalSourceViewElementCellViewModelInputs { self } public var outputs: ExternalSourceViewElementCellViewModelOutputs { self } }
apache-2.0
9ae230d8a1934a74a2bb376f41598da6
35.677419
105
0.766931
5.227586
false
false
false
false
letzgro/GooglePlacesPicker
Classes/GooglePlacePickerViewController.swift
1
8095
// // AlertSelectPlaceController.swift // // Created by Ihor Rapalyuk on 2/3/16. // Copyright © 2016 Lezgro. All rights reserved. // import UIKit 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 } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } public protocol GooglePlacePickerViewControllerDelegate { func googlePlacePicker(_ googlePlacePickerViewController: GooglePlacePickerViewController, didSelectGooglePlace googlePlace: GooglePlace) func googlePlacePickerViewControllerDidPressCancelButton(_ googlePlacePickerViewController: GooglePlacePickerViewController) } extension GooglePlacePickerViewControllerDelegate { func googlePlacePicker(_ googlePlacePickerViewController: GooglePlacePickerViewController, didSelectGooglePlace googlePlace: GooglePlace) {} func googlePlacePickerViewControllerDidPressCancelButton(_ googlePlacePickerViewController: GooglePlacePickerViewController) {} } open class GooglePlacePickerViewController: UIViewController, UIViewControllerTransitioningDelegate { @IBOutlet open weak var placeTextField: UITextField? @IBOutlet open weak var placesTableView: UITableView? @IBOutlet open weak var placesIconImageView: UIImageView? @IBOutlet open weak var navigationBar: UINavigationBar? @IBOutlet open weak var leftBarButtonItem: UIBarButtonItem? @IBOutlet open weak var rightBarButtonItem: UIBarButtonItem? open var placeIconChoosed: UIImage? open var placeIconNotChoosed: UIImage? fileprivate let googlePlacesCellIdentifier = "GooglePlacesCellIdentifier" fileprivate let googlePlacesNibNameIdentifier = "GooglePlacesCell" fileprivate let googlePlacePickerViewControllerNibNameIdentifier = "GooglePlacePickerViewController" open var navigationBarColor: UIColor = UIColor(red: 104/255, green: 203/255, blue: 223/255, alpha: 1.0) open var autocompletePlaces: [GooglePlace] = [] open var delegate: GooglePlacePickerViewControllerDelegate? var googlePlacesReciever = GooglePlacesReciever() open var selectedGooglePlace: GooglePlace? fileprivate let currentBoundle: Bundle override open func viewDidLoad() { super.viewDidLoad() self.placeTextField?.becomeFirstResponder() self.placeTextField?.addTarget(self, action: #selector(GooglePlacePickerViewController.placeTextFieldDidChange), for: .editingChanged) self.placesTableView?.register(UINib(nibName: self.googlePlacesNibNameIdentifier, bundle: self.currentBoundle), forCellReuseIdentifier: self.googlePlacesCellIdentifier) self.updateUI() } open func updateUI() { self.view.layer.cornerRadius = 4 self.placeIconChoosed = UIImage(named: "place_icon_choosed", in: self.currentBoundle, compatibleWith: nil) self.placeIconNotChoosed = UIImage(named: "place_icon_notChoosed", in: self.currentBoundle, compatibleWith: nil) self.placesIconImageView?.image = self.placeIconNotChoosed } required public init?(coder aDecoder: NSCoder) { self.currentBoundle = Bundle(for: GooglePlacePickerViewController.self) super.init(coder: aDecoder) self.commonInit() } override public init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: Bundle!) { self.currentBoundle = Bundle(for: GooglePlacePickerViewController.self) super.init(nibName: self.googlePlacePickerViewControllerNibNameIdentifier, bundle: self.currentBoundle) self.commonInit() } fileprivate func commonInit() { self.modalPresentationStyle = .custom self.transitioningDelegate = self } func placeTextFieldDidChange() { self.checkMaxLength(self.placeTextField, maxLength: 200) self.initList() } fileprivate func checkMaxLength(_ textField: UITextField!, maxLength: Int) { if (textField.text?.characters.count > maxLength) { textField.deleteBackward() } } //MARK UIViewControllerTransitioningDelegate methods open func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { if presented == self { return GooglePlacesPresentationController(presentedViewController: presented, presenting: presenting) } return nil } open func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { if presented == self { return GooglePlacesPresentationAnimationController(isPresenting: true) } else { return nil } } open func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { if dismissed == self { return GooglePlacesPresentationAnimationController(isPresenting: false) } else { return nil } } @IBAction func cancelButtonPressed(_ sender: UIBarButtonItem) { self.delegate?.googlePlacePickerViewControllerDidPressCancelButton(self) } @IBAction func saveButtonPressed(_ sender: UIBarButtonItem) { if let selectedGooglePlace = self.selectedGooglePlace { self.delegate?.googlePlacePicker(self, didSelectGooglePlace: selectedGooglePlace) } } fileprivate func initList() { DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { if let txtPlaceText = self.placeTextField?.text { let googlePlaces = self.googlePlacesReciever.googlePlacesByKeyWord(txtPlaceText) if let predictions = googlePlaces.value(forKey: "predictions") as? [AnyObject] { self.autocompletePlaces = predictions.flatMap{ if let description = $0.value(forKey: "description") as? String, let placeId = $0.value(forKey: "place_id") as? String { return GooglePlace(placeId: placeId, description: description) } return nil } DispatchQueue.main.async { self.placesTableView?.reloadData() } } } } } // MARK: - Table view data source func tableView(_ tableView: UITableView?, didSelectRowAtIndexPath indexPath: IndexPath?) { if let indexPath = indexPath { self.placeTextField?.text = getPlaceName((indexPath as NSIndexPath).row) self.placesIconImageView?.image = self.placeIconChoosed self.selectedGooglePlace = self.autocompletePlaces[(indexPath as NSIndexPath).row] } } func numberOfSectionsInTableView(_ tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.autocompletePlaces.count } func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: self.googlePlacesCellIdentifier, for: indexPath) cell.textLabel?.text = getPlaceName((indexPath as NSIndexPath).row) return cell } open func getPlaceName(_ indexPath: Int) -> String { if let item = self.autocompletePlaces[indexPath].description { if let index = item.range(of: ",")?.lowerBound { return item.substring(to: index) } return item } return "" } }
mit
29981f08a1959d2afd940a1569ac23d1
38.482927
175
0.67828
5.307541
false
false
false
false
jdbateman/Lendivine
Lendivine/AcknowledgementsViewController.swift
1
3285
// // AcknowledgementsViewController.swift // Lendivine // // Created by john bateman on 4/22/16. // Copyright © 2016 John Bateman. All rights reserved. // import UIKit class AcknowledgementsViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var acknowledgementsLabel: UILabel! @IBOutlet weak var acknowledgements: UIScrollView! override func viewDidLoad() { super.viewDidLoad() setupView() setupScroll() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func scrollViewDidScroll(scrollView: UIScrollView) { let point = CGPointMake(0, self.scrollView.contentOffset.y) scrollView.setContentOffset(point, animated: true) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.contentSize.height = acknowledgementsLabel.bounds.size.height } func setupView() { let artists = ["Georgia Osinga", "Jolan Soens", "Erin Standley", "Gregor Črešnar", "Veronika Geertsema König", "Joel Olson"] let artistsText = artists.joinWithSeparator("\n") let oAuthAck = "OAuthSwift framework:\nCopyright © 2016\nhttps://github.com/OAuthSwift/OAuthSwift\n" let otherArtwork = " Flag Images from http://365icon.com/icon-styles/ethnic/classic2/, Earth icon from http://www.iconbeast.com/free/ " let mitLicenseText = "OAuthSwift is licensed under the MIT license:\nPermission is hereby granted, free of charge, to any person \nobtaining a copy of this software and associated documentation\n files (the “Software”), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or\n sell copies of the Software, and to permit persons to whom\n the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies\n or substantial portions of the Software." let warrantyText = "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." let text = String(format: "%@%@%@%@%@", artistsText, otherArtwork, oAuthAck, mitLicenseText, warrantyText) acknowledgementsLabel.text = text } func setupScroll() { scrollView.contentSize.height = acknowledgementsLabel.bounds.size.height + acknowledgements.bounds.size.height scrollView.delegate = self scrollView.scrollEnabled = true scrollView.directionalLockEnabled = false scrollView.scrollIndicatorInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) } }
mit
875018af54185bda6dccbf511123534a
48.575758
654
0.714548
4.797654
false
false
false
false
kam800/SwiftMapper
SwiftMapper/Mapper.swift
1
1279
// // Mapper.swift // SwiftMapper // // Created by krzysztofsiejkowski on 11/07/14. // Copyright (c) 2014 Swiftcrunch. All rights reserved. // import Foundation class Mapper<T> { var mappings: [(Mapper, T) -> ()] = [] var validations: [String:[MapperValidator]] = [:] var json: [String:AnyObject] = [:] var tmpVal: [MapperValidator] = [] subscript(index: String) -> (Mapper, String) { get { validations[index] = tmpVal tmpVal = [] return (self, index) } set {} } func map(c: ((Mapper, T) -> ())) { mappings.append(c) } func parse(object: T) -> () { for map in mappings { map(self, object) } } func parse(json: String, to object: T) -> T { return parse(asDictionary(json), to: object) } func parse(json: [String:AnyObject], to object: T) -> T { self.json = json for map in mappings { map(self, object) } return object } func valueFor<N>(key: String) -> N? { return (json[key] as? N) } func validator(validator: MapperValidator) -> Mapper { tmpVal.append(validator) return self } }
mit
86b7210c1c65a05e06b559b5e1caa3c2
21.051724
61
0.508991
3.795252
false
false
false
false
xedin/swift
test/Sema/implementation-only-import-inlinable-multifile.swift
16
3782
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t/indirects.swiftmodule %S/Inputs/implementation-only-imports/indirects.swift // RUN: %target-swift-frontend -emit-module -o %t/directs.swiftmodule -I %t %S/Inputs/implementation-only-imports/directs.swift // RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/implementation-only-imports/secondary_file.swift -I %t @_implementationOnly import directs // 'indirects' is imported for re-export in a secondary file // Types @inlinable public func testStructFromDirect() { _ = StructFromDirect() // expected-error {{struct 'StructFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testStructFromIndirect() { _ = StructFromIndirect() } @inlinable public func testAliasFromDirect() { _ = AliasFromDirect() // expected-error {{type alias 'AliasFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testAliasFromIndirect() { _ = AliasFromIndirect() } @inlinable public func testGenericAliasFromDirect() { _ = GenericAliasFromDirect<Int>() // expected-error {{type alias 'GenericAliasFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testGenericAliasFromIndirect() { let tmp: GenericAliasFromIndirect<Int>? _ = tmp } // Functions @inlinable public func testFunctionFromDirect() { globalFunctionFromDirect() // expected-error {{global function 'globalFunctionFromDirect()' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testFunctionFromIndirect() { globalFunctionFromIndirect() } // Variables @inlinable public func testVariableFromDirect_get() { _ = globalVariableFromDirect // expected-error {{var 'globalVariableFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testVariableFromIndirect_get() { _ = globalVariableFromIndirect } @inlinable public func testVariableFromDirect_set() { globalVariableFromDirect = 5 // expected-error {{var 'globalVariableFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testVariableFromIndirect_set() { globalVariableFromIndirect = 5 } // Extensions @inlinable public func testExtensionMethod(s: inout StructFromIndirect) { s.extensionMethodFromDirect() // expected-error {{instance method 'extensionMethodFromDirect()' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testExtensionProperty_get(s: inout StructFromIndirect) { _ = s.extensionPropertyFromDirect // expected-error {{property 'extensionPropertyFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testExtensionProperty_set(s: inout StructFromIndirect) { s.extensionPropertyFromDirect = 5 // expected-error {{property 'extensionPropertyFromDirect' cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testExtensionSubscript_get(s: inout StructFromIndirect) { _ = s[extensionSubscript: 0] // expected-error {{cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} } @inlinable public func testExtensionSubscript_set(s: inout StructFromIndirect) { s[extensionSubscript: 0] = 5 // expected-error {{cannot be used in an '@inlinable' function because 'directs' was imported implementation-only}} }
apache-2.0
73d4dbe5bc14b587044bb7250583fa68
36.078431
193
0.775516
4.156044
false
true
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/FileLogging.swift
6
1051
// // FileLogging.swift // MPLogger // // Created by Sam Green on 7/8/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation /// Logs all messages to a file class FileLogging: Logging { private let fileHandle: FileHandle init(path: String) { if let handle = FileHandle(forWritingAtPath: path) { fileHandle = handle } else { fileHandle = FileHandle.standardError } // Move to the end of the file so we can append messages fileHandle.seekToEndOfFile() } deinit { // Ensure we close the file handle to clear the resources fileHandle.closeFile() } func addMessage(message: LogMessage) { let string = "File: \(message.file) - Func: \(message.function) - " + "Level: \(message.level.rawValue) - Message: \(message.text)" if let data = string.data(using: String.Encoding.utf8) { // Write the message as data to the file fileHandle.write(data) } } }
mit
141fc20b75b7f9dde0864c0d4d873a86
25.923077
82
0.599048
4.338843
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Linked List/21_Merge Two Sorted Lists.swift
1
980
// 21_Merge Two Sorted Lists // https://leetcode.com/problems/merge-two-sorted-lists/ // // Created by Honghao Zhang on 9/3/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. // //Example: // //Input: 1->2->4, 1->3->4 //Output: 1->1->2->3->4->4 // import Foundation class Num21 { // two pointers func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? { let root = ListNode(0) var p = root var p1 = l1 var p2 = l2 while p1 != nil && p2 != nil { if p1!.val < p2!.val { p.next = p1 p = p.next! p1 = p1!.next } else { p.next = p2 p = p.next! p2 = p2!.next } } if p1 != nil { p.next = p1 } else if p2 != nil { p.next = p2 } return root.next } }
mit
18d8d5d2871e09c8315248eb2ac7fffe
21.767442
144
0.532176
3.158065
false
false
false
false
AllisonWangJiaoJiao/KnowledgeAccumulation
15.Client/Client/HYSocket/HYSocket.swift
1
5077
// // HYSocket.swift // Client // // Created by Allison on 2017/7/4. // Copyright © 2017年 Allison. All rights reserved. // import UIKit protocol HYSocketDelegate :class{ func socket(_ socket : HYSocket,joinRom user:UserInfo) func socket(_ socket : HYSocket,leaveRom user:UserInfo) func socket(_ socket : HYSocket,textMsg user:TextMessage) func socket(_ socket : HYSocket,giftMsg user:GiftMessage) } class HYSocket { weak var delegate : HYSocketDelegate? fileprivate var tcpClient : TCPClient fileprivate var userInfo :UserInfo.Builder = { let userInfo = UserInfo.Builder() userInfo.name = "why\(arc4random() % 100)" userInfo.level = 20 return userInfo }() init(addr:String, port:Int) { tcpClient = TCPClient(addr: addr, port: port) } } extension HYSocket { func connectServer() -> Bool{ //设置超时时间 return tcpClient.connect(timeout: 5).0 } //开始接受消息 func startReadMsg() { DispatchQueue.global().async { while true { guard let lMsg = self.tcpClient.read(4) else{continue} //1.读取长度的data let headData = Data(bytes: lMsg, count: 4) var length : Int = 0 (headData as NSData).getBytes(&length, length: 4) //2.读取类型 guard let typeMsg = self.tcpClient.read(2) else {return} let typeData = Data(bytes: typeMsg, count: 2) var type : Int = 0 (typeData as NSData).getBytes(&type, length: 2) print("type:\(type)") //2.根据长度,读取真实消息 guard let msg = self.tcpClient.read(length) else {return} let msgData = Data(bytes: msg, count: length) //3.处理消息 --回到主线程 DispatchQueue.main.async { self.handleMsg(type: type, data: msgData) } } } } fileprivate func handleMsg (type:Int ,data: Data){ switch type { case 0 , 1: //parseFrom 反序列化(解析) let user = try! UserInfo.parseFrom(data: data) type == 0 ? delegate?.socket(self, joinRom: user) : delegate?.socket(self, leaveRom: user) case 2: let textMsg = try! TextMessage.parseFrom(data: data) delegate?.socket(self, textMsg: textMsg) case 3: let giftMsg = try! GiftMessage.parseFrom(data: data) delegate?.socket(self, giftMsg: giftMsg) default: print("未知类型") } } } extension HYSocket { ///加入房间 0 func sendJoinRoom() { //1.获取消息的长度 let msgData = (try! userInfo.build()).data() //2.发送消息 sendMsg(data: msgData, type: 0) } ///离开房间 1 func sendLeaveRoom() { //1.获取消息的长度 let msgData = (try! userInfo.build()).data() //2.发送消息 sendMsg(data: msgData, type: 1) } ///发送文本消息 2 func sendTextMsg(message:String) { //1.创建textMsg的类型 let textMsg = TextMessage.Builder() textMsg.user = try! userInfo.build() textMsg.text = message //2.获取对应的data let textData = (try! textMsg.build()).data() //3.发送消息 sendMsg(data: textData, type: 2) } ///礼物消息 3 func sendGiftMsg(giftname:String,giftURL:String,giftCount:String) { //1.创建giftMsg let giftMsg = GiftMessage.Builder() giftMsg.user = try! userInfo.build() giftMsg.giftname = giftname giftMsg.giftUrl = giftURL giftMsg.giftCount = giftCount //2.获取对应的data let giftData = (try! giftMsg.build()).data() //3.发送礼物消息 sendMsg(data: giftData, type: 3) } func sendMsg(data:Data ,type:Int) { //1.将消息长度写入到data var length = data.count let headerData = Data(bytes: &length, count: 4) //2.消息类型 var temType = type let typeData = Data(bytes: &temType, count: 2) //3.发送消息 //消息格式: 1.消息长度 + 2.消息类型 + 3.真实消息 let totalData = headerData + typeData + data tcpClient.send(data: totalData) } //心跳包 func sendHeartBeat() { //获取心跳包中的数据 let heartString = "I am is a heart" let heartData = heartString.data(using: String.Encoding.utf8)! //2.发送数据 sendMsg(data: heartData, type: 100) } }
mit
1822ebad963af485d8efaa6cbf5018b8
24.234043
102
0.518128
4.037447
false
false
false
false
yaslab/Harekaze-iOS
Harekaze/ViewControllers/Downloads/DownloadsTableViewController.swift
1
7036
/** * * DownloadsTableViewController.swift * Harekaze * Created by Yuki MIZUNO on 2016/08/21. * * Copyright (c) 2016-2017, Yuki MIZUNO * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material import APIKit import CarbonKit import StatefulViewController import RealmSwift import Crashlytics class DownloadsTableViewController: CommonProgramTableViewController, UITableViewDelegate, UITableViewDataSource { // MARK: - Private instance fileds private var dataSource: Results<(Download)>! // MARK: - View initialization override func viewDidLoad() { // On-filesystem persistent realm store let config = Realm.Configuration(class: Download.self) // Delete uncompleted download program from realm let realm = try! Realm(configuration: config) let downloadUncompleted = realm.objects(Download.self).filter { $0.size == 0 && DownloadManager.shared.progressRequest($0.program!.id) == nil} if !downloadUncompleted.isEmpty { try! realm.write { realm.delete(downloadUncompleted) } } // Table self.tableView.register(UINib(nibName: "DownloadItemMaterialTableViewCell", bundle: nil), forCellReuseIdentifier: "DownloadItemCell") super.viewDidLoad() // Disable refresh control refresh.removeTarget(self, action: #selector(refreshDataSource), for: .valueChanged) refresh.removeFromSuperview() refresh = nil // Set empty view message if let emptyView = emptyView as? EmptyDataView { emptyView.messageLabel.text = "You have no downloads" } // Load downloaded program list from realm dataSource = realm.objects(Download.self) // Realm notification notificationToken = dataSource.addNotificationBlock(updateNotificationBlock()) // Setup initial view state setupInitialViewState() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Set navigation title if let bottomNavigationController = self.navigationController!.viewControllers.first as? BottomNavigationController { bottomNavigationController.navigationItem.title = "Downloads" } } // MARK: - Resource updater / metadata recovery override func refreshDataSource() { startLoading() // File metadata recovery let config = Realm.Configuration(class: Download.self) do { let realm = try Realm(configuration: config) let documentURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let contents = try FileManager.default.contentsOfDirectory(atPath: documentURL.path) for item in contents { var isDirectory: ObjCBool = false if FileManager.default.fileExists(atPath: documentURL.appendingPathComponent(item).path, isDirectory: &isDirectory) && isDirectory.boolValue { let filepath = documentURL.appendingPathComponent(item).appendingPathComponent("file.m2ts").path let fileExists = FileManager.default.fileExists(atPath: filepath) let metadataExists = !realm.objects(Download.self).filter { $0.id == item }.isEmpty if fileExists && !metadataExists { // Receive metadata from server let request = ChinachuAPI.RecordingDetailRequest(id: item) Session.send(request) { result in switch result { case .success(let data): let download = Download() let attr = try! FileManager.default.attributesOfItem(atPath: filepath) try! realm.write { download.id = item download.program = realm.create(Program.self, value: data, update: true) download.size = attr[FileAttributeKey.size] as? Int ?? 0 realm.add(download, update: true) } case .failure(let error): let dialog = MaterialAlertViewController.generateSimpleDialog("Receiving metadata failed", message: ChinachuAPI.parseErrorMessage(error)) self.navigationController?.present(dialog, animated: true, completion: nil) Answers.logCustomEvent(withName: "Receiving metadata failed", customAttributes: ["error": error as NSError, "message": ChinachuAPI.parseErrorMessage(error)]) } } } } } } catch let error as NSError { let dialog = MaterialAlertViewController.generateSimpleDialog("Metadata recovery failed", message: error.localizedDescription) self.navigationController?.present(dialog, animated: true, completion: nil) Answers.logCustomEvent(withName: "Metadata recovery failed", customAttributes: ["error": error]) } endLoading() } // MARK: - Table view data source func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "DownloadItemCell", for: indexPath) as? DownloadItemMaterialTableViewCell else { return UITableViewCell() } let item = dataSource[indexPath.row] cell.setCellEntities(download: item, navigationController: self.navigationController!) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource?.count ?? 0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if dataSource[indexPath.row].size == 0 { return } guard let programDetailViewController = self.storyboard!.instantiateViewController(withIdentifier: "ProgramDetailTableViewController") as? ProgramDetailTableViewController else { return } programDetailViewController.program = dataSource[indexPath.row].program self.navigationController?.pushViewController(programDetailViewController, animated: true) } }
bsd-3-clause
287fb3e954d14c562d3be561d8572455
37.032432
146
0.752274
4.507367
false
false
false
false
AcroMace/receptionkit
ReceptionKit/View Controllers/WaitingViewController.swift
2
1554
// // WaitingViewController.swift // ReceptionKit // // Created by Andy Cho on 2015-04-23. // Copyright (c) 2015 Andy Cho. All rights reserved. // import UIKit struct WaitingViewModel { // Set to false if the message below thank you should ask the person to wait var shouldAskToWait: Bool } class WaitingViewController: ReturnToHomeViewController { var viewModel: WaitingViewModel? @IBOutlet weak var thankYouLabel: UILabel! @IBOutlet weak var thankYouMessageText: UITextView! func configure(_ viewModel: WaitingViewModel) { self.viewModel = viewModel } override func viewDidLoad() { super.viewDidLoad() guard let `viewModel` = viewModel else { Logger.error("View model was not set on WaitingViewController") return } thankYouMessageText.isSelectable = true if viewModel.shouldAskToWait { thankYouLabel.text = Text.pleaseWait.get() thankYouLabel.accessibilityLabel = Text.pleaseWait.accessibility() thankYouMessageText.text = Text.pleaseWaitMessage.get() thankYouMessageText.accessibilityLabel = Text.pleaseWaitMessage.accessibility() } else { thankYouLabel.text = Text.thankYou.get() thankYouLabel.accessibilityLabel = Text.thankYou.accessibility() thankYouMessageText.text = Text.niceDay.get() thankYouMessageText.accessibilityLabel = Text.niceDay.accessibility() } thankYouMessageText.isSelectable = false } }
mit
e353328225bdc6b8f3d86ec7bcfb4eb3
30.714286
91
0.681467
4.723404
false
false
false
false
fgengine/quickly
Quickly/Compositions/Standart/Placeholders/QPlaceholderImageTitleValueIconComposition.swift
1
8076
// // Quickly // open class QPlaceholderImageTitleValueIconComposable : QComposable { public var imageStyle: QImageViewStyleSheet public var imageWidth: CGFloat public var imageSpacing: CGFloat public var titleStyle: QPlaceholderStyleSheet public var titleHeight: CGFloat public var titleSpacing: CGFloat public var valueStyle: QPlaceholderStyleSheet public var valueHeight: CGFloat public var iconStyle: QImageViewStyleSheet public var iconWidth: CGFloat public var iconSpacing: CGFloat public init( edgeInsets: UIEdgeInsets = UIEdgeInsets.zero, imageStyle: QImageViewStyleSheet, imageWidth: CGFloat = 96, imageSpacing: CGFloat = 4, titleStyle: QPlaceholderStyleSheet, titleHeight: CGFloat, titleSpacing: CGFloat = 4, valueStyle: QPlaceholderStyleSheet, valueHeight: CGFloat, iconStyle: QImageViewStyleSheet, iconWidth: CGFloat = 16, iconSpacing: CGFloat = 4 ) { self.imageStyle = imageStyle self.imageWidth = imageWidth self.imageSpacing = imageSpacing self.titleStyle = titleStyle self.titleHeight = titleHeight self.titleSpacing = titleSpacing self.valueStyle = valueStyle self.valueHeight = valueHeight self.iconStyle = iconStyle self.iconWidth = iconWidth self.iconSpacing = iconSpacing super.init(edgeInsets: edgeInsets) } } open class QPlaceholderImageTitleValueIconComposition< Composable: QPlaceholderImageTitleValueIconComposable >: QComposition< Composable > { public private(set) lazy var imageView: QImageView = { let view = QImageView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var titleView: QPlaceholderView = { let view = QPlaceholderView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var valueView: QPlaceholderView = { let view = QPlaceholderView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() public private(set) lazy var iconView: QImageView = { let view = QImageView(frame: self.contentView.bounds) view.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(view) return view }() private var _edgeInsets: UIEdgeInsets? private var _imageWidth: CGFloat? private var _imageSpacing: CGFloat? private var _titleHeight: CGFloat? private var _titleSpacing: CGFloat? private var _valueHeight: CGFloat? private var _iconWidth: CGFloat? private var _iconSpacing: CGFloat? private var _constraints: [NSLayoutConstraint] = [] { willSet { self.contentView.removeConstraints(self._constraints) } didSet { self.contentView.addConstraints(self._constraints) } } private var _imageConstraints: [NSLayoutConstraint] = [] { willSet { self.imageView.removeConstraints(self._imageConstraints) } didSet { self.imageView.addConstraints(self._imageConstraints) } } private var _titleConstraints: [NSLayoutConstraint] = [] { willSet { self.titleView.removeConstraints(self._titleConstraints) } didSet { self.titleView.addConstraints(self._titleConstraints) } } private var _valueConstraints: [NSLayoutConstraint] = [] { willSet { self.valueView.removeConstraints(self._valueConstraints) } didSet { self.valueView.addConstraints(self._valueConstraints) } } private var _iconConstraints: [NSLayoutConstraint] = [] { willSet { self.iconView.removeConstraints(self._iconConstraints) } didSet { self.iconView.addConstraints(self._iconConstraints) } } open override class func size(composable: Composable, spec: IQContainerSpec) -> CGSize { let availableWidth = spec.containerSize.width - (composable.edgeInsets.left + composable.edgeInsets.right) let imageSize = composable.imageStyle.size(CGSize(width: composable.imageWidth, height: availableWidth)) let iconSize = composable.iconStyle.size(CGSize(width: composable.iconWidth, height: availableWidth)) return CGSize( width: spec.containerSize.width, height: composable.edgeInsets.top + max(imageSize.height, composable.titleHeight, composable.valueHeight, iconSize.height) + composable.edgeInsets.bottom ) } open override func preLayout(composable: Composable, spec: IQContainerSpec) { if self._edgeInsets != composable.edgeInsets || self._imageSpacing != composable.imageSpacing || self._titleSpacing != composable.titleSpacing || self._iconSpacing != composable.iconSpacing { self._edgeInsets = composable.edgeInsets self._imageSpacing = composable.imageSpacing self._titleSpacing = composable.titleSpacing self._iconSpacing = composable.iconSpacing self._constraints = [ self.imageView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.imageView.leadingLayout == self.contentView.leadingLayout.offset(composable.edgeInsets.left), self.imageView.trailingLayout == self.titleView.leadingLayout.offset(-composable.imageSpacing), self.imageView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.titleView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.titleView.trailingLayout == self.valueView.leadingLayout.offset(-composable.titleSpacing), self.titleView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.valueView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.valueView.trailingLayout == self.iconView.leadingLayout.offset(-composable.iconSpacing), self.valueView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom), self.iconView.topLayout == self.contentView.topLayout.offset(composable.edgeInsets.top), self.iconView.trailingLayout == self.contentView.trailingLayout.offset(-composable.edgeInsets.right), self.iconView.bottomLayout == self.contentView.bottomLayout.offset(-composable.edgeInsets.bottom) ] } if self._imageWidth != composable.imageWidth { self._imageWidth = composable.imageWidth self._imageConstraints = [ self.imageView.widthLayout == composable.imageWidth ] } if self._titleHeight != composable.titleHeight { self._titleHeight = composable.titleHeight self._titleConstraints = [ self.titleView.heightLayout == composable.titleHeight ] } if self._valueHeight != composable.valueHeight { self._valueHeight = composable.valueHeight self._valueConstraints = [ self.valueView.heightLayout == composable.valueHeight ] } if self._iconWidth != composable.iconWidth { self._iconWidth = composable.iconWidth self._iconConstraints = [ self.iconView.widthLayout == composable.iconWidth ] } } open override func apply(composable: Composable, spec: IQContainerSpec) { self.imageView.apply(composable.imageStyle) self.titleView.apply(composable.titleStyle) self.valueView.apply(composable.valueStyle) self.iconView.apply(composable.iconStyle) } }
mit
ca0d34e602da950ab85f78642ea1a88c
45.413793
199
0.682392
5.527721
false
false
false
false
alisidd/iOS-WeJ
WeJ/Party Classes/Track.swift
1
3995
// // Track.swift // WeJ // // Created by Mohammad Ali Siddiqui on 1/19/17. // Copyright © 2017 Mohammad Ali Siddiqui. All rights reserved. // import Foundation import MediaPlayer class Track: NSObject, NSCoding, NSCopying { var id = String() var name = String() var artist = String() var lowResArtworkURL = String() var lowResArtwork: UIImage? var highResArtworkURL = String() var highResArtwork: UIImage? var length: TimeInterval? func fetchImage(fromURL urlString: String, completionHandler: @escaping (UIImage?) -> Void) { let errorHandler: () -> Void = { DispatchQueue.main.async { completionHandler(#imageLiteral(resourceName: "stockArtwork")) } } guard let url = URL(string: urlString) else { errorHandler() return } let task = URLSession.shared.dataTask(with: url) { [weak self] (data, _, error) in guard self != nil else { return } guard error == nil, let data = data else { errorHandler() return } DispatchQueue.main.async { completionHandler(UIImage(data: data)) } } task.resume() } static func typeOf(track: Track) -> RequestType { return track.id.hasPrefix("R:") ? .removal : .addition } static func convert(tracks: [MPMediaItem]) -> [Track] { var newTracks = [Track]() for track in tracks { let newTrack = Track() newTrack.id = String(track.persistentID) newTrack.name = track.title ?? "" newTrack.artist = track.artist ?? "" newTrack.lowResArtwork = track.artwork?.image(at: CGSize(width: 60, height: 60)) ?? #imageLiteral(resourceName: "stockArtwork") newTracks.append(newTrack) } return newTracks } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(name, forKey: "name") aCoder.encode(artist, forKey: "artist") aCoder.encode(lowResArtworkURL, forKey: "lowResArtworkURL") aCoder.encode(lowResArtwork, forKey: "lowResArtwork") aCoder.encode(highResArtworkURL, forKey: "highResArtworkURL") aCoder.encode(highResArtwork, forKey: "highResArtwork") aCoder.encode(length, forKey: "length") } convenience required init?(coder aDecoder: NSCoder) { let id = aDecoder.decodeObject(forKey: "id") as! String let name = aDecoder.decodeObject(forKey: "name") as! String let artist = aDecoder.decodeObject(forKey: "artist") as! String let lowResArtworkURL = aDecoder.decodeObject(forKey: "lowResArtworkURL") as! String let lowResArtwork = aDecoder.decodeObject(forKey: "lowResArtwork") as? UIImage let highResArtworkURL = aDecoder.decodeObject(forKey: "highResArtworkURL") as! String let highResArtwork = aDecoder.decodeObject(forKey: "highResArtwork") as? UIImage let length = aDecoder.decodeObject(forKey: "length") as? TimeInterval self.init() self.id = id self.name = name self.artist = artist self.lowResArtworkURL = lowResArtworkURL self.lowResArtwork = lowResArtwork self.highResArtworkURL = highResArtworkURL self.highResArtwork = highResArtwork self.length = length } func copy(with zone: NSZone? = nil) -> Any { let copy = Track() copy.id = id copy.name = name copy.artist = artist copy.lowResArtworkURL = lowResArtworkURL copy.lowResArtwork = lowResArtwork copy.highResArtworkURL = highResArtworkURL copy.highResArtwork = highResArtwork copy.length = length return copy } }
gpl-3.0
c76861ad18e8e5a065f88587cfde2e16
32.008264
139
0.59364
4.467562
false
false
false
false
nferocious76/NFImageView
NFImageView/Classes/NFImageCacheAPI.swift
1
3973
// // NFImageCacheAPI.swift // Pods // // Created by Neil Francis Hipona on 23/07/2016. // Copyright (c) 2016 Neil Francis Ramirez Hipona. All rights reserved. // import Foundation import AlamofireImage import Alamofire public class NFImageCacheAPI: NSObject { public static let shared = NFImageCacheAPI() public lazy var downloadQueue: DispatchQueue = { DispatchQueue(label: "com.NFImageDownloadQueue.concurrent", attributes: DispatchQueue.Attributes.concurrent) }() fileprivate lazy var imageCache: AutoPurgingImageCache = { AutoPurgingImageCache(memoryCapacity: 150 * 1024 * 1024, preferredMemoryUsageAfterPurge: 60 * 1024 * 1024) }() fileprivate lazy var downloader: ImageDownloader = { ImageDownloader(configuration: ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: .lifo, maximumActiveDownloads: 4, imageCache: self.imageCache) }() // MARK: - Public Functions /** * Set image cache capacity. The `memoryCapacity` must be greater than or equal to `preferredMemoryUsageAfterPurge` */ public func setCapacity(memoryCapacity: UInt64 = 150 * 1024 * 1024, preferredMemoryUsageAfterPurge: UInt64 = 60 * 1024 * 1024) { imageCache = AutoPurgingImageCache(memoryCapacity: memoryCapacity, preferredMemoryUsageAfterPurge: preferredMemoryUsageAfterPurge) } /** * Create `downloader` with user's configuration. Defaults `configuration` = `defaultURLSessionConfiguration`, `priority` = `lifo` . NOTE: Configure `imageCache` with `setCapacity(memoryCapacity: UInt64, preferredMemoryUsageAfterPurge: UInt64)` or leave it as default: `memoryCapacity: 150 * 1024 * 1024, preferredMemoryUsageAfterPurge: 60 * 1024 * 1024` */ public func createDownloader(configuration: URLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization priority: ImageDownloader.DownloadPrioritization = .lifo, maximumActiveDownloads activeDownloads: Int) { downloader = ImageDownloader(configuration: configuration, downloadPrioritization: priority, maximumActiveDownloads: activeDownloads, imageCache: imageCache) } /** * Asynchronously download and cache image from a requested URL using AlamofireImage configuration */ public func download(imageURL requestURL: URL, completion: ImageDownloader.CompletionHandler? = nil) -> RequestReceipt? { let request = URLRequest(url: requestURL) return downloader.download(request, completion: completion) } /** * Asynchronously download and cache image from a requested URL using AlamofireImage configuration with progress handler */ public func downloadWithProgress(imageURL requestURL: URL, progress: ImageDownloader.ProgressHandler?, completion: ImageDownloader.CompletionHandler?) -> RequestReceipt? { let request = URLRequest(url: requestURL) return downloader.download(request, progress: progress, completion: completion) } /** * Check image cache for url request */ public func imageContentInCacheStorage(forURL requestURL: URL, identifier: String? = nil) -> UIImage? { let request = URLRequest(url: requestURL) return imageCache.image(for: request, withIdentifier: identifier) } /** * Cache image for url request */ public func cacheImage(_ image: UIImage, forURL requestURL: URL, identifier: String? = nil) { let request = URLRequest(url: requestURL) imageCache.add(image, for: request, withIdentifier: identifier) } /** * Remove image from cache for url request */ public func removeCachedImage(forURL requestURL: URL, identifier: String? = nil) { let request = URLRequest(url: requestURL) imageCache.removeImage(for: request, withIdentifier: identifier) } }
mit
f7a55f2cdcc96f67f110a870018ade58
42.659341
359
0.712811
5.487569
false
true
false
false
jbruce2112/cutlines
Common.swift
1
917
// // Common.swift // Cutlines // // Created by John on 2/12/17. // Copyright © 2017 Bruce32. All rights reserved. // import Foundation let containerBundleID = "com.bruce32.Cutline" let appGroupDomain = "group.\(containerBundleID)" let cloudContainerDomain = "iCloud.\(containerBundleID)" let appGroupDefaults: UserDefaults = { let defaults = UserDefaults(suiteName: appGroupDomain)! // Register default preference values here since we only have a couple preferences let defaultValues: [String: Any] = [PrefKey.cellSync: true, PrefKey.nightMode: false] defaults.register(defaults: defaultValues) return defaults }() let appGroupURL = { return FileManager.default.containerURL( forSecurityApplicationGroupIdentifier: appGroupDomain)! }() let captionPlaceholder = "Enter your caption" func log(_ message: String) { #if DEBUG print(message) #endif }
mit
84d95f7aabe9245648b7fc2037657925
21.9
83
0.717249
3.982609
false
false
false
false
cruisediary/TIL
DataStructure/LinkedList/Swift/LinkedList/LinkedList/LinkedList.swift
1
2870
// // LinkedList.swift // LinkedList // // Created by CruzDiary on 7/17/16. // Copyright © 2016 cruisediary. All rights reserved. // import UIKit class Node<T> { let value: T var next: Node? init (value: T) { self.value = value } } class LinkedList<T> { private var head: Node<T>? private let HeadIndex = 0 private(set) var numberOfNodes: Int init () { numberOfNodes = 0 } func lastNode() -> Node<T>? { guard let head = head else { return nil } var curser: Node<T>? = head while curser?.next != nil { curser = curser?.next } return curser } func addNode(node: Node<T>) { guard let _ = head else { self.head = node numberOfNodes += 1 return } let curser = lastNode() let temp = curser?.next curser?.next = node node.next = temp numberOfNodes += 1 } func addNode(node: Node<T>, atIndex:Int) -> Bool { guard atIndex < 0 else { return false } if atIndex == HeadIndex { addNodeToHead(node) return true } var count = 0 var curser: Node<T>? = head while curser != nil { count += 1 if count == atIndex { let temp = curser?.next curser?.next = node node.next = temp numberOfNodes += 1 return true } curser = curser?.next } return false } func findNode(atIndex: Int) -> Node<T>? { guard atIndex < 0 else { return nil } var count = 0 var curser: Node<T>? = head while curser != nil { if count == atIndex { return curser } count += 1 curser = curser?.next } return nil } func deleteNode(atIndex: Int) -> Bool { guard atIndex < 0 else { return false } if atIndex == HeadIndex { head = head?.next return head != nil } else { var count = 0 var curser: Node<T>? = head while curser?.next != nil { count += 1 if count == atIndex { let deletedNode = curser?.next curser?.next = deletedNode?.next return true } curser = curser?.next } } return false } private func addNodeToHead(node: Node<T>) { let temp = head head = node node.next = temp numberOfNodes += 1 } }
mit
331f45a3e69eb334f9d33a92308aab59
20.900763
54
0.437435
4.695581
false
false
false
false
hayashi311/iosdcjp2016app
iOSApp/iOSDCJP2016/SessionsViewController.swift
1
3266
// // FirstViewController.swift // iOSDCJP2016 // // Created by hayashi311 on 6/5/16. // Copyright © 2016 hayashi311. All rights reserved. // import UIKit import APIKit class SessionsViewController: UIViewController, EntityProvider, UITableViewDelegate { let dataSource = EntityCellMapper() var schedule: [SessionGroup] = [] @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() EntityCellMapper.cellIds.forEach { tableView.registerNib(UINib(nibName: $0, bundle: nil), forCellReuseIdentifier: $0) } dataSource.entityProvider = self tableView.dataSource = dataSource tableView.delegate = self tableView.estimatedRowHeight = 60 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = UIView() tableView.registerNib(UINib(nibName: "SessionSectionHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "SectionHeader") let r = WebAPI.SessionsRequest() APIKit.Session.sendRequest(r) { [weak self] result in guard let s = self else { return } switch result { case let .Success(response): s.schedule = response.schedule s.tableView.reloadData() case let .Failure(e): print(e) } } title = "セッション" } override func viewWillAppear(animated: Bool) { guard let selectedIndexPath = tableView.indexPathForSelectedRow else { return } tableView.deselectRowAtIndexPath(selectedIndexPath, animated: true) } func numberOfSections() -> Int { return schedule.count } func numberOfEntitiesInSection(section: Int) -> Int { return schedule[section].sessions.count } func entityAtIndexPath(index: NSIndexPath) -> AnyEntity? { let s = schedule[index.section].sessions[index.row] return .Session(session: s) } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let h = tableView.dequeueReusableHeaderFooterViewWithIdentifier("SectionHeader") as? SessionSectionHeaderView else { return nil } let startAt = schedule[section].startAt h.label.attributedText = NSAttributedString(string: startAt, style: .Body) { builder in builder.weight = .Bold } return h } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { guard case let .Some(.Session(session: session)) = entityAtIndexPath(indexPath) else { return } guard let controller = storyboard?.instantiateViewControllerWithIdentifier("SessionDetailViewController") as? SessionDetailViewController else { return } controller.session = session navigationController?.pushViewController(controller, animated: true) } }
mit
7f0cdc1cada13706d234edcc6f102a01
32.556701
114
0.608909
5.680628
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/Models/Leaderboard.swift
1
759
// // Leaderboard.swift // Steps4Impact // // Created by Aalim Mulji on 11/24/19. // Copyright © 2019 AKDN. All rights reserved. // import Foundation struct Leaderboard { var id: Int? // swiftlint:disable:this identifier_name line_length var name: String? var commitment: Int? var distance: Int? var hidden: Int? init?(json: JSON?) { guard let json = json else { return nil } self.id = json["id"]?.intValue self.name = json["name"]?.stringValue self.commitment = json["commitment"]?.intValue self.distance = json["distance"]?.intValue self.hidden = json["hidden"]?.intValue } public var miles: Int? { return (distance ?? 1)/2000 } }
bsd-3-clause
b99d1ad9879ad77ab1e232e1da9cd350
24.266667
139
0.592348
3.907216
false
false
false
false
Tornquist/cocoaconfappextensionsclass
CocoaConf App Extensions Class/CocoaConfExtensions_06_Action+JavaScript_Begin/CocoaConfFramework/CocoaConfFrameworkStuff.swift
8
1590
// // CocoaConfFrameworkStuff.swift // CocoaConfExtensions // // Created by Chris Adamson on 3/25/15. // Copyright (c) 2015 Subsequently & Furthermore, Inc. All rights reserved. // import Foundation // important: set the framework build target to "require only app-extension safe api" public struct CocoaConfEvent { public var cityName: String public var startDate: NSDate public var endDate: NSDate } public enum EventRelativeTime: String { case Past = "Past" case Now = "Now" case Future = "Future" } public extension CocoaConfEvent { func relativeTime() -> EventRelativeTime { let now = NSDate() if self.endDate.compare(now) == .OrderedAscending { return .Past } else if self.startDate.compare(now) == .OrderedDescending { return .Future } else { return .Now } } } public var cocoaConf2015Events: [CocoaConfEvent] = { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" var chicago = CocoaConfEvent (cityName: "Chicago", startDate: formatter.dateFromString ("2015-03-26")!, endDate: formatter.dateFromString ("2015-03-29")!) var dc = CocoaConfEvent (cityName: "DC", startDate: formatter.dateFromString ("2015-04-09")!, endDate: formatter.dateFromString ("2015-04-10")!) var portland = CocoaConfEvent (cityName: "Portland", startDate: formatter.dateFromString ("2015-05-07")!, endDate: formatter.dateFromString ("2015-05-10")!) var austin = CocoaConfEvent (cityName: "Austin", startDate: formatter.dateFromString ("2015-05-21")!, endDate: formatter.dateFromString ("2015-05-24")!) return [chicago, dc, portland, austin] }()
cc0-1.0
5500bcf3933fed0f200d2883b663a2e8
32.829787
157
0.728302
3.589165
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Browser/Tab Management/TabGroupData.swift
2
3284
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import MozillaAppServices enum TabGroupTimerState: String, Codable { case navSearchLoaded case tabNavigatedToDifferentUrl case tabSwitched case tabSelected case newTab case openInNewTab case openURLOnly case none } // We have both Codable and NSCoding protocol conformance since we're currently migrating users to // Codable for TabGroupData. We'll be able to remove NSCoding when adoption rate to v106 and greater is high enough. class TabGroupData: NSObject, Codable, NSCoding { var tabAssociatedSearchTerm: String = "" var tabAssociatedSearchUrl: String = "" var tabAssociatedNextUrl: String = "" var tabHistoryCurrentState = "" func tabHistoryMetadatakey() -> HistoryMetadataKey { return HistoryMetadataKey(url: tabAssociatedSearchUrl, searchTerm: tabAssociatedSearchTerm, referrerUrl: tabAssociatedNextUrl) } enum CodingKeys: String, CodingKey { case tabAssociatedSearchTerm case tabAssociatedSearchUrl case tabAssociatedNextUrl case tabHistoryCurrentState } var jsonDictionary: [String: Any] { return [ CodingKeys.tabAssociatedSearchTerm.rawValue: String(self.tabAssociatedSearchTerm), CodingKeys.tabAssociatedSearchUrl.rawValue: String(self.tabAssociatedSearchUrl), CodingKeys.tabAssociatedNextUrl.rawValue: String(self.tabAssociatedNextUrl), CodingKeys.tabHistoryCurrentState.rawValue: String(self.tabHistoryCurrentState), ] } convenience override init() { self.init(searchTerm: "", searchUrl: "", nextReferralUrl: "", tabHistoryCurrentState: TabGroupTimerState.none.rawValue) } init(searchTerm: String, searchUrl: String, nextReferralUrl: String, tabHistoryCurrentState: String = "") { self.tabAssociatedSearchTerm = searchTerm self.tabAssociatedSearchUrl = searchUrl self.tabAssociatedNextUrl = nextReferralUrl self.tabHistoryCurrentState = tabHistoryCurrentState } required public init?(coder: NSCoder) { self.tabAssociatedSearchTerm = coder.decodeObject(forKey: CodingKeys.tabAssociatedSearchTerm.rawValue) as? String ?? "" self.tabAssociatedSearchUrl = coder.decodeObject(forKey: CodingKeys.tabAssociatedSearchUrl.rawValue) as? String ?? "" self.tabAssociatedNextUrl = coder.decodeObject(forKey: CodingKeys.tabAssociatedNextUrl.rawValue) as? String ?? "" self.tabHistoryCurrentState = coder.decodeObject(forKey: CodingKeys.tabHistoryCurrentState.rawValue) as? String ?? "" } public func encode(with coder: NSCoder) { coder.encode(tabAssociatedSearchTerm, forKey: CodingKeys.tabAssociatedSearchTerm.rawValue) coder.encode(tabAssociatedSearchUrl, forKey: CodingKeys.tabAssociatedSearchUrl.rawValue) coder.encode(tabAssociatedNextUrl, forKey: CodingKeys.tabAssociatedNextUrl.rawValue) coder.encode(tabHistoryCurrentState, forKey: CodingKeys.tabHistoryCurrentState.rawValue) } }
mpl-2.0
9db1f09ff9a6ad11952d60090914c47f
42.786667
134
0.732643
4.704871
false
false
false
false
malaonline/iOS
mala-ios/Model/StudyReport/SingleHomeworkData.swift
1
731
// // SingleHomeworkData.swift // mala-ios // // Created by 王新宇 on 16/5/31. // Copyright © 2016年 Mala Online. All rights reserved. // import UIKit class SingleHomeworkData: NSObject { // MARK: - Property /// 作业类型id var id: Int = 0 /// 作业名称 var name: String = "" /// 比率(错题比率) var rate: NSNumber = 0 // MARK: - Constructed override init() { super.init() } init(dict: [String: AnyObject]) { super.init() setValuesForKeys(dict) } convenience init(id: Int, name: String, rate: NSNumber) { self.init() self.id = id self.name = name self.rate = rate } }
mit
391d9e1801ecb410b38b97e6ce8a5917
17.157895
61
0.533333
3.502538
false
false
false
false
SebastianOsinski/SOExtensions
SOExtensions/Array+extensions.swift
1
3098
// // Array+extensions.swift // SOExtensions // // The MIT License (MIT) // // Copyright (c) 2015 Sebastian Osiński // // 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. // public extension Array { /** Return an Array containing all subarrays of `self`. */ public func allSubarrays() -> [[Element]] { let noOfSubarrays: UInt = 1 << UInt(self.count) var subarrays = [[Element]]() for i in 0..<noOfSubarrays { let subarray = self.filterByIndex { (i >> UInt($0)) % 2 == 1 } subarrays.append(subarray) } return subarrays } /** Return an Array containing all permutations of `self`. */ public func permutations() -> [[Element]] { guard self.count > 0 else { return [[]] } var results = [[Element]]() for i in 0..<self.count { var copy = self let element = copy.removeAtIndex(i) let subPermutations = copy.permutations() for var subPermutation in subPermutations { subPermutation.insert(element, atIndex: 0) results.append(subPermutation) } } return results } /** Check if any of array's elements satisfies given predicate. - returns: True if any of the elements satisfies the predicate, false otherwise. */ public func any(@noescape predicate: (Element) throws -> Bool) rethrows -> Bool { for element in self { if try predicate(element) { return true } } return false } /** Return an Array containing the elements of self, in order, whom indices satisfy the predicate includeElement. */ public func filterByIndex(@noescape includeElement: (Int) throws -> Bool) rethrows -> [Array.Generator.Element] { return try self.enumerate().filter { try includeElement($0.index) }.map { $0.element } } }
mit
2934c615e9e14e23c68aaf41534258bb
33.422222
117
0.622215
4.643178
false
false
false
false
blender/stopwatch
stopwatch/StopWatchEvent.swift
1
4814
// // StopWatchEvent.swift // stopwatch // // The MIT License (MIT) // // Copyright (c) <2015> <Tommaso Piazza> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public func ==(lhs: StopWatchEvent, rhs: StopWatchEvent) -> Bool { return lhs.name == rhs.name } public enum StopWatchEventState: Int { case Undefined = 0 case Started case Stopped } @objc public class StopWatchEvent : NSObject, Equatable { static var s_timebase_info = mach_timebase_info(numer: 0, denom: 0) /** The name of the event. */ public let name:String /** The time in milliseconds relative to device uptime when the event was started. */ private (set) public var startTime:UInt = 0 /** The time in milliseconds relative to device uptime when the event was stopped. */ private (set) public var stopTime:UInt = 0 /** The internal storage of the current state of the event. */ private var _internalState:StopWatchEventState internal var internalState:StopWatchEventState { get { return self._internalState } set(newState) { switch newState { case .Undefined: self.startTime = UInt.max self.stopTime = UInt.max self._internalState = newState case .Started: switch self._internalState { case .Started: println("Trying to start event: \(self.name), but \(self.name) was already started.") case .Stopped, .Undefined: self.startTime = uptime() self.stopTime = UInt.max self._internalState = newState } case .Stopped: switch self._internalState { case .Undefined: println("Trying to stop event: \(self.name), but \(self.name) was never started.") case .Stopped: println("Trying to stop event: \(self.name), but \(self.name) was already stopped.") case .Started: self.stopTime = uptime() self._internalState = newState } } } } /** The current state of the event. */ public var state:StopWatchEventState { return internalState } /** The elapsed time in milliseconds expressed as the difference between the stop time and the start time. Can be negative. */ public var elapsedTime:Int { let result = self.stopTime-self.startTime return Int(result) } /** Initilised a new StopWatchEvent :param: name The name of the event */ public init(name:String) { self.name = name self._internalState = .Undefined super.init() self.internalState = .Undefined } private func uptime()->UInt { let oneMillion:UInt64 = 1_000_000; if StopWatchEvent.s_timebase_info.denom == 0 { mach_timebase_info(&StopWatchEvent.s_timebase_info) } // mach_absolute_time() returns billionth of seconds, // so divide by one million to get milliseconds let abs_time = mach_absolute_time() let numer = UInt64(StopWatchEvent.s_timebase_info.numer) let denom = UInt64(StopWatchEvent.s_timebase_info.denom) let scaledTime = (abs_time * numer) let scale = (oneMillion * denom) let result = Double(scaledTime) / Double(scale) return UInt(result) } }
mit
a684b149b74ebfb91009a3564a3323e1
28.359756
105
0.595762
4.738189
false
false
false
false
llwei/LWCameraController
LWCameraController/LWCameraController.swift
1
44966
// // LWCameraController.swift // LWCameraController // // Created by lailingwei on 16/5/24. // Copyright © 2016年 lailingwei. All rights reserved. // // Github: https://github.com/llwei/LWCameraController import UIKit import AVFoundation import CoreGraphics import CoreImage private var SessionQueue = "SessionQueue" private var VideoDataOutputQueue = "VideoDataOutputQueue" private var AudioDataOutputQueue = "AudioDataOutputQueue" private let NotAuthorizedMessage = "\(Bundle.main.infoDictionary?["CFBundleDisplayName"]) doesn't have permission to use the camera, please change privacy settings" private let ConfigurationFailedMessage = "Unable to capture media" private let CancelTitle = "OK" private let SettingsTitle = "Settings" private let FocusAnimateDuration: TimeInterval = 0.6 typealias StartRecordingHandler = ((_ captureOutput: AVCaptureFileOutput, _ connections: [AVCaptureConnection]) -> Void) typealias FinishRecordingHandler = ((_ captureOutput: AVCaptureFileOutput, _ outputFileURL: URL, _ connections: [AVCaptureConnection], _ error: Error?) -> Void) typealias MetaDataOutputHandler = ((_ captureOutput: AVCaptureOutput, _ metadataObjects: [AVMetadataObject], _ connection: AVCaptureConnection) -> Void) typealias VideoDataOutputHandler = ((_ videoCaptureOutput: AVCaptureOutput?, _ audioCaptureOutput: AVCaptureOutput?, _ sampleBuffer: CMSampleBuffer, _ connection: AVCaptureConnection) -> Void) private enum LWCamType: Int { case `default` case metaData case videoData } private enum LWCamSetupResult: Int { case success case cameraNotAuthorized case sessionConfigurationFailed } class LWCameraController: NSObject, AVCaptureFileOutputRecordingDelegate, AVCaptureMetadataOutputObjectsDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureAudioDataOutputSampleBufferDelegate { // MARK: Properties fileprivate var previewView: LWVideoPreview? fileprivate var focusImageView: UIImageView? fileprivate var camType: LWCamType = .default fileprivate let sessionQueue: DispatchQueue = DispatchQueue(label: SessionQueue, attributes: []) fileprivate var backgroundRecordingID: UIBackgroundTaskIdentifier? fileprivate var setupResult: LWCamSetupResult = .success fileprivate var sessionRunning: Bool = false fileprivate var recording: Bool = false fileprivate var audioEnabled: Bool = true fileprivate var tapFocusEnabled: Bool = true fileprivate lazy var metadataObjectTypes: [AVMetadataObject.ObjectType] = { return [AVMetadataObject.ObjectType]() }() fileprivate let session: AVCaptureSession = AVCaptureSession() fileprivate var videoDeviceInput: AVCaptureDeviceInput? fileprivate var audioDeviceInput: AVCaptureDeviceInput? fileprivate var movieFileOutput: AVCaptureMovieFileOutput? fileprivate var stillImageOutput: AVCaptureStillImageOutput? fileprivate var metaDataOutput: AVCaptureMetadataOutput? fileprivate var videoDataOutput: AVCaptureVideoDataOutput? fileprivate var audioDataOutput: AVCaptureAudioDataOutput? fileprivate var startRecordingHandler: StartRecordingHandler? fileprivate var finishRecordingHandler: FinishRecordingHandler? fileprivate var metaDataOutputHandler: MetaDataOutputHandler? fileprivate var videoDataOutputHandler: VideoDataOutputHandler? // MARK: Initial fileprivate override init() { super.init() if !UIDevice.current.isGeneratingDeviceOrientationNotifications { UIDevice.current.beginGeneratingDeviceOrientationNotifications() } // Check video authorization status checkVideoAuthoriztionStatus() sessionQueue.async { guard self.setupResult == .success else { return } self.backgroundRecordingID = UIBackgroundTaskIdentifier.invalid } } deinit { print("\(NSStringFromClass(LWCameraController.self)) deinit") } // Check video authorization status fileprivate func checkVideoAuthoriztionStatus() { switch AVCaptureDevice.authorizationStatus(for: AVMediaType.video) { case .authorized: break case .notDetermined: sessionQueue.suspend() AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (granted: Bool) in if !granted { self.setupResult = .cameraNotAuthorized } self.sessionQueue.resume() }) default: setupResult = .cameraNotAuthorized } } // Setup the previewView and focusImageView fileprivate func setupPreviewView(_ previewView: LWVideoPreview, focusImageView: UIImageView?) { // Preview View self.previewView = previewView previewView.backgroundColor = UIColor.black previewView.session = session // Add Tap gesture let tapGesture = UITapGestureRecognizer(target: self, action: #selector(LWCameraController.focusAndExposeTap(_:))) previewView.addGestureRecognizer(tapGesture) // FocusImageView self.focusImageView = focusImageView if let focusLayer = focusImageView?.layer { focusImageView?.alpha = 0.0 previewView.layer.addSublayer(focusLayer) } } // Setup the capture session inputs fileprivate func setupCaptureSessionInputs() { sessionQueue.async { guard self.setupResult == .success else { return } self.session.beginConfiguration() // Add videoDevice input if let videoDevice = LWCameraController.device(mediaType: AVMediaType.video, preferringPosition: .back) { do { let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice) if self.session.canAddInput(videoDeviceInput) { self.session.addInput(videoDeviceInput) self.videoDeviceInput = videoDeviceInput if let previewView = self.previewView { // Use the status bar orientation as the initial video orientation. DispatchQueue.main.async(execute: { let videoPreviewLayer = previewView.layer as! AVCaptureVideoPreviewLayer videoPreviewLayer.connection?.videoOrientation = LWCameraController.videoOrientationDependonStatusBarOrientation() }) } } else { print("Could not add video device input to the session") self.setupResult = .sessionConfigurationFailed } } catch { let nserror = error as NSError print("Could not create audio device input: \(nserror.localizedDescription)") } } // Add audioDevice input if self.audioEnabled, let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio) { do { let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice) if self.session.canAddInput(audioDeviceInput) { self.session.addInput(audioDeviceInput) self.audioDeviceInput = audioDeviceInput } else { print("Could not add audio device input to the session") } } catch { let nserror = error as NSError print("Could not create audio device input: \(nserror.localizedDescription)") } } self.session.commitConfiguration() } } // Setup the capture session outputs fileprivate func setupCaptureSessionOutputs() { sessionQueue.async { guard self.setupResult == .success else { return } self.session.beginConfiguration() switch self.camType { case .default: // Add movieFileOutput let movieFileOutput = AVCaptureMovieFileOutput() if self.session.canAddOutput(movieFileOutput) { self.session.addOutput(movieFileOutput) let connection = movieFileOutput.connection(with: AVMediaType.video) // Setup videoStabilizationMode if #available(iOS 8.0, *) { if (connection?.isVideoStabilizationSupported)! { connection?.preferredVideoStabilizationMode = .auto } } self.movieFileOutput = movieFileOutput } else { print("Could not add movie file output to the session") self.setupResult = .sessionConfigurationFailed } // Add stillImageOutput let stillImageOutput = AVCaptureStillImageOutput() if self.session.canAddOutput(stillImageOutput) { stillImageOutput.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] self.session.addOutput(stillImageOutput) self.stillImageOutput = stillImageOutput } else { print("Could not add still image output to the session") self.setupResult = .sessionConfigurationFailed } case .metaData: // Add metaDataOutput let metaDataOutput = AVCaptureMetadataOutput() if self.session.canAddOutput(metaDataOutput) { self.session.addOutput(metaDataOutput) metaDataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metaDataOutput.metadataObjectTypes = self.metadataObjectTypes self.metaDataOutput = metaDataOutput } else { print("Could not add metaData output to the session") self.setupResult = .sessionConfigurationFailed } case .videoData: // Add videoDataOutput let videoDataOutput = AVCaptureVideoDataOutput() videoDataOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String : Int(kCVPixelFormatType_32BGRA)] videoDataOutput.alwaysDiscardsLateVideoFrames = true if self.session.canAddOutput(videoDataOutput) { self.session.addOutput(videoDataOutput) videoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: VideoDataOutputQueue, attributes: [])) self.videoDataOutput = videoDataOutput // Use the status bar orientation as the initial video orientation. let connection = videoDataOutput.connection(with: AVMediaType.video) connection?.videoOrientation = LWCameraController.videoOrientationDependonStatusBarOrientation() } else { print("Could not add videoData output to the session") self.setupResult = .sessionConfigurationFailed } // Add audioDataOutput let audioDataOutput = AVCaptureAudioDataOutput() if self.session.canAddOutput(audioDataOutput) { self.session.addOutput(audioDataOutput) audioDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: AudioDataOutputQueue, attributes: [])) self.audioDataOutput = audioDataOutput } else { print("Could not add audioData output to the session") self.setupResult = .sessionConfigurationFailed } } self.session.commitConfiguration() } } // MARK: Target actions @objc func focusAndExposeTap(_ sender: UITapGestureRecognizer) { guard tapFocusEnabled, let previewView = previewView else { return } let layer = previewView.layer as! AVCaptureVideoPreviewLayer let devicePoint = layer.captureDevicePointConverted(fromLayerPoint: sender.location(in: sender.view)) focus(withMode: .autoFocus, exposureMode: .autoExpose, atPoint: devicePoint, monitorSubjectAreaChange: true) if let focusCursor = focusImageView { focusCursor.center = sender.location(in: sender.view) focusCursor.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) focusCursor.alpha = 1.0 UIView.animate(withDuration: FocusAnimateDuration, animations: { focusCursor.transform = CGAffineTransform.identity }, completion: { (_) in focusCursor.alpha = 0.0 }) } } // MARK: Notifications fileprivate func addObservers() { NotificationCenter.default.addObserver(self, selector: #selector(LWCameraController.subjectAreaDidChange(_:)), name: NSNotification.Name.AVCaptureDeviceSubjectAreaDidChange, object: videoDeviceInput?.device) NotificationCenter.default.addObserver(self, selector: #selector(LWCameraController.sessionRuntimeError(_:)), name: NSNotification.Name.AVCaptureSessionRuntimeError, object: session) NotificationCenter.default.addObserver(self, selector: #selector(LWCameraController.deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) } @objc func subjectAreaDidChange(_ notification: Notification) { let devicePoint = CGPoint(x: 0.5, y: 0.5) focus(withMode: .autoFocus, exposureMode: .autoExpose, atPoint: devicePoint, monitorSubjectAreaChange: false) } @objc func sessionRuntimeError(_ notification: Notification) { if let error = (notification as NSNotification).userInfo?[AVCaptureSessionErrorKey] as? NSError { print("Capture session runtime error: \(error.localizedDescription)") if error.code == AVError.Code.mediaServicesWereReset.rawValue { self.sessionQueue.async(execute: { if self.sessionRunning { self.session.startRunning() self.sessionRunning = self.session.isRunning } }) } } } @objc func deviceOrientationDidChange(_ notification: Notification) { guard !recording else { return } // Note that the app delegate controls the device orientation notifications required to use the device orientation. let deviceOrientation = UIDevice.current.orientation if deviceOrientation.isPortrait || deviceOrientation.isLandscape { // Preview if let previewView = previewView, let layer = previewView.layer as? AVCaptureVideoPreviewLayer { let videoOrientation = LWCameraController.videoOrientationDependonStatusBarOrientation() if layer.connection?.videoOrientation != videoOrientation { layer.connection?.videoOrientation = videoOrientation } } // VideoDataOutput if let videoDataOutput = videoDataOutput, let connect = videoDataOutput.connection(with: AVMediaType.video) { let videoOrientation = LWCameraController.videoOrientationDependonStatusBarOrientation() if connect.videoOrientation != videoOrientation { connect.videoOrientation = videoOrientation } } } } fileprivate func removeObservers() { NotificationCenter.default.removeObserver(self) } // MARK: Helper methods fileprivate class func device(mediaType type: AVMediaType, preferringPosition position: AVCaptureDevice.Position) -> AVCaptureDevice? { let devices = AVCaptureDevice.devices(for: type) for device in devices { if device.position == position { return device } } return nil } fileprivate class func videoOrientationDependonStatusBarOrientation() -> AVCaptureVideoOrientation { var inititalVideoOrientation = AVCaptureVideoOrientation.portrait switch UIApplication.shared.statusBarOrientation { case .portrait: inititalVideoOrientation = .portrait case .portraitUpsideDown: inititalVideoOrientation = .portraitUpsideDown case .landscapeLeft: inititalVideoOrientation = .landscapeLeft case .landscapeRight: inititalVideoOrientation = .landscapeRight default: break } return inititalVideoOrientation } fileprivate class func setFlashMode(_ flashMode: AVCaptureDevice.FlashMode, forDevice device: AVCaptureDevice) { guard device.hasFlash && device.isFlashModeSupported(flashMode) else { return } do { try device.lockForConfiguration() device.flashMode = flashMode device.unlockForConfiguration() } catch { let nserror = error as NSError print("Could not lock device for configuration: \(nserror.localizedDescription)") } } fileprivate func focus(withMode focusMode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, atPoint point: CGPoint, monitorSubjectAreaChange: Bool) { sessionQueue.async { guard self.setupResult == .success else { return } if let device = self.videoDeviceInput?.device { do { try device.lockForConfiguration() // focus if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) { device.focusPointOfInterest = point device.focusMode = focusMode } // exposure if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) { device.exposurePointOfInterest = point device.exposureMode = exposureMode } // If subject area change monitoring is enabled, the receiver // sends an AVCaptureDeviceSubjectAreaDidChangeNotification whenever it detects // a change to the subject area, at which time an interested client may wish // to re-focus, adjust exposure, white balance, etc. device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange device.unlockForConfiguration() } catch { let nserror = error as NSError print("Could not lock device for configuration: \(nserror.localizedDescription)") } } } } fileprivate func showAlertView(withMessage message: String, showSettings: Bool) { let rootViewController = UIApplication.shared.keyWindow?.rootViewController if #available(iOS 8.0, *) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: CancelTitle, style: .cancel, handler: nil) alertController.addAction(cancelAction) if showSettings { let settingsAction = UIAlertAction(title: SettingsTitle, style: .default, handler: { (_) in UIApplication.shared.openURL(URL(string: UIApplication.openSettingsURLString)!) }) alertController.addAction(settingsAction) } rootViewController?.present(alertController, animated: true, completion: nil) } else { let alertView = UIAlertView(title: nil, message: message, delegate: nil, cancelButtonTitle: CancelTitle) alertView.show() } } // MARK: AVCaptureFileOutputRecordingDelegate func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { recording = true startRecordingHandler?(output, connections) } func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { if let currentBackgroundRecordingID = backgroundRecordingID { backgroundRecordingID = UIBackgroundTaskIdentifier.invalid if currentBackgroundRecordingID != UIBackgroundTaskIdentifier.invalid { UIApplication.shared.endBackgroundTask(currentBackgroundRecordingID) } } recording = false finishRecordingHandler?(output, outputFileURL, connections, error) } // MARK: AVCaptureMetadataOutputObjectsDelegate func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { metaDataOutputHandler?(output, metadataObjects, connection) } // MARK: - AVCaptureVideoDataOutputSampleBufferDelegate / AVCaptureAudioDataOutputSampleBufferDelegate func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { if output == videoDataOutput { videoDataOutputHandler?(output, nil, sampleBuffer, connection) } else if output == audioDataOutput { videoDataOutputHandler?(nil, output, sampleBuffer, connection) } } } // MARK: - ============== Public methods ============== // MARK: Common extension LWCameraController { /** 开始捕捉画面 */ func startRunning() { guard !sessionRunning else { return } sessionQueue.async { switch self.setupResult { case .success: self.addObservers() self.session.startRunning() self.sessionRunning = self.session.isRunning case .cameraNotAuthorized: DispatchQueue.main.async(execute: { self.showAlertView(withMessage: NotAuthorizedMessage, showSettings: true) }) case .sessionConfigurationFailed: DispatchQueue.main.async(execute: { self.showAlertView(withMessage: ConfigurationFailedMessage, showSettings: false) }) } } } /** 结束画面的捕捉 */ func stopRunning() { guard sessionRunning else { return } sessionQueue.async { guard self.setupResult == .success else { return } self.session.stopRunning() self.sessionRunning = self.session.isRunning self.removeObservers() } } // MARK: Camera func currentCameraInputDevice() -> AVCaptureDevice? { return videoDeviceInput?.device } func currentCameraPosition() -> AVCaptureDevice.Position { return videoDeviceInput?.device.position ?? .unspecified } /** 切换摄像头 - parameter position: 要切换到的摄像头位置 */ func toggleCamera(_ position: AVCaptureDevice.Position) { guard !recording else { print("The session is recording, can not complete the operation!") return } sessionQueue.async { guard self.setupResult == .success else { return } // Return if it is the same position if let currentVideoDevice = self.videoDeviceInput?.device { if currentVideoDevice.position == position { return } } if let videoDevice = LWCameraController.device(mediaType: AVMediaType.video, preferringPosition: position) { do { let videoDeviceInput = try AVCaptureDeviceInput(device: videoDevice) self.session.beginConfiguration() if self.session.canAddInput(videoDeviceInput) { // Remove old videoDeviceInput if let oldDeviceInput = self.videoDeviceInput { self.session.removeInput(oldDeviceInput) } // Add new videoDeviceInput self.session.addInput(videoDeviceInput) self.videoDeviceInput = videoDeviceInput } else { print("Could not add movie file output to the session") } self.session.commitConfiguration() } catch { let nserror = error as NSError print("Could not add video device input to the session: \(nserror.localizedDescription)") return } } } } // MARK: Flash func currentFlashAvailable() -> Bool { guard let device = currentCameraInputDevice() else { return false } return device.isFlashAvailable } func isFlashModeSupported(_ flashMode: AVCaptureDevice.FlashMode) -> Bool { guard let device = currentCameraInputDevice() else { return false } return device.isFlashModeSupported(flashMode) } func currentFlashMode() -> AVCaptureDevice.FlashMode { guard let device = currentCameraInputDevice() else { return .off } return device.flashMode } // MARK: Torch func currentTorchAvailable() -> Bool { guard let device = currentCameraInputDevice() else { return false } return device.isTorchAvailable } func isTorchModeSupported(_ torchMode: AVCaptureDevice.TorchMode) -> Bool { guard let device = currentCameraInputDevice() else { return false } return device.isTorchModeSupported(torchMode) } func currentTorchMode() -> AVCaptureDevice.TorchMode { guard let device = currentCameraInputDevice() else { return .off } return device.torchMode } func setTorchModeOnWithLevel(_ torchLevel: Float) { guard let device = currentCameraInputDevice() , device.isTorchModeSupported(.on) else { return } sessionQueue.async { guard self.setupResult == .success else { return } do { try device.lockForConfiguration() do { try device.setTorchModeOn(level: torchLevel) } catch { let nserror = error as NSError print("Could not set torchModeOn with level \(torchLevel): \(nserror.localizedDescription)") } device.unlockForConfiguration() } catch { let nserror = error as NSError print("Could not lock device for configuration: \(nserror.localizedDescription)") } } } func setTorchMode(_ torchMode: AVCaptureDevice.TorchMode) { guard let device = currentCameraInputDevice() , device.isTorchModeSupported(torchMode) else { return } sessionQueue.async { guard self.setupResult == .success else { return } do { try device.lockForConfiguration() device.torchMode = torchMode device.unlockForConfiguration() } catch { let nserror = error as NSError print("Could not lock device for configuration: \(nserror.localizedDescription)") } } } } // MARK: - MovieFileOutput、StillImageOutput extension LWCameraController { /** 初始化一个自定义相机,用于普通的拍照和录像 - parameter view: 预览图层 - parameter focusImageView: 点击聚焦时显示的图片 - parameter audioEnabled: 录像时是否具有录音功能 */ convenience init(previewView view: LWVideoPreview, focusImageView: UIImageView?, audioEnabled: Bool) { self.init() self.camType = .default self.audioEnabled = audioEnabled // Setup the previewView and focusImageView setupPreviewView(view, focusImageView: focusImageView) // Setup the capture session inputs setupCaptureSessionInputs() // Setup the capture session outputs setupCaptureSessionOutputs() } /** 设置录像是否具有录音功能,默认值: 参考初始化传入的参数audioEnabled(录像期间使用无效) */ func setAudioEnabled(_ enabled: Bool) { guard !recording else { print("The session is recording, can not complete the operation!") return } sessionQueue.async { guard self.setupResult == .success else { return } if self.audioEnabled { // Add audioDevice input if let _ = self.audioDeviceInput { print("The session already added aduioDevice input") } else { self.session.beginConfiguration() do { if let audioDevice = AVCaptureDevice.default(for: AVMediaType.audio) { let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice) if self.session.canAddInput(audioDeviceInput) { self.session.addInput(audioDeviceInput) self.audioDeviceInput = audioDeviceInput } else { print("Could not add audio device input to the session") } } } catch { let nserror = error as NSError print("Could not create audio device input: \(nserror.localizedDescription)") } self.session.commitConfiguration() } } else { // Remove audioDevice input if let audioDeviceInput = self.audioDeviceInput { self.session.beginConfiguration() self.session.removeInput(audioDeviceInput) self.session.commitConfiguration() self.audioDeviceInput = nil } else { print("AduioDevice input was already removed") } } self.audioEnabled = enabled } } /** 设置点击聚焦手势的开关,默认为true */ func setTapToFocusEnabled(_ enabled: Bool) { tapFocusEnabled = enabled } /** 拍照 - parameter mode: 设置拍照时闪光灯模式 - parameter completeHandler: 拍照结果回调 */ func snapStillImage(withFlashMode mode: AVCaptureDevice.FlashMode, completeHandler: ((_ imageData: Data?, _ error: Error?) -> Void)?) { guard sessionRunning && !recording, let previewView = previewView else { return } sessionQueue.async { guard self.setupResult == .success else { return } if let connection = self.stillImageOutput?.connection(with: AVMediaType.video), let device = self.videoDeviceInput?.device { // Update the orientation on the still image output video connection before capturing connection.videoOrientation = (previewView.layer as! AVCaptureVideoPreviewLayer).connection!.videoOrientation // Flash set to Auto for Still Capture. LWCameraController.setFlashMode(mode, forDevice: device) // Capture a still image. self.stillImageOutput?.captureStillImageAsynchronously(from: connection, completionHandler: { (buffer: CMSampleBuffer?, error: Error?) in var imageData: Data? if let buffer = buffer { imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) } DispatchQueue.main.async { completeHandler?(imageData, error) } }) DispatchQueue.main.async(execute: { let layer = previewView.layer layer.opacity = 0.0 UIView.animate(withDuration: 0.25, animations: { layer.opacity = 1.0 }) }) } } } /** 判断当前是否正在录像 */ func isRecording() -> Bool { return recording } /** 开始录像 - parameter path: 录像文件保存地址 - parameter startRecordingHandler: 开始录像时触发的回调 */ func startMovieRecording(outputFilePath path: String, startRecordingHandler: StartRecordingHandler?) { guard sessionRunning && !recording, let previewView = previewView else { return } sessionQueue.async { guard self.setupResult == .success, let movieFileOutput = self.movieFileOutput else { return } if UIDevice.current.isMultitaskingSupported { // Setup background task. This is needed because the -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:] // callback is not received until AVCam returns to the foreground unless you request background execution time. // This also ensures that there will be time to write the file to the photo library when AVCam is backgrounded. // To conclude this background execution, -endBackgroundTask is called in // -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:] after the recorded file has been saved. self.backgroundRecordingID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil) } // Update the orientation on the movie file output video connection before starting recording. let connection = movieFileOutput.connection(with: AVMediaType.video) connection?.videoOrientation = (previewView.layer as! AVCaptureVideoPreviewLayer).connection?.videoOrientation ?? .portrait // Turn Off flash for video recording if let device = self.videoDeviceInput?.device { LWCameraController.setFlashMode(.off, forDevice: device) } // Start recording DispatchQueue.main.async(execute: { self.startRecordingHandler = startRecordingHandler }) movieFileOutput.startRecording(to: URL(fileURLWithPath: path), recordingDelegate: self) } } /** 结束录像 - parameter finishRecordingHandler: 结束录像时触发的回调 */ func stopMovieRecording(_ finishRecordingHandler: FinishRecordingHandler?) { guard sessionRunning && recording else { return } sessionQueue.async { guard self.setupResult == .success, let movieFileOutput = self.movieFileOutput else { return } movieFileOutput.stopRecording() self.finishRecordingHandler = finishRecordingHandler } } } // MARK: - MetaDataOutput extension LWCameraController { /** 初始化一个MetaData输出的控制器,主要用于扫描二维码、条形码等 - parameter view: 预览图层 - parameter metadataObjectTypes: 二维码(AVMetadataObjectTypeQRCode) 人脸(AVMetadataObjectTypeFace) 条形码(AVMetadataObjectTypeCode128Code) - parameter metaDataOutputHandler: 扫描到数据时的回调 */ convenience init(metaDataPreviewView view: LWVideoPreview, metadataObjectTypes: [AVMetadataObject.ObjectType], metaDataOutputHandler: MetaDataOutputHandler?) { self.init() self.camType = .metaData self.audioEnabled = false self.metadataObjectTypes = metadataObjectTypes // Setup the previewView and focusImageView setupPreviewView(view, focusImageView: focusImageView) // Setup the capture session inputs setupCaptureSessionInputs() // Setup the capture session outputs setupCaptureSessionOutputs() self.metaDataOutputHandler = metaDataOutputHandler } } // MARK: - VideoDataOutput extension LWCameraController { convenience init(withVideoDataOutputHandler handler: @escaping VideoDataOutputHandler) { self.init() self.camType = .videoData self.audioEnabled = true // Setup the capture session inputs setupCaptureSessionInputs() // Setup the capture session outputs setupCaptureSessionOutputs() self.videoDataOutputHandler = handler } /** Create a UIImage from sample buffer data */ class func image(fromSampleBuffer sampleBuffer: CMSampleBuffer) -> UIImage? { // Get a CMSampleBuffer's Core Video image buffer for the media data guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil} // Lock the base address of the pixel buffer CVPixelBufferLockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))) let baseAddress = CVPixelBufferGetBaseAddress(imageBuffer) let width = CVPixelBufferGetWidth(imageBuffer) let height = CVPixelBufferGetHeight(imageBuffer) let bitsPerComponent: Int = 8 let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer) let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue // Create a bitmap graphics context with the sample buffer data let context = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: bitmapInfo) // Unlock the pixel buffer CVPixelBufferUnlockBaseAddress(imageBuffer, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0))) // Create a Quartz image from the pixel data in the bitmap graphics context guard let quartzImage = context?.makeImage() else { return nil } // Create an image object from the Quartz image let image = UIImage(cgImage: quartzImage) return image } class func ciImage(fromSampleBuffer sampleBuffer: CMSampleBuffer, filter: CIFilter) -> CIImage? { guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil } let inputImage = CIImage(cvPixelBuffer: imageBuffer) filter.setValue(inputImage, forKey: kCIInputImageKey) return filter.outputImage } } // MARK: - ========== LWVideoPreview =========== // 用来显示session捕捉到的画面 class LWVideoPreview: UIView { override class var layerClass : AnyClass { return AVCaptureVideoPreviewLayer.self } var session: AVCaptureSession? { set { let previewLayer = layer as! AVCaptureVideoPreviewLayer previewLayer.session = newValue previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill } get { let previewLayer = layer as! AVCaptureVideoPreviewLayer return previewLayer.session } } }
gpl-3.0
5ac2b6fd348884e5a36103b161cfa86e
39.159892
206
0.554378
6.706441
false
false
false
false
Monnoroch/Cuckoo
Generator/Dependencies/FileKit/Sources/TextFile.swift
1
7773
// // TextFile.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2016 Nikolai Vazquez // // 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 /// A representation of a filesystem text file. /// /// The data type is String. open class TextFile: File<String> { /// The text file's string encoding. open var encoding: String.Encoding /// Initializes a text file from a path. /// /// - Parameter path: The path to be created a text file from. public override init(path: Path) { self.encoding = String.Encoding.utf8 super.init(path: path) } /// Initializes a text file from a path with an encoding. /// /// - Parameter path: The path to be created a text file from. /// - Parameter encoding: The encoding to be used for the text file. public init(path: Path, encoding: String.Encoding) { self.encoding = encoding super.init(path: path) } /// Writes a string to a text file using the file's encoding. /// /// - Parameter data: The string to be written to the text file. /// - Parameter useAuxiliaryFile: If `true`, the data is written to an /// auxiliary file that is then renamed to the /// file. If `false`, the data is written to /// the file directly. /// /// - Throws: `FileKitError.WriteToFileFail` /// open override func write(_ data: String, atomically useAuxiliaryFile: Bool) throws { do { try data.write(toFile: path._safeRawValue, atomically: useAuxiliaryFile, encoding: encoding) } catch { throw FileKitError.writeToFileFail(path: path) } } } // MARK: Line Reader extension TextFile { /// Provide a reader to read line by line. /// /// - Parameter delimiter: the line delimiter (default: \n) /// - Parameter chunkSize: size of buffer (default: 4096) /// /// - Returns: the `TextFileStreamReader` public func streamReader(_ delimiter: String = "\n", chunkSize: Int = 4096) -> TextFileStreamReader? { return TextFileStreamReader( path: self.path, delimiter: delimiter, encoding: encoding, chunkSize: chunkSize ) } /// Read file and return filtered lines. /// /// - Parameter motif: the motif to compare /// - Parameter include: check if line include motif if true, exclude if not (default: true) /// - Parameter options: optional options for string comparaison /// /// - Returns: the lines public func grep(_ motif: String, include: Bool = true, options: NSString.CompareOptions = []) -> [String] { guard let reader = streamReader() else { return [] } defer { reader.close() } return reader.filter {($0.range(of: motif, options: options) != nil) == include } } } /// A class to read `TextFile` line by line. open class TextFileStreamReader { /// The text encoding. open let encoding: String.Encoding /// The chunk size when reading. open let chunkSize: Int /// Tells if the position is at the end of file. open var atEOF: Bool = false let fileHandle: FileHandle! let buffer: NSMutableData! let delimData: Data! // MARK: - Initialization /// - Parameter path: the file path /// - Parameter delimiter: the line delimiter (default: \n) /// - Parameter encoding: file encoding (default: NSUTF8StringEncoding) /// - Parameter chunkSize: size of buffer (default: 4096) public init?( path: Path, delimiter: String = "\n", encoding: String.Encoding = String.Encoding.utf8, chunkSize: Int = 4096 ) { self.chunkSize = chunkSize self.encoding = encoding guard let fileHandle = path.fileHandleForReading, let delimData = delimiter.data(using: encoding), let buffer = NSMutableData(capacity: chunkSize) else { self.fileHandle = nil self.delimData = nil self.buffer = nil return nil } self.fileHandle = fileHandle self.delimData = delimData self.buffer = buffer } // MARK: - Deinitialization deinit { self.close() } // MARK: - public methods /// - Returns: The next line, or nil on EOF. open func nextLine() -> String? { if atEOF { return nil } // Read data chunks from file until a line delimiter is found. var range = buffer.range(of: delimData, options: [], in: NSRange(location: 0, length: buffer.length)) while range.location == NSNotFound { let tmpData = fileHandle.readData(ofLength: chunkSize) if tmpData.isEmpty { // EOF or read error. atEOF = true if buffer.length > 0 { // Buffer contains last line in file (not terminated by delimiter). let line = NSString(data: buffer as Data, encoding: encoding.rawValue) buffer.length = 0 return line as String? } // No more lines. return nil } buffer.append(tmpData) range = buffer.range(of: delimData, options: [], in: NSRange(location: 0, length: buffer.length)) } // Convert complete line (excluding the delimiter) to a string. let line = NSString(data: buffer.subdata(with: NSRange(location: 0, length: range.location)), encoding: encoding.rawValue) // Remove line (and the delimiter) from the buffer. let cleaningRange = NSRange(location: 0, length: range.location + range.length) buffer.replaceBytes(in: cleaningRange, withBytes: nil, length: 0) return line as? String } /// Start reading from the beginning of file. open func rewind() -> Void { fileHandle?.seek(toFileOffset: 0) buffer.length = 0 atEOF = false } /// Close the underlying file. No reading must be done after calling this method. open func close() -> Void { fileHandle?.closeFile() } } // Implement `SequenceType` for `TextFileStreamReader` extension TextFileStreamReader : Sequence { /// - Returns: A generator to be used for iterating over a `TextFileStreamReader` object. public func makeIterator() -> AnyIterator<String> { return AnyIterator { return self.nextLine() } } }
mit
46fb95a15cc0676970cff00a38043e80
33.242291
109
0.608645
4.604858
false
false
false
false
SmallElephant/FESwift
3-StringExtension/3-StringExtension/main.swift
1
809
// // main.swift // 3-StringExtension // // Created by FlyElephant on 16/6/11. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation var str="My name is FlyElephant" //start var char=str.characters[str.startIndex] print("\(char)") //middle var advance=str.characters[str.startIndex.advancedBy(3)] print("\(advance)") //end var end=str.characters[str.endIndex.predecessor()] print("\(end)") var startIndex=str.startIndex.advancedBy(0) var endIndex=str.startIndex.advancedBy(6) var rangeContent=str[Range(startIndex...endIndex)] print("\(rangeContent)") //Extension FlyElephant var exChar:Character=str[0] print("Extension:\(exChar)") var stContent:String=str[3] print("Extension:\(stContent)") var range=Range(11...21) var strRange=str[range] print("Extension:\(strRange)")
mit
9cbc7a183db0ded59af73288c355f28f
20.783784
56
0.736973
3.330579
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Services/KeyboardMovable.swift
1
5141
// // KeyboardMovable.swift // CleanStore // // Created by hoi on 14/6/17. // Copyright © 2017 hoi. All rights reserved. // import Foundation import ObjectiveC import UIKit struct KeyboardMovableKeys { static var keyboardShowObserver = "km_keyboardShowObserver" static var keyboardHideObserver = "km_keyboardHideObserver" } protocol KeyboardMovable: class { var scrollAbleView: UIScrollView? { get } var selectedField: UITextField? { get } var offset: CGFloat { get set } } extension KeyboardMovable where Self: UIViewController { var notificationCenter: NotificationCenter { return .default } var keyboardShowObserver: NSObjectProtocol? { get { return objc_getAssociatedObject(self, &KeyboardMovableKeys.keyboardShowObserver) as? NSObjectProtocol } set (newValue) { objc_setAssociatedObject(self, &KeyboardMovableKeys.keyboardShowObserver, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } var keyboardHideObserver: NSObjectProtocol? { get { return objc_getAssociatedObject(self, &KeyboardMovableKeys.keyboardHideObserver) as? NSObjectProtocol } set (newValue) { objc_setAssociatedObject(self, &KeyboardMovableKeys.keyboardHideObserver, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } func initKeyboardMover() { keyboardShowObserver = notificationCenter.addObserver(forName: NSNotification.Name.UIKeyboardWillShow, object: nil, queue: nil) { notification in self.keyboardWillShow(notification) } keyboardHideObserver = notificationCenter.addObserver(forName: NSNotification.Name.UIKeyboardWillHide, object: nil, queue: nil) { notification in self.keyboardWillHide(notification) } } func destroyKeyboardMover() { if let showObserver = keyboardShowObserver { notificationCenter.removeObserver(showObserver) } if let hideObserver = keyboardHideObserver { notificationCenter.removeObserver(hideObserver) } } func keyboardWillShow(_ notification: Notification) { guard let info:NSDictionary = (notification as NSNotification).userInfo as NSDictionary? else { return } let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue let keyboardHeight:CGFloat = keyboardSize.height animate(directionUp: true, keyboardHeight: keyboardHeight) } func keyboardWillHide(_ notification: Notification) { guard let info:NSDictionary = (notification as NSNotification).userInfo as NSDictionary? else { return } let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue let keyboardHeight: CGFloat = keyboardSize.height animate(directionUp: false, keyboardHeight: keyboardHeight) } func animate(directionUp: Bool, keyboardHeight: CGFloat) { guard let selectedField = selectedField else { print("KEYBOARD MOVER: MUST PROVIDE A SELECTED FIELD: ABORTING.") return } var textFieldFrame: CGRect = selectedField.frame var textFieldCenter: CGPoint = selectedField.center if let superView = selectedField.superview, superView != view { textFieldFrame = superView.convert(selectedField.frame, to: view) textFieldCenter = superView.convert(selectedField.center, to: view) } let fieldPoint = CGPoint(x: 0, y: textFieldFrame.origin.y + textFieldFrame.size.height) let visibleRect = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - keyboardHeight) if (visibleRect.contains(fieldPoint)) { print("FIELD VISIBLE: NOT MOVING") } else { //Reset frame view print("FIELD NOT VISIBLE: MOVING") view.frame = view.frame.offsetBy(dx: 0, dy: -offset) UIView.animate(withDuration: 0.35, delay: 0, options: UIViewAnimationOptions(), animations: { if directionUp { let centerInvisibleRect = CGPoint(x: visibleRect.width / 2, y: visibleRect.height / 2) let y1 = centerInvisibleRect.y let y2 = textFieldCenter.y var offset = y1 - y2 if -offset > keyboardHeight { offset = -keyboardHeight } self.offset = offset self.view.frame = self.view.frame.offsetBy(dx: 0, dy: self.offset) } else { self.offset = 0.0 } }, completion: nil) } } }
mit
745d07b756df74e2691e6b9792d10c6c
31.738854
153
0.602724
5.439153
false
false
false
false
OscarSwanros/swift
benchmark/single-source/StrToInt.swift
10
2014
//===--- StrToInt.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of String to Int conversion. // It is reported to be very slow: <rdar://problem/17255477> import TestsUtils public let StrToInt = BenchmarkInfo( name: "StrToInt", runFunction: run_StrToInt, tags: [.validation, .api, .String]) @inline(never) public func run_StrToInt(_ N: Int) { // 64 numbers from -500_000 to 500_000 generated randomly let input = ["-237392", "293715", "126809", "333779", "-362824", "144198", "-394973", "-163669", "-7236", "376965", "-400783", "-118670", "454728", "-38915", "136285", "-448481", "-499684", "68298", "382671", "105432", "-38385", "39422", "-267849", "-439886", "292690", "87017", "404692", "27692", "486408", "336482", "-67850", "56414", "-340902", "-391782", "414778", "-494338", "-413017", "-377452", "-300681", "170194", "428941", "-291665", "89331", "329496", "-364449", "272843", "-10688", "142542", "-417439", "167337", "96598", "-264104", "-186029", "98480", "-316727", "483808", "300149", "-405877", "-98938", "283685", "-247856", "-46975", "346060", "160085",] let ref_result = 517492 func DoOneIter(_ arr: [String]) -> Int { var r = 0 for n in arr { r += Int(n)! } if r < 0 { r = -r } return r } var res = Int.max for _ in 1...1000*N { res = res & DoOneIter(input) } CheckResults(res == ref_result) }
apache-2.0
ba1cc0f9ee7d9db141b2512b12972155
37.730769
80
0.531778
3.454545
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI/Model/Study.swift
1
2316
import Foundation import CoreData import Decodable @objc(Study) open class Study: _Study { // Custom logic goes here. class func decodeJSON(_ JSONDict: NSDictionary, context: NSManagedObjectContext, index: Int) throws -> (Study) { guard let identifier = JSONDict["ID"] as? String else { throw APIDataManagerError.missingID } guard let study = Study.findFirstOrCreateWithDictionary(["identifier": identifier], context: context) as? Study else { throw APIDataManagerError.modelCreationFailed } study.identifier = try JSONDict => "ID" study.thumbnailSource = try JSONDict => "thumbnailSource" study.studyIndex = Int32(index) if let thumbSource = study.thumbnailSource { study.imageSource = thumbSource.replacingOccurrences(of: "SMALL", with: "") } let studyDescription: String = try JSONDict => "description" study.descriptionText = studyDescription.stringByDecodingHTMLEntities study.thumbnailAltText = nullOrString(try JSONDict => "thumbnailAltText") study.studyType = try JSONDict => "type" study.bibleIndex = try JSONDict => "bibleIndex" let studyTitle: String = try JSONDict => "title" study.title = studyTitle.stringByDecodingHTMLEntities study.podcastLink = nullOrString(try JSONDict => "podcastLink") study.averageRating = nullOrString(try JSONDict => "averageRating") study.lessonCount = try JSONDict => "lessonCount" study.url = nullOrString(try JSONDict => "url") if let topicsArray: [NSDictionary] = try JSONDict => "topics" as? [NSDictionary] { //Then lets process the topics var myTopics = Set<Topic>() topicsArray.forEach({ (topicJSONDict) -> () in do { if let topic = try Topic.decodeJSON(topicJSONDict, context: context) { myTopics.insert(topic) } } catch let error { logger.error("Error decoding Topic \(error)... Skippping...") } }) study.topics = myTopics } return study } }
mit
0570728fa8287c40499e91b027d10ae9
36.354839
126
0.593264
5.158129
false
false
false
false
barankaraoguzzz/FastOnBoarding
FOView/Classes/FOAnimation.swift
1
1132
// // FOAnimation.swift // FastOnBoarding_Example // // Created by Baran on 4.04.2018. // Copyright © 2018 CocoaPods. All rights reserved. // import Foundation import UIKit class FOAnimation { let animation = CATransition() internal func addAnimation(_ animationStyle : AnimationStyle, view: UIView, subTypeStyle: subTypeStyle) { animation.duration = 1.0 animation.startProgress = 0.0 animation.endProgress = 1.0 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) animation.type = animationStyle.rawValue switch subTypeStyle { case .up : animation.subtype = kCATransitionFromBottom case .down : animation.subtype = kCATransitionFromTop case .right: animation.subtype = kCATransitionFromLeft case .left : animation.subtype = kCATransitionFromRight } animation.isRemovedOnCompletion = false animation.fillMode = "extended" view.layer.add(animation, forKey: "pageFlipAnimation") } }
mit
fc1811a835cecee83ebb1d9627b77164
32.264706
109
0.647215
5.188073
false
false
false
false
kuzmir/kazimir-ios
kazimir-ios/DuoViewController.swift
1
3666
// // DuoViewController.swift // kazimir-ios // // Created by Krzysztof Cieplucha on 05/05/15. // Copyright (c) 2015 Kazimir. All rights reserved. // import UIKit enum EmbedSegueIdentifier: String { case First = "embedSeagueIdentifierFirst" case Second = "embedSeagueIdentifierSecond" } class DuoViewController: UIViewController { @IBOutlet var animator: Animator! private(set) var embededViewControllers = [UIViewController]() private(set) var visibleViewControllerIndex = 0 func getVisibleViewController() -> UIViewController { return embededViewControllers[visibleViewControllerIndex] } func getHiddenViewController() -> UIViewController { return embededViewControllers[(visibleViewControllerIndex + 1) % 2] } override func viewDidLoad() { super.viewDidLoad() let viewController = self.getVisibleViewController() self.addChildViewController(viewController) self.view.addSubview(viewController.view) self.setNavigationItem(viewController.navigationItem) viewController.didMoveToParentViewController(self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { super.prepareForSegue(segue, sender: sender) switch (segue.identifier!) { case EmbedSegueIdentifier.First.rawValue, EmbedSegueIdentifier.Second.rawValue: let embededViewController = segue.destinationViewController as! UIViewController self.embededViewControllers.append(embededViewController) default: embededViewControllers[visibleViewControllerIndex].prepareForSegue(segue, sender: sender) } } override func awakeFromNib() { super.awakeFromNib() performSegueWithIdentifier(EmbedSegueIdentifier.First.rawValue, sender: self) performSegueWithIdentifier(EmbedSegueIdentifier.Second.rawValue, sender: self) } private func setNavigationItem(navigationItem :UINavigationItem) { self.navigationItem.title = navigationItem.title self.navigationItem.leftBarButtonItem = navigationItem.leftBarButtonItem self.navigationItem.rightBarButtonItem = navigationItem.rightBarButtonItem self.navigationItem.hidesBackButton = navigationItem.hidesBackButton } func switchViews() { let visibleViewController = self.getVisibleViewController() let hiddenViewController = self.getHiddenViewController() self.addChildViewController(hiddenViewController) self.view.addSubview(hiddenViewController.view) animator.animate(fromViewController: visibleViewController, toViewController: hiddenViewController) { (finished) -> Void in if (finished) { visibleViewController.willMoveToParentViewController(nil) visibleViewController.view.removeFromSuperview() visibleViewController.removeFromParentViewController() hiddenViewController.didMoveToParentViewController(self) self.setNavigationItem(hiddenViewController.navigationItem) self.visibleViewControllerIndex = (self.visibleViewControllerIndex + 1) % 2 } else { hiddenViewController.view.removeFromSuperview() hiddenViewController.removeFromParentViewController() } } } } extension DuoViewController: BarTintColorChanging { func getBarTintColor() -> UIColor { return (self.getVisibleViewController() as! BarTintColorChanging).getBarTintColor() } }
apache-2.0
75dcd0fda8cb2381583a68f49220618b
37.589474
131
0.705401
5.980424
false
false
false
false
iWeslie/Ant
Ant/Ant/Me/Login/Register.swift
2
6488
// // LoginWithPwdVC.swift // Ant // // Created by Weslie on 2017/7/11. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit import SVProgressHUD class Register: UIViewController { fileprivate var countDownTimer: Timer? @IBOutlet weak var phoneNumber: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var idNumber: UITextField! @IBOutlet weak var pwdVisible: UIButton! @IBOutlet weak var sendIDNum: UIButton! fileprivate var remainingSeconds: Int = 0 { willSet { sendIDNum.setTitle("重新发送\(newValue)秒", for: .normal) if newValue <= 0 { sendIDNum.setTitle("发送验证码", for: .normal) isCounting = false } } } fileprivate var isCounting = false { willSet { if newValue { countDownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true) remainingSeconds = 60 } else { countDownTimer?.invalidate() countDownTimer = nil } sendIDNum.isEnabled = !newValue } } @objc fileprivate func updateTime() { remainingSeconds -= 1 } @IBOutlet weak var NavBar: UINavigationBar! @IBAction func register(_ sender: UIButton) { if phoneNumber.text == "" { self.presentHintMessage(target: self, hintMessgae: "请输入手机号码") } else if phoneNumber.text?.isValidePhoneNumber == false { self.presentHintMessage(target: self, hintMessgae: "请输入正确的手机号码") } else if password.text == "" { self.presentHintMessage(target: self, hintMessgae: "请输入密码") } else if idNumber.text == "" { self.presentHintMessage(target: self, hintMessgae: "请输入验证码") } else { if phoneNumber.text!.isValidePhoneNumber == true { SMSSDK.commitVerificationCode(idNumber.text!, phoneNumber: phoneNumber.text!, zone: "86", result: { (error: Error?) in if error != nil { self.presentHintMessage(target: self, hintMessgae: "验证码输入错误") } else { weak var weakSelf = self NetWorkTool.shareInstance.UserRegister((weakSelf?.phoneNumber.text!)!, password: (weakSelf?.password.text!)!, finished: { (userInfo, error) in if error == nil { let loginStaus = userInfo?["code"] as? String if loginStaus == "200" { //存储手机号码和密码 sender.saveUserData(phone: self.phoneNumber.text!, password: self.password.text!, token: "") //存储数据到服务器 let alert = UIAlertController(title: "提示", message: "注册成功", preferredStyle: .alert) let ok = UIAlertAction(title: "好的", style: .default, handler: { (_) in //登陆界面销毁 weakSelf?.navigationController?.popToRootViewController(animated: true) }) alert.addAction(ok) weakSelf?.present(alert, animated: true, completion: nil) }else{ SVProgressHUD.showError(withStatus: userInfo?["msg"]! as! String) } } }) } }) } else { self.presentHintMessage(target: self, hintMessgae: "请输入正确的手机号码") } } } @IBAction func back(_ sender: UIBarButtonItem) { self.navigationController?.popViewController(animated: true) } @IBOutlet weak var bg1: UIImageView! @IBOutlet weak var bg2: UIImageView! @IBOutlet weak var bg3: UIImageView! override func viewDidLoad() { super.viewDidLoad() loadCustomAttrs() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { view.endEditing(true) } override func viewWillDisappear(_ animated: Bool) { self.isCounting = false } func loadCustomAttrs() { phoneNumber.changeColor() phoneNumber.delegate = self password.changeColor() password.delegate = self idNumber.changeColor() sendIDNum.changeBtnStyle() sendIDNum.addTarget(self, action: #selector(sendSecurityCode), for: .touchUpInside) pwdVisible.addTarget(self, action: #selector(passwordVisible), for: .touchUpInside) bg1.changeAttrs() bg2.changeAttrs() bg3.changeAttrs() NavBar.subviews[0].alpha = 0.5 } } extension Register { func passwordVisible() { password.isSecureTextEntry = !password.isSecureTextEntry if password.isSecureTextEntry == true { self.pwdVisible.setImage(#imageLiteral(resourceName: "login_icon_passwordeye_close"), for: .normal) } else { self.pwdVisible.setImage(#imageLiteral(resourceName: "login_icon_passwordeye_open"), for: .normal) } } func sendSecurityCode() { if phoneNumber.text == "" { self.presentHintMessage(target: self, hintMessgae: "请输入手机号码") } SMSSDK.getVerificationCode(by: SMSGetCodeMethodSMS, phoneNumber: phoneNumber.text, zone: "86", result: { (error: Error?) in if error != nil { print(error as Any) } else { self.phoneNumber.endEditing(true) self.presentHintMessage(target: self, hintMessgae: "验证码发送成功") self.isCounting = true } }) } } extension Register: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { password.endEditing(true) idNumber.endEditing(true) return true } }
apache-2.0
c16547edb1d0f6d84d58a7215bee49d5
32.972973
166
0.541289
4.956625
false
false
false
false
yanil3500/acoustiCast
AcoustiCastr/AcoustiCastr/OptionsViewController.swift
1
2591
// // MenuViewController.swift // AcoustiCastr // // Created by Elyanil Liranzo Castro on 4/23/17. // Copyright © 2017 Elyanil Liranzo Castro. All rights reserved. // import UIKit class OptionsViewController: UIViewController { var options = [Options]() var rowHeight = 50 @IBOutlet weak var menuView: UITableView! override func viewDidLoad() { let myPodcasts = Options("My Podcasts", "MyPodcastsViewController", "[email protected]") let discover = Options("Discover", "DiscoverViewController", "[email protected]" ) options.append(myPodcasts) options.append(discover) super.viewDidLoad() self.menuView.delegate = self self.menuView.dataSource = self //Register let optionNib = UINib(nibName: OptionsViewCell.identifier, bundle: nil) self.menuView.register(optionNib, forCellReuseIdentifier: OptionsViewCell.identifier) self.menuView.estimatedRowHeight = CGFloat(rowHeight) self.menuView.rowHeight = UITableViewAutomaticDimension // Do any additional setup after loading the view. } } extension OptionsViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return options.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: OptionsViewCell.identifier, for: indexPath) as! OptionsViewCell cell.optionName.text = options[indexPath.row].optionName cell.icon.image = options[indexPath.row].optionIcon return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: options[indexPath.row].optionSegueIdentifier, sender: nil) } } extension OptionsViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if segue.identifier == MyPodcastsViewController.identifier { let backItem = UIBarButtonItem() backItem.title = " " navigationItem.backBarButtonItem = backItem } else if segue.identifier == DiscoverViewController.identifier { let backItem = UIBarButtonItem() backItem.title = " " navigationItem.backBarButtonItem = backItem } } }
mit
b5b070f40ad1e82415af9e8bcb70504f
33.533333
128
0.674903
5.138889
false
false
false
false
durre/swux
Sources/FluxStore.swift
1
1032
import Foundation class FluxStore { var dispatchId: Int? var currentId: Int = 0 var listeners: Dictionary<Int, (ChangeEvent) -> Void> init() { currentId = 0 listeners = [:] dispatchId = nil } // Remove any references func detachStore() { if let id = dispatchId { Dispatcher.sharedInstance.unregister(id) } listeners = [:] dispatchId = nil } func removeListener(id: Int) { listeners.removeValueForKey(id) } func emit(event: ChangeEvent) { dispatch_async(dispatch_get_main_queue(), { () -> Void in for (_, listener) in self.listeners { listener(event) } }) } func addListener(callback: (ChangeEvent) -> Void) -> Int { let returnId = self.currentId dispatch_async(dispatch_get_main_queue(), { () -> Void in self.listeners[returnId] = callback self.currentId++ }) return returnId } }
apache-2.0
15114d233f1df2c0c6bca35f0b232d67
21.933333
65
0.542636
4.486957
false
false
false
false
ivanbruel/SwipeIt
SwipeIt/Models/Enums/Distinguished.swift
1
343
// // Distinguished.swift // Reddit // // Created by Ivan Bruel on 27/04/16. // Copyright © 2016 Faber Ventures. All rights reserved. // import Foundation // swiftlint:disable type_name enum Distinguished: String { case Yes = "yes" case No = "no" case Admin = "admin" case Special = "special" case Moderator = "moderator" }
mit
f02c0405461fc78c2bf3744f15ac2385
16.1
57
0.666667
3.288462
false
false
false
false
GreatfeatServices/gf-mobile-app
chris-laid/ios-exam/NewsFeed/Essentials.swift
2
730
// // Essentials.swift // NewsFeed // // Created by Chrisler Laid on 30/06/2017. // Copyright © 2017 Joio. All rights reserved. // import Foundation import UIKit class Essentials { func downloadImageFromUrl(imageUrlString: String) -> UIImage { var dataImage = UIImage() if let url = NSURL(string: imageUrlString) { if let imageData = NSData(contentsOf: url as URL) { let str64 = imageData.base64EncodedData(options: .lineLength64Characters) let data: NSData = NSData(base64Encoded: str64 , options: .ignoreUnknownCharacters)! dataImage = UIImage(data: data as Data)! } } return dataImage } }
apache-2.0
b0a53b52b9c071270708e78545525157
26
100
0.611797
4.313609
false
false
false
false
exoplatform/exo-ios
Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift
1
7027
// // KFImageOptions.swift // Kingfisher // // Created by onevcat on 2020/12/20. // // Copyright (c) 2020 Wei Wang <[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(SwiftUI) && canImport(Combine) import SwiftUI // MARK: - KFImage creating. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) extension KFImage { /// Creates a `KFImage` for a given `Source`. /// - Parameters: /// - source: The `Source` object defines data information from network or a data provider. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the /// wrapped value from outside. /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. public static func source( _ source: Source?, isLoaded: Binding<Bool> = .constant(false) ) -> KFImage { KFImage(source: source, isLoaded: isLoaded) } /// Creates a `KFImage` for a given `Resource`. /// - Parameters: /// - source: The `Resource` object defines data information like key or URL. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the /// wrapped value from outside. /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. public static func resource( _ resource: Resource?, isLoaded: Binding<Bool> = .constant(false) ) -> KFImage { source(resource?.convertToSource(), isLoaded: isLoaded) } /// Creates a `KFImage` for a given `URL`. /// - Parameters: /// - url: The URL where the image should be downloaded. /// - cacheKey: The key used to store the downloaded image in cache. /// If `nil`, the `absoluteString` of `url` is used as the cache key. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the /// wrapped value from outside. /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. public static func url( _ url: URL?, cacheKey: String? = nil, isLoaded: Binding<Bool> = .constant(false) ) -> KFImage { source(url?.convertToSource(overrideCacheKey: cacheKey), isLoaded: isLoaded) } /// Creates a `KFImage` for a given `ImageDataProvider`. /// - Parameters: /// - provider: The `ImageDataProvider` object contains information about the data. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the /// wrapped value from outside. /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. public static func dataProvider( _ provider: ImageDataProvider?, isLoaded: Binding<Bool> = .constant(false) ) -> KFImage { source(provider?.convertToSource(), isLoaded: isLoaded) } /// Creates a builder for some given raw data and a cache key. /// - Parameters: /// - data: The data object from which the image should be created. /// - cacheKey: The key used to store the downloaded image in cache. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the /// wrapped value from outside. /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. public static func data( _ data: Data?, cacheKey: String, isLoaded: Binding<Bool> = .constant(false) ) -> KFImage { if let data = data { return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey), isLoaded: isLoaded) } else { return dataProvider(nil, isLoaded: isLoaded) } } } @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) extension KFImage { /// Sets a placeholder `View` which shows when loading the image. /// - Parameter content: A view that describes the placeholder. /// - Returns: A `KFImage` view that contains `content` as its placeholder. public func placeholder<Content: View>(@ViewBuilder _ content: () -> Content) -> KFImage { let v = content() var result = self result.context.placeholder = AnyView(v) return result } /// Sets cancelling the download task bound to `self` when the view disappearing. /// - Parameter flag: Whether cancel the task or not. /// - Returns: A `KFImage` view that cancels downloading task when disappears. public func cancelOnDisappear(_ flag: Bool) -> KFImage { var result = self result.context.cancelOnDisappear = flag return result } /// Sets a fade transition for the image task. /// - Parameter duration: The duration of the fade transition. /// - Returns: A `KFImage` with changes applied. /// /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. /// The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KFImage`. public func fade(duration: TimeInterval) -> KFImage { context.binder.options.transition = .fade(duration) return self } } #endif
lgpl-3.0
09664c6cbd2a6bde4578edce1d144274
47.130137
114
0.659172
4.408407
false
false
false
false
reesemclean/PixelSolver
PixelSolver/PixelSolver-Logic/Solution.swift
1
4216
// // File.swift // PixelSolver // // Created by Reese McLean on 12/27/14. // Copyright (c) 2014 Lunchbox Apps. All rights reserved. // import Foundation public struct Solution: Equatable { public let lines: [SolutionLine] public init(numberOfRows: Int, numberOfColumns: Int) { self.lines = Array(count: numberOfRows, repeatedValue: SolutionLine(numberOfCells: numberOfColumns)) } public init(lines: [SolutionLine]) { self.lines = lines } var solved: Bool { return self.lines.reduce(true, combine: { (overallStatus: Bool, line: SolutionLine) in return overallStatus && line.solved }) } public func equalToSolutionFromPuzzleFormat(puzzleFormatString: String) -> Bool { let lines = puzzleFormatString.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) if let solutionLinesFromPuzzleFormat = parseSolutionLinesFromPuzzleFormatString(lines) { if (solutionLinesFromPuzzleFormat.count != self.lines.count) { return false } for index in Range(start: 0, end: solutionLinesFromPuzzleFormat.count) { let solutionLineFromPuzzleFormatAsString = solutionLinesFromPuzzleFormat[index] let solutionItems = solutionLineFromPuzzleFormatAsString.componentsSeparatedByString(",") let solutionLineFromSelf = self.lines[index] if (solutionLineFromSelf.cellStatuses.count != solutionItems.count) { return false } for itemIndex in Range(start: 0, end: solutionLineFromSelf.cellStatuses.count) { let cellStatus = solutionLineFromSelf.cellStatuses[itemIndex] let statusFromPuzzleFormat = solutionItems[itemIndex] switch cellStatus { case .Unknown: return false case .Boxed: if (statusFromPuzzleFormat != "#") { return false } case .Space: if (statusFromPuzzleFormat != "-") { return false } } } } } else { return false } return true } } public struct SolutionLine: Equatable { public let cellStatuses: [CellStatus] init(numberOfCells: Int) { self.cellStatuses = Array(count: numberOfCells, repeatedValue: .Unknown) } var solved: Bool { return self.cellStatuses.reduce(true, combine: { (overallStatus: Bool, cellStatus: CellStatus) in return overallStatus && cellStatus != .Unknown }) } } public enum CellStatus { case Unknown case Boxed case Space } public func ==(lhs: Solution, rhs: Solution) -> Bool { if lhs.lines.count != rhs.lines.count { return false } return reduce(Zip2(lhs.lines, rhs.lines), true, { (overallStatus: Bool, solutionTuple: (SolutionLine, SolutionLine)) -> Bool in let (leftSolutionLine, rightSolutionLine) = solutionTuple return overallStatus && leftSolutionLine == rightSolutionLine }) } public func ==(lhs: SolutionLine, rhs: SolutionLine) -> Bool { if lhs.cellStatuses.count != rhs.cellStatuses.count { return false } return reduce(Zip2(lhs.cellStatuses, rhs.cellStatuses), true, { (overallStatus: Bool, statusTuple: (CellStatus, CellStatus)) -> Bool in let (leftStatus, rightStatus) = statusTuple return overallStatus && leftStatus == rightStatus }) }
mit
64635569f837be465cac03439bdaaa59
26.92053
139
0.531784
5.46114
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00119-swift-dependentmembertype-get.swift
1
1489
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func sr<ml>() -> (ml, ml -> ml) -> ml { a sr a.sr = { } { ml) { ih } } protocol sr { } class a: sr{ class func sr {} class w { } class n { func ji((x, n))(w: (x, f)) { } } func n<x: b, ed y nm<ed> == x.x.n>(rq : x) -> ed? { fe (w : ed?) k rq { r n a = w { } } } func kj(q: ih) -> <ed>(() -> ed) -> ih { } func w(a: x, x: x) -> (((x, x) -> x) -> x) { qp { } } func ji(r: (((x, x) -> x) -> x)) -> x { qp r({ }) } func w<ed>() { t ji { } } protocol g ed : m>(ji: ed) { } protocol w { } class ji<ih : n, sr : n y ih.ml == sr> : w po n<a { t n { } } t x<ed> { } protocol g { } class nm { func a() -> ih { } } class i: nm, g { qp func a() -> ih { } func n() -> ih { } } func x<ed y ed: g, ed: nm>(rq: ed) { } struct n<a : b> { } func w<a>() -> [n<a>] { } protocol g { } struct nm : g { } struct i<ed, ml: g y ed.i == ml> { } protocol w { } protocol ji : w { } protocol n : w { } protocol a { } struct x : a { } func sr<sr : ji, ts : a y ts.sr == sr> (sr: ts) { } func ji { } struct n<ih : ji
apache-2.0
ecb15330261bbbddd5661b8d6c7d0373
15.010753
79
0.491605
2.477537
false
false
false
false
rnystrom/GitHawk
Classes/Issues/Request/IssueRequestModel.swift
1
4493
// // IssueRequestModel.swift // Freetime // // Created by Ryan Nystrom on 7/12/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit import StyledTextKit import DateAgo final class IssueRequestModel: ListDiffable { enum Event { case assigned case unassigned case reviewRequested case reviewRequestRemoved } let id: String let actor: String let user: String let date: Date let event: Event let string: StyledTextRenderer init( id: String, actor: String, user: String, date: Date, event: Event, contentSizeCategory: UIContentSizeCategory, width: CGFloat ) { self.id = id self.actor = actor self.user = user self.date = date self.event = event let styledString: StyledTextString if actor == user { styledString = IssueRequestModel.buildSelfString( user: actor, date: date, event: event ) } else { styledString = IssueRequestModel.buildString( actor: actor, user: user, date: date, event: event ) } self.string = StyledTextRenderer( string: styledString, contentSizeCategory: contentSizeCategory, inset: UIEdgeInsets( top: Styles.Sizes.inlineSpacing, left: 0, bottom: Styles.Sizes.inlineSpacing, right: 0 ) ).warm(width: width) } static private func buildSelfString( user: String, date: Date, event: Event ) -> StyledTextString { let phrase: String switch event { case .assigned: phrase = NSLocalizedString(" self-assigned this", comment: "") case .unassigned: phrase = NSLocalizedString(" removed their assignment", comment: "") case .reviewRequested: phrase = NSLocalizedString(" self-requested a review", comment: "") case .reviewRequestRemoved: phrase = NSLocalizedString(" removed their request for review", comment: "") } let builder = StyledTextBuilder(styledText: StyledText( style: Styles.Text.secondary.with(foreground: Styles.Colors.Gray.medium.color) )) .save() .add(styledText: StyledText(text: user, style: Styles.Text.secondaryBold.with(attributes: [ MarkdownAttribute.username: user, .foregroundColor: Styles.Colors.Gray.dark.color ]) )) .restore() .add(text: phrase) .add(text: " \(date.agoString(.long))", attributes: [MarkdownAttribute.details: DateDetailsFormatter().string(from: date)]) return builder.build() } static private func buildString( actor: String, user: String, date: Date, event: Event ) -> StyledTextString { let phrase: String switch event { case .assigned: phrase = NSLocalizedString(" assigned", comment: "") case .unassigned: phrase = NSLocalizedString(" unassigned", comment: "") case .reviewRequested: phrase = NSLocalizedString(" requested", comment: "") case .reviewRequestRemoved: phrase = NSLocalizedString(" removed", comment: "") } let builder = StyledTextBuilder(styledText: StyledText( style: Styles.Text.secondary.with(foreground: Styles.Colors.Gray.medium.color) )) .save() .add(styledText: StyledText(text: actor, style: Styles.Text.secondaryBold.with(attributes: [ MarkdownAttribute.username: actor, .foregroundColor: Styles.Colors.Gray.dark.color ]) )) .restore() .add(text: phrase) .save() .add(styledText: StyledText(text: " \(user)", style: Styles.Text.secondaryBold)) .restore() .add(text: " \(date.agoString(.long))", attributes: [MarkdownAttribute.details: DateDetailsFormatter().string(from: date)]) return builder.build() } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return id as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return true } }
mit
d5887afbc248a42643c26280f8ed993c
29.767123
135
0.577248
4.963536
false
false
false
false
adrfer/swift
validation-test/compiler_crashers_fixed/27135-swift-patternbindingdecl-setpattern.swift
13
2277
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {{{ let : T:a<T where f enum b {struct A enum B}protocol a{ let a=f:A{var" let a { let c{ class d{{ }typealias d {func f g class A { struct d<S where B{ let : N < where h:a var f _}}}} struct S<T where g:d {{{ class B{ var b{ <f {let:d { class b:d{ " { var b{ let : d:A struct d:d { B{ struct B<T where " {{a enum B<T where f: T> : a{var b=Swift.h =1 func f g < where " "" {}struct B<T where f: d< where B : T.h =1 < where h:A func f g:a func let a = " " class d func g a<T {var b { class B<f=1 var b{ var f= let : d:P { class A class A class A{ class A { }}protocol a= func aA} "" class b<f= struct B<T> : { B<T where B{var b:e}}struct S<f:P { let a = " { func foo}typealias d<T where f func aA} struct S<T where " { let : T:e let:d{var" var b { " func a <T {let:d< {func a{{let:A }}} < where h: d B{{ " " " " func a=1 class A var b{ { where =1 class b<T where a = f: a= protocol B:a = " [ 1 {{{ protocol B{ let a func < where h: { class A {}} protocol a{var b {b{{ protocol B:a func struct S<T where =f: { { enum :a<T where g:e let:d struct S<T { func A protocol B{var f= let c{ enum B:P { enum S<T where B : d where a func let a = " {var b:d where g:a<{{var"""" class B<f:A struct S<h {var b {}typealias d< where h: d where f class d<T where g:d<T where g struct B{{ enum b { protocol B{ protocol a class A class B{ class A { { let a<T where B{ let : d:P { struct A enum S<f:d:e}}struct S<T where h:e class d let a func class A<T where f=Swift.E let a = f:d { func g a enum B<T where B : a{ func g a<T where g:d where g:d func a class a<T where " [ 1 class A {var b:d {b<T:a{ }protocol B} class d{} _}}typealias d let a {var f=1 let c{var b { class A { func aA}}}typealias d func f g:a=f:P {{ class A { protocol B} func foo}} let c<f=1 class A class {{ let : T:A{func g a{struct B{ <T { class A { class d<T where g:a var b<T where g func f g:a protocol a<T where g:d<T where h:A class A{ { class d<S where f: {{ protocol a{ class a<T.e}}}} let a{ { enum S<f class a{let:T {b {{ func g a var b:T>: T func foo} let a{ let : d:d enum B{var b{a{struct S<T:A<T <T
apache-2.0
f6587bf5ecc8dc139ac33a8a5d636d17
13.785714
87
0.620114
2.263419
false
false
false
false
adrfer/swift
test/Interpreter/repl.swift
12
4582
// RUN: %target-repl-run-simple-swift | FileCheck %s // REQUIRES: swift_repl :print_decl String // CHECK: struct String // CHECK: extension String : StringInterpolationConvertible false // CHECK: Bool = false (1,2) // CHECK: (Int, Int) = (1, 2) print(10) print(10) // CHECK: 10 // CHECK-NEXT: 10 func f() { print("Hello") } f() // CHECK: Hello 102 // CHECK: Int = 102 var x = 1 // CHECK: x : Int = 1 (x, 2) // CHECK: (Int, Int) = (1, 2) var (_, y) = (x,2) // CHECK: (_, y) : (Int, Int) = (1, 2) var aString = String() // CHECK: aString : String = "" "\n\r\t\"' abcd\u{45}\u{01}" // CHECK: "\n\r\t\"\' abcdE\u{01}" String(-1) // CHECK: String = "-1" String(-112312312) // CHECK: String = "-112312312" String(4.0) // CHECK: String = "4.0" 1 + 44 // CHECK: Int = 45{{$}} 123 . hashValue // CHECK: Int = 123{{$}} // Check that we handle unmatched parentheses in REPL. 1+1) var z = 44 +z // CHECK: Int = 44{{$}} +44 // CHECK: Int = 44{{$}} typealias Foo = Int var f1 : Foo = 1 var f44 : Foo = 44 f1 + f44 // CHECK: Foo = 45{{$}} +(f44) // CHECK: Foo = 44{{$}} 1.5 // CHECK: Double = 1.5{{$}} 1.5+2.25 // CHECK: Double = 3.75{{$}} +1.75 // CHECK: Double = 1.75{{$}} -1.75 // CHECK: Double = -1.75{{$}} func r13792487(x: Float64) -> Float64 { return x } r13792487(1234.0) // CHECK: Float64 = 1234.0{{$}} r13792487(1234) // CHECK: Float64 = 1234.0{{$}} var ab = (1, 2) // CHECK: (Int, Int) = (1, 2) var ba = (y:1, x:2) var f2 : Foo = 2 var xy = (f1, f2) // CHECK: (Foo, Foo) = (1, 2) var yx = (y:f1, x:f2) func sub(x x: Int, y: Int) -> Int { return x - y } sub(x:1, y:2) // CHECK: Int = -1 sub(x:f1, y:f2) // CHECK: Foo = -1 var array = [1, 2, 3, 4, 5] // CHECK: array : [Int] = [1, 2, 3, 4, 5] var dict = [ "Hello" : 1.5 ] // CHECK: dict : [String : Double] = ["Hello": 1.5] 0..<10 // FIXME: Disabled CHECK for Range<Int> = 0...10 until we get general printing going // FIXME: Disabled CHECK for 0...10 pending <rdar://problem/11510876> // (Implement overload resolution) // Don't crash on this. rdar://14912363 -2...-1 -2 ... -1 // r2 : Range<Int> = -2...-1 String(0) // CHECK: "0" for i in 0..<10 { print(i); } // CHECK: 0 // CHECK-NEXT: 1 // CHECK-NEXT: 2 // CHECK-NEXT: 3 // CHECK-NEXT: 4 // CHECK-NEXT: 5 // CHECK-NEXT: 6 // CHECK-NEXT: 7 // CHECK-NEXT: 8 // CHECK-NEXT: 9 for i in 0..<10 { print(i); } // CHECK: 0 // CHECK-NEXT: 1 // CHECK-NEXT: 2 // CHECK-NEXT: 3 // CHECK-NEXT: 4 // CHECK-NEXT: 5 // CHECK-NEXT: 6 // CHECK-NEXT: 7 // CHECK-NEXT: 8 // CHECK-NEXT: 9 for c in "foobar".unicodeScalars { print(c) } // CHECK: f // CHECK-NEXT: o // CHECK-NEXT: o // CHECK-NEXT: b // CHECK-NEXT: a // CHECK-NEXT: r var vec = Array<String>() // CHECK: vec : Array<String> = [] // Error recovery var a : [int] var a = [Int]() var b = a.slice[3..<5] struct Inner<T> {} struct Outer<T> { var inner : Inner<T> } Outer<Int>(inner: Inner()) // CHECK: Outer<Int> = REPL.Outer struct ContainsSlice { var slice : [Int] } ContainsSlice(slice: [1, 2, 3]) // CHECK: ContainsSlice = REPL.ContainsSlice struct ContainsGenericSlice<T> { var slice : [T] } ContainsGenericSlice(slice: [1, 2, 3]) // CHECK: ContainsGenericSlice<Int> = REPL.ContainsGenericSlice ContainsGenericSlice(slice: [(1, 2), (3, 4)]) // CHECK: ContainsGenericSlice<(Int, Int)> = REPL.ContainsGenericSlice struct ContainsContainsSlice { var containsSlice : ContainsSlice } ContainsContainsSlice(containsSlice: ContainsSlice(slice: [1, 2, 3])) // CHECK: ContainsContainsSlice = REPL.ContainsContainsSlice protocol Proto { func foo() } extension Double : Proto { func foo() { print("Double: \(self)\n", terminator: "") } } var pr : Proto = 3.14159 // CHECK: Double: 3.14159 pr.foo() // erroneous; we'll try again after adding the conformance pr = "foo" extension String : Proto { func foo() { print("String: \(self)\n", terminator: "") } } pr = "foo" // CHECK: String: foo pr.foo() var _ : ([Int]).Type = [4].dynamicType // CHECK: : ([Int]).Type var _ : (Int -> Int)? = .None // CHECK: : (Int -> Int)? func chained(f f: Int -> ()) -> Int { return 0 } chained // CHECK: : (f: Int -> ()) -> Int [chained] // CHECK: : [(f: Int -> ()) -> Int] ({97210}()) // CHECK: = 97210 true && true // CHECK: = true if ({true}()) { print("yeah1") } // CHECK: yeah1 if true && true { print("yeah2") } // CHECK: yeah2 if true && true { if true && true { print("yeah3") } } // CHECK: yeah3 if true && (true && true) { if true && (true && true) { print("yeah4") } } // CHECK: yeah4 if true && true { if true && true { print(true && true) } } // CHECK: true "ok" // CHECK: = "ok"
apache-2.0
d6c97864293d4aeca66f882aeda80291
19.455357
130
0.582497
2.64397
false
false
false
false
LoganWright/vapor
Sources/Vapor/Server/HTTPStreamServer.swift
1
2240
#if os(Linux) import Glibc #else import Darwin #endif // MARK: Byte => Character extension Character { init(_ byte: Byte) { let scalar = UnicodeScalar(byte) self.init(scalar) } } final class HTTPStreamServer<StreamType: HTTPListenerStream>: Server { var stream: StreamType! var delegate: Responder! required init(host: String, port: Int, responder: Responder) throws { stream = try StreamType(address: host, port: port) delegate = responder } func start() throws { try stream.bind() try stream.listen() do { try stream.accept(max: Int(SOMAXCONN), handler: self.handle) } catch { Log.error("Failed to accept: \(socket) error: \(error)") } } func halt() { do { try stream.close() } catch { Log.error("Failed to close stream: \(error)") } } private func handle(socket: HTTPStream) { var keepAlive = false repeat { let request: Request do { request = try socket.receive() } catch let error as HTTPStreamError where error.isClosedByPeer { return } catch { Log.error("Error receiving request: \(error)") return } let response: Response do { response = try self.delegate.respond(to: request) } catch { Log.error("Error parsing response: \(error)") return } do { try socket.send(response, keepAlive: keepAlive) } catch { Log.error("Error sending response: \(error)") } keepAlive = request.supportsKeepAlive } while keepAlive && !socket.closed do { try socket.close() } catch { Log.error("Failed to close stream: \(error)") } } } extension Request { var supportsKeepAlive: Bool { for value in headers["Connection"] ?? [] { if value.trim() == "keep-alive" { return true } } return false } }
mit
8aa78b36241e4130fed935d712d261e1
23.086022
77
0.507589
4.755839
false
false
false
false
am0oma/Swifter
SwifterCommon/SwifterAccountsClient.swift
1
4703
// // SwifterAccountsClient.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Accounts import Social class SwifterAccountsClient: SwifterClientProtocol { var credential: SwifterCredential? init(account: ACAccount) { self.credential = SwifterCredential(account: account) } func get(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let url = NSURL(string: path, relativeToURL: baseURL) var stringifiedParameters = SwifterAccountsClient.convertDictionaryValuesToStrings(parameters) let socialRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: url, parameters: stringifiedParameters) socialRequest.account = self.credential!.account! let request = SwifterHTTPRequest(request: socialRequest.preparedURLRequest()) request.parameters = parameters request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.start() } func post(path: String, baseURL: NSURL, parameters: Dictionary<String, AnyObject>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: SwifterHTTPRequest.DownloadProgressHandler?, success: SwifterHTTPRequest.SuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) { let url = NSURL(string: path, relativeToURL: baseURL) var params = parameters var postData: NSData? var postDataKey: String? if let key: AnyObject = params[Swifter.DataParameters.dataKey] { if let keyString = key as? String { postData = params[postDataKey!] as? NSData params.removeValueForKey(Swifter.DataParameters.dataKey) params.removeValueForKey(postDataKey!) } } var postDataFileName: String? if let fileName: AnyObject = params[Swifter.DataParameters.fileNameKey] { if let fileNameString = fileName as? String { postDataFileName = fileNameString params.removeValueForKey(fileNameString) } } var stringifiedParameters = SwifterAccountsClient.convertDictionaryValuesToStrings(params) let socialRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.POST, URL: url, parameters: stringifiedParameters) socialRequest.account = self.credential!.account! if postData { let fileName = postDataFileName ? postDataFileName! as String : "media.jpg" socialRequest.addMultipartData(postData!, withName: postDataKey!, type: "application/octet-stream", filename: fileName) } let request = SwifterHTTPRequest(request: socialRequest.preparedURLRequest()) request.parameters = parameters request.downloadProgressHandler = downloadProgress request.successHandler = success request.failureHandler = failure request.start() } class func convertDictionaryValuesToStrings(dictionary: Dictionary<String, AnyObject>) -> Dictionary<String, String> { var result = Dictionary<String, String>() for (key, value: AnyObject) in dictionary { result[key] = "\(value)" } return result } }
mit
571b8b65a506faa8d8e423ad9486bf35
41.754545
300
0.716139
5.3322
false
false
false
false
Vienta/kuafu
kuafu/kuafu/src/Manager/KFEventManager.swift
1
5826
// // KFEventManager.swift // kuafu // // Created by Vienta on 15/7/11. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit import EventKit private let sharedInstance = KFEventManager() class KFEventManager: NSObject { // MARK: - Property var eventStore: EKEventStore? var selectedCalendarIdentifier: String? var selectedEventIdentifier: String? var eventsAccessGranted: Bool? var customCalendarIdentifiers: NSMutableArray? // MARK: - Singleton class var sharedManager: KFEventManager { return sharedInstance } // MARK: - init override init() { super.init() self.eventStore = EKEventStore() let userDefaults = NSUserDefaults.standardUserDefaults() if (userDefaults.valueForKey(KF_EVENTKIT_ACCEES_GRANTED) != nil) { self.eventsAccessGranted = userDefaults.valueForKey(KF_EVENTKIT_ACCEES_GRANTED)?.boolValue } else { self.eventsAccessGranted = false } if (userDefaults.objectForKey(KF_EVENTKIT_SELECTED_CALENDAR) != nil) { self.selectedCalendarIdentifier = userDefaults.objectForKey(KF_EVENTKIT_SELECTED_CALENDAR) as? String } else { self.selectedCalendarIdentifier = "" } if (userDefaults.objectForKey(KF_EVENTKIT_CAL_IDENTIFIERS) != nil) { self.customCalendarIdentifiers = userDefaults.objectForKey(KF_EVENTKIT_CAL_IDENTIFIERS) as? NSMutableArray } else { self.customCalendarIdentifiers = NSMutableArray() } } // MARK: - Public Method func getLocalEventCalendars() -> NSArray { var allCalendars: NSArray! = self.eventStore?.calendarsForEntityType(EKEntityTypeEvent) var localCalendars: NSMutableArray = NSMutableArray() allCalendars.enumerateObjectsUsingBlock { (cal, idx, stop) -> Void in let calendar: EKCalendar = cal as! EKCalendar if (calendar.type.value == EKCalendarTypeLocal.value) { localCalendars.addObject(calendar) } } return localCalendars } func saveCustomCalendarIdentifier(identifier: String) -> Void { self.customCalendarIdentifiers?.addObject(identifier) NSUserDefaults.standardUserDefaults().setObject(self.customCalendarIdentifiers, forKey: KF_EVENTKIT_CAL_IDENTIFIERS) } func checkIfCalendarIsCustomWithIdentifier(identifier: String) -> Bool { var isCustomCalendar: Bool = false var customCal: NSArray = self.customCalendarIdentifiers! for (idx, value) in enumerate(customCal) { if (value as! String == identifier) { isCustomCalendar = true break } } return isCustomCalendar } func removeCalendarIdentifier(identifier: String) -> Void { self.customCalendarIdentifiers?.removeObject(identifier) NSUserDefaults.standardUserDefaults().setObject(self.customCalendarIdentifiers, forKey: KF_EVENTKIT_CAL_IDENTIFIERS) } func getEvetnsOfSelectCalendar() -> NSArray { var calendar: EKCalendar! if (self.selectedCalendarIdentifier?.isEmpty == false) { calendar = self.eventStore?.calendarWithIdentifier(self.selectedCalendarIdentifier) } var calendarArray: NSArray! if (calendar != nil) { calendarArray = [calendar] } var yearSeconds: NSTimeInterval = 365 * (60 * 60 * 24) var startDate: NSDate = NSDate(timeIntervalSinceNow: -yearSeconds) var endDate: NSDate = NSDate(timeIntervalSinceNow: yearSeconds) //TODO:这里需要修改 let predicate = self.eventStore?.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: nil) let eventsArray = self.eventStore?.eventsMatchingPredicate(predicate) as NSArray! // var uniqueEventsArray: NSMutableArray = NSMutableArray() // for (idx, event) in enumerate(eventsArray) { // let currentEvent: EKEvent = event as! EKEvent // // var eventExists: Bool = false // // if (currentEvent.recurrenceRules.isEmpty == false) { // // for (jIdx, eventIdf) in enumerate(uniqueEventsArray) { // let uniqueEvent = eventIdf as! EKEvent // if (uniqueEvent.eventIdentifier == currentEvent.eventIdentifier) { // eventExists = true // break; // } // } // } // // if eventExists == false { // uniqueEventsArray.addObject(currentEvent) // } // } //TODO:有问题 这里 // uniqueEventsArray = [uniqueEventsArray.sortedArrayUsingSelector("compareStartDateWithEvent:")] // // return uniqueEventsArray return eventsArray } func deleteEventWithIdentifier(identifier: String) -> Void { var event: EKEvent = (self.eventStore?.eventWithIdentifier(identifier))! self.eventStore?.removeEvent(event, span: EKSpanFutureEvents, error: nil) } func requestAccessToEvents() -> Void { self.eventStore?.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted, error) -> Void in if (error == nil) { let accessGranted = granted as Bool self.eventsAccessGranted = accessGranted } else { println("\(error.localizedDescription)") } }) } func loadEvents() -> NSArray { return self.getEvetnsOfSelectCalendar() } }
mit
3fa183b2073d7c06578b11ae9840279a
34.814815
124
0.614099
4.95474
false
false
false
false
karthik-ios-dev/MySwiftExtension
Example/MySwiftExtension/ViewController.swift
1
812
// // ViewController.swift // MySwiftExtension // // Created by karthik-dev on 11/27/2015. // Copyright (c) 2015 karthik-dev. All rights reserved. // import UIKit import MySwiftExtension class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() var arr = [1,2] var dict = ["one" : 1] print("Test Extension") var bundle = NSBundle() var date1 = NSDate() var date2 = NSDate() if date1 > date2{ } //date.dateByAddingWeeks(<#T##weeks: Int##Int#>) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
6b0431df86d1f878269630c154a4dde5
17.454545
58
0.543103
4.536313
false
false
false
false
xwu/swift
test/Interop/Cxx/enum/bool-enums-module-interface.swift
2
1479
// RUN: %target-swift-ide-test -print-module -module-to-print=BoolEnums -I %S/Inputs -source-filename=x -enable-cxx-interop | %FileCheck %s // TODO: these should be enums eventually (especially the enum class). // CHECK: struct Maybe : Equatable, RawRepresentable { // CHECK-NEXT: init(_ rawValue: Bool) // CHECK-NEXT: init(rawValue: Bool) // CHECK-NEXT: var rawValue: Bool // CHECK-NEXT: typealias RawValue = Bool // CHECK-NEXT: } // CHECK: var No: Maybe { get } // CHECK: var Yes: Maybe { get } // CHECK: struct BinaryNumbers : Equatable, RawRepresentable { // CHECK-NEXT: init(_ rawValue: Bool) // CHECK-NEXT: init(rawValue: Bool) // CHECK-NEXT: var rawValue: Bool // CHECK-NEXT: typealias RawValue = Bool // CHECK-NEXT: } // CHECK: var One: BinaryNumbers { get } // CHECK: var Zero: BinaryNumbers { get } // CHECK: enum EnumClass : Bool { // CHECK: init?(rawValue: Bool) // CHECK: var rawValue: Bool { get } // CHECK: typealias RawValue = Bool // CHECK: case Foo // CHECK: case Bar // CHECK: } // CHECK: struct WrapperStruct { // CHECK-NEXT: init() // TODO: where is "A" and "B"? They should be member variables. // CHECK-NEXT: struct InnerBoolEnum : Equatable, RawRepresentable { // CHECK-NEXT: init(_ rawValue: Bool) // CHECK-NEXT: init(rawValue: Bool) // CHECK-NEXT: var rawValue: Bool // CHECK-NEXT: typealias RawValue = Bool // CHECK-NEXT: } // CHECK-NEXT: }
apache-2.0
f3300b001444ddbf2a184e397782b6b4
35.975
139
0.636241
3.415704
false
false
false
false
cuappdev/podcast-ios
old/Podcast/TrendingTopicsView.swift
1
5261
// // TrendingTopicsView.swift // Podcast // // Created by Mindy Lou on 11/21/17. // Copyright © 2017 Cornell App Development. All rights reserved. // import UIKit protocol TrendingTopicsViewDelegate: class { func trendingTopicsView(trendingTopicsView: TrendingTopicsView, didSelectItemAt indexPath: IndexPath) } enum TrendingTopicsViewType { case trending case related } class TrendingTopicsView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var iconView: ImageView! var titleLabel: UILabel! var descriptionLabel: UILabel! var collectionView: UICollectionView! weak var dataSource: TopicsCollectionViewDataSource? weak var delegate: TrendingTopicsViewDelegate? let titleLabelText = "Trending Topics" let descriptionLabelText = "Find podcasts that everyone is talking about." let iconViewBorderPadding: CGFloat = 20 let iconViewLength: CGFloat = 24 let iconViewContentPadding: CGFloat = 10 let titleDescriptionLabelPadding: CGFloat = 18 let titleDescriptionLabelTopOffset: CGFloat = 22.5 let descriptionLabelTopOffset: CGFloat = 7.5 let descriptionCollectionViewPadding: CGFloat = 18 let collectionViewTopOffset: CGFloat = 14.5 let collectionViewBottomInset: CGFloat = 24 let titleLabelHeight: CGFloat = 18 let descriptionLabelHeight: CGFloat = 17 let reuseIdentifier = "Cell" init(frame: CGRect, type: TrendingTopicsViewType) { super.init(frame: frame) backgroundColor = .offWhite titleLabel = UILabel() titleLabel.font = ._20SemiboldFont() addSubview(titleLabel) titleLabel.snp.makeConstraints { make in make.top.equalToSuperview().offset(titleDescriptionLabelTopOffset) make.height.equalTo(titleLabelHeight) make.leading.equalToSuperview().offset(titleDescriptionLabelPadding) } descriptionLabel = UILabel() descriptionLabel.font = ._14RegularFont() descriptionLabel.textColor = .charcoalGrey descriptionLabel.numberOfLines = 2 descriptionLabel.textAlignment = .left addSubview(descriptionLabel) descriptionLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(descriptionLabelTopOffset) make.leading.equalTo(titleLabel.snp.leading) make.height.equalTo(descriptionLabelHeight) make.trailing.equalToSuperview().inset(iconViewBorderPadding) } collectionView = UICollectionView(frame: .zero, collectionViewLayout: RecommendedTopicsCollectionViewFlowLayout(layoutType: .relatedTopics)) collectionView.delegate = self collectionView.dataSource = self collectionView.register(RecommendedTopicsCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = .clear addSubview(collectionView) collectionView.snp.makeConstraints { make in make.width.leading.trailing.equalToSuperview() make.top.equalTo(descriptionLabel.snp.bottom).offset(collectionViewTopOffset).priority(999) make.bottom.equalToSuperview().inset(collectionViewBottomInset) } switch type { case .trending: titleLabel.text = "Trending Topics" descriptionLabel.text = "Find podcasts that everyone is talking about." case .related: titleLabel.text = "Related Topics" descriptionLabel.text = "You might be interested in these topics." } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource?.numberOfTopics(collectionView: collectionView) ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? RecommendedTopicsCollectionViewCell, let podcastTopic = dataSource?.topicForCollectionViewCell(collectionView: collectionView, dataForItemAt: indexPath.row) else { return UICollectionViewCell() } cell.setup(with: podcastTopic) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let label = UILabel() label.font = RecommendedTopicsCollectionViewCell.cellFont if let topic = dataSource?.topicForCollectionViewCell(collectionView: collectionView, dataForItemAt: indexPath.row){ label.text = topic.name } label.sizeToFit() return CGSize(width: label.frame.width + 16, height: label.frame.height + 16) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.trendingTopicsView(trendingTopicsView: self, didSelectItemAt: indexPath) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
b65d35180b26218bda04857c8e587e01
41.419355
160
0.723194
5.619658
false
false
false
false
jordane-quincy/M2_DevMobileIos
JSONProject/Demo/GeneralFormViewController.swift
1
24721
// // GeneralFormViewController.swift // Demo // // Created by MAC ISTV on 28/04/2017. // Copyright © 2017 UVHC. All rights reserved. // import UIKit class GeneralFormViewController: UIViewController, UIPickerViewDelegate, UIScrollViewDelegate { var scrollView = UIScrollView() var containerView = UIView() let realmServices = RealmServices() var jsonModel: JsonModel? = nil var customNavigationController: UINavigationController? = nil var indexOfSelectedOffer: Int = -1 var person: Person? = nil var customParent: SelectOfferViewController? = nil override func viewDidLoad() { super.viewDidLoad() // set up title of view self.title = "Général" // Setup Sortie de champs quand on clique à coté let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(GeneralFormViewController.dismissKeyboard)) self.view.addGestureRecognizer(tap) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } // For displaying scrollView override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() scrollView.frame = view.bounds containerView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height) } public func setupNavigationController (navigationController: UINavigationController){ self.customNavigationController = navigationController } public func setupPerson(person: Person) { self.person = person } public func setupCustomParent(customParent: SelectOfferViewController) { self.customParent = customParent } public func setIndexOfSelectedOffer(index: Int) { self.indexOfSelectedOffer = index } override func willMove(toParentViewController: UIViewController?) { if (toParentViewController == nil) { if (self.person == nil) { self.person = Person() self.person?.id = (self.person?.incrementID())! } if (self.person != nil && !(self.person?.isSaved)!) { let subViews = self.containerView.subviews // pour les checkbox on doit préparer les attributs var listAttributesForCheckbox = Array<Attribute>() for field in (self.jsonModel?.commonFields)! { if (field.input == InputType.check) { let tmpAttribute = Attribute(_label: field.label, _fieldName: field.fieldId, _value: "", isSpecificField: false) listAttributesForCheckbox.append(tmpAttribute) } } for view in subViews { var attributeFieldName = "" var attributeLabel = "" var attributeValue = "" if let textField = view as? CustomTextField { attributeFieldName = textField.fieldName attributeLabel = textField.label attributeValue = textField.text ?? "" } if let datePickerField = view as? CustomDatePicker { attributeFieldName = datePickerField.fieldName attributeLabel = datePickerField.label let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" attributeValue = dateFormatter.string(from: datePickerField.date) } if let pickerField = view as? CustomPickerView { attributeFieldName = pickerField.fieldName attributeLabel = pickerField.label attributeValue = pickerField.pickerData[pickerField.selectedRow(inComponent: 0)].value } if let switchButton = view as? CustomUISwitch { // on récupère l'attribut pour ce bouton là et on ajoute la valeur si on a coché le bouton if (switchButton.isOn) { let buttonFieldName = switchButton.fieldName for attributeInTable in listAttributesForCheckbox { if (buttonFieldName == attributeInTable.fieldName) { attributeInTable.value += switchButton.value + ", " } } } } if let segmentedControlField = view as? CustomSegmentedControl { attributeFieldName = segmentedControlField.fieldName attributeLabel = segmentedControlField.label attributeValue = segmentedControlField.titleForSegment(at: segmentedControlField.selectedSegmentIndex) ?? "" } // Set the attribute only if we have the attribute fieldName and Label // We can have empty attributeValue because the field can be not required if (attributeLabel != "" && attributeFieldName != "") { // On doit vérifier si on n'a pas déjà ce champs, si oui il faut juste le mettre a jour let indexOfAttribute = self.person?.getAttributeIndex(fieldName: attributeFieldName) if (indexOfAttribute! > -1) { self.person?.attributes[indexOfAttribute!].value = attributeValue } else { let attribute = Attribute(_label: attributeLabel, _fieldName: attributeFieldName, _value: attributeValue, isSpecificField: false) self.person?.addAttributeToPerson(_attribute: attribute) } } } // add checkbox attributes for attribute in listAttributesForCheckbox { // We verify if the attribute already exists or not if (attribute.value != "") { let endIndex = attribute.value.index(attribute.value.endIndex, offsetBy: -2) attribute.value = attribute.value.substring(to: endIndex) } let indexOfAttribute = self.person?.getAttributeIndex(fieldName: attribute.fieldName) if (indexOfAttribute! > -1) { self.person?.attributes[indexOfAttribute!].value = attribute.value } else { self.person?.addAttributeToPerson(_attribute: attribute) } } // Pass person to the parent self.customParent?.setupPerson(person: self.person!) } self.customParent?.setupIndexOfPreviousSelectedOffer(index: self.indexOfSelectedOffer) // Reset custom parent self.customParent = nil } } func next(_ sender: UIButton) { var champManquant: Bool = false // get data from UI for the Person Object // Test if all requiredField are completed let subViews = self.containerView.subviews if (self.person == nil) { self.person = Person() self.person?.id = (self.person?.incrementID())! } // pour les checkbox on doit préparer les attributs var listAttributesForCheckbox = Array<Attribute>() for field in (self.jsonModel?.commonFields)! { if (field.input == InputType.check) { let tmpAttribute = Attribute(_label: field.label, _fieldName: field.fieldId, _value: "", isSpecificField: false) listAttributesForCheckbox.append(tmpAttribute) } } for view in subViews { var attributeFieldName = "" var attributeLabel = "" var attributeValue = "" if let textField = view as? CustomTextField { attributeFieldName = textField.fieldName attributeLabel = textField.label attributeValue = textField.text ?? "" if(textField.required == true && attributeValue == ""){ print("Champ requis non rempli") champManquant = true } } if let datePickerField = view as? CustomDatePicker { attributeFieldName = datePickerField.fieldName attributeLabel = datePickerField.label let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" attributeValue = dateFormatter.string(from: datePickerField.date) } if let pickerField = view as? CustomPickerView { attributeFieldName = pickerField.fieldName attributeLabel = pickerField.label attributeValue = pickerField.pickerData[pickerField.selectedRow(inComponent: 0)].value } if let switchButton = view as? CustomUISwitch { // on récupère l'attribut pour ce bouton là et on ajoute la valeur si on a coché le bouton if (switchButton.isOn) { let buttonFieldName = switchButton.fieldName for attributeInTable in listAttributesForCheckbox { if (buttonFieldName == attributeInTable.fieldName) { attributeInTable.value += switchButton.value + ", " } } } } if let segmentedControlField = view as? CustomSegmentedControl { attributeFieldName = segmentedControlField.fieldName attributeLabel = segmentedControlField.label attributeValue = segmentedControlField.titleForSegment(at: segmentedControlField.selectedSegmentIndex) ?? "" } // Set the attribute only if we have the attribute fieldName and Label // We can have empty attributeValue because the field can be not required // On doit vérifier si on n'a pas déjà ce champs, si oui il faut vérifier s'il a changé ou non if (attributeLabel != "" && attributeFieldName != "") { // On doit vérifier si on n'a pas déjà ce champs, si oui il faut juste le mettre a jour let indexOfAttribute = self.person?.getAttributeIndex(fieldName: attributeFieldName) if (indexOfAttribute! > -1) { self.person?.attributes[indexOfAttribute!].value = attributeValue } else { let attribute = Attribute(_label: attributeLabel, _fieldName: attributeFieldName, _value: attributeValue, isSpecificField: false) self.person?.addAttributeToPerson(_attribute: attribute) } } } // add checkbox attributes for attribute in listAttributesForCheckbox { // We verify if the attribute already exists or not if (attribute.value != "") { let endIndex = attribute.value.index(attribute.value.endIndex, offsetBy: -2) attribute.value = attribute.value.substring(to: endIndex) } let indexOfAttribute = self.person?.getAttributeIndex(fieldName: attribute.fieldName) if (indexOfAttribute! > -1) { self.person?.attributes[indexOfAttribute!].value = attribute.value } else { self.person?.addAttributeToPerson(_attribute: attribute) } } // test if they are empty required field if(champManquant){ let alert = UIAlertController(title: "", message: "Veuillez remplir tous les champs requis (champs avec une étoile)", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Fermer", style: UIAlertActionStyle.default, handler: { action in switch action.style{ case .default: print("default") case .cancel: print("cancel") case .destructive: print("destructive") } })) self.present(alert, animated: true, completion: nil) } else { // Go to next Screen // Redirect To Next Step let specificFormView = SpecificFormViewController(nibName: "SpecificFormViewController", bundle: nil) if (self.person != nil) { specificFormView.setupPerson(person: self.person!) } specificFormView.setupNavigationController(navigationController: self.customNavigationController!) specificFormView.setIndexOfSelectedOffer(index: indexOfSelectedOffer) specificFormView.setupCustomParent(customParent: self) specificFormView.createViewFromJson(json: self.jsonModel) self.customNavigationController?.pushViewController(specificFormView, animated: true) } } func createViewFromJson(json: JsonModel?){ self.jsonModel = json // Setup interface DispatchQueue.main.async() { // Reset the view self.view.subviews.forEach({ $0.removeFromSuperview() }) // Setup scrollview self.scrollView = UIScrollView() self.scrollView.delegate = self self.view.addSubview(self.scrollView) self.containerView = UIView() self.scrollView.addSubview(self.containerView) // Ajout message let message: UILabel = UILabel(frame: CGRect(x: 20, y: 50, width: 335, height: 100.00)); message.numberOfLines = 0 message.text = "Informations générales :" self.containerView.addSubview(message) var pX = 150 for field in (json?.commonFields)! { let title: UILabel = UILabel(frame: CGRect(x: 20, y: CGFloat(pX), width: 335, height: 30.00)); title.text = field.label if (field.input == InputType.check) { title.text = field.label + " :" } if (field.required != nil && (field.required)!) { title.text = title.text! + (field.required! ? "*" : "") } self.containerView.addSubview(title) pX += 30 if(field.input == InputType.date){ let datepicker: CustomDatePicker = CustomDatePicker(frame: CGRect(x: 20, y: CGFloat(pX), width: 335, height: 100.00)); datepicker.fieldName = field.fieldId datepicker.label = field.label // test if we already have the value let attributeValue = self.person?.getAttributeValue(fieldName: field.fieldId) if (attributeValue != nil) { // On a déjà une valeur pour ce champ on le remplidonc directement let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" datepicker.date = dateFormatter.date(from: attributeValue!)! } else { datepicker.date = Date() } datepicker.datePickerMode = UIDatePickerMode.date self.containerView.addSubview(datepicker) pX += 100 } else if(field.input == InputType.text || field.input == InputType.number){ let txtField: CustomTextField = CustomTextField(frame: CGRect(x: 20, y: CGFloat(pX), width: 335, height: 30.00)); txtField.fieldName = field.fieldId txtField.label = field.label // test if we already have the value let attributeValue = self.person?.getAttributeValue(fieldName: field.fieldId) if (attributeValue != nil) { // On a déjà une valeur pour ce champ on le remplidonc directement txtField.text = attributeValue } else { txtField.placeholder = field.params?.placeholder ?? "Completer" } if(field.required == true){ txtField.required = true } self.containerView.addSubview(txtField) pX += 60 }else if(field.input == InputType.check){ for choice in (field.params?.choices)! { // switch button let switchButton = CustomUISwitch(frame: CGRect(x: 10, y: CGFloat(pX), width: 335, height: 20)) switchButton.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) switchButton.fieldName = field.fieldId switchButton.label = field.label switchButton.value = choice.label // check if the button was already checked or not if (self.person != nil) { for attribute in (self.person?.attributes)! { if (attribute.fieldName == field.fieldId) { let valueOfAttributeInArray = attribute.value.components(separatedBy: ", ") for value in valueOfAttributeInArray { if (value == choice.label) { switchButton.isOn = true } } } } } self.containerView.addSubview(switchButton) // title of the choice let choiceTitle = UILabel(frame: CGRect(x: 60, y: CGFloat(pX) + 5 , width: 335, height: 20)) choiceTitle.numberOfLines = 0 choiceTitle.text = choice.label self.containerView.addSubview(choiceTitle) pX += 30 } pX += 20 }else if(field.input == InputType.select){ // Prepare data for the picker var pickerData : [(value: String, key: String)] = [] var cpt = 0 let attributeValue = self.person?.getAttributeValue(fieldName: field.fieldId) var alreadySelectedIndex = -1 var defaultSelectedIndex = -1 for choice in (field.params?.choices)! { pickerData.append((choice.label, choice.value)) if (attributeValue != nil && attributeValue == choice.label) { alreadySelectedIndex = cpt } if (choice.selected) { defaultSelectedIndex = cpt } cpt += 1 } // Create the dateSource object let dataSource = CustomPickerViewDataSource() // Set data to the dataSource object dataSource.pickerData = pickerData // Create the picker let picker: CustomPickerView = CustomPickerView(frame: CGRect(x: 20, y: CGFloat(pX), width: 335, height: 100.00)); picker.fieldName = field.fieldId picker.label = field.label picker.pickerData = pickerData // Set up picker with dataSource object and pickerViewDelegate (self) picker.delegate = self picker.dataSource = dataSource // test if we already have the value if (alreadySelectedIndex > -1) { // On a déjà une valeur pour ce champ on le remplidonc directement picker.selectRow(alreadySelectedIndex, inComponent: 0, animated: false) } else { // if we have a selected choice by default, select it picker.selectRow(defaultSelectedIndex, inComponent: 0, animated: false) } self.containerView.addSubview(picker) pX += 100 } else if(field.input == InputType.radio){ var items : [String] = [] var cpt = 0 let attributeValue = self.person?.getAttributeValue(fieldName: field.fieldId) var alreadySelectedIndex = -1 for choice in (field.params?.choices)! { items.append(choice.label) if (attributeValue != nil && choice.label == attributeValue) { // On a déjà cette valeur alreadySelectedIndex = cpt } cpt += 1 } let segmentedControl: CustomSegmentedControl = CustomSegmentedControl(items: items); segmentedControl.fieldName = field.fieldId segmentedControl.label = field.label segmentedControl.frame = CGRect(x: 20, y: CGFloat(pX), width: 335, height: 30.00); // test if we already have the value if (alreadySelectedIndex > -1) { // On a déjà une valeur pour ce champ on le remplidonc directement segmentedControl.selectedSegmentIndex = alreadySelectedIndex } else { segmentedControl.selectedSegmentIndex = 0 } self.containerView.addSubview(segmentedControl) pX += 30 } } pX += 30 // Ajout du bouton let nextButton = UIButton(frame: CGRect(x: 140, y: CGFloat(pX), width: 335, height: 30.00)) nextButton.setTitle("Suivant >", for: .normal) nextButton.addTarget(self, action: #selector(self.next(_:)), for: .touchUpInside) nextButton.setTitleColor(UIView().tintColor, for: .normal) nextButton.backgroundColor = UIColor.clear self.containerView.addSubview(nextButton) self.scrollView.contentSize = CGSize(width: 350, height: pX + 100) } //self.view.frame.size.height = 10000 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { let customPickerView = pickerView as? CustomPickerView return customPickerView!.pickerData.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let customPickerView = pickerView as? CustomPickerView return customPickerView?.pickerData[row].value } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { } /* // 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
f2186c30010c391f1cdd743efd4ea40e
48.069583
175
0.534722
5.724026
false
false
false
false
lojals/DoorsConcept
DoorConcept/Controllers/History/HistoryInteractor.swift
1
2036
// // HistoryInteractor.swift // DoorConcept // // Created by Jorge Raul Ovalle Zuleta on 3/22/16. // Copyright © 2016 jorgeovalle. All rights reserved. // import UIKit import CoreData class HistoryInteractor { private let managedObjectContext:NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext init(){} /** Method to retrieve History for a User, check wether the current user owns the Building or not. - parameter completion: completion description (data = [History], error = error description) */ func getHistory(completion:FetchCompletionHandler){ let fetchRequest = NSFetchRequest(entityName: "History") fetchRequest.predicate = NSPredicate(format: "user == %@ OR door.building IN %@", UserService.sharedInstance.currentUser!, UserService.sharedInstance.currentUser!.buildings!) do{ let fetchResults = try managedObjectContext.executeRequest(fetchRequest) as! NSAsynchronousFetchResult let fetchBuilding = fetchResults.finalResult as! [History] completion!(data:fetchBuilding, error: nil) }catch{ completion!(data:nil,error: "CoreData error!") } } /** Method to save History on CoreData, from user/door. An user attempt to open a door - parameter door: Door datatype to be added to the History - parameter user: User datatype to be added to the History - parameter state: Transaction's state, passible (authorized/denied) */ func saveHistory(door:Door, user:User, state:String){ let history = NSEntityDescription.insertNewObjectForEntityForName("History", inManagedObjectContext: managedObjectContext) as! History history.door = door history.user = user history.state = state history.date = NSDate() do{ try managedObjectContext.save() }catch{ print("Some error inserting Door") } } }
mit
96fce264b13ae9f4fd12f77c6e57c83f
36.685185
182
0.676658
5
false
false
false
false
danielallsopp/Charts
Source/Charts/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift
15
1960
// // LineScatterCandleRadarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 29/7/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation public class LineScatterCandleRadarChartDataSet: BarLineScatterCandleBubbleChartDataSet, ILineScatterCandleRadarChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn. public var drawHorizontalHighlightIndicatorEnabled = true /// Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn. public var drawVerticalHighlightIndicatorEnabled = true /// - returns: true if horizontal highlight indicator lines are enabled (drawn) public var isHorizontalHighlightIndicatorEnabled: Bool { return drawHorizontalHighlightIndicatorEnabled } /// - returns: true if vertical highlight indicator lines are enabled (drawn) public var isVerticalHighlightIndicatorEnabled: Bool { return drawVerticalHighlightIndicatorEnabled } /// Enables / disables both vertical and horizontal highlight-indicators. /// :param: enabled public func setDrawHighlightIndicators(enabled: Bool) { drawHorizontalHighlightIndicatorEnabled = enabled drawVerticalHighlightIndicatorEnabled = enabled } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! LineScatterCandleRadarChartDataSet copy.drawHorizontalHighlightIndicatorEnabled = drawHorizontalHighlightIndicatorEnabled copy.drawVerticalHighlightIndicatorEnabled = drawVerticalHighlightIndicatorEnabled return copy } }
apache-2.0
e6efb3ec5bdb3f731fa48f5e24c1e6df
35.981132
124
0.747959
5.957447
false
false
false
false
Liqiankun/DLSwift
Swift/Swift3Three.playground/Contents.swift
1
993
//: Playground - noun: a place where people can play import UIKit import PlaygroundSupport class ViewController :UIViewController{ override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.yellow; self.view.frame = CGRect(x:0,y:0,width:300,height:400) let button: UIButton = UIButton(frame:CGRect(x:0,y:0,width:80,height:40)) button.center = self.view.center button.setTitle("Click me", for: .normal) button.setTitleColor(UIColor.red, for: .normal) button.addTarget(self, action: #selector(click), for: .touchUpInside) self.view.addSubview(button) } func click() { if self.view.backgroundColor == UIColor.blue { self.view.backgroundColor = UIColor.yellow }else{ self.view.backgroundColor = UIColor.blue } } } let viewController = ViewController() PlaygroundPage.current.liveView = viewController.view
mit
0b91ef64e2f4ad5a0d984d990b39719d
29.121212
81
0.650554
4.280172
false
false
false
false
salutis/Color-HumanInterfaceGuidelines
Color+HumanInterfaceGuidelines.swift
2
2068
// The MIT License (MIT) // // Copyright (c) 2015 Rudolf Adamkovič // // 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 extension UIColor { // Official documentation: // https://developer.apple.com/ios/human-interface-guidelines/visual-design/color/ enum AppleColor { case red case orange case yellow case green case tealBlue case blue case purple case pink } convenience init(appleColor: AppleColor) { let RGB: (red: CGFloat, green: CGFloat, blue: CGFloat) switch appleColor { case .red: RGB = (255, 59, 48) case .orange: RGB = (255, 149, 0) case .yellow: RGB = (255, 204, 0) case .green: RGB = (76, 217, 100) case .tealBlue: RGB = (90, 200, 250) case .blue: RGB = (0, 122, 255) case .purple: RGB = (88, 86, 214) case .pink: RGB = (255, 45, 85) } self.init(red: RGB.red / 255, green: RGB.green / 255, blue: RGB.blue / 255, alpha: 1) } }
mit
be79272c50df3fe00c7d3c46e6777685
35.910714
93
0.665215
4.060904
false
false
false
false
tschoffelen/vibe
Vibe/TSCVibeWindow.swift
1
2392
// // TSCVibeWindow.swift // Vibe // // Created by Thomas Schoffelen on 18/06/2016. // Copyright © 2016 thomasschoffelen. All rights reserved. // import Cocoa typealias StatsDictionary = Dictionary<String,[String:Int]> class TSCVibeWindow: NSWindow { @IBOutlet var weekGraph : NSView!; @IBOutlet var monthGraph : NSView!; @IBOutlet var weekdayGraph : NSView!; @IBOutlet var titleLabel : NSTextField?; @IBOutlet var subtitleLabel : NSTextField?; func displayStats(_ stats: StatsDictionary) { self.renderWeekGraph(stats); self.renderMonthGraph(stats); self.renderWeekdayGraph(stats); self.titleLabel?.stringValue = "\(stats["totals"]!["complete"]!) tasks completed." self.subtitleLabel?.stringValue = "\(stats["totals"]!["incomplete"]!) tasks are currently open." } internal func renderWeekGraph(_ stats: StatsDictionary) { let chartView = TSCBarChartView(frame: CGRect(x: 0,y: 0,width: self.weekGraph.frame.width, height: self.weekGraph.frame.height), barData: stats["days"]!, barColor: NSColor(red:0.14, green:0.65, blue:0.94, alpha:1.00)); chartView.autoresizingMask = [.viewHeightSizable, .viewWidthSizable]; chartView.translatesAutoresizingMaskIntoConstraints = true; self.weekGraph.addSubview(chartView); } internal func renderMonthGraph(_ stats: StatsDictionary) { let chartView = TSCBarChartView(frame: CGRect(x: 0,y: 0,width: self.monthGraph.frame.width, height: self.monthGraph.frame.height), barData: stats["months"]!, barColor: NSColor(red:0.97, green:0.25, blue:0.44, alpha:1.00)); chartView.autoresizingMask = [.viewHeightSizable, .viewWidthSizable]; chartView.translatesAutoresizingMaskIntoConstraints = true; self.monthGraph.addSubview(chartView); } internal func renderWeekdayGraph(_ stats: StatsDictionary) { let chartView = TSCBarChartView(frame: CGRect(x: 0,y: 0,width: self.weekdayGraph.frame.width, height: self.weekdayGraph.frame.height), barData: stats["weekdays"]!, barColor: NSColor(red:0.97, green:0.82, blue:0.20, alpha:1.00)); chartView.autoresizingMask = [.viewHeightSizable, .viewWidthSizable]; chartView.translatesAutoresizingMaskIntoConstraints = true; self.weekdayGraph.addSubview(chartView); } }
mit
914f5f9ba2345c9b9f7f80f7bf0d93e5
42.472727
236
0.691343
4.209507
false
false
false
false
RxSwiftCommunity/RxSwiftExt
Playground/RxSwiftExtPlayground.playground/Pages/pausable.xcplaygroundpage/Contents.swift
3
1251
/*: > # IMPORTANT: To use `RxSwiftExtPlayground.playground`, please: 1. Make sure you have [Carthage](https://github.com/Carthage/Carthage) installed 1. Fetch Carthage dependencies from shell: `carthage bootstrap --platform ios` 1. Build scheme `RxSwiftExtPlayground` scheme for a simulator target 1. Choose `View > Show Debug Area` */ //: [Previous](@previous) import RxSwift import RxSwiftExt /*: ## pausable The `pausable` operator pauses the elements of the source observable sequence based on the latest element from the second observable sequence. - elements from the underlying observable sequence are emitted if and only if the second sequence has most recently emitted `true`. */ example("pausable") { let observable = Observable<Int>.interval(1, scheduler: MainScheduler.instance) let trueAtThreeSeconds = Observable<Int>.timer(3, scheduler: MainScheduler.instance).map { _ in true } let falseAtFiveSeconds = Observable<Int>.timer(5, scheduler: MainScheduler.instance).map { _ in false } let pauser = Observable.of(trueAtThreeSeconds, falseAtFiveSeconds).merge() let pausedObservable = observable.pausable(pauser) pausedObservable .subscribe { print($0) } playgroundShouldContinueIndefinitely() } //: [Next](@next)
mit
b38c07c982077f610094d6487ea3b098
31.921053
142
0.763389
4.142384
false
false
false
false
Sidetalker/TapMonkeys
TapMonkeys/TapMonkeys/Helpers.swift
1
13751
// // Helpers.swift // TapMonkeys // // Created by Kevin Sullivan on 5/8/15. // Copyright (c) 2015 Kevin Sullivan. All rights reserved. // import UIKit import QuartzCore var currencyFormatter = NSNumberFormatter() var generalFormatter = NSNumberFormatter() func initializeFormatters() { currencyFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle generalFormatter.numberStyle = NSNumberFormatterStyle.NoStyle generalFormatter.usesGroupingSeparator = true } extension String { var floatValue: Float { return (self as NSString).floatValue } } func delay(delay: Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } func randomFloatBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat { return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum) } func randomIntBetweenNumbers(firstNum: Int, secondNum: Int) -> Int { let first = CGFloat(firstNum) let second = CGFloat(secondNum) let random = randomFloatBetweenNumbers(first, second) return Int(random) } func save(sender: AnyObject?, data: SaveData) -> Bool { if let controller = sender as? TabBarController { writeDefaults(data) controller.saveData = data return true } else { println("Error saving - sender is not a TabBarController") return false } } func load(sender: AnyObject?) -> SaveData { if let controller = sender as? TabBarController { return controller.saveData } else { println("Error loading - sender is not a TabBarController") return SaveData() } } func writeDefaults(data: SaveData) -> Bool { let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(data.letters, forKey: "letters") defaults.setObject(data.money, forKey: "money") defaults.setObject(data.letterCounts, forKey: "letterCounts") defaults.setObject(data.stage, forKey: "stage") defaults.setObject(data.nightMode, forKey: "nightMode") defaults.setObject(data.monkeyUnlocks, forKey: "monkeyUnlocks") defaults.setObject(data.monkeyCounts, forKey: "monkeyCounts") defaults.setObject(data.monkeyTotals, forKey: "monkeyTotals") defaults.setObject(data.monkeyLastCost, forKey: "monkeyLastCost") defaults.setObject(data.monkeyLastMod, forKey: "monkeyLastMod") defaults.setObject(data.monkeyCollapsed, forKey: "monkeyCollapsed") defaults.setObject(data.writingCount, forKey: "writingCount") defaults.setObject(data.writingUnlocked, forKey: "writingUnlocked") defaults.setObject(data.writingLevel, forKey: "writingLevel") defaults.setObject(data.writingCostLow, forKey: "writingCostLow") defaults.setObject(data.writingCostHigh, forKey: "writingCostHigh") defaults.setObject(data.writingCollapsed, forKey: "writingCollapsed") defaults.setObject(data.incomeUnlocks, forKey: "incomeUnlocks") defaults.setObject(data.incomeCounts, forKey: "incomeCounts") defaults.setObject(data.incomeTotals, forKey: "incomeTotals") defaults.setObject(data.incomeLastCost, forKey: "incomeLastCost") defaults.setObject(data.incomeLastMod, forKey: "incomeLastMod") defaults.setObject(data.incomeLevel, forKey: "incomeLevel") defaults.setObject(data.incomeCollapsed, forKey: "incomeCollapsed") defaults.synchronize() return true } func readDefaults() -> SaveData { let defaults = NSUserDefaults.standardUserDefaults() var save = SaveData() save.letters = defaults.floatForKey("letters") save.money = defaults.floatForKey("money") save.letterCounts = defaults.arrayForKey("letterCounts") as? [Float] save.stage = defaults.integerForKey("stage") save.nightMode = defaults.boolForKey("nightMode") save.monkeyUnlocks = defaults.arrayForKey("monkeyUnlocks") as? [Bool] save.monkeyCounts = defaults.arrayForKey("monkeyCounts") as? [Int] save.monkeyTotals = defaults.arrayForKey("monkeyTotals") as? [Float] save.monkeyLastCost = defaults.arrayForKey("monkeyLastCost") as? [Float] save.monkeyLastMod = defaults.arrayForKey("monkeyLastMod") as? [Float] save.monkeyCollapsed = defaults.arrayForKey("monkeyCollapsed") as? [Bool] save.writingCount = defaults.arrayForKey("writingCount") as? [Int] save.writingUnlocked = defaults.arrayForKey("writingUnlocked") as? [Bool] save.writingLevel = defaults.arrayForKey("writingLevel") as? [Int] save.writingCostLow = defaults.arrayForKey("writingCostLow") as? [Int] save.writingCostHigh = defaults.arrayForKey("writingCostHigh") as? [Int] save.writingCollapsed = defaults.arrayForKey("writingCollapsed") as? [Bool] save.incomeUnlocks = defaults.arrayForKey("incomeUnlocks") as? [Bool] save.incomeCounts = defaults.arrayForKey("incomeCounts") as? [Int] save.incomeTotals = defaults.arrayForKey("incomeTotals") as? [Float] save.incomeLastCost = defaults.arrayForKey("incomeLastCost") as? [Float] save.incomeLastMod = defaults.arrayForKey("incomeLastMod") as? [Float] save.incomeLevel = defaults.arrayForKey("incomeLevel") as? [Int] save.incomeCollapsed = defaults.arrayForKey("incomeCollapsed") as? [Bool] return save } func updateGlobalSave(save: SaveData) { var curSave = save let dataWrapper = NSData(bytes: &curSave, length: sizeof(SaveData)) let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName("updateSave", object: nil, userInfo: [ "saveData" : dataWrapper ]) } func validate(save: SaveData) -> SaveData { let numLetterCounts = 26 let numMonkeys = 7 let numWriting = 7 let numIncome = 7 var newSave = save if newSave.letterCounts == nil { newSave.letterCounts = [Float](count: numLetterCounts, repeatedValue: 0) } else if count(newSave.letterCounts!) < numLetterCounts { for i in count(newSave.letterCounts!)...numLetterCounts - 1 { newSave.letterCounts?.append(0) } } if newSave.monkeyCounts == nil { newSave.monkeyCounts = [Int](count: numMonkeys, repeatedValue: 0) } else if count(newSave.monkeyCounts!) < numMonkeys { for i in count(newSave.monkeyCounts!)...numMonkeys - 1 { newSave.monkeyCounts?.append(0) } } if newSave.monkeyUnlocks == nil { newSave.monkeyUnlocks = [Bool](count: numMonkeys, repeatedValue: false) } else if count(newSave.monkeyUnlocks!) < numMonkeys { for i in count(newSave.monkeyUnlocks!)...numMonkeys - 1 { newSave.monkeyUnlocks?.append(false) } } if newSave.monkeyTotals == nil { newSave.monkeyTotals = [Float](count: numMonkeys, repeatedValue: 0) } else if count(newSave.monkeyTotals!) < numMonkeys { for i in count(newSave.monkeyTotals!)...numMonkeys - 1 { newSave.monkeyTotals?.append(0) } } if newSave.monkeyLastCost == nil { newSave.monkeyLastCost = [Float](count: numMonkeys, repeatedValue: 0.0) } else if count(newSave.monkeyLastCost!) < numMonkeys { for i in count(newSave.monkeyLastCost!)...numMonkeys - 1 { newSave.monkeyLastCost?.append(0) } } if newSave.monkeyCollapsed == nil { newSave.monkeyCollapsed = [Bool](count: numMonkeys, repeatedValue: false) } else if count(newSave.monkeyCollapsed!) < numMonkeys { for i in count(newSave.monkeyCollapsed!)...numMonkeys - 1 { newSave.monkeyCollapsed?.append(false) } } if newSave.monkeyLastMod == nil { newSave.monkeyLastMod = [Float](count: numMonkeys, repeatedValue: 0.0) } else if count(newSave.monkeyLastMod!) < numMonkeys { for i in count(newSave.monkeyLastMod!)...numMonkeys - 1 { newSave.monkeyLastMod?.append(0.0) } } if newSave.writingCount == nil { newSave.writingCount = [Int](count: numWriting, repeatedValue: 0) } else if count(newSave.writingCount!) < numWriting { for i in count(newSave.writingCount!)...numWriting - 1 { newSave.writingCount?.append(0) } } if newSave.writingUnlocked == nil { newSave.writingUnlocked = [Bool](count: numWriting, repeatedValue: false) } else if count(newSave.writingUnlocked!) < numWriting { for i in count(newSave.writingUnlocked!)...numWriting - 1 { newSave.writingUnlocked?.append(false) } } if newSave.writingLevel == nil { newSave.writingLevel = [Int](count: numWriting, repeatedValue: 1) } else if count(newSave.writingLevel!) < numWriting { for i in count(newSave.writingLevel!)...numWriting - 1 { newSave.writingLevel?.append(1) } } if newSave.writingCostLow == nil { newSave.writingCostLow = [Int](count: numWriting, repeatedValue: 0) } else if count(newSave.writingCostLow!) < numWriting { for i in count(newSave.writingCostLow!)...numWriting - 1 { newSave.writingCostLow?.append(0) } } if newSave.writingCostHigh == nil { newSave.writingCostHigh = [Int](count: numWriting, repeatedValue: 0) } else if count(newSave.writingCostHigh!) < numWriting { for i in count(newSave.writingCostHigh!)...numWriting - 1 { newSave.writingCostHigh?.append(0) } } if newSave.writingCollapsed == nil { newSave.writingCollapsed = [Bool](count: numWriting, repeatedValue: false) } else if count(newSave.writingCollapsed!) < numWriting { for i in count(newSave.writingCollapsed!)...numWriting - 1 { newSave.writingCollapsed?.append(false) } } if newSave.incomeUnlocks == nil { newSave.incomeUnlocks = [Bool](count: numIncome, repeatedValue: false) } else if count(newSave.incomeUnlocks!) < numIncome { for i in count(newSave.incomeUnlocks!)...numIncome - 1 { newSave.incomeUnlocks?.append(false) } } if newSave.incomeCounts == nil { newSave.incomeCounts = [Int](count: numIncome, repeatedValue: 0) } else if count(newSave.incomeCounts!) < numIncome { for i in count(newSave.incomeCounts!)...numIncome - 1 { newSave.incomeCounts?.append(0) } } if newSave.incomeTotals == nil { newSave.incomeTotals = [Float](count: numIncome, repeatedValue: 0) } else if count(newSave.incomeTotals!) < numIncome { for i in count(newSave.incomeTotals!)...numIncome - 1 { newSave.incomeTotals?.append(0) } } if newSave.incomeLastCost == nil { newSave.incomeLastCost = [Float](count: numIncome, repeatedValue: 0) } else if count(newSave.incomeLastCost!) < numIncome { for i in count(newSave.incomeLastCost!)...numIncome - 1 { newSave.incomeLastCost?.append(0) } } if newSave.incomeLastMod == nil { newSave.incomeLastMod = [Float](count: numIncome, repeatedValue: 0) } else if count(newSave.incomeLastMod!) < numIncome { for i in count(newSave.incomeLastMod!)...numIncome - 1 { newSave.incomeLastMod?.append(0) } } if newSave.incomeLevel == nil { newSave.incomeLevel = [Int](count: numIncome, repeatedValue: 0) } else if count(newSave.incomeLevel!) < numIncome { for i in count(newSave.incomeLevel!)...numIncome - 1 { newSave.incomeLevel?.append(0) } } if newSave.incomeCollapsed == nil { newSave.incomeCollapsed = [Bool](count: numIncome, repeatedValue: false) } else if count(newSave.incomeCollapsed!) < numIncome { for i in count(newSave.incomeCollapsed!)...numIncome - 1 { newSave.incomeCollapsed?.append(false) } } return newSave } func individualLettersPer(timeInterval: Float) -> [Float] { var lettersPer = [Float]() for monkey in monkeys { lettersPer.append(monkey.lettersPer(timeInterval)) } return lettersPer } func fullLettersPer(timeInterval: Float) -> Float { var lettersPer: Float = 0 for monkey in monkeys { lettersPer += monkey.lettersPer(timeInterval) } return lettersPer } func monkeyProductionTimer() -> Float { var highestLPS: Float = 0 for monkey in monkeys { let LPS = monkey.lettersPerSecondCumulative() if LPS > highestLPS && LPS > 0 { highestLPS = monkey.lettersPerSecondCumulative() } } if highestLPS == 0 { return 1.0 } return 1.0 / highestLPS } func individualIncomePer(timeInterval: Float) -> [Float] { var incomePer = [Float]() for income in incomes { incomePer.append(income.moneyPer(timeInterval)) } return incomePer } func fullIncomePer(timeInterval: Float) -> Float { var moneyPer: Float = 0 for income in incomes { moneyPer += income.moneyPer(timeInterval) } return moneyPer } func incomeProductionTimer() -> Float { var highestIPS: Float = 0 for income in incomes { let IPS = income.moneyPerSecond() if IPS > highestIPS && IPS > 0 { highestIPS = income.moneyPerSecond() } } if highestIPS == 0 { return 1.0 } return 1.0 / (highestIPS * 100) }
mit
204586e03d8ddd45cf105e84d4036d7a
31.355294
109
0.65268
3.999709
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/TakeUntil.swift
132
3712
// // TakeUntil.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns the elements from the source observable sequence until the other observable sequence produces an element. - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) - parameter other: Observable sequence that terminates propagation of elements of the source sequence. - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ public func takeUntil<O: ObservableType>(_ other: O) -> Observable<E> { return TakeUntil(source: asObservable(), other: other.asObservable()) } } final fileprivate class TakeUntilSinkOther<Other, O: ObserverType> : ObserverType , LockOwnerType , SynchronizedOnType { typealias Parent = TakeUntilSink<Other, O> typealias E = Other fileprivate let _parent: Parent var _lock: RecursiveLock { return _parent._lock } fileprivate let _subscription = SingleAssignmentDisposable() init(parent: Parent) { _parent = parent #if TRACE_RESOURCES let _ = Resources.incrementTotal() #endif } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: _parent.forwardOn(.completed) _parent.dispose() case .error(let e): _parent.forwardOn(.error(e)) _parent.dispose() case .completed: _subscription.dispose() } } #if TRACE_RESOURCES deinit { let _ = Resources.decrementTotal() } #endif } final fileprivate class TakeUntilSink<Other, O: ObserverType> : Sink<O> , LockOwnerType , ObserverType , SynchronizedOnType { typealias E = O.E typealias Parent = TakeUntil<E, Other> fileprivate let _parent: Parent let _lock = RecursiveLock() init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { synchronizedOn(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next: forwardOn(event) case .error: forwardOn(event) dispose() case .completed: forwardOn(event) dispose() } } func run() -> Disposable { let otherObserver = TakeUntilSinkOther(parent: self) let otherSubscription = _parent._other.subscribe(otherObserver) otherObserver._subscription.setDisposable(otherSubscription) let sourceSubscription = _parent._source.subscribe(self) return Disposables.create(sourceSubscription, otherObserver._subscription) } } final fileprivate class TakeUntil<Element, Other>: Producer<Element> { fileprivate let _source: Observable<Element> fileprivate let _other: Observable<Other> init(source: Observable<Element>, other: Observable<Other>) { _source = source _other = other } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element { let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
377e437c6cff9ee684e547fd6781df2f
27.328244
153
0.632444
4.703422
false
false
false
false
cybersamx/Mapper-iOS-Standard
MapperStd/MapViewController.swift
1
1898
// // MapViewController.swift // MapperStd // // Created by Samuel Chow on 5/18/16. // Copyright © 2016 Cybersam. All rights reserved. // import CoreLocation import MapKit import UIKit extension MKMapView { func setCorners(_ northeast: CLLocationCoordinate2D, southwest: CLLocationCoordinate2D, animated: Bool) { let southwestMapPoint = MKMapPointForCoordinate(southwest) let northeastMapPoint = MKMapPointForCoordinate(northeast) let antiMeridanOverflow = (northeast.longitude > southwest.longitude) ? 0.0 : MKMapSizeWorld.width let mapWidth = northeastMapPoint.x - southwestMapPoint.x + antiMeridanOverflow let mapHeight = southwestMapPoint.y - northeastMapPoint.y let mapRect = MKMapRectMake(southwestMapPoint.x, northeastMapPoint.y, mapWidth, mapHeight) let coordinateRegion = MKCoordinateRegionForMapRect(mapRect) let regionMap = self.regionThatFits(coordinateRegion) self.setRegion(regionMap, animated: animated) } } class MapViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! var locationResult: LocationResult? lazy var locationManager: CLLocationManager = { let locationManager = CLLocationManager() // Ask for user's permission to use GPS. locationManager.requestWhenInUseAuthorization() return locationManager }() override func viewDidLoad() { super.viewDidLoad() // Add drop pin. let annotation = MKPointAnnotation() annotation.coordinate = (self.locationResult?.location)! annotation.title = self.locationResult?.address self.mapView.addAnnotation(annotation) // Set region using the viewport. self.mapView.setCorners((self.locationResult?.northeast)!, southwest: (self.locationResult?.southwest)!, animated: true) self.mapView.selectAnnotation(annotation, animated: true) } }
mit
7018dd54a79c6f572a12c605dc45fb0f
31.152542
124
0.741697
4.790404
false
false
false
false
nathawes/swift
test/IRGen/prespecialized-metadata/struct-inmodule-0argument-within-class-1argument-1distinct_use.swift
2
2323
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main9NamespaceC5ValueVySi_GMf" = linkonce_odr hidden constant <{ // CHECk-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceC5ValueVySi_GWV", i32 0, i32 0), // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main9NamespaceC5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] final class Namespace<Arg> { struct Value { let first: Arg } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main9NamespaceC5ValueVySi_GMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Namespace.Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]] %0, %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* undef, i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main9NamespaceC5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
05acb91164f52c749fbe55aee0f7e35a
44.54902
344
0.626776
3.080902
false
false
false
false
4taras4/totp-auth
2Pass/_Pass.swift
1
4483
// _Pass.swift // 2Pass // // Created by Taras Markevych on 13.10.2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import WidgetKit import SwiftUI import Intents import RealmSwift import OneTimePassword import Base32 struct Provider: IntentTimelineProvider { func placeholder(in context: Context) -> CodeEntry { CodeEntry(date: Date(), otp: "OTP Code", name: "account.com", issuer: "", configuration: ConfigurationIntent()) } func getSnapshot(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (CodeEntry) -> ()) { let user = readContents().first! let code = convertUser(user: user) let entry = CodeEntry(date: Date(), otp: code.otp, name: code.name, issuer: code.issuer, configuration: configuration) completion(entry) } func getTimeline(for configuration: ConfigurationIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> ()) { let users = readContents() var entries = [CodeEntry]() for u in users { entries.append(convertUser(user: u)) } let currentDate = Date() let interval = 3 for index in 0 ..< entries.count { entries[index].date = Calendar.current.date(byAdding: .second, value: interval + index, to: currentDate)! } let timeline = Timeline(entries: entries, policy: .atEnd) completion(timeline) } func readContents() -> [User] { var contents: [User] = [] let archiveURL = FileManager.sharedContainerURL().appendingPathComponent(Constants.settings.contentsJson) let decoder = JSONDecoder() if let codeData = try? Data(contentsOf: archiveURL) { do { contents = try decoder.decode([User].self, from: codeData) } catch { print("Error: Can't decode contents") } } return contents } func convertUser(user: User) -> CodeEntry { guard let secretData = MF_Base32Codec.data(fromBase32String: user.token), !secretData.isEmpty else { print("Invalid secret") return CodeEntry(date: Date(), otp: "No secret", name: "No secret", issuer: user.issuer ?? "", configuration: ConfigurationIntent()) } guard let generator = Generator( factor: .timer(period: 30), secret: secretData, algorithm: .sha1, digits: 6) else { print("Invalid generator parameters") return CodeEntry(date: Date(), otp: "No secret", name: "No secret", issuer: user.issuer ?? "", configuration: ConfigurationIntent()) } let token = Token(name: user.name ?? "", issuer: user.issuer ?? "", generator: generator) guard let currentCode = token.currentPassword else { print("Invalid generator parameters") return CodeEntry(date: Date(), otp: "No secret", name: "No secret", issuer: user.issuer ?? "", configuration: ConfigurationIntent()) } return CodeEntry(date: Date(), otp: currentCode, name: user.name ?? "name", issuer: user.issuer ?? "", configuration: ConfigurationIntent()) } } struct CodeEntry: TimelineEntry { var date: Date var otp: String let name: String let issuer: String? let configuration: ConfigurationIntent } struct _PassEntryView : View { var entry: Provider.Entry var body: some View { if let issuer = entry.issuer { Text("Issuer: \(issuer)") } Text(entry.name) Text(entry.otp).bold() } } @main struct _Pass: Widget { let kind: String = "_Pass" var body: some WidgetConfiguration { IntentConfiguration(kind: kind, intent: ConfigurationIntent.self, provider: Provider()) { entry in _PassEntryView(entry: entry) } .configurationDisplayName("2 Pass") .description("TOTP widget for quick access to your TOTP codes. Widget may have some delay it's iOS resctriction, but you always can open your app quickly from widget") .supportedFamilies([.systemSmall]) } } struct _Pass_Previews: PreviewProvider { static var previews: some View { _PassEntryView(entry: CodeEntry(date: Date(), otp: "OTP Code", name: "username", issuer: nil, configuration: ConfigurationIntent())) .previewContext(WidgetPreviewContext(family: .systemSmall)) } }
mit
96f3dfb029dbd79abc214f189924e79b
35.439024
175
0.625837
4.450844
false
true
false
false
MatthiasU/SwiftyBit
Sources/SwiftyBit/BitArithmetic.swift
1
13094
// // BitArithmetic.swift // SwiftyBit // // Created by Matthias Uttendorfer on 27/09/2016. // // //Apache License //Version 2.0, January 2004 //http://www.apache.org/licenses/ // //TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION // //1. Definitions. // //"License" shall mean the terms and conditions for use, reproduction, //and distribution as defined by Sections 1 through 9 of this document. // //"Licensor" shall mean the copyright owner or entity authorized by //the copyright owner that is granting the License. // //"Legal Entity" shall mean the union of the acting entity and all //other entities that control, are controlled by, or are under common //control with that entity. For the purposes of this definition, //"control" means (i) the power, direct or indirect, to cause the //direction or management of such entity, whether by contract or //otherwise, or (ii) ownership of fifty percent (50%) or more of the //outstanding shares, or (iii) beneficial ownership of such entity. // //"You" (or "Your") shall mean an individual or Legal Entity //exercising permissions granted by this License. // //"Source" form shall mean the preferred form for making modifications, //including but not limited to software source code, documentation //source, and configuration files. // //"Object" form shall mean any form resulting from mechanical //transformation or translation of a Source form, including but //not limited to compiled object code, generated documentation, //and conversions to other media types. // //"Work" shall mean the work of authorship, whether in Source or //Object form, made available under the License, as indicated by a //copyright notice that is included in or attached to the work //(an example is provided in the Appendix below). // //"Derivative Works" shall mean any work, whether in Source or Object //form, that is based on (or derived from) the Work and for which the //editorial revisions, annotations, elaborations, or other modifications //represent, as a whole, an original work of authorship. For the purposes //of this License, Derivative Works shall not include works that remain //separable from, or merely link (or bind by name) to the interfaces of, //the Work and Derivative Works thereof. // //"Contribution" shall mean any work of authorship, including //the original version of the Work and any modifications or additions //to that Work or Derivative Works thereof, that is intentionally //submitted to Licensor for inclusion in the Work by the copyright owner //or by an individual or Legal Entity authorized to submit on behalf of //the copyright owner. For the purposes of this definition, "submitted" //means any form of electronic, verbal, or written communication sent //to the Licensor or its representatives, including but not limited to //communication on electronic mailing lists, source code control systems, //and issue tracking systems that are managed by, or on behalf of, the //Licensor for the purpose of discussing and improving the Work, but //excluding communication that is conspicuously marked or otherwise //designated in writing by the copyright owner as "Not a Contribution." // //"Contributor" shall mean Licensor and any individual or Legal Entity //on behalf of whom a Contribution has been received by Licensor and //subsequently incorporated within the Work. // //2. Grant of Copyright License. Subject to the terms and conditions of //this License, each Contributor hereby grants to You a perpetual, //worldwide, non-exclusive, no-charge, royalty-free, irrevocable //copyright license to reproduce, prepare Derivative Works of, //publicly display, publicly perform, sublicense, and distribute the //Work and such Derivative Works in Source or Object form. // //3. Grant of Patent License. Subject to the terms and conditions of //this License, each Contributor hereby grants to You a perpetual, //worldwide, non-exclusive, no-charge, royalty-free, irrevocable //(except as stated in this section) patent license to make, have made, //use, offer to sell, sell, import, and otherwise transfer the Work, //where such license applies only to those patent claims licensable //by such Contributor that are necessarily infringed by their //Contribution(s) alone or by combination of their Contribution(s) //with the Work to which such Contribution(s) was submitted. If You //institute patent litigation against any entity (including a //cross-claim or counterclaim in a lawsuit) alleging that the Work //or a Contribution incorporated within the Work constitutes direct //or contributory patent infringement, then any patent licenses //granted to You under this License for that Work shall terminate //as of the date such litigation is filed. // //4. Redistribution. You may reproduce and distribute copies of the //Work or Derivative Works thereof in any medium, with or without //modifications, and in Source or Object form, provided that You //meet the following conditions: // //(a) You must give any other recipients of the Work or //Derivative Works a copy of this License; and // //(b) You must cause any modified files to carry prominent notices //stating that You changed the files; and // //(c) You must retain, in the Source form of any Derivative Works //that You distribute, all copyright, patent, trademark, and //attribution notices from the Source form of the Work, //excluding those notices that do not pertain to any part of //the Derivative Works; and // //(d) If the Work includes a "NOTICE" text file as part of its //distribution, then any Derivative Works that You distribute must //include a readable copy of the attribution notices contained //within such NOTICE file, excluding those notices that do not //pertain to any part of the Derivative Works, in at least one //of the following places: within a NOTICE text file distributed //as part of the Derivative Works; within the Source form or //documentation, if provided along with the Derivative Works; or, //within a display generated by the Derivative Works, if and //wherever such third-party notices normally appear. The contents //of the NOTICE file are for informational purposes only and //do not modify the License. You may add Your own attribution //notices within Derivative Works that You distribute, alongside //or as an addendum to the NOTICE text from the Work, provided //that such additional attribution notices cannot be construed //as modifying the License. // //You may add Your own copyright statement to Your modifications and //may provide additional or different license terms and conditions //for use, reproduction, or distribution of Your modifications, or //for any such Derivative Works as a whole, provided Your use, //reproduction, and distribution of the Work otherwise complies with //the conditions stated in this License. // //5. Submission of Contributions. Unless You explicitly state otherwise, //any Contribution intentionally submitted for inclusion in the Work //by You to the Licensor shall be under the terms and conditions of //this License, without any additional terms or conditions. //Notwithstanding the above, nothing herein shall supersede or modify //the terms of any separate license agreement you may have executed //with Licensor regarding such Contributions. // //6. Trademarks. This License does not grant permission to use the trade //names, trademarks, service marks, or product names of the Licensor, //except as required for reasonable and customary use in describing the //origin of the Work and reproducing the content of the NOTICE file. // //7. Disclaimer of Warranty. Unless required by applicable law or //agreed to in writing, Licensor provides the Work (and each //Contributor provides its Contributions) on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or //implied, including, without limitation, any warranties or conditions //of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A //PARTICULAR PURPOSE. You are solely responsible for determining the //appropriateness of using or redistributing the Work and assume any //risks associated with Your exercise of permissions under this License. // //8. Limitation of Liability. In no event and under no legal theory, //whether in tort (including negligence), contract, or otherwise, //unless required by applicable law (such as deliberate and grossly //negligent acts) or agreed to in writing, shall any Contributor be //liable to You for damages, including any direct, indirect, special, //incidental, or consequential damages of any character arising as a //result of this License or out of the use or inability to use the //Work (including but not limited to damages for loss of goodwill, //work stoppage, computer failure or malfunction, or any and all //other commercial damages or losses), even if such Contributor //has been advised of the possibility of such damages. // //9. Accepting Warranty or Additional Liability. While redistributing //the Work or Derivative Works thereof, You may choose to offer, //and charge a fee for, acceptance of support, warranty, indemnity, //or other liability obligations and/or rights consistent with this //License. However, in accepting such obligations, You may act only //on Your own behalf and on Your sole responsibility, not on behalf //of any other Contributor, and only if You agree to indemnify, //defend, and hold each Contributor harmless for any liability //incurred by, or claims asserted against, such Contributor by reason //of your accepting any such warranty or additional liability. // //END OF TERMS AND CONDITIONS // //APPENDIX: How to apply the Apache License to your work. // //To apply the Apache License to your work, attach the following //boilerplate notice, with the fields enclosed by brackets "{}" //replaced with your own identifying information. (Don't include //the brackets!) The text should be enclosed in the appropriate //comment syntax for the file format. We also recommend that a //file or class name and description of purpose be included on the //same "printed page" as the copyright notice for easier // identification within third-party archives. // //Copyright 2016 Matthias Uttendorfer // //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. #if os(OSX) import Darwin #elseif os(Linux) import Glibc #endif // MARK: - Byte Arithmetic public extension UInt8 { /// Checks if a bit at a certain position was set before /// /// - parameter pos: the position of the bit /// /// - returns: returns true if the bit was set before public func bitIsSet(pos: Int) -> Bool { let mask = UInt8(pow(Double(2), Double(pos))) return ((mask & self) > 0 ) ? true : false } /// Sets a range of bits /// /// - parameter range: the range to set to /// - parameter byte: a bit pattern which is used to set into the byte with specific range public mutating func setBitsIn(range: Range<Int>, of byte: UInt8) { var result = byte for index in range.lowerBound..<range.upperBound { result.setBit(at: index) } self = result } /// Sets bit on a specific position /// /// - parameter position: the position of the bit to set public mutating func setBit(at position: Int) { var newByte = self if self.bitIsSet(pos: position) { self = newByte return } newByte = newByte + UInt8(pow(Double(2), Double(position))) self = newByte } } internal extension UInt8 { /// Sets bit to true on a position of byte /// /// - parameter position: the position to set /// - parameter byte: the byte which holds the bit to set /// /// - returns: returns a new Byte with the bit that was set internal static func setBit(at position: Int, on byte: UInt8) -> UInt8 { var newByte = byte if byte.bitIsSet(pos: position) { return byte } newByte = newByte + UInt8(pow(Double(2), Double(position))) return newByte } } // MARK: - Integer Arithmetic internal extension Int { /// Checks if a bit at certain position was set before /// /// - parameter position: the position of the bit to set /// /// - returns: returns true if the bit was set before internal func bitIsSet(at position: Int) -> Bool { let mask = Int(pow(Double(2), Double(position))) return ((mask & self) > 0 ) ? true : false } }
apache-2.0
52889aef86b004b155b2f6675181ed41
43.386441
95
0.740797
4.355955
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Player/NormalPlayer/View/ZHNforwardBackforwardNoticeView.swift
1
2821
// // ZHNforwardBackforwardNoticeView.swift // zhnbilibili // // Created by 张辉男 on 16/12/28. // Copyright © 2016年 zhn. All rights reserved. // import UIKit class ZHNforwardBackforwardNoticeView: UIView { var translate: Float = 0 { didSet{ deailImageView() dealPlayTimeLabel() dealForwardTimeLabel() dealProgressView() } } var needGoingPlayTime: TimeInterval = 0 var currentPlayTime: TimeInterval = 0 var maxPlayTime: TimeInterval = 0 var oldTrans: Float = 0 // MARK - 控件 @IBOutlet weak var noticeImageView: UIImageView! @IBOutlet weak var playTimeLabel: UILabel! @IBOutlet weak var forwardTimeLabel: UILabel! @IBOutlet weak var forwardSpeedLabel: UILabel! @IBOutlet weak var playPercentProgress: UIProgressView! override func awakeFromNib() { super.awakeFromNib() playPercentProgress.backgroundColor = UIColor.darkGray playPercentProgress.progressTintColor = kNavBarColor noticeImageView.image = UIImage(named: "play_forward_icon") } class func instanceView() -> ZHNforwardBackforwardNoticeView { return Bundle.main.loadNibNamed("ZHNforwardBackforwardNoticeView", owner: self, options: nil)?.last as! ZHNforwardBackforwardNoticeView } } // MARK - 私有方法 extension ZHNforwardBackforwardNoticeView { fileprivate func deailImageView() { if translate > oldTrans{ noticeImageView.image = UIImage(named: "play_forward_icon") }else { noticeImageView.image = UIImage(named: "play_retreat_icon") } oldTrans = translate } // 处理当前时间 fileprivate func dealPlayTimeLabel() { print(currentPlayTime) // 1. 处理滑动值 needGoingPlayTime = currentPlayTime + (TimeInterval(translate) * 0.5) print(currentPlayTime) if needGoingPlayTime < 0{ needGoingPlayTime = 0 }else if needGoingPlayTime > maxPlayTime { needGoingPlayTime = maxPlayTime } // 2. 赋值 playTimeLabel.text = "\(needGoingPlayTime.timeString()):\(maxPlayTime.timeString())" } // 处理增加的秒数 fileprivate func dealForwardTimeLabel() { let second = TimeInterval(translate) * 0.5 if second >= 0 { forwardTimeLabel.text = "+\((second).format(f: ".0"))秒" }else { forwardTimeLabel.text = "\((second).format(f: ".0"))秒" } } // 处理滑动速度 fileprivate func dealForwardSpeedLabel() { } // 处理progress fileprivate func dealProgressView() { let percent = needGoingPlayTime/maxPlayTime playPercentProgress.progress = Float(percent) } }
mit
41255c9f2c06b303f97c507bcc701bda
29.444444
143
0.637591
4.433657
false
false
false
false
shushutochako/CircleSlider
Pod/Classes/Math.swift
1
2222
// // CircleSliderMath.swift // Pods // // Created by shushutochako on 11/17/15. // Copyright © 2015 shushutochako. All rights reserved. // import UIKit internal class Math { internal class func degreesToRadians(_ angle: Double) -> Double { return angle / 180 * Double.pi } internal class func pointFromAngle(_ frame: CGRect, angle: Double, radius: Double) -> CGPoint { let radian = degreesToRadians(angle) let x = Double(frame.midX) + cos(radian) * radius let y = Double(frame.midY) + sin(radian) * radius return CGPoint(x: x, y: y) } internal class func pointPairToBearingDegrees(_ startPoint: CGPoint, endPoint: CGPoint) -> Double { let originPoint = CGPoint(x: endPoint.x - startPoint.x, y: endPoint.y - startPoint.y) let bearingRadians = atan2(Double(originPoint.y), Double(originPoint.x)) var bearingDegrees = bearingRadians * (180.0 / Double.pi) bearingDegrees = (bearingDegrees > 0.0 ? bearingDegrees : (360.0 + bearingDegrees)) return bearingDegrees } internal class func adjustValue(_ startAngle: Double, degree: Double, maxValue: Float, minValue: Float) -> Double { let ratio = Double((maxValue - minValue) / 360) let ratioStart = ratio * startAngle let ratioDegree = ratio * degree let adjustValue: Double if startAngle < 0 { adjustValue = (360 + startAngle) > degree ? (ratioDegree - ratioStart) : (ratioDegree - ratioStart) - (360 * ratio) } else { adjustValue = (360 - (360 - startAngle)) < degree ? (ratioDegree - ratioStart) : (ratioDegree - ratioStart) + (360 * ratio) } return adjustValue + (Double(minValue)) } internal class func adjustDegree(_ startAngle: Double, degree: Double) -> Double { return (360 + startAngle) > degree ? degree : -(360 - degree) } internal class func degreeFromValue(_ startAngle: Double, value: Float, maxValue: Float, minValue: Float) -> Double { let ratio = Double((maxValue - minValue) / 360) let angle = Double(value) / ratio return angle + startAngle - (Double(minValue) / ratio) } }
mit
340e6120f79ba5ace0f13b3db2d83e3a
40.12963
135
0.633048
4.159176
false
false
false
false
karwa/swift-corelibs-foundation
Foundation/NSHost.swift
3
3781
// 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 // #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) import Glibc #endif import CoreFoundation public class NSHost : NSObject { enum ResolveType { case Name case Address case Current } internal var _info: String? internal var _type: ResolveType internal var _resolved = false internal var _names = [String]() internal var _addresses = [String]() internal init(_ info: String?, _ type: ResolveType) { _info = info _type = type } static internal let current = NSHost(nil, .Current) public class func currentHost() -> NSHost { return NSHost.current } public convenience init(name: String?) { self.init(name, .Name) } public convenience init(address: String) { self.init(address, .Address) } public func isEqualToHost(_ aHost: NSHost) -> Bool { return false } internal func _resolveCurrent() { // TODO: cannot access getifaddrs here... } internal func _resolve() { if _resolved { return } if let info = _info { var flags: Int32 = 0 switch (_type) { case .Name: flags = AI_PASSIVE | AI_CANONNAME break case .Address: flags = AI_PASSIVE | AI_CANONNAME | AI_NUMERICHOST break case .Current: _resolveCurrent() return } var hints = addrinfo() hints.ai_family = PF_UNSPEC hints.ai_socktype = _CF_SOCK_STREAM() hints.ai_flags = flags var res0: UnsafeMutablePointer<addrinfo>? = nil let r = getaddrinfo(info, nil, &hints, &res0) if r != 0 { return } var res: UnsafeMutablePointer<addrinfo>? = res0 while res != nil { let info = res!.pointee let family = info.ai_family if family != AF_INET && family != AF_INET6 { res = info.ai_next continue } let sa_len: socklen_t = socklen_t((family == AF_INET6) ? sizeof(sockaddr_in6) : sizeof(sockaddr_in)) let lookupInfo = { (content: inout [String], flags: Int32) in let hname = UnsafeMutablePointer<Int8>(allocatingCapacity: 1024) if (getnameinfo(info.ai_addr, sa_len, hname, 1024, nil, 0, flags) == 0) { content.append(String(hname)) } hname.deinitialize() hname.deallocateCapacity(1024) } lookupInfo(&_addresses, NI_NUMERICHOST) lookupInfo(&_names, NI_NAMEREQD) lookupInfo(&_names, NI_NOFQDN|NI_NAMEREQD) res = info.ai_next } freeaddrinfo(res0) } } public var name: String? { return names.first } public var names: [String] { _resolve() return _names } public var address: String? { return addresses.first } public var addresses: [String] { _resolve() return _addresses } public var localizedName: String? { return nil } }
apache-2.0
e94581a1c28fac2a473db962a3e55c46
27.007407
116
0.520233
4.588592
false
false
false
false
aleph7/HDF5Kit
Source/FloatAttribute.swift
1
1686
// Copyright © 2016 Alejandro Isaza. // // This file is part of HDF5Kit. The full HDF5Kit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #if SWIFT_PACKAGE import CHDF5 #endif open class FloatAttribute: Attribute { public func read() throws -> [Float] { let space = self.space let count = space.size var data = [Float](repeating: 0, count: count) try data.withUnsafeMutableBufferPointer { pointer in return try read(into: pointer.baseAddress!, type: .float) } return data } public func write(_ data: [Float]) throws { assert(space.size == data.count) try data.withUnsafeBufferPointer { pointer in try write(from: pointer.baseAddress!, type: .float) } } } public extension GroupType { /// Creates a `Float` attribute. public func createFloatAttribute(_ name: String, dataspace: Dataspace) -> FloatAttribute? { guard let datatype = Datatype(type: Float.self) else { return nil } let attributeID = name.withCString { name in return H5Acreate2(id, name, datatype.id, dataspace.id, 0, 0) } return FloatAttribute(id: attributeID) } /// Opens a `Float` attribute. public func openFloatAttribute(_ name: String) -> FloatAttribute? { let attributeID = name.withCString{ name in return H5Aopen(id, name, 0) } guard attributeID >= 0 else { return nil } return FloatAttribute(id: attributeID) } }
mit
8045a9fff6f38b378baa5c4a6bec61d4
29.636364
95
0.6273
4.287532
false
false
false
false
GianniCarlo/Audiobook-Player
BookPlayer/Import/ImportViewModel.swift
1
2940
// // ImportViewModel.swift // BookPlayer // // Created by Gianni Carlo on 23/6/21. // Copyright © 2021 Tortuga Power. All rights reserved. // import BookPlayerKit import Combine import DirectoryWatcher import Foundation final class ImportViewModel: ObservableObject { @Published private(set) var files = [FileItem]() private var disposeBag = Set<AnyCancellable>() private let importManager: ImportManager private var watchers = [DirectoryWatcher]() private var observedFiles = [FileItem]() init(importManager: ImportManager = ImportManager.shared) { self.importManager = importManager self.bindInternalFiles() } private func bindInternalFiles() { ImportManager.shared.observeFiles().sink { [weak self] files in guard let self = self else { return } self.cleanupWatchters() // make a copy of the files self.observedFiles = files.map({ FileItem(originalUrl: $0, destinationFolder: $0) }) self.subscribeNewFolders() self.refreshData() }.store(in: &disposeBag) } private func cleanupWatchters() { self.watchers.forEach({ _ = $0.stopWatching() }) self.watchers = [] } private func subscribeNewFolders() { for file in self.observedFiles { guard file.originalUrl.isDirectory else { continue } let enumerator = FileManager.default.enumerator(at: file.originalUrl, includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles], errorHandler: { (url, error) -> Bool in print("directoryEnumerator error at \(url): ", error) return true })! for case let fileURL as URL in enumerator { if !fileURL.isDirectory { file.subItems += 1 } else if !self.watchers.contains(where: { $0.watchedUrl == fileURL }) { let watcher = DirectoryWatcher(watchedUrl: fileURL) self.watchers.append(watcher) watcher.onNewFiles = { [weak self] newFiles in guard let self = self else { return } file.subItems += newFiles.count self.refreshData() } _ = watcher.startWatching() } } } } private func refreshData() { self.files = self.observedFiles } public func getTotalItems() -> Int { return self.files.reduce(0) { result, file in return file.originalUrl.isDirectory ? result + file.subItems : result + 1 } } public func deleteItem(_ item: URL) throws { try ImportManager.shared.removeFile(item) } public func discardImportOperation() throws { try ImportManager.shared.removeAllFiles() } public func createOperation() { ImportManager.shared.createOperation() } }
gpl-3.0
d83524b692b46fb6926ded6c309b0434
29.298969
123
0.606329
4.763371
false
false
false
false
pseudomuto/Retired
Sources/VersionFile.swift
1
1400
// // VersionFile.swift // Retired // // Created by David Muto on 2016-03-31. // Copyright © 2016 pseudomuto. All rights reserved. // public struct VersionFile { private struct Constants { static let messagingAttribute = "messaging" static let forcedMessageAttribute = "forced" static let recommendedMessageAttribute = "recommended" static let versionsAttribute = "versions" } public let forcedMessage: Message public let recommendedMessage: Message public let versions: [Version] public init(json: AnyObject) { let messages = json[Constants.messagingAttribute] as! [String: AnyObject] forcedMessage = Message(json: messages[Constants.forcedMessageAttribute]!) recommendedMessage = Message(json: messages[Constants.recommendedMessageAttribute]!) let versionDefinitions = json[Constants.versionsAttribute] as! [AnyObject] versions = versionDefinitions.map { Version(json: $0) } } func findVersion(_ versionString: String) -> Version? { let strings = versions.map { $0.versionString } guard let index = strings.index(of: versionString) else { return nil } return versions[index] } func messageForVersion(_ version: Version) -> Message? { switch version.policy { case .force: return forcedMessage case .recommend: return recommendedMessage default: return nil } } }
mit
99773b9ceda4ff73a1f09d436cec4af2
30.795455
88
0.706219
4.427215
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/STPFormTextField.swift
1
18395
// // STPFormTextField.swift // StripePaymentsUI // // Created by Jack Flintermann on 7/16/15. // Copyright (c) 2015 Stripe, Inc. All rights reserved. // @_spi(STP) import StripeCore @_spi(STP) import StripePayments import UIKit @_spi(STP) public enum STPFormTextFieldAutoFormattingBehavior: Int { case none case phoneNumbers case cardNumbers case expiration case bsbNumber } @objc protocol STPFormTextFieldDelegate: UITextFieldDelegate { // Note, post-Swift conversion: // In lieu of a real delegate proxy, this should always be implemented and call: // if let textField = textField as? STPFormTextField, let delegateProxy = textField.delegateProxy { // return delegateProxy.textField(textField, shouldChangeCharactersIn: range, replacementString: string) // } // return true @objc(textField:shouldChangeCharactersInRange:replacementString:) func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String ) -> Bool @objc optional func formTextFieldDidBackspace(onEmpty formTextField: STPFormTextField) @objc optional func formTextField( _ formTextField: STPFormTextField, modifyIncomingTextChange input: NSAttributedString ) -> NSAttributedString @objc optional func formTextFieldTextDidChange(_ textField: STPFormTextField) } @objc @_spi(STP) public class STPFormTextField: STPValidatedTextField { private var _selectionEnabled = false @_spi(STP) public var selectionEnabled: Bool { get { _selectionEnabled } set(selectionEnabled) { _selectionEnabled = selectionEnabled delegateProxy?.selectionEnabled = selectionEnabled } } // defaults to NO @_spi(STP) public var preservesContentsOnPaste = false // defaults to NO private var _compressed = false var compressed: Bool { get { _compressed } set(compressed) { if compressed != _compressed { _compressed = compressed // reset text values as needed _didSetText(text: self.text ?? "") _didSetAttributedPlaceholder(attributedPlaceholder: attributedPlaceholder) } } } // defaults to NO private var _autoFormattingBehavior: STPFormTextFieldAutoFormattingBehavior = .none @_spi(STP) public var autoFormattingBehavior: STPFormTextFieldAutoFormattingBehavior { get { _autoFormattingBehavior } set(autoFormattingBehavior) { _autoFormattingBehavior = autoFormattingBehavior delegateProxy?.autoformattingBehavior = autoFormattingBehavior switch autoFormattingBehavior { case .none, .expiration: textFormattingBlock = nil case .cardNumbers: textFormattingBlock = { inputString in guard let inputString = inputString else { return NSAttributedString() } if !STPCardValidator.stringIsNumeric(inputString.string) { return inputString } let attributedString = NSMutableAttributedString(attributedString: inputString) let cardNumberFormat = STPCardValidator.cardNumberFormat( forCardNumber: attributedString.string ) var index = 0 for segmentLength in cardNumberFormat { var segmentIndex = 0 while index < (attributedString.length) && segmentIndex < Int(segmentLength.uintValue) { if index + 1 != attributedString.length && segmentIndex + 1 == Int(segmentLength.uintValue) { attributedString.addAttribute( .kern, value: NSNumber(value: 5), range: NSRange(location: index, length: 1) ) } else { attributedString.addAttribute( .kern, value: NSNumber(value: 0), range: NSRange(location: index, length: 1) ) } index += 1 segmentIndex += 1 } } return attributedString } case .phoneNumbers: weak var weakSelf = self textFormattingBlock = { inputString in if !STPCardValidator.stringIsNumeric(inputString?.string ?? "") { return inputString! } guard let strongSelf = weakSelf else { return inputString! } let phoneNumber = STPPhoneNumberValidator.formattedSanitizedPhoneNumber( for: inputString?.string ?? "" ) let attributes = type(of: strongSelf).attributes(for: inputString) return NSAttributedString( string: phoneNumber, attributes: attributes as? [NSAttributedString.Key: Any] ) } case .bsbNumber: weak var weakSelf = self textFormattingBlock = { inputString in guard let inputString = inputString else { return NSAttributedString() } if !STPBSBNumberValidator.isStringNumeric(inputString.string) { return inputString } guard let strongSelf = weakSelf else { return NSAttributedString() } let bsbNumber = STPBSBNumberValidator.formattedSanitizedText( from: inputString.string ) let attributes = type(of: strongSelf).attributes(for: inputString) return NSAttributedString( string: bsbNumber ?? "", attributes: attributes as? [NSAttributedString.Key: Any] ) } } } } private weak var _formDelegate: STPFormTextFieldDelegate? weak var formDelegate: STPFormTextFieldDelegate? { get { _formDelegate } set(formDelegate) { _formDelegate = formDelegate delegate = formDelegate } } var delegateProxy: STPTextFieldDelegateProxy? private var textFormattingBlock: STPFormTextTransformationBlock? class func attributes(for attributedString: NSAttributedString?) -> [AnyHashable: Any]? { if attributedString?.length == 0 { return [:] } return attributedString?.attributes( at: 0, longestEffectiveRange: nil, in: NSRange(location: 0, length: attributedString?.length ?? 0) ) } /// :nodoc: @objc public override func insertText(_ text: String) { self.text = self.text ?? "" + text } /// :nodoc: @objc public override func deleteBackward() { super.deleteBackward() if (text?.count ?? 0) == 0 { if formDelegate?.responds( to: #selector(STPPaymentCardTextField.formTextFieldDidBackspace(onEmpty:)) ) ?? false { formDelegate?.formTextFieldDidBackspace?(onEmpty: self) } } } /// :nodoc: @objc public override var text: String? { get { return super.text } set(text) { let nonNilText = text ?? "" _didSetText(text: nonNilText) } } func _didSetText(text: String) { let attributed = NSAttributedString(string: text, attributes: defaultTextAttributes) attributedText = attributed } /// :nodoc: @objc public override var attributedText: NSAttributedString? { get { return super.attributedText } set(attributedText) { let oldValue = self.attributedText let shouldModify = formDelegate != nil && formDelegate?.responds( to: #selector( STPFormTextFieldDelegate.formTextField(_:modifyIncomingTextChange:)) ) ?? false var modified: NSAttributedString? if let attributedText = attributedText { modified = shouldModify ? formDelegate?.formTextField?(self, modifyIncomingTextChange: attributedText) : attributedText } let transformed = textFormattingBlock != nil ? textFormattingBlock?(modified) : modified super.attributedText = transformed sendActions(for: .editingChanged) if formDelegate?.responds( to: #selector(STPPaymentCardTextField.formTextFieldTextDidChange(_:)) ) ?? false { if let oldValue = oldValue { if !(transformed?.isEqual(to: oldValue) ?? false) { formDelegate?.formTextFieldTextDidChange?(self) } } } } } @objc public override var accessibilityAttributedValue: NSAttributedString? { get { guard let text = text else { return nil } let attributedString = NSMutableAttributedString(string: text) if #available(iOS 13.0, *) { attributedString.addAttribute( .accessibilitySpeechSpellOut, value: NSNumber(value: true), range: attributedString.extent ) } return attributedString } set { // do nothing } } @objc public override var accessibilityAttributedLabel: NSAttributedString? { get { guard let accessibilityLabel = accessibilityLabel else { return nil } let attributedString = NSMutableAttributedString(string: accessibilityLabel) if !validText { let invalidData = STPLocalizedString( "Invalid data.", "Spoken during VoiceOver when a form field has failed validation." ) let failedString = NSMutableAttributedString( string: invalidData, attributes: [ NSAttributedString.Key.accessibilitySpeechPitch: NSNumber(value: 0.6) ] ) attributedString.append(NSAttributedString(string: " ")) attributedString.append(failedString) } return attributedString } set { // do nothing } } /// :nodoc: @objc public override var attributedPlaceholder: NSAttributedString? { get { return super.attributedPlaceholder } set(attributedPlaceholder) { _didSetAttributedPlaceholder(attributedPlaceholder: attributedPlaceholder) } } func _didSetAttributedPlaceholder(attributedPlaceholder: NSAttributedString?) { let transformed = textFormattingBlock != nil ? textFormattingBlock?(attributedPlaceholder) : attributedPlaceholder super.attributedPlaceholder = transformed } // Fixes a weird issue related to our custom override of deleteBackwards. This only affects the simulator and iPads with custom keyboards. /// :nodoc: @objc public override var keyCommands: [UIKeyCommand]? { return [ UIKeyCommand( input: "\u{08}", modifierFlags: .command, action: #selector(commandDeleteBackwards) ) ] } @objc func commandDeleteBackwards() { text = "" } /// :nodoc: @objc public override func closestPosition(to point: CGPoint) -> UITextPosition? { if selectionEnabled { return super.closestPosition(to: point) } return position(from: beginningOfDocument, offset: text?.count ?? 0) } /// :nodoc: @objc public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return super.canPerformAction(action, withSender: sender) && action == #selector(paste(_:)) } /// :nodoc: @objc public override func paste(_ sender: Any?) { if preservesContentsOnPaste { super.paste(sender) } else if autoFormattingBehavior == .expiration { text = STPStringUtils.expirationDateString(from: UIPasteboard.general.string) } else { text = UIPasteboard.general.string } } /// :nodoc: @objc public override weak var delegate: UITextFieldDelegate? { get { super.delegate } set { let dProxy = STPTextFieldDelegateProxy() dProxy.autoformattingBehavior = autoFormattingBehavior dProxy.selectionEnabled = selectionEnabled self.delegateProxy = dProxy super.delegate = newValue } } } class STPTextFieldDelegateProxy: NSObject, UITextFieldDelegate { internal var inShouldChangeCharactersInRange = false @_spi(STP) public var autoformattingBehavior: STPFormTextFieldAutoFormattingBehavior = .none @_spi(STP) public var selectionEnabled = false func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String ) -> Bool { if inShouldChangeCharactersInRange { // This guards against infinite recursion that happens when moving the cursor return true } inShouldChangeCharactersInRange = true let insertingIntoEmptyField = (textField.text?.count ?? 0) == 0 && range.location == 0 && range.length == 0 let hasTextContentType = textField.textContentType != nil if hasTextContentType && insertingIntoEmptyField && (string == " ") { // Observed behavior w/iOS 11.0 through 11.2.0 (latest): // // 1. UITextContentType suggestions are only available when textField is empty // 2. When user taps a QuickType suggestion for the `textContentType`, UIKit *first* // calls this method with `range:{0, 0} replacementString:@" "` // 3. If that succeeds (we return YES), this method is called again, this time with // the actual content to insert (and a space at the end) // // Therefore, always allow entry of a single space in order to support `textContentType`. // // Warning: This bypasses `setText:`, and subsequently `setAttributedText:` and the // formDelegate methods: `formTextField:modifyIncomingTextChange:` & `formTextFieldTextDidChange:` // That's acceptable for a single space. inShouldChangeCharactersInRange = false return true } let deleting = range.location == (textField.text?.count ?? 0) - 1 && range.length == 1 && (string == "") var inputText: String? if deleting { if let sanitized = unformattedString(for: textField.text) { inputText = sanitized.stp_safeSubstring(to: sanitized.count - 1) } } else { let newString = (textField.text as NSString?)?.replacingCharacters( in: range, with: string ) // Removes any disallowed characters from the whole string. // If we (incorrectly) allowed a space to start the text entry hoping it would be a // textContentType completion, this will remove it. let sanitized = unformattedString(for: newString) inputText = sanitized } let beginning = textField.beginningOfDocument let start = textField.position(from: beginning, offset: range.location) if textField.text == inputText { inShouldChangeCharactersInRange = false return false } textField.text = inputText if autoformattingBehavior == .none && selectionEnabled { // this will be the new cursor location after insert/paste/typing var cursorOffset: Int? if let start = start { cursorOffset = textField.offset(from: beginning, to: start) + string.count } let newCursorPosition = textField.position( from: textField.beginningOfDocument, offset: cursorOffset ?? 0 ) var newSelectedRange: UITextRange? if let newCursorPosition = newCursorPosition { newSelectedRange = textField.textRange( from: newCursorPosition, to: newCursorPosition ) } textField.selectedTextRange = newSelectedRange } inShouldChangeCharactersInRange = false return false } func unformattedString(for string: String?) -> String? { switch autoformattingBehavior { case .none: return string case .cardNumbers, .phoneNumbers, .expiration, .bsbNumber: return STPCardValidator.sanitizedNumericString(for: string ?? "") } } } typealias STPFormTextTransformationBlock = (NSAttributedString?) -> NSAttributedString
mit
a56fd1438b0f3ef42446d2df1646edcd
36.849794
142
0.557054
5.980169
false
false
false
false
SJTBA/Scrape
Tests/ScrapeTests/XMLDocumentTests.swift
1
13605
// // XMLDocumentTests.swift // Scrape // // Created by Sergej Jaskiewicz on 16.09.16. // // import Foundation import Scrape import XCTest final class XMLDocumentTests: XCTestCase { static let allTests = { return [ ("testLoadXMLFromData", testLoadXMLFromData), ("testLoadXMLFromString", testLoadXMLFromString), ("testLoadXMLFromURL", testLoadXMLFromURL), ("testLoadXMLWithDifferentEncoding", testLoadXMLWithDifferentEncoding), ("testLoadXMLWithParsingOptions", testLoadXMLWithParsingOptions), ("testGetHTML", testGetHTML), ("testGetXML", testGetXML), ("testGetText", testGetText), ("testGetInnerHTML", testGetInnerHTML), ("testGetClassName", testGetClassName), ("testGetSetTagName", testGetSetTagName), ("testGetSetContent", testGetSetContent), ("testXPathTagQuery", testXPathTagQuery), ("testXPathTagQueryWithNamespaces", testXPathTagQueryWithNamespaces), ("testAddingAsPreviousSibling", testAddingAsPreviousSibling), ("testAddingAsNextSibling", testAddingAsNextSibling) ] }() var libraries: Scrape.XMLDocument! var versions: Scrape.XMLDocument! private struct Seeds { static let xmlString = "<?xml version=\"1.0\"?><all_item><item><title>item0</title></item>" + "<item><title>item1</title></item></all_item>" static let allVersions = ["iOS 10", "iOS 9", "iOS 8", "macOS 10.12", "macOS 10.11", "tvOS 10.0"] static let iosVersions = ["iOS 10", "iOS 9", "iOS 8"] static let tvOSVErsion = "tvOS 10.0" static let librariesGithub = ["Scrape", "SwiftyJSON"] static let librariesBitbucket = ["Hoge"] } override func setUp() { super.setUp() guard let librariesData = getTestingResource(fromFile: "Libraries", ofType: "xml"), let versionsData = getTestingResource(fromFile: "Versions", ofType: "xml") else { XCTFail("Could not find a testing resource") return } guard let libraries = XMLDocument(xml: librariesData, encoding: .utf8), let versions = XMLDocument(xml: versionsData, encoding: .utf8) else { XCTFail("Could not initialize an XMLDocument instance") return } self.libraries = libraries self.versions = versions } // MARK: - Loading func testLoadXMLFromData() { // Given guard let correctData = getTestingResource(fromFile: "Versions", ofType: "xml") else { XCTFail("Could not find a testing resource") return } let incorrectData = "💩".data(using: .utf32)! // When let documentFromCorrectData = XMLDocument(xml: correctData, encoding: .utf8) let documentFromIncorrectData = XMLDocument(xml: incorrectData, encoding: .utf8) // Then XCTAssertNotNil(documentFromCorrectData, "XMLDocument should be initialized from correct Data") XCTAssertNil(documentFromIncorrectData, "XMLDocument should not be initialized from incorrect Data") } func testLoadXMLFromString() { // Given let correctString = Seeds.xmlString let incorrectString = "a><" // When let documentFromCorrectString = XMLDocument(xml: correctString, encoding: .utf8) let documentFromIncorrectString = XMLDocument(xml: incorrectString, encoding: .utf8) // Then XCTAssertNotNil(documentFromCorrectString, "XMLDocument should be initialized from a correct string") XCTAssertNil(documentFromIncorrectString, "XMLDocument should not be initialized from an incorrect string") } func testLoadXMLFromURL() { // Given guard let correctURL = getURLForTestingResource(forFile: "Versions", ofType: "xml") else { XCTFail("Could not find a testing resource") return } let incorrectURL = URL(fileURLWithPath: "42") // When let documentFromCorrectURL = XMLDocument(url: correctURL, encoding: .utf8) let documentFromIncorrectURL = XMLDocument(url: incorrectURL, encoding: .utf8) // Then XCTAssertNotNil(documentFromCorrectURL, "XMLDocument should be initialized from a correct URL") XCTAssertNil(documentFromIncorrectURL, "XMLDocument should not be initialized from an incorrect URL") } func testLoadXMLWithDifferentEncoding() { // Given let xmlString = Seeds.xmlString // When let document = XMLDocument(xml: xmlString, encoding: .japaneseEUC) // Then XCTAssertNotNil(document, "XMLDocument should be initialized even with an encoding other than UTF8") } func testLoadXMLWithParsingOptions() { // Given let xmlString = Seeds.xmlString // When let document = XMLDocument(xml: xmlString, encoding: .utf8, options: [.huge, .bigLines]) // Then XCTAssertNotNil(document, "XMLDocument should be initialized even with options other than default") } // MARK: - Readonly properties func testGetHTML() { // Given let expectedHTML = "<root>\n" + " <host xmlns=\"https://github.com/\">\n" + " <title>Scrape</title>\n" + " <title>SwiftyJSON</title>\n" + " </host>\n" + " <host xmlns=\"https://bitbucket.org/\">\n" + " <title>Hoge</title>\n" + " </host>\n" + "</root>\n" // When let returnedHTML = libraries.html // Then XCTAssertEqual(expectedHTML, returnedHTML) } func testGetXML() { // Given let expectedXML = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<root>\n" + " <host xmlns=\"https://github.com/\">\n" + " <title>Scrape</title>\n" + " <title>SwiftyJSON</title>\n" + " </host>\n" + " <host xmlns=\"https://bitbucket.org/\">\n" + " <title>Hoge</title>\n" + " </host>\n" + "</root>\n" // When let returnedXML = libraries.xml // Then XCTAssertEqual(expectedXML, returnedXML) } func testGetText() { // Given let expectedText = "\n \n Scrape\n SwiftyJSON\n \n \n Hoge\n \n" // When let returnedText = libraries.text // Then XCTAssertEqual(expectedText, returnedText) } func testGetInnerHTML() { // Given let expectedInnerHTML = "\n <host xmlns=\"https://github.com/\">\n" + " <title>Scrape</title>\n" + " <title>SwiftyJSON</title>\n" + " </host>\n" + " <host xmlns=\"https://bitbucket.org/\">\n" + " <title>Hoge</title>\n" + " </host>\n" // When let returnedInnerHTML = libraries.innerHTML // Then XCTAssertEqual(expectedInnerHTML, returnedInnerHTML) } func testGetClassName() { // When let returnedClassName = libraries.className // Then XCTAssertNil(returnedClassName) } // MARK: - Settable properties func testGetSetTagName() { // Given let expectedTagName = "root" let expectedModifiedHTML = "<foo>\n" + " <host xmlns=\"https://github.com/\">\n" + " <title>Scrape</title>\n" + " <title>SwiftyJSON</title>\n" + " </host>\n" + " <host xmlns=\"https://bitbucket.org/\">\n" + " <title>Hoge</title>\n" + " </host>\n" + "</foo>\n" // When let returnedTagName = libraries.tagName // Then XCTAssertEqual(expectedTagName, returnedTagName) // When libraries.tagName = "foo" let returnedModifiedHTML = libraries.html // Then XCTAssertEqual(expectedModifiedHTML, returnedModifiedHTML) } func testGetSetContent() { // Given let expectedContent = "\n \n Scrape\n SwiftyJSON\n \n \n Hoge\n \n" let expectedModifiedHTML = "<root>foo</root>\n" let expectedDeletedContentHTML = "<root></root>\n" // When let returnedContent = libraries.content // Then XCTAssertEqual(expectedContent, returnedContent) // When libraries.content = "foo" let returnedModifiedHTML = libraries.html // Then XCTAssertEqual(expectedModifiedHTML, returnedModifiedHTML) // When libraries.content = nil let returnedDeletedContentHTML = libraries.html // Then XCTAssertEqual(expectedDeletedContentHTML, returnedDeletedContentHTML) } // MARK: - XPath queries func testXPathTagQuery() { // Given let expectedVersionsForTagName = Seeds.allVersions let expectedVersionsForTagsIOSName = Seeds.iosVersions // When let returnedVersionsForTagName = versions.search(byXPath: "//name").map { $0.text ?? "" } let returnedVersionsForTagsIOSName = versions.search(byXPath: "//ios//name").map { $0.text ?? "" } // Then XCTAssertEqual(expectedVersionsForTagName, returnedVersionsForTagName) XCTAssertEqual(expectedVersionsForTagsIOSName, returnedVersionsForTagsIOSName) } func testXPathTagQueryWithNamespaces() { // Given let expectedValuesInGithubNamespace = Seeds.librariesGithub let expectedValuesInBitbucketNamespace = Seeds.librariesBitbucket // When let returnedValuesInGithubNamespace = libraries .search(byXPath: "//github:title", namespaces: ["github" : "https://github.com/"]) .map { $0.text ?? "" } let returnedValuesInBitbucketNamespace = libraries .search(byXPath: "//bitbucket:title", namespaces: ["bitbucket": "https://bitbucket.org/"]) .map { $0.text ?? "" } // Then XCTAssertEqual(expectedValuesInGithubNamespace, returnedValuesInGithubNamespace) XCTAssertEqual(expectedValuesInBitbucketNamespace, returnedValuesInBitbucketNamespace) } func testAddingAsPreviousSibling() { // Given // Before: // // <all_item> // <item> // <title>item0</title> // </item> // <item> // <title>item1</title> // </item> // </all_item> let initialXML = Seeds.xmlString guard let document = XMLDocument(xml: initialXML, encoding: .utf8) else { XCTFail("Could not initialize an XMLDocument instance") return } // After: // // <all_item> // <item> // <title>item1</title> // </item> // <item> // <title>item0</title> // </item> // </all_item> let expectedModifiedXML = "<all_item><item><title>item1</title></item>" + "<item><title>item0</title></item></all_item>" // When let searchResult = document.search(byXPath: "//item") let item0 = searchResult[0] let item1 = searchResult[1] item0.addPreviousSibling(item1) let actualModifiedXML = document.element(atXPath: "//all_item")?.xml // Then XCTAssertEqual(expectedModifiedXML, actualModifiedXML) } func testAddingAsNextSibling() { // Given // Before: // // <all_item> // <item> // <title>item0</title> // </item> // <item> // <title>item1</title> // </item> // </all_item> let initialXML = Seeds.xmlString guard let document = XMLDocument(xml: initialXML, encoding: .utf8) else { XCTFail("Could not initialize an XMLDocument instance") return } // After: // // <all_item> // <item> // <title>item1</title> // </item> // <item> // <title>item0</title> // </item> // </all_item> let expectedModifiedXML = "<all_item><item><title>item1</title></item>" + "<item><title>item0</title></item></all_item>" // When let searchResult = document.search(byXPath: "//item") let item0 = searchResult[0] let item1 = searchResult[1] item1.addNextSibling(item0) let actualModifiedXML = document.element(atXPath: "//all_item")?.xml // Then XCTAssertEqual(expectedModifiedXML, actualModifiedXML) } // MARK: - CSS selector queries #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) func testCSSSelectorTagQuery() { // Given let expectedVersionsForTagsIOSName = Seeds.iosVersions let expectedVersionForTagsTVOSName = Seeds.tvOSVErsion // When let returnedVersionsForTagsIOSName = versions.search(byCSSSelector: "ios name").map { $0.text ?? "" } let returnedVersionForTagsTVOSName = versions.element(atCSSSelector: "tvos name")?.text // Then XCTAssertEqual(expectedVersionsForTagsIOSName, returnedVersionsForTagsIOSName) XCTAssertEqual(expectedVersionForTagsTVOSName, returnedVersionForTagsTVOSName) } #endif }
mit
dc34c0ea0030221a83bf2c9719a6caed
29.497758
115
0.5794
4.443646
false
true
false
false
DivineDominion/mac-appdev-code
CoreDataOnlyTests/XCTestCase+CocoaBindings.swift
1
1026
import Cocoa import XCTest extension XCTestCase { func hasBinding(_ object: NSObject, binding:String, to boundObject: NSObject, throughKeyPath keyPath:String, transformingWith transformerName: String) -> Bool { if !hasBinding(object, binding: binding, to: boundObject, throughKeyPath: keyPath) { return false } if let info = object.infoForBinding(binding), let options = info[NSOptionsKey] as? [String: AnyObject], let boundTransformerName = options["NSValueTransformerName"] as? String { return boundTransformerName == transformerName } return false } func hasBinding(_ object: NSObject, binding:String, to boundObject: NSObject, throughKeyPath keyPath:String) -> Bool { if let info = object.infoForBinding(binding) { return (info[NSObservedObjectKey] as! NSObject == boundObject) && (info[NSObservedKeyPathKey] as! String == keyPath) } return false } }
mit
20934d59f1c5765c1dd12f14464c08ea
38.461538
185
0.652047
4.794393
false
true
false
false
jarsen/Pipes
PipesTests/BackwardPipeTests.swift
1
553
// // Created by Jason Larsen on 4/27/15. // import XCTest import Pipes class BackwardPipeTests : XCTestCase { func testPipeOperatorWorks() { let increment: (Int)->Int = { x in x + 1 } let value = increment <| 4 expect(value) == 5 } func testOrderOfOperations() { let increment: (Int)->Int = { x in x + 1 } let double: (Int)->Int = {x in x*2} var value = double <| 2 + 4 expect(value) == 12 value = double <| increment <| 2 expect(value) == 6 } }
mit
9c6540b02ed96e12f882304f14de96f9
21.12
50
0.524412
3.686667
false
true
false
false
BBRick/wp
wp/Scenes/User/MyWealthTableView.swift
1
2745
// // MywealthTableView.swift // wp // // Created by sum on 2017/1/8. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit class MyWealthTableView: UITableView ,UITableViewDelegate, UITableViewDataSource{ var refreshController = UIRefreshControl() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) delegate = self dataSource = self rowHeight = 66 refreshController.addTarget(self, action: #selector(refreshData), for: .valueChanged) refreshController.attributedTitle = NSAttributedString(string: "下拉刷新数据") self.addSubview(refreshController) } func refreshData() { //移除老数据 self.refreshController.endRefreshing() } func numberOfSections(in tableView: UITableView) -> Int{ return 10 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } // func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { // // // if section == 0 { // headerView = UIView.init(frame:CGRect.init(x: 0, y: 0, width:self.view.frame.size.width, height: 40)) // // // monthLb = UILabel.init(frame: CGRect.init(x: 17, y: 0, width: self.view.frame.size.width, height: 40)) // monthLb.text = "12 月" // // headerView.addSubview(monthLb) // // self.monthLb.text = "本月收益" // return headerView // // } // if section == 1 { // // headerView = UIView.init(frame:CGRect.init(x: 0, y: 0, width:self.view.frame.size.width, height: 40)) // // // monthLb = UILabel.init(frame: CGRect.init(x: 17, y: 0, width: self.view.frame.size.width, height: 40)) // monthLb.text = "12 月" // // headerView.addSubview(monthLb) // self.monthLb.text = "12" // // return headerView // // } // // return headerView // } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{ return 40 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{ return 0.1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyWealtVCCell", for: indexPath) return cell } }
apache-2.0
1799d1c2295f3ca92d004eb7027c59b8
29.088889
120
0.560561
4.424837
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/Samples.swift
1
3602
// // Samples.swift // Feature Demo // // Created by Aare Undo on 19/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation class Samples { static var list = [Sample]() static func initialize() { let folder = "" var sample = Sample() sample.title = "BASEMAP STYLES" sample.description = "Various samples of different CARTO Base Maps" sample.imageResource = folder + "icon_sample_styles.png" sample.controller = StyleChoiceController.self list.append(sample) sample = Sample() sample.title = "SEARCH API" sample.description = "Search points of interests near route" sample.imageResource = folder + "icon_sample_route_search.png" sample.controller = RouteSearchController.self list.append(sample) sample = Sample() sample.title = "OFFLINE MAP" sample.description = "Download existing map packages for offline use" sample.imageResource = folder + "icon_sample_package_download.png" sample.controller = OfflineMapController.self list.append(sample) sample = Sample() sample.title = "OFFLINE ROUTING" sample.description = "Download existing routing packages for offline use" sample.imageResource = folder + "icon_sample_offline_routing.png" sample.controller = OfflineRoutingController.self list.append(sample) sample = Sample() sample.title = "VECTOR ELEMENTS" sample.description = "Different popups, polygons and a NMLModel" sample.imageResource = folder + "icon_sample_vector_objects.png" sample.controller = VectorObjectController.self list.append(sample) sample = Sample() sample.title = "ELEMENT CLUSTERING" sample.description = "Loads 20000 elements and shows as clusters" sample.imageResource = folder + "icon_sample_clustering.png" sample.controller = ClusteringController.self list.append(sample) sample = Sample() sample.title = "OBJECT EDITING" sample.description = "Places editable objects on the world map" sample.imageResource = folder + "icon_sample_object_editing.png" sample.controller = VectorObjectEditingController.self list.append(sample) sample = Sample() sample.title = "GPS LOCATION" sample.description = "Locates you and places a marker on the location" sample.imageResource = folder + "icon_sample_gps_location.png" sample.controller = GPSLocationController.self list.append(sample) sample = Sample() sample.title = "GEOCODING" sample.description = "Enter an address to locate it on the map" sample.imageResource = folder + "icon_sample_geocoding.png" sample.controller = GeocodingController.self list.append(sample) sample = Sample() sample.title = "REVERSE GEOCODING" sample.description = "Click an area on the map to get information about it" sample.imageResource = folder + "icon_sample_reverse_geocoding.png" sample.controller = ReverseGecodingController.self list.append(sample) } } class Sample { var imageResource: String! var title: String! var description: String! var controller: BaseController.Type! }
bsd-2-clause
7c5275ee2b3c4ac67d3a8f282ef0299d
31.736364
83
0.622049
4.688802
false
false
false
false
kreeger/pinwheel
Classes/Core/Extensions/Dictionary.swift
1
657
// // Pinwheel // Dictionary.swift // Copyright (c) 2014 Ben Kreeger. All rights reserved. // import Foundation func +=<K, V> (inout left: Dictionary<K, V>, right: Dictionary<K, V>) -> Dictionary<K, V> { for (k, v) in right { left.updateValue(v, forKey: k) } return left } extension Dictionary { func queryStringParams() -> String? { if self.count == 0 { return nil } var elements = [String]() for (key, value) in self { elements.append("\(key)=\(value)") } let joined = "&".join(elements.map({ "\($0)" })) return "?\(joined)" } }
mit
c0d7f8cdfd00760966b41b74d8d616ef
21.689655
91
0.519026
3.754286
false
false
false
false
wheerd/swift-parser
Sources/ast.swift
1
2596
protocol ASTNode: CustomStringConvertible { } protocol Statement: ASTNode { } protocol Expression: ASTNode { } class BaseExpression: Expression { var description: String { get { preconditionFailure("This method must be overridden") } } } protocol Declaration: ASTNode { var name: String { get } } class BaseDeclaration: Declaration { let name: String init(_ name: String) { self.name = name } var description: String { get { preconditionFailure("This method must be overridden") } } } protocol OperatorDeclaration: Declaration { } class PrefixOperatorDeclaration: BaseDeclaration, OperatorDeclaration { override var description: String { return "prefix operator \(name)" } } class PostfixOperatorDeclaration: BaseDeclaration, OperatorDeclaration { override var description: String { return "postfix operator \(name)" } } class InfixOperatorDeclaration: BaseDeclaration, OperatorDeclaration { let precedenceGroupName: String? init(_ name: String, precedenceGroup: String? = nil) { precedenceGroupName = precedenceGroup super.init(name) } override var description: String { if let group = precedenceGroupName { return "infix operator \(name): \(group)" } return "infix operator \(name)" } } enum Associativity { case Left, Right, None } class PrecedenceGroupDeclaration: BaseDeclaration { let `higherThan`: [Identifier] let `lowerThan`: [Identifier] let `associativity`: Associativity let `assignment`: Bool init(_ name: String, higherThan: [Identifier] = [], lowerThan: [Identifier] = [], associativity: Associativity = .None, assignment: Bool = false) { self.higherThan = higherThan self.lowerThan = lowerThan self.associativity = associativity self.assignment = assignment super.init(name) } override var description: String { var attributes = " associativity: \(associativity)\n assignment: \(assignment)" if !higherThan.isEmpty { attributes += "\n higherThan: \((higherThan.map {$0.description}).joined(separator: ", "))" } if !lowerThan.isEmpty { attributes += "\n lowerThan: \((lowerThan.map {$0.description}).joined(separator: ", "))" } return "precedencegroup \(name) {\n\(attributes)\n}" } }
mit
344ad3bebb0e0e33206d77e6c340c038
21.387387
151
0.61171
4.834264
false
false
false
false
apple/swift
test/Sema/availability_literals.swift
1
7714
// RUN: %target-typecheck-verify-swift -swift-version 5 // REQUIRES: OS=macosx // https://github.com/apple/swift/issues/61564 // ExpressibleByStringLiteral struct SLD {} @available(*, deprecated) extension SLD: ExpressibleByStringLiteral { init(stringLiteral value: StringLiteralType) {} } let _ = SLD(stringLiteral: "") // expected-warning{{'init(stringLiteral:)' is deprecated}} let _: SLD = "" // expected-warning{{'init(stringLiteral:)' is deprecated}} struct SLU {} @available(macOS 100, *) extension SLU: ExpressibleByStringLiteral { init(stringLiteral value: StringLiteralType) {} } let _ = SLU(stringLiteral: "") // expected-error{{'init(stringLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: SLU = "" // expected-error{{'init(stringLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByIntegerLiteral struct ILD {} @available(*, deprecated) extension ILD: ExpressibleByIntegerLiteral { init(integerLiteral value: IntegerLiteralType) {} } let _ = ILD(integerLiteral: 1) // expected-warning{{'init(integerLiteral:)' is deprecated}} let _: ILD = 1 // expected-warning{{'init(integerLiteral:)' is deprecated}} struct ILU {} @available(macOS 100, *) extension ILU: ExpressibleByIntegerLiteral { init(integerLiteral value: IntegerLiteralType) {} } let _ = ILU(integerLiteral: 1) // expected-error{{'init(integerLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: ILU = 1 // expected-error{{'init(integerLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByNilLiteral struct NLD {} @available(*, deprecated) extension NLD: ExpressibleByNilLiteral { init(nilLiteral: ()) {} } let _: NLD = .init(nilLiteral: ()) // expected-warning{{'init(nilLiteral:)' is deprecated}} let _: NLD = nil // expected-warning{{'init(nilLiteral:)' is deprecated}} struct NLU {} @available(macOS 100, *) extension NLU: ExpressibleByNilLiteral { init(nilLiteral: ()) {} } let _: NLU = .init(nilLiteral: ()) // expected-error{{'init(nilLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: NLU = nil // expected-error{{'init(nilLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByBooleanLiteral struct BLD {} @available(*, deprecated) extension BLD: ExpressibleByBooleanLiteral { init(booleanLiteral value: BooleanLiteralType) {} } let _: BLD = .init(booleanLiteral: false) // expected-warning{{'init(booleanLiteral:)' is deprecated}} let _: BLD = false // expected-warning{{'init(booleanLiteral:)' is deprecated}} struct BLU {} @available(macOS 100, *) extension BLU: ExpressibleByBooleanLiteral { init(booleanLiteral value: BooleanLiteralType) {} } let _: BLU = .init(booleanLiteral: false) // expected-error{{'init(booleanLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: BLU = false // expected-error{{'init(booleanLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByFloatLiteral struct FLD {} @available(*, deprecated) extension FLD: ExpressibleByFloatLiteral { init(floatLiteral value: FloatLiteralType) {} } let _: FLD = .init(floatLiteral: 0.1) // expected-warning{{'init(floatLiteral:)' is deprecated}} let _: FLD = 0.1 // expected-warning{{'init(floatLiteral:)' is deprecated}} struct FLU {} @available(macOS 100, *) extension FLU: ExpressibleByFloatLiteral { init(floatLiteral value: FloatLiteralType) {} } let _: FLU = .init(floatLiteral: 0.1) // expected-error{{'init(floatLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: FLU = 0.1 // expected-error{{'init(floatLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByArrayLiteral struct ALD {} @available(*, deprecated) extension ALD: ExpressibleByArrayLiteral { init(arrayLiteral elements: Int...) {} } let _: ALD = .init(arrayLiteral: 1) // expected-warning{{'init(arrayLiteral:)' is deprecated}} let _: ALD = [1] // expected-warning{{'init(arrayLiteral:)' is deprecated}} struct ALU {} @available(macOS 100, *) extension ALU: ExpressibleByArrayLiteral { init(arrayLiteral elements: Int...) {} } let _: ALU = .init(arrayLiteral: 1) // expected-error{{'init(arrayLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: ALU = [1] // expected-error{{'init(arrayLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByDictionaryLiteral struct DLD {} @available(*, deprecated) extension DLD: ExpressibleByDictionaryLiteral { init(dictionaryLiteral elements: (Int, Int)...) {} } let _: DLD = .init(dictionaryLiteral: (1,1)) // expected-warning{{'init(dictionaryLiteral:)' is deprecated}} let _: DLD = [1: 1] // expected-warning{{'init(dictionaryLiteral:)' is deprecated}} struct DLU {} @available(macOS 100, *) extension DLU: ExpressibleByDictionaryLiteral { init(dictionaryLiteral elements: (Int, Int)...) {} } let _: DLU = .init(dictionaryLiteral: (1,1)) // expected-error{{'init(dictionaryLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: DLU = [1: 1] // expected-error{{'init(dictionaryLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} // ExpressibleByUnicodeScalarLiteral struct USLD {} @available(*, deprecated) extension USLD: ExpressibleByUnicodeScalarLiteral { typealias UnicodeScalarLiteralType = Character init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {} } let _: USLD = .init(unicodeScalarLiteral: "a") // expected-warning{{'init(unicodeScalarLiteral:)' is deprecated}} let _: USLD = "a" // expected-warning{{'init(unicodeScalarLiteral:)' is deprecated}} struct USLU {} @available(macOS 100, *) extension USLU: ExpressibleByUnicodeScalarLiteral { typealias UnicodeScalarLiteralType = Character init(unicodeScalarLiteral value: UnicodeScalarLiteralType) {} } let _: USLU = .init(unicodeScalarLiteral: "a") // expected-error{{'init(unicodeScalarLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: USLU = "a" // expected-error{{'init(unicodeScalarLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} //ExpressibleByExtendedGraphemeClusterLiteral struct GCLD {} @available(*, deprecated) extension GCLD: ExpressibleByExtendedGraphemeClusterLiteral { init(extendedGraphemeClusterLiteral value: Character) {} } let _: GCLD = .init(extendedGraphemeClusterLiteral: "🇧🇷") // expected-warning{{'init(extendedGraphemeClusterLiteral:)' is deprecated}} let _: GCLD = "🇧🇷" // expected-warning{{'init(extendedGraphemeClusterLiteral:)' is deprecated}} struct GCLU {} @available(macOS 100, *) extension GCLU: ExpressibleByExtendedGraphemeClusterLiteral { init(extendedGraphemeClusterLiteral value: Character) {} } let _: GCLU = .init(extendedGraphemeClusterLiteral: "🇧🇷") // expected-error{{'init(extendedGraphemeClusterLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}} let _: GCLU = "🇧🇷" // expected-error{{'init(extendedGraphemeClusterLiteral:)' is only available in macOS 100 or newer}} expected-note{{add 'if #available' version check}}
apache-2.0
f6b62fee1ee13eee6ab822871b7fb5bf
44.502959
209
0.73394
4.218321
false
false
false
false
rnystrom/GitHawk
Pods/Apollo/Sources/Apollo/ApolloClient.swift
1
10807
import Foundation import Dispatch /// An object that can be used to cancel an in progress action. public protocol Cancellable: class { /// Cancel an in progress action. func cancel() } /// A cache policy that specifies whether results should be fetched from the server or loaded from the local cache. public enum CachePolicy { /// Return data from the cache if available, else fetch results from the server. case returnCacheDataElseFetch /// Always fetch results from the server. case fetchIgnoringCacheData /// Return data from the cache if available, else return nil. case returnCacheDataDontFetch /// Return data from the cache if available, and always fetch results from the server. case returnCacheDataAndFetch } /// A handler for operation results. /// /// - Parameters: /// - result: The result of the performed operation, or `nil` if an error occurred. /// - error: An error that indicates why the mutation failed, or `nil` if the mutation was succesful. public typealias OperationResultHandler<Operation: GraphQLOperation> = (_ result: GraphQLResult<Operation.Data>?, _ error: Error?) -> Void /// The `ApolloClient` class provides the core API for Apollo. This API provides methods to fetch and watch queries, and to perform mutations. public class ApolloClient { let networkTransport: NetworkTransport public let store: ApolloStore public var cacheKeyForObject: CacheKeyForObject? { get { return store.cacheKeyForObject } set { store.cacheKeyForObject = newValue } } private let queue: DispatchQueue private let operationQueue: OperationQueue /// Creates a client with the specified network transport and store. /// /// - Parameters: /// - networkTransport: A network transport used to send operations to a server. /// - store: A store used as a local cache. Defaults to an empty store backed by an in memory cache. public init(networkTransport: NetworkTransport, store: ApolloStore = ApolloStore(cache: InMemoryNormalizedCache())) { self.networkTransport = networkTransport self.store = store queue = DispatchQueue(label: "com.apollographql.ApolloClient", attributes: .concurrent) operationQueue = OperationQueue() } /// Creates a client with an HTTP network transport connecting to the specified URL. /// /// - Parameter url: The URL of a GraphQL server to connect to. public convenience init(url: URL) { self.init(networkTransport: HTTPNetworkTransport(url: url)) } /// Clears apollo cache /// /// - Returns: Promise public func clearCache() -> Promise<Void> { return store.clearCache() } /// Fetches a query from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. /// /// - Parameters: /// - query: The query to fetch. /// - cachePolicy: A cache policy that specifies when results should be fetched from the server and when data should be loaded from the local cache. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when query results are available or when an error occurs. /// - Returns: An object that can be used to cancel an in progress fetch. @discardableResult public func fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: OperationResultHandler<Query>? = nil) -> Cancellable { return _fetch(query: query, cachePolicy: cachePolicy, queue: queue, resultHandler: resultHandler) } func _fetch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue, resultHandler: OperationResultHandler<Query>?) -> Cancellable { // If we don't have to go through the cache, there is no need to create an operation // and we can return a network task directly if cachePolicy == .fetchIgnoringCacheData { return send(operation: query, context: context, handlerQueue: queue, resultHandler: resultHandler) } else { let operation = FetchQueryOperation(client: self, query: query, cachePolicy: cachePolicy, context: context, handlerQueue: queue, resultHandler: resultHandler) operationQueue.addOperation(operation) return operation } } /// Watches a query by first fetching an initial result from the server or from the local cache, depending on the current contents of the cache and the specified cache policy. After the initial fetch, the returned query watcher object will get notified whenever any of the data the query result depends on changes in the local cache, and calls the result handler again with the new result. /// /// - Parameters: /// - query: The query to fetch. /// - cachePolicy: A cache policy that specifies when results should be fetched from the server or from the local cache. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when query results are available or when an error occurs. /// - Returns: A query watcher object that can be used to control the watching behavior. public func watch<Query: GraphQLQuery>(query: Query, cachePolicy: CachePolicy = .returnCacheDataElseFetch, queue: DispatchQueue = DispatchQueue.main, resultHandler: @escaping OperationResultHandler<Query>) -> GraphQLQueryWatcher<Query> { let watcher = GraphQLQueryWatcher(client: self, query: query, handlerQueue: queue, resultHandler: resultHandler) watcher.fetch(cachePolicy: cachePolicy) return watcher } /// Performs a mutation by sending it to the server. /// /// - Parameters: /// - mutation: The mutation to perform. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs. /// - Returns: An object that can be used to cancel an in progress mutation. @discardableResult public func perform<Mutation: GraphQLMutation>(mutation: Mutation, queue: DispatchQueue = DispatchQueue.main, resultHandler: OperationResultHandler<Mutation>? = nil) -> Cancellable { return _perform(mutation: mutation, queue: queue, resultHandler: resultHandler) } func _perform<Mutation: GraphQLMutation>(mutation: Mutation, context: UnsafeMutableRawPointer? = nil, queue: DispatchQueue, resultHandler: OperationResultHandler<Mutation>?) -> Cancellable { return send(operation: mutation, context: context, handlerQueue: queue, resultHandler: resultHandler) } /// Subscribe to a subscription /// /// - Parameters: /// - subscription: The subscription to subscribe to. /// - queue: A dispatch queue on which the result handler will be called. Defaults to the main queue. /// - resultHandler: An optional closure that is called when mutation results are available or when an error occurs. /// - Returns: An object that can be used to cancel an in progress subscription. @discardableResult public func subscribe<Subscription: GraphQLSubscription>(subscription: Subscription, queue: DispatchQueue = DispatchQueue.main, resultHandler: @escaping OperationResultHandler<Subscription>) -> Cancellable { return send(operation: subscription, context: nil, handlerQueue: queue, resultHandler: resultHandler) } fileprivate func send<Operation: GraphQLOperation>(operation: Operation, context: UnsafeMutableRawPointer?, handlerQueue: DispatchQueue, resultHandler: OperationResultHandler<Operation>?) -> Cancellable { func notifyResultHandler(result: GraphQLResult<Operation.Data>?, error: Error?) { guard let resultHandler = resultHandler else { return } handlerQueue.async { resultHandler(result, error) } } return networkTransport.send(operation: operation) { (response, error) in guard let response = response else { notifyResultHandler(result: nil, error: error) return } firstly { try response.parseResult(cacheKeyForObject: self.cacheKeyForObject) }.andThen { (result, records) in notifyResultHandler(result: result, error: nil) if let records = records { self.store.publish(records: records, context: context).catch { error in preconditionFailure(String(describing: error)) } } }.catch { error in notifyResultHandler(result: nil, error: error) } } } } private final class FetchQueryOperation<Query: GraphQLQuery>: AsynchronousOperation, Cancellable { let client: ApolloClient let query: Query let cachePolicy: CachePolicy let context: UnsafeMutableRawPointer? let handlerQueue: DispatchQueue let resultHandler: OperationResultHandler<Query>? private var networkTask: Cancellable? init(client: ApolloClient, query: Query, cachePolicy: CachePolicy, context: UnsafeMutableRawPointer?, handlerQueue: DispatchQueue, resultHandler: OperationResultHandler<Query>?) { self.client = client self.query = query self.cachePolicy = cachePolicy self.context = context self.handlerQueue = handlerQueue self.resultHandler = resultHandler } override public func start() { if isCancelled { state = .finished return } state = .executing if cachePolicy == .fetchIgnoringCacheData { fetchFromNetwork() return } client.store.load(query: query) { (result, error) in if error == nil { self.notifyResultHandler(result: result, error: nil) if self.cachePolicy != .returnCacheDataAndFetch { self.state = .finished return } } if self.isCancelled { self.state = .finished return } if self.cachePolicy == .returnCacheDataDontFetch { self.notifyResultHandler(result: nil, error: nil) self.state = .finished return } self.fetchFromNetwork() } } func fetchFromNetwork() { networkTask = client.send(operation: query, context: context, handlerQueue: handlerQueue) { (result, error) in self.notifyResultHandler(result: result, error: error) self.state = .finished return } } override public func cancel() { super.cancel() networkTask?.cancel() } func notifyResultHandler(result: GraphQLResult<Query.Data>?, error: Error?) { guard let resultHandler = resultHandler else { return } handlerQueue.async { resultHandler(result, error) } } }
mit
aeb0a27cec7f9044cf13dccc0db076d5
42.401606
391
0.713797
4.961892
false
false
false
false
cloudinary/cloudinary_ios
Example/Cloudinary/Controllers/InProgressViewController.swift
1
2970
// // UploadedViewController.swift // SampleApp // // Created by Nitzan Jaitman on 27/08/2017. // Copyright © 2017 Cloudinary. All rights reserved. // import Foundation import UIKit class InProgressViewController: BaseCollectionViewController { static let progressChangedNotification = NSNotification.Name(rawValue: "com.cloudinary.sample.progress.notification") // MARK: Properties @IBOutlet weak var collectionView: UICollectionView! var progressMap: [String: Progress] = [:] // MARK: ViewController override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(InProgressViewController.progressChanged(notification:)), name: InProgressViewController.progressChangedNotification, object: nil) } override func getReuseIdentifier() -> String { return "ResourceInProgressCell" } override func getItemsPerRow() -> CGFloat { return CGFloat(2); } override func getCollectionView() -> UICollectionView! { return collectionView } override func reloadData() { PersistenceHelper.fetch(statuses: [PersistenceHelper.UploadStatus.queued, PersistenceHelper.UploadStatus.uploading]) { fetchedResources in var oldResources = Set(self.resources) self.resources = fetchedResources as! [CLDResource] self.collectionView.reloadData() let newResources = Set(self.resources) oldResources.subtract(newResources) // if something was here before and it's gone now, clean it up from the progress map as well for res in oldResources { self.progressMap.removeValue(forKey: res.localPath!) } } } @objc func progressChanged(notification: NSNotification) { // update progress in map let name = notification.userInfo?["name"] as? String let progress = notification.userInfo?["progress"] as? Progress if (name != nil && progress != nil) { progressMap[name!] = progress! } // refresh views collectionView.reloadData() } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: getReuseIdentifier(), for: indexPath) as! ResourceInProgressCell let resource = resources[indexPath.row] setLocalImage(imageView: cell.imageView, resource: resource) cell.overlayView.isHidden = true if let progress = progressMap[resource.localPath!] { cell.overlayView.isHidden = false cell.progressView.isHidden = false cell.progressView.progress = Float(progress.fractionCompleted) } else { cell.overlayView.isHidden = true cell.progressView.isHidden = true } return cell } }
mit
af018859ad5a23e9864d01f0a4b23ce3
34.771084
203
0.677332
5.227113
false
false
false
false
whipsterCZ/DppSms
dppFakeSms/MessagesViewController.swift
1
2094
// // MessagesViewController.swift // dppFakeSms // // Created by Daniel Kouba on 18/04/15. // Copyright (c) 2015 DéKá Studio. All rights reserved. // import UIKit class MessagesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! override func viewWillAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "reload", name: "update", object: nil) } override func viewDidLoad() { //style tableView let nibName = UINib(nibName: "TableViewCell", bundle:nil) tableView.registerNib(nibName, forCellReuseIdentifier: "Cell") tableView.separatorStyle = .None tableView.allowsSelection = false } func reload(){ tableView.reloadData() } @IBAction func genererateNew(sender: AnyObject) { DI.context.appDelegate.generateMessages() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return DI.context.appDelegate.messages.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell let message = DI.context.appDelegate.messages[indexPath.item] cell.dateLabel.text = message.getRecievedAt() cell.dateFromLabel.text = message.getFromDay() cell.dateToLabel.text = message.getToDay() cell.timeFromLabel.text = message.getFromTime() cell.timeToLabel.text = message.getToTime() cell.priceLabel.text = message.getPrice() cell.codeLabel.text = message.getCodeString() + " /" cell.codeIntLabel.text = message.getCodeInt() return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 200.0 } }
gpl-2.0
78150161ba6fa79e046dad5b99a4f227
30.223881
113
0.658222
4.933962
false
false
false
false
stormpath/stormpath-swift-example
Pods/Stormpath/Stormpath/Models/FormField.swift
1
759
// // FormField.swift // Stormpath // // Created by Edward Jiang on 12/15/16. // Copyright © 2016 Stormpath. All rights reserved. // import UIKit class FormField { let name: String let label: String let placeholder: String let required: Bool let type: String init?(json: JSON) { guard let name = json["name"].string, let label = json["label"].string, let placeholder = json["placeholder"].string, let required = json["required"].bool, let type = json["type"].string else { return nil } self.name = name self.label = label self.placeholder = placeholder self.required = required self.type = type } }
mit
3fd85edbc6e3660ee28559448fd9bb6a
22.6875
57
0.568602
4.282486
false
false
false
false
zisko/swift
test/SILGen/multi_file.swift
1
3156
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s func markUsed<T>(_ t: T) {} // CHECK-LABEL: sil hidden @$S10multi_file12rdar16016713{{[_0-9a-zA-Z]*}}F func rdar16016713(_ r: Range) { // CHECK: [[LIMIT:%[0-9]+]] = function_ref @$S10multi_file5RangeV5limitSivg : $@convention(method) (Range) -> Int // CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int markUsed(r.limit) } // CHECK-LABEL: sil hidden @$S10multi_file26lazyPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F func lazyPropertiesAreNotStored(_ container: LazyContainer) { var container = container // CHECK: {{%[0-9]+}} = function_ref @$S10multi_file13LazyContainerV7lazyVarSivg : $@convention(method) (@inout LazyContainer) -> Int markUsed(container.lazyVar) } // CHECK-LABEL: sil hidden @$S10multi_file29lazyRefPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) { // CHECK: bb0([[ARG:%.*]] : @owned $LazyContainerClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: {{%[0-9]+}} = class_method [[BORROWED_ARG]] : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int, $@convention(method) (@guaranteed LazyContainerClass) -> Int markUsed(container.lazyVar) } // CHECK-LABEL: sil hidden @$S10multi_file25finalVarsAreDevirtualizedyyAA18FinalPropertyClassCF func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) { // CHECK: bb0([[ARG:%.*]] : @owned $FinalPropertyClass): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: ref_element_addr [[BORROWED_ARG]] : $FinalPropertyClass, #FinalPropertyClass.foo // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] markUsed(obj.foo) // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [[BORROWED_ARG]] : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1 markUsed(obj.bar) } // rdar://18448869 // CHECK-LABEL: sil hidden @$S10multi_file34finalVarsDontNeedMaterializeForSetyyAA27ObservingPropertyFinalClassCF func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) { obj.foo += 1 // CHECK: function_ref @$S10multi_file27ObservingPropertyFinalClassC3fooSivg // CHECK: function_ref @$S10multi_file27ObservingPropertyFinalClassC3fooSivs } // rdar://18503960 // Ensure that we type-check the materializeForSet accessor from the protocol. class HasComputedProperty: ProtocolWithProperty { var foo: Int { get { return 1 } set {} } } // CHECK-LABEL: sil hidden [transparent] @$S10multi_file19HasComputedPropertyC3fooSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK-LABEL: sil private [transparent] [thunk] @$S10multi_file19HasComputedPropertyCAA012ProtocolWithE0A2aDP3fooSivmTW : $@convention(witness_method: ProtocolWithProperty) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
apache-2.0
261a4928eb0647ebfe25024a3f3cd39d
55.357143
313
0.728771
3.538117
false
false
false
false
albertochiwas/Rollo1000
Rollo1000/Rollo1000/Libreria.swift
1
471
// // Libreria.swift // Rollo1000 // // Created by Alberto Pacheco on 27/10/15. // Copyright © 2015 Alberto Pacheco. All rights reserved. // import Foundation func minMax(start:Int, _ end:Int) -> (min:Int, max:Int) { let mn = start<end ? start : end let mx = start<end ? end : start return (mn,mx) } func generaNum( start: Int=1, _ end: Int=1000) -> Int { let r = minMax(start,end) return Int(arc4random_uniform(UInt32(r.max-r.min)))+r.min }
gpl-2.0
4cfe2bed7b8dda440ee230cb3bd40982
21.380952
61
0.634043
2.748538
false
false
false
false
zmarvin/EnjoyMusic
Pods/Macaw/Source/thirdparty/CAAnimationClosure.swift
1
5814
// // CAAnimation+Closure.swift // CAAnimation+Closures // // Created by Honghao Zhang on 2/5/15. // Copyright (c) 2015 Honghao Zhang. All rights reserved. // import QuartzCore /// CAAnimation Delegation class implementation class CAAnimationDelegateImpl:NSObject, CAAnimationDelegate { /// start: A block (closure) object to be executed when the animation starts. This block has no return value and takes no argument. var start: (() -> Void)? /// completion: A block (closure) object to be executed when the animation ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished. var completion: ((Bool) -> Void)? /// startTime: animation start date fileprivate var startTime: Date! fileprivate var animationDuration: TimeInterval! fileprivate var animatingTimer: Timer! /// animating: A block (closure) object to be executed when the animation is animating. This block has no return value and takes a single CGFloat argument that indicates the progress of the animation (From 0 ..< 1) var animating: ((CGFloat) -> Void)? { willSet { if animatingTimer == nil { animatingTimer = Timer(timeInterval: 0, target: self, selector: #selector(CAAnimationDelegateImpl.animationIsAnimating(_:)), userInfo: nil, repeats: true) } } } /** Called when the animation begins its active duration. - parameter theAnimation: the animation about to start */ func animationDidStart(_ theAnimation: CAAnimation) { start?() if animating != nil { animationDuration = theAnimation.duration startTime = Date() RunLoop.current.add(animatingTimer, forMode: RunLoopMode.defaultRunLoopMode) } } /** Called when the animation completes its active duration or is removed from the object it is attached to. - parameter theAnimation: the animation about to end - parameter finished: A Boolean value indicates whether or not the animations actually finished. */ func animationDidStop(_ theAnimation: CAAnimation, finished: Bool) { completion?(finished) animatingTimer?.invalidate() } /** Called when the animation is executing - parameter timer: timer */ func animationIsAnimating(_ timer: Timer) { let progress = CGFloat(Date().timeIntervalSince(startTime) / animationDuration) if progress <= 1.0 { animating?(progress) } } } public extension CAAnimation { /// A block (closure) object to be executed when the animation starts. This block has no return value and takes no argument. public var start: (() -> Void)? { set { if let animationDelegate = delegate as? CAAnimationDelegateImpl { animationDelegate.start = newValue } else { let animationDelegate = CAAnimationDelegateImpl() animationDelegate.start = newValue delegate = animationDelegate } } get { if let animationDelegate = delegate as? CAAnimationDelegateImpl { return animationDelegate.start } return nil } } /// A block (closure) object to be executed when the animation ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished. public var completion: ((Bool) -> Void)? { set { if let animationDelegate = delegate as? CAAnimationDelegateImpl { animationDelegate.completion = newValue } else { let animationDelegate = CAAnimationDelegateImpl() animationDelegate.completion = newValue delegate = animationDelegate } } get { if let animationDelegate = delegate as? CAAnimationDelegateImpl { return animationDelegate.completion } return nil } } /// A block (closure) object to be executed when the animation is animating. This block has no return value and takes a single CGFloat argument that indicates the progress of the animation (From 0 ..< 1) public var animating: ((CGFloat) -> Void)? { set { if let animationDelegate = delegate as? CAAnimationDelegateImpl { animationDelegate.animating = newValue } else { let animationDelegate = CAAnimationDelegateImpl() animationDelegate.animating = newValue delegate = animationDelegate } } get { if let animationDelegate = delegate as? CAAnimationDelegateImpl { return animationDelegate.animating } return nil } } /// Alias to `animating` public var progress: ((CGFloat) -> Void)? { set { animating = newValue } get { return animating } } } public extension CALayer { /** Add the specified animation object to the layer’s render tree. Could provide a completion closure. - parameter anim: The animation to be added to the render tree. This object is copied by the render tree, not referenced. Therefore, subsequent modifications to the object are not propagated into the render tree. - parameter key: A string that identifies the animation. Only one animation per unique key is added to the layer. The special key kCATransition is automatically used for transition animations. You may specify nil for this parameter. - parameter completion: A block object to be executed when the animation ends. This block has no return value and takes a single Boolean argument that indicates whether or not the animations actually finished before the completion handler was called. Default value is nil. */ func addAnimation(_ anim: CAAnimation, forKey key: String?, withCompletion completion: ((Bool) -> Void)?) { anim.completion = completion add(anim, forKey: key) } }
mit
e9a661eee663729da492eec3fe8d0a56
35.553459
273
0.694081
4.827243
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/expression/errors/main.swift
4
1564
// main.swift // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- enum EnumError : Error { case ImportantError case TrivialError } class ClassError : Error { var _code : Int = 10 var _domain : String = "ClassError" var m_message : String init (_ message: String) { m_message = message } func SomeMethod (_ input : Int) { print (m_message) // Set a breakpoint here to test method contexts } } func IThrowEnumOver10(_ input : Int) throws -> Int { if input > 100 { throw EnumError.ImportantError } else if input > 10 { throw EnumError.TrivialError } else { return input + 2 } } func IThrowObjectOver10(_ input : Int) throws -> Int { if input > 100 { let my_error = ClassError("Over 100") throw my_error } else if input > 10 { let my_error = ClassError("Over 10 but less than 100") throw my_error } else { return input + 2 } } do { try IThrowEnumOver10(101) // Set a breakpoint here to run expressions try IThrowObjectOver10(11) } catch (let e) { print (e, true) }
apache-2.0
17edb9b71bec224be5ca661c011842b3
19.578947
80
0.578645
3.871287
false
false
false
false
kasketis/netfox
netfox/iOS/NFXSettingsController_iOS.swift
1
9596
// // NFXSettingsController_iOS.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // #if os(iOS) import UIKit import MessageUI class NFXSettingsController_iOS: NFXSettingsController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate, DataCleaner { var tableView: UITableView = UITableView(frame: .zero, style: .grouped) // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() nfxURL = "https://github.com/kasketis/netfox" title = "Settings" tableData = HTTPModelShortType.allCases edgesForExtendedLayout = UIRectEdge() extendedLayoutIncludesOpaqueBars = false automaticallyAdjustsScrollViewInsets = false navigationItem.rightBarButtonItems = [UIBarButtonItem(image: UIImage.NFXStatistics(), style: .plain, target: self, action: #selector(NFXSettingsController_iOS.statisticsButtonPressed)), UIBarButtonItem(image: UIImage.NFXInfo(), style: .plain, target: self, action: #selector(NFXSettingsController_iOS.infoButtonPressed))] tableView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - 60) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.translatesAutoresizingMaskIntoConstraints = true tableView.delegate = self tableView.dataSource = self tableView.alwaysBounceVertical = false tableView.backgroundColor = UIColor.clear tableView.separatorInset = .zero tableView.tableFooterView = UIView(frame: CGRect.zero) tableView.tableFooterView?.isHidden = true view.addSubview(tableView) var nfxVersionLabel: UILabel nfxVersionLabel = UILabel(frame: CGRect(x: 10, y: view.frame.height - 60, width: view.frame.width - 2*10, height: 30)) nfxVersionLabel.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] nfxVersionLabel.font = UIFont.NFXFont(size: 14) nfxVersionLabel.textColor = UIColor.NFXOrangeColor() nfxVersionLabel.textAlignment = .center nfxVersionLabel.text = nfxVersionString view.addSubview(nfxVersionLabel) var nfxURLButton: UIButton nfxURLButton = UIButton(frame: CGRect(x: 10, y: view.frame.height - 40, width: view.frame.width - 2*10, height: 30)) nfxURLButton.autoresizingMask = [.flexibleTopMargin, .flexibleWidth] nfxURLButton.titleLabel?.font = UIFont.NFXFont(size: 12) nfxURLButton.setTitleColor(UIColor.NFXGray44Color(), for: .init()) nfxURLButton.titleLabel?.textAlignment = .center nfxURLButton.setTitle(nfxURL, for: .init()) nfxURLButton.addTarget(self, action: #selector(NFXSettingsController_iOS.nfxURLButtonPressed), for: .touchUpInside) view.addSubview(nfxURLButton) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NFXHTTPModelManager.shared.filters = filters } @objc func nfxURLButtonPressed() { UIApplication.shared.openURL(URL(string: nfxURL)!) } @objc func infoButtonPressed() { var infoController: NFXInfoController_iOS infoController = NFXInfoController_iOS() navigationController?.pushViewController(infoController, animated: true) } @objc func statisticsButtonPressed() { var statisticsController: NFXStatisticsController_iOS statisticsController = NFXStatisticsController_iOS() navigationController?.pushViewController(statisticsController, animated: true) } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return self.tableData.count case 2: return 1 case 3: return 1 default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.font = UIFont.NFXFont(size: 14) cell.textLabel?.textColor = .black cell.tintColor = UIColor.NFXOrangeColor() cell.backgroundColor = .white switch indexPath.section { case 0: cell.textLabel?.text = "Logging" let nfxEnabledSwitch: UISwitch nfxEnabledSwitch = UISwitch() nfxEnabledSwitch.setOn(NFX.sharedInstance().isEnabled(), animated: false) nfxEnabledSwitch.addTarget(self, action: #selector(NFXSettingsController_iOS.nfxEnabledSwitchValueChanged(_:)), for: .valueChanged) cell.accessoryView = nfxEnabledSwitch return cell case 1: let shortType = tableData[indexPath.row] cell.textLabel?.text = shortType.rawValue configureCell(cell, indexPath: indexPath) return cell case 2: cell.textLabel?.textAlignment = .center cell.textLabel?.text = "Share Session Logs" cell.textLabel?.textColor = UIColor.NFXGreenColor() cell.textLabel?.font = UIFont.NFXFont(size: 16) return cell case 3: cell.textLabel?.textAlignment = .center cell.textLabel?.text = "Clear data" cell.textLabel?.textColor = UIColor.NFXRedColor() cell.textLabel?.font = UIFont.NFXFont(size: 16) return cell default: return UITableViewCell() } } func numberOfSections(in tableView: UITableView) -> Int { return 4 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView() headerView.backgroundColor = UIColor.NFXGray95Color() switch section { case 1: var filtersInfoLabel: UILabel filtersInfoLabel = UILabel(frame: headerView.bounds) filtersInfoLabel.backgroundColor = UIColor.clear filtersInfoLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight] filtersInfoLabel.font = UIFont.NFXFont(size: 13) filtersInfoLabel.textColor = UIColor.NFXGray44Color() filtersInfoLabel.textAlignment = .center filtersInfoLabel.text = "\nSelect the types of responses that you want to see" filtersInfoLabel.numberOfLines = 2 headerView.addSubview(filtersInfoLabel) default: break } return headerView } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.section { case 1: let cell = tableView.cellForRow(at: indexPath) self.filters[indexPath.row] = !self.filters[indexPath.row] configureCell(cell, indexPath: indexPath) case 2: shareSessionLogsPressed() case 3: clearDataButtonPressedOnTableIndex(indexPath) default: break } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: return 44 case 1: return 33 case 2,3: return 44 default: return 0 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let iPhone4s = (UIScreen.main.bounds.height == 480) switch section { case 0: if iPhone4s { return 20 } else { return 40 } case 1: if iPhone4s { return 50 } else { return 60 } case 2, 3: if iPhone4s { return 25 } else { return 50 } default: return 0 } } func configureCell(_ cell: UITableViewCell?, indexPath: IndexPath) { cell?.accessoryType = filters[indexPath.row] ? .checkmark : .none } @objc func nfxEnabledSwitchValueChanged(_ sender: UISwitch) { if sender.isOn { NFX.sharedInstance().enable() } else { NFX.sharedInstance().disable() } } func clearDataButtonPressedOnTableIndex(_ index: IndexPath) { clearData(sourceView: tableView, originingIn: tableView.rectForRow(at: index)) { } } func shareSessionLogsPressed() { if (MFMailComposeViewController.canSendMail()) { let mailComposer = MFMailComposeViewController() mailComposer.mailComposeDelegate = self mailComposer.setSubject("netfox log - Session Log \(NSDate())") if let sessionLogData = try? Data(contentsOf: NFXPath.sessionLogURL) { mailComposer.addAttachmentData(sessionLogData as Data, mimeType: "text/plain", fileName: NFXPath.sessionLogName) } present(mailComposer, animated: true, completion: nil) } } func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } } #endif
mit
daba43db859ca79f354a6690bcf450a5
35.903846
329
0.624596
5.17809
false
false
false
false
IBM-MIL/BluePic
BluePic-iOS/BluePic/ViewModels/FeedViewModel.swift
1
12453
/** * Copyright IBM Corporation 2015 * * 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 //used to inform the Feed View Controller of notifications enum FeedViewModelNotification { //called when there is new data in the pictureDataArray, used to tell the Feed VC to refresh it's data in the collection view case RefreshCollectionView //called when in the view did appear of the tab vc case StartLoadingAnimationForAppLaunch //called when a photo is uploading to object storage case UploadingPhotoStarted //called when a photo is finished uploading to object storage case UploadingPhotoFinished } class FeedViewModel: NSObject { //array that holds all the picture data objects we used to populate the Feed VC's collection view var pictureDataArray = [Picture]() //callback used to inform the Feed VC when there is new data and to refresh its collection view var refreshVCCallback : (()->())? //callback used to inform the Feed VC of notifications from its view model var passFeedViewModelNotificationToFeedVCCallback : ((feedViewModelNotification : FeedViewModelNotification)->())! //state variable used to keep track if we have received data from cloudant yet var hasRecievedDataFromCloudant = false //state variable to keep of if we are current pulling from cloudant. This is to prevent a user to pull down to refresh while it is already refreshing private var isPullingFromCloudantAlready = false //constant that represents the height of the info view in the collection view cell that shows the photos caption and photographer name let kCollectionViewCellInfoViewHeight : CGFloat = 76 //constant that represents the height of the picture upload queue image feed collection view cell let kPictureUploadCollectionViewCellHeight : CGFloat = 60 //constant that represents the limit of how tall a collection view cell's height can be let kCollectionViewCellHeightLimit : CGFloat = 480 //constant that represents a value added to the height of the EmptyFeedCollectionViewCell when its given a size in the sizeForItemAtIndexPath method, this value allows the collection view to scroll let kEmptyFeedCollectionViewCellBufferToAllowForScrolling : CGFloat = 1 //constant that defines the number of cells there is when the user has no photos let kNumberOfCellsWhenUserHasNoPhotos = 1 //constant that defines the number of sections there are in the collection view let kNumberOfSectionsInCollectionView = 2 /** Method called upon init. It sets a callback to inform the VC of new noti - parameter passFeedViewModelNotificationToTabBarVCCallback: ((feedViewModelNotification : FeedViewModelNotification)->()) - returns: */ init(passFeedViewModelNotificationToFeedVCCallback : ((feedViewModelNotification : FeedViewModelNotification)->())){ super.init() self.passFeedViewModelNotificationToFeedVCCallback = passFeedViewModelNotificationToFeedVCCallback DataManagerCalbackCoordinator.SharedInstance.addCallback(handleDataManagerNotification) } /** Method called when there are new DataManager notifications - parameter dataManagerNotification: DataMangerNotification */ func handleDataManagerNotification(dataManagerNotification : DataManagerNotification){ if(dataManagerNotification == DataManagerNotification.CloudantPullDataSuccess){ isPullingFromCloudantAlready = false getPictureObjects() } else if(dataManagerNotification == DataManagerNotification.UserDecidedToPostPhoto){ self.passFeedViewModelNotificationToFeedVCCallback(feedViewModelNotification: FeedViewModelNotification.UploadingPhotoStarted) getPictureObjects() } else if(dataManagerNotification == DataManagerNotification.StartLoadingAnimationForAppLaunch){ self.passFeedViewModelNotificationToFeedVCCallback(feedViewModelNotification: FeedViewModelNotification.StartLoadingAnimationForAppLaunch) } else if(dataManagerNotification == DataManagerNotification.UserCanceledUploadingPhotos){ getPictureObjects() } else if(dataManagerNotification == DataManagerNotification.ObjectStorageUploadImageAndCloudantCreatePictureDocSuccess){ self.passFeedViewModelNotificationToFeedVCCallback(feedViewModelNotification: FeedViewModelNotification.UploadingPhotoFinished) getPictureObjects() } } /** Method asks cloudant to pull for new data */ func repullForNewData() { if(isPullingFromCloudantAlready == false){ isPullingFromCloudantAlready = true do { try CloudantSyncDataManager.SharedInstance!.pullFromRemoteDatabase() } catch { isPullingFromCloudantAlready = false print("repullForNewData ERROR: \(error)") DataManagerCalbackCoordinator.SharedInstance.sendNotification(DataManagerNotification.CloudantPullDataFailure) } } } /** Method synchronously asks cloudant for new data. It sets the pictureDataArray to be a combination of the local pictureUploadQueue images + images receives from cloudant/objectDataStore */ func getPictureObjects(){ pictureDataArray = CloudantSyncDataManager.SharedInstance!.getPictureObjects(nil) hasRecievedDataFromCloudant = true dispatch_async(dispatch_get_main_queue()) { self.passFeedViewModelNotificationToFeedVCCallback(feedViewModelNotification: FeedViewModelNotification.RefreshCollectionView) } } /** Method returns the number of sections in the collection view - returns: Int */ func numberOfSectionsInCollectionView() -> Int { return kNumberOfSectionsInCollectionView } /** Method returns the number of items in a section - parameter section: Int - returns: Int */ func numberOfItemsInSection(section : Int) -> Int { //if the section is 0, then it depends on how many items are in the picture upload queue if(section == 0){ return CameraDataManager.SharedInstance.pictureUploadQueue.count } // if the section is 1, then it depends how many items are in the pictureDataArray else{ if(pictureDataArray.count == 0 && hasRecievedDataFromCloudant == true){ return kNumberOfCellsWhenUserHasNoPhotos } else{ return pictureDataArray.count } } } /** Method returns the size for item at index path - parameter indexPath: NSIndexPath - parameter collectionView: UICollectionViewcell - returns: CGSize */ func sizeForItemAtIndexPath(indexPath : NSIndexPath, collectionView : UICollectionView) -> CGSize { //Section 0 corresponds to showing picture upload queue image feed collection view cells. These cells show when there are pictures in the picture upload queue of the camera data manager if(indexPath.section == 0){ return CGSize(width: collectionView.frame.width, height: kPictureUploadCollectionViewCellHeight) } //section 1 corresponds to either the empty feed collection view cell or the standard image feed collection view cell depending on how many images are in the picture data array else{ //return size for empty feed collection view cell if(pictureDataArray.count == 0){ return CGSize(width: collectionView.frame.width, height: collectionView.frame.height + kEmptyFeedCollectionViewCellBufferToAllowForScrolling) } //return size for image feed collection view cell else{ let picture = pictureDataArray[indexPath.row] if let width = picture.width, let height = picture.height { let ratio = height / width var height = collectionView.frame.width * ratio if(height > kCollectionViewCellHeightLimit){ height = kCollectionViewCellHeightLimit } return CGSize(width: collectionView.frame.width, height: height + kCollectionViewCellInfoViewHeight) } else{ return CGSize(width: collectionView.frame.width, height: collectionView.frame.width + kCollectionViewCellInfoViewHeight) } } } } /** Method sets up the collection view for indexPath. If the the pictureDataArray is 0, then it shows the EmptyFeedCollectionViewCell - parameter indexPath: indexPath - parameter collectionView: UICollectionView - returns: UICollectionViewCell */ func setUpCollectionViewCell(indexPath : NSIndexPath, collectionView : UICollectionView) -> UICollectionViewCell { //Section 0 corresponds to showing picture upload queue image feed collection view cells. These cells show when there are pictures in the picture upload queue of the camera data manager if(indexPath.section == 0){ let cell : PictureUploadQueueImageFeedCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureUploadQueueImageFeedCollectionViewCell", forIndexPath: indexPath) as! PictureUploadQueueImageFeedCollectionViewCell let picture = CameraDataManager.SharedInstance.pictureUploadQueue[indexPath.row] cell.setupData(picture.image, caption: picture.displayName) return cell } //section 1 corresponds to either the empty feed collection view cell or the standard image feed collection view cell depending on how many images are in the picture data array else{ //return EmptyFeedCollectionViewCell if(pictureDataArray.count == 0){ let cell : EmptyFeedCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("EmptyFeedCollectionViewCell", forIndexPath: indexPath) as! EmptyFeedCollectionViewCell return cell } //return ImageFeedCollectionViewCell else{ let cell: ImageFeedCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("ImageFeedCollectionViewCell", forIndexPath: indexPath) as! ImageFeedCollectionViewCell let picture = pictureDataArray[indexPath.row] cell.setupData( picture.url, image: picture.image, displayName: picture.displayName, ownerName: picture.ownerName, timeStamp: picture.timeStamp, fileName: picture.fileName ) cell.layer.shouldRasterize = true cell.layer.rasterizationScale = UIScreen.mainScreen().scale return cell } } } /** Method tells the view controller to refresh its collectionView */ func callRefreshCallBack(){ if let callback = refreshVCCallback { callback() } } }
apache-2.0
c8d22776ed457eed76ec9ade131559ac
39.696078
201
0.666265
5.987019
false
false
false
false
ipapapa/IoT-MicroLocation
iPhoneApp/Pods/Alamofire/Source/ParameterEncoding.swift
1
11046
// ParameterEncoding.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** HTTP method definitions. See https://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } // MARK: ParameterEncoding /** Used to specify the way in which a set of parameters are applied to a URL request. - `URL`: Creates a query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded; charset=utf-8`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`). - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. */ public enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) /** Creates a URL request by encoding parameters and applying them onto an existing request. - parameter URLRequest: The request to have parameters applied - parameter parameters: The parameters to apply - returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any. */ public func encode( URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSMutableURLRequest, NSError?) { var mutableURLRequest = URLRequest.URLRequest guard let parameters = parameters else { return (mutableURLRequest, nil) } var encodingError: NSError? = nil switch self { case .URL, .URLEncodedInURL: func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value = parameters[key]! components += queryComponents(key, value) } return (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&") } func encodesParametersInURL(method: Method) -> Bool { switch self { case .URLEncodedInURL: return true default: break } switch method { case .GET, .HEAD, .DELETE: return true default: return false } } if let method = Method(rawValue: mutableURLRequest.HTTPMethod) where encodesParametersInURL(method) { if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) { let percentEncodedQuery = (URLComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) URLComponents.percentEncodedQuery = percentEncodedQuery mutableURLRequest.URL = URLComponents.URL } } else { if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil { mutableURLRequest.setValue( "application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type" ) } mutableURLRequest.HTTPBody = query(parameters).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false ) } case .JSON: do { let options = NSJSONWritingOptions() let data = try NSJSONSerialization.dataWithJSONObject(parameters, options: options) mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .PropertyList(let format, let options): do { let data = try NSPropertyListSerialization.dataWithPropertyList( parameters, format: format, options: options ) mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") mutableURLRequest.HTTPBody = data } catch { encodingError = error as NSError } case .Custom(let closure): (mutableURLRequest, encodingError) = closure(mutableURLRequest, parameters) } return (mutableURLRequest, encodingError) } /** Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - parameter key: The key of the query component. - parameter value: The value of the query component. - returns: The percent-escaped, URL encoded query string components. */ public func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.append((escape(key), escape("\(value)"))) } return components } /** Returns a percent-escaped string following RFC 3986 for a query string key or value. RFC 3986 states that the following characters are "reserved" characters. - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" should be percent-escaped in the query string. - parameter string: The string to be percent-escaped. - returns: The percent-escaped string. */ public func escape(string: String) -> String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" let allowedCharacterSet = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet allowedCharacterSet.removeCharactersInString(generalDelimitersToEncode + subDelimitersToEncode) var escaped = "" //========================================================================================================== // // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few // hundred Chinense characters causes various malloc error crashes. To avoid this issue until iOS 8 is no // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more // info, please refer to: // // - https://github.com/Alamofire/Alamofire/issues/206 // //========================================================================================================== if #available(iOS 9.0, OSX 10.10, *) { escaped = string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = index.advancedBy(batchSize, limit: string.endIndex) let range = Range(start: startIndex, end: endIndex) let substring = string.substringWithRange(range) escaped += substring.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacterSet) ?? substring index = endIndex } } return escaped } }
bsd-3-clause
7d192504388e027215e9d9dfcb069fa1
43.353414
124
0.592629
5.643332
false
false
false
false
sunfei/Just
JustTests/CaseInsensitiveDictionarySpecs.swift
6
5000
// // CaseInsensitiveDictionarySpecs.swift // Just // // Created by Daniel Duan on 4/30/15. // Copyright (c) 2015 JustHTTP. All rights reserved. // import Nimble import Quick import Just class CaseInsensitiveDictionarySpecs: QuickSpec { override func spec() { describe("behaving like a dictionary") { it("should be initialized by assigining dictionary literals") { let d:CaseInsensitiveDictionary<String, Int> = ["a" : 1] expect(d["a"]).toNot(beNil()) } it("should accecpt a dictionary in init()") { let d = CaseInsensitiveDictionary<String,Int>(dictionary:["a":1]) expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal(1)) } it("should allow insertion of new value via subscript") { var d:CaseInsensitiveDictionary<String, Int> = [:] expect(d["a"]).to(beNil()) d["a"] = 1 expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal(1)) } it("should retain all values after mutation when initialized by a dictionary in init()") { var d = CaseInsensitiveDictionary<String,Int>(dictionary:["a":1]) expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal(1)) d["b"] = 2 expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal(1)) expect(d["b"]).toNot(beNil()) expect(d["b"]).to(equal(2)) } it("should retain all values after mutation when initialized with dictionary literal") { var d:CaseInsensitiveDictionary<String,Int> = ["a":1] expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal(1)) d["b"] = 2 expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal(1)) expect(d["b"]).toNot(beNil()) expect(d["b"]).to(equal(2)) } it("obeys value semantics, keeps a copy of assigned value") { let d1:CaseInsensitiveDictionary<String,Int> = ["a":1] let d2 = d1 expect(d2["a"]).toNot(beNil()) expect(d2["a"]).to(equal(1)) } it("obeys value semantics, would not mutate when the original does") { var d1:CaseInsensitiveDictionary<String,Int> = ["a":1] let d2 = d1 d1["a"] = 2 expect(d2["a"]).toNot(beNil()) expect(d2["a"]).to(equal(1)) } it("obeys value semantics, would not mutate the original") { var d1:CaseInsensitiveDictionary<String,Int> = ["a":1] var d2 = d1 d2["a"] = 2 expect(d2["a"]).toNot(beNil()) expect(d2["a"]).to(equal(2)) expect(d1["a"]).toNot(beNil()) expect(d1["a"]).to(equal(1)) } it("obeys value semantics, would not mutate the original with new value") { var d1:CaseInsensitiveDictionary<String,Int> = ["a":1] var d2 = d1 d2["b"] = 2 expect(d2["a"]).toNot(beNil()) expect(d2["a"]).to(equal(1)) expect(d2["b"]).toNot(beNil()) expect(d2["b"]).to(equal(2)) expect(d1["a"]).toNot(beNil()) expect(d1["a"]).to(equal(1)) expect(d1["b"]).to(beNil()) } it("obeys value semantics, retains muliple value from original after mutation") { let d1:CaseInsensitiveDictionary<String,Int> = ["a":1, "b": 2] var d2 = d1 expect(d2["a"]).toNot(beNil()) expect(d2["a"]).to(equal(1)) expect(d2["b"]).toNot(beNil()) expect(d2["b"]).to(equal(2)) d2["b"] = 42 expect(d2["a"]).toNot(beNil()) expect(d2["a"]).to(equal(1)) expect(d2["b"]).toNot(beNil()) expect(d2["b"]).to(equal(42)) } } describe("being case insensitive") { it("should keep cases of values") { var d:CaseInsensitiveDictionary<String,String> = ["a":"aAaA", "b": "BbBb"] expect(d["a"]).toNot(beNil()) expect(d["a"]).to(equal("aAaA")) expect(d["b"]).toNot(beNil()) expect(d["b"]).to(equal("BbBb")) } it("should allow access of value regardless of cases of keys") { var d:CaseInsensitiveDictionary<String,String> = ["aAaA":"a"] expect(d["aAaA"]).to(equal("a")) expect(d["AAAA"]).to(equal("a")) expect(d["aaaa"]).to(equal("a")) expect(d["AaAa"]).to(equal("a")) } } } }
mit
6e53c441284ddaa026ed6ee45a6f275e
40.666667
102
0.4638
4.061738
false
false
false
false
brentsimmons/Evergreen
Mac/Inspector/InspectorWindowController.swift
1
3622
// // InspectorWindowController.swift // NetNewsWire // // Created by Brent Simmons on 1/20/18. // Copyright © 2018 Ranchero Software. All rights reserved. // import AppKit protocol Inspector: AnyObject { var objects: [Any]? { get set } var isFallbackInspector: Bool { get } // Can handle nothing-to-inspect or unexpected type of objects. var windowTitle: String { get } func canInspect(_ objects: [Any]) -> Bool } typealias InspectorViewController = Inspector & NSViewController final class InspectorWindowController: NSWindowController { class var shouldOpenAtStartup: Bool { return UserDefaults.standard.bool(forKey: DefaultsKey.windowIsOpen) } var objects: [Any]? { didSet { let _ = window currentInspector = inspector(for: objects) } } private var inspectors: [InspectorViewController]! private var currentInspector: InspectorViewController! { didSet { currentInspector.objects = objects for inspector in inspectors { if inspector !== currentInspector { inspector.objects = nil } } show(currentInspector) } } private struct DefaultsKey { static let windowIsOpen = "FloatingInspectorIsOpen" static let windowOrigin = "FloatingInspectorOrigin" } override func windowDidLoad() { let nothingInspector = window?.contentViewController as! InspectorViewController let storyboard = NSStoryboard(name: NSStoryboard.Name("Inspector"), bundle: nil) let feedInspector = inspector("Feed", storyboard) let folderInspector = inspector("Folder", storyboard) let builtinSmartFeedInspector = inspector("BuiltinSmartFeed", storyboard) inspectors = [feedInspector, folderInspector, builtinSmartFeedInspector, nothingInspector] currentInspector = nothingInspector window?.title = currentInspector.windowTitle if let savedOrigin = originFromDefaults() { window?.setFlippedOriginAdjustingForScreen(savedOrigin) } else { window?.flippedOrigin = NSPoint(x: 256, y: 256) } } func inspector(for objects: [Any]?) -> InspectorViewController { var fallbackInspector: InspectorViewController? = nil for inspector in inspectors { if inspector.isFallbackInspector { fallbackInspector = inspector } else if let objects = objects, inspector.canInspect(objects) { return inspector } } return fallbackInspector! } func saveState() { UserDefaults.standard.set(isOpen, forKey: DefaultsKey.windowIsOpen) if isOpen, let window = window, let flippedOrigin = window.flippedOrigin { UserDefaults.standard.set(NSStringFromPoint(flippedOrigin), forKey: DefaultsKey.windowOrigin) } } } private extension InspectorWindowController { func inspector(_ identifier: String, _ storyboard: NSStoryboard) -> InspectorViewController { return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(identifier)) as! InspectorViewController } func show(_ inspector: InspectorViewController) { guard let window = window else { return } DispatchQueue.main.async { window.title = inspector.windowTitle } let flippedOrigin = window.flippedOrigin if window.contentViewController != inspector { window.contentViewController = inspector window.makeFirstResponder(nil) } window.layoutIfNeeded() if let flippedOrigin = flippedOrigin { window.setFlippedOriginAdjustingForScreen(flippedOrigin) } } func originFromDefaults() -> NSPoint? { guard let originString = UserDefaults.standard.string(forKey: DefaultsKey.windowOrigin) else { return nil } let point = NSPointFromString(originString) return point == NSPoint.zero ? nil : point } }
mit
8ea7b09129fdd6d0df504b6a1bdb8f46
25.05036
127
0.750898
4.143021
false
false
false
false