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
iCodeForever/ifanr
ifanr/Pods/Alamofire/Source/ParameterEncoding.swift
20
16615
// // ParameterEncoding.swift // // Copyright (c) 2014-2016 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 HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } // MARK: - /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// 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. /// /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. /// /// - returns: The encoded request. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// 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`). public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// requests and sets as the HTTP body for requests with any other HTTP method. /// - queryString: Sets or appends encoded query string result to existing query string. /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. public enum Destination { case methodDependent, queryString, httpBody } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination // MARK: Initialization /// Creates a `URLEncoding` instance using the specified destination. /// /// - parameter destination: The destination defining where the encoded query string is to be applied. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent) { self.destination = destination } // MARK: Encoding /// 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. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return urlRequest } /// 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(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: "\(key)[]", value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape((value.boolValue ? "1" : "0")))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape((bool ? "1" : "0")))) } 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 = "!$&'()*+,;=" var allowedCharacterSet = CharacterSet.urlQueryAllowed allowedCharacterSet.remove(charactersIn: "\(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 Chinese 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 8.3, *) { escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string } else { let batchSize = 50 var index = string.startIndex while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string.substring(with: range) escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? substring index = endIndex } } return escaped } private func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bool { switch destination { case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } } // MARK: - /// Uses `JSONSerialization` 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`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { return JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates a `JSONEncoding` instance using the specified options. /// /// - parameter options: The options for writing the parameters as JSON data. /// /// - returns: The new `JSONEncoding` instance. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding /// 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. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } } // MARK: - /// Uses `PropertyListSerialization` 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`. public struct PropertyListEncoding: ParameterEncoding { // MARK: Properties /// Returns a default `PropertyListEncoding` instance. public static var `default`: PropertyListEncoding { return PropertyListEncoding() } /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } /// The property list serialization format. public let format: PropertyListSerialization.PropertyListFormat /// The options for writing the parameters as plist data. public let options: PropertyListSerialization.WriteOptions // MARK: Initialization /// Creates a `PropertyListEncoding` instance using the specified format and options. /// /// - parameter format: The property list serialization format. /// - parameter options: The options for writing the parameters as plist data. /// /// - returns: The new `PropertyListEncoding` instance. public init( format: PropertyListSerialization.PropertyListFormat = .xml, options: PropertyListSerialization.WriteOptions = 0) { self.format = format self.options = options } // MARK: Encoding /// 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. /// /// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try PropertyListSerialization.data( fromPropertyList: parameters, format: format, options: options ) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) } return urlRequest } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } }
mit
d36e011becd1a7410c3d854d9d905e21
40.024691
123
0.646043
5.085706
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/DealersComponent/View Model/DefaultDealersViewModelFactory.swift
1
11974
import EurofurenceModel import Foundation import UIKit public struct DefaultDealersViewModelFactory: DealersViewModelFactory, DealersIndexDelegate { private let dealersService: DealersService private let defaultIconData: Data private let refreshService: RefreshService private let viewModel: ViewModel private let searchViewModel: SearchViewModel private let categoriesViewModel: CategoriesViewModel public init(dealersService: DealersService, refreshService: RefreshService) { let defaultAvatarImage = UIImage(named: "defaultAvatar", in: .module, compatibleWith: nil).unsafelyUnwrapped let defaultImageData = defaultAvatarImage.pngData().unsafelyUnwrapped self.init(dealersService: dealersService, defaultIconData: defaultImageData, refreshService: refreshService) } public init( dealersService: DealersService, defaultIconData: Data, refreshService: RefreshService ) { self.dealersService = dealersService self.defaultIconData = defaultIconData self.refreshService = refreshService let index = dealersService.makeDealersIndex() viewModel = ViewModel(refreshService: refreshService) searchViewModel = SearchViewModel(index: index) categoriesViewModel = CategoriesViewModel(categoriesCollection: index.availableCategories) index.setDelegate(self) } public func makeDealersViewModel(completionHandler: @escaping (DealersViewModel) -> Void) { completionHandler(viewModel) } public func makeDealersSearchViewModel(completionHandler: @escaping (DealersSearchViewModel) -> Void) { completionHandler(searchViewModel) } public func makeDealerCategoriesViewModel(completionHandler: @escaping (DealerCategoriesViewModel) -> Void) { completionHandler(categoriesViewModel) } public func alphabetisedDealersDidChange(to alphabetisedGroups: [AlphabetisedDealersGroup]) { let (groups, indexTitles) = makeViewModels(from: alphabetisedGroups) let event = AllDealersChangedEvent( rawGroups: alphabetisedGroups, alphabetisedGroups: groups, indexTitles: indexTitles ) viewModel.consume(event: event) } public func indexDidProduceSearchResults(_ searchResults: [AlphabetisedDealersGroup]) { let (groups, indexTitles) = makeViewModels(from: searchResults) let event = SearchResultsDidChangeEvent( rawGroups: searchResults, alphabetisedGroups: groups, indexTitles: indexTitles ) searchViewModel.consume(event: event) } private func makeViewModels( from alphabetisedGroups: [AlphabetisedDealersGroup] ) -> (groups: [DealersGroupViewModel], titles: [String]) { let groups = alphabetisedGroups.map { (alphabetisedGroup) -> DealersGroupViewModel in return DealersGroupViewModel(title: alphabetisedGroup.indexingString, dealers: alphabetisedGroup.dealers.map(makeDealerViewModel)) } let indexTitles = alphabetisedGroups.map(\.indexingString) return (groups: groups, titles: indexTitles) } private func makeDealerViewModel(for dealer: Dealer) -> DealerVM { return DealerVM(dealer: dealer, defaultIconData: defaultIconData) } private class AllDealersChangedEvent { private(set) var rawGroups: [AlphabetisedDealersGroup] private(set) var alphabetisedGroups: [DealersGroupViewModel] private(set) var indexTitles: [String] init( rawGroups: [AlphabetisedDealersGroup], alphabetisedGroups: [DealersGroupViewModel], indexTitles: [String] ) { self.rawGroups = rawGroups self.alphabetisedGroups = alphabetisedGroups self.indexTitles = indexTitles } } private struct SearchResultsDidChangeEvent { private(set) var rawGroups: [AlphabetisedDealersGroup] private(set) var alphabetisedGroups: [DealersGroupViewModel] private(set) var indexTitles: [String] init( rawGroups: [AlphabetisedDealersGroup], alphabetisedGroups: [DealersGroupViewModel], indexTitles: [String] ) { self.rawGroups = rawGroups self.alphabetisedGroups = alphabetisedGroups self.indexTitles = indexTitles } } private class ViewModel: DealersViewModel, RefreshServiceObserver { private let refreshService: RefreshService private var rawGroups = [AlphabetisedDealersGroup]() private var groups = [DealersGroupViewModel]() private var indexTitles = [String]() init(refreshService: RefreshService) { self.refreshService = refreshService refreshService.add(self) } private var delegate: DealersViewModelDelegate? func setDelegate(_ delegate: DealersViewModelDelegate) { self.delegate = delegate delegate.dealerGroupsDidChange(groups, indexTitles: indexTitles) } func identifierForDealer(at indexPath: IndexPath) -> DealerIdentifier? { return rawGroups[indexPath.section].dealers[indexPath.item].identifier } func refresh() { refreshService.refreshLocalStore { (_) in } } func consume(event: AllDealersChangedEvent) { rawGroups = event.rawGroups groups = event.alphabetisedGroups indexTitles = event.indexTitles delegate?.dealerGroupsDidChange(groups, indexTitles: indexTitles) } func refreshServiceDidBeginRefreshing() { delegate?.dealersRefreshDidBegin() } func refreshServiceDidFinishRefreshing() { delegate?.dealersRefreshDidFinish() } } private class SearchViewModel: DealersSearchViewModel { private let index: DealersIndex private var rawGroups = [AlphabetisedDealersGroup]() private var groups = [DealersGroupViewModel]() private var indexTitles = [String]() init(index: DealersIndex) { self.index = index } private var delegate: DealersSearchViewModelDelegate? func setSearchResultsDelegate(_ delegate: DealersSearchViewModelDelegate) { self.delegate = delegate delegate.dealerSearchResultsDidChange(groups, indexTitles: indexTitles) } func updateSearchResults(with query: String) { index.performSearch(term: query) } func identifierForDealer(at indexPath: IndexPath) -> DealerIdentifier? { return rawGroups[indexPath.section].dealers[indexPath.item].identifier } func consume(event: SearchResultsDidChangeEvent) { rawGroups = event.rawGroups groups = event.alphabetisedGroups indexTitles = event.indexTitles delegate?.dealerSearchResultsDidChange(groups, indexTitles: indexTitles) } } private struct DealerVM: DealerViewModel { private let dealer: Dealer private let defaultIconData: Data init(dealer: Dealer, defaultIconData: Data) { self.dealer = dealer self.defaultIconData = defaultIconData title = dealer.preferredName subtitle = dealer.alternateName isPresentForAllDays = dealer.isAttendingOnThursday && dealer.isAttendingOnFriday && dealer.isAttendingOnSaturday isAfterDarkContentPresent = dealer.isAfterDark } var title: String var subtitle: String? var isPresentForAllDays: Bool var isAfterDarkContentPresent: Bool func fetchIconPNGData(completionHandler: @escaping (Data) -> Void) { dealer.fetchIconPNGData { (iconPNGData) in completionHandler(iconPNGData ?? self.defaultIconData) } } } private class CategoriesViewModel: DealerCategoriesViewModel, DealerCategoriesCollectionObserver { private let categoriesCollection: DealerCategoriesCollection private var categoryViewModels = [CategoryViewModel]() init(categoriesCollection: DealerCategoriesCollection) { self.categoriesCollection = categoriesCollection categoriesCollection.add(self) regenerateCategoryViewModels() } var numberOfCategories: Int { return categoryViewModels.count } func categoryViewModel(at index: Int) -> DealerCategoryViewModel { return categoryViewModels[index] } func categoriesCollectionDidChange(_ collection: DealerCategoriesCollection) { regenerateCategoryViewModels() } private func regenerateCategoryViewModels() { categoryViewModels = (0..<categoriesCollection.numberOfCategories) .map(categoriesCollection.category(at:)) .map(CategoryViewModel.init) } } private class CategoryViewModel: DealerCategoryViewModel, DealerCategoryObserver { private let category: DealerCategory private var currentState: CategoryViewModelState init(category: DealerCategory) { self.category = category currentState = CategoryViewModelState() category.add(self) } func categoryDidActivate(_ category: DealerCategory) { currentState = ActiveCategoryViewModelState(state: currentState) } func categoryDidDeactivate(_ category: DealerCategory) { currentState = InactiveCategoryViewModelState(state: currentState) } var title: String { return category.name } func add(_ observer: DealerCategoryViewModelObserver) { currentState.add(observer) } func toggleCategoryActiveState() { currentState.toggleCategoryState(category: category) } } private class CategoryViewModelState { private var observers: [DealerCategoryViewModelObserver] init() { observers = [] } init(state: CategoryViewModelState) { observers = state.observers enterState() } final func enterState() { observers.forEach(provideCurrentStateContext) } final func add(_ observer: DealerCategoryViewModelObserver) { observers.append(observer) provideCurrentStateContext(to: observer) } func provideCurrentStateContext(to observer: DealerCategoryViewModelObserver) { } func toggleCategoryState(category: DealerCategory) { } } private class InactiveCategoryViewModelState: CategoryViewModelState { override func provideCurrentStateContext(to observer: DealerCategoryViewModelObserver) { observer.categoryDidEnterInactiveState() } override func toggleCategoryState(category: DealerCategory) { category.activate() } } private class ActiveCategoryViewModelState: CategoryViewModelState { override func provideCurrentStateContext(to observer: DealerCategoryViewModelObserver) { observer.categoryDidEnterActiveState() } override func toggleCategoryState(category: DealerCategory) { category.deactivate() } } }
mit
09a020f8743ea8bb00bd819481aa6698
32.634831
116
0.645816
5.701905
false
false
false
false
prey/prey-ios-client
Prey/Classes/Trigger.swift
1
7749
// // Trigger.swift // Prey // // Created by Javier Cala Uribe on 4/07/19. // Copyright © 2019 Prey, Inc. All rights reserved. // import Foundation import CoreData import UIKit class Trigger : PreyAction { // MARK: Properties // MARK: Functions // Prey command override func start() { PreyLogger("Check triggers on panel") checkTriggers(self) isActive = true } // Update Triggers locally func updateTriggers(_ response:NSArray) { PreyLogger("Update triggers") // Delete all triggers on Device deleteAllTriggersOnDevice() // Delete all triggersOnCoreData deleteAllTriggersOnCoreData() // Add triggers to CoreData addTriggersToCoreData(response, withContext:PreyCoreData.sharedInstance.managedObjectContext) // Add triggers to Device addTriggersToDevice() isActive = false // Remove trigger action PreyModule.sharedInstance.checkStatus(self) } // Send event to panel func sendEventToPanel(_ triggersArray:[Triggers], withCommand cmd:kCommand, withStatus status:kStatus){ // Create a triggerId array with new triggers let triggerArray = NSMutableArray() for itemAdded in triggersArray { let triggersId : [String: Double] = [ "id" : itemAdded.id!.doubleValue, "state" : 1] triggerArray.add(triggersId) } let data = try? JSONSerialization.data(withJSONObject: triggerArray) // Params struct let params:[String: String] = [ kData.status.rawValue : status.rawValue, kData.target.rawValue : kAction.triggers.rawValue, kData.command.rawValue : cmd.rawValue, kData.reason.rawValue : String(data: data!, encoding: .utf8)!] // Send info to panel if let username = PreyConfig.sharedInstance.userApiKey, PreyConfig.sharedInstance.isRegistered { PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:params, messageId:nil, httpMethod:Method.POST.rawValue, endPoint:responseDeviceEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.dataSend, preyAction:nil, onCompletion:{(isSuccess: Bool) in PreyLogger("Request dataSend")})) } else { PreyLogger("Error send data auth") } } // Delete all triggers on device func deleteAllTriggersOnDevice() { UIApplication.shared.cancelAllLocalNotifications() } // Delete all triggersOnCoreData func deleteAllTriggersOnCoreData() { let localTriggersArray = PreyCoreData.sharedInstance.getCurrentTriggers() let context = PreyCoreData.sharedInstance.managedObjectContext for localTrigger in localTriggersArray { context?.delete(localTrigger) } } // Add triggers to CoreData func addTriggersToCoreData(_ response:NSArray, withContext context:NSManagedObjectContext) { for serverTriggersArray in response { // Init NSManagedObject type Triggers let trigger = NSEntityDescription.insertNewObject(forEntityName: "Triggers", into: context) as! Triggers // Attributes from Triggers let attributes = trigger.entity.attributesByName for (attribute,description) in attributes { if var value = (serverTriggersArray as AnyObject).value(forKey: attribute) { switch description.attributeType { case .doubleAttributeType: value = NSNumber(value: (value as AnyObject).doubleValue as Double) default: value = ((value as AnyObject) is NSNull) ? "" : value as! String } // Save {value,key} in Trigger item trigger.setValue(value, forKey: attribute) } } // Check events if let eventsArray = (serverTriggersArray as AnyObject).value(forKey: "automation_events") as? NSArray { for eventItem in eventsArray { let eventsTrigger = NSEntityDescription.insertNewObject(forEntityName: "TriggersEvents", into: context) as! TriggersEvents if let type = (eventItem as AnyObject).value(forKey: "type") as? String { eventsTrigger.type = type } if let info = (eventItem as AnyObject).value(forKey: "info") as? NSDictionary { do { let data = try JSONSerialization.data(withJSONObject: info) eventsTrigger.info = String(data: data, encoding: .utf8) } catch let error as NSError { PreyLogger("json error trigger: \(error.localizedDescription)") } } trigger.addToEvents(eventsTrigger) } } // Check actions if let actionArray = ((serverTriggersArray) as AnyObject).value(forKey: "automation_actions") as? NSArray { for actionItem in actionArray { let actionTrigger = NSEntityDescription.insertNewObject(forEntityName: "TriggersActions", into: context) as! TriggersActions if let delay = (actionItem as AnyObject).value(forKey: "delay") as? Double { actionTrigger.delay = NSNumber(value:delay) } if let action = (actionItem as AnyObject).value(forKey: "action") as? NSDictionary { let localActionArray = NSMutableArray() localActionArray.add(action) do { let data = try JSONSerialization.data(withJSONObject: localActionArray) actionTrigger.action = String(data: data, encoding: .utf8) } catch let error as NSError{ PreyLogger("json error trigger: \(error.localizedDescription)") } } trigger.addToActions(actionTrigger) } } } // Save CoreData do { try context.save() } catch { PreyLogger("Couldn't save trigger: \(error)") } } // Add triggers to Device func addTriggersToDevice() { let localTriggersArray = PreyCoreData.sharedInstance.getCurrentTriggers() for localTrigger in localTriggersArray { PreyLogger("Name trigger "+String(format: "%f", (localTrigger.id?.floatValue)!)) let timeEvent = ["exact_time", "repeat_time"] var onlyTimeEvents = true for itemTrigger in localTrigger.events!.allObjects as! [TriggersEvents] { guard timeEvent.contains(itemTrigger.type!) else { onlyTimeEvents = false break } } if onlyTimeEvents { TriggerManager.sharedInstance.scheduleTrigger(localTrigger) } } // Added triggers sendEventToPanel(localTriggersArray, withCommand:kCommand.start , withStatus:kStatus.started) } }
gpl-3.0
b2ad3896e2da6455bf0fe9d56aeccb13
37.934673
331
0.561177
5.630814
false
false
false
false
CatchChat/Yep
Yep/Views/Cells/ProfileFeeds/ProfileFeedsCell.swift
1
4767
// // ProfileFeedsCell.swift // Yep // // Created by nixzhu on 15/11/17. // Copyright © 2015年 Catch Inc. All rights reserved. // import UIKit import YepKit final class ProfileFeedsCell: UICollectionViewCell { @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var iconImageViewLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var imageView2: UIImageView! @IBOutlet weak var imageView3: UIImageView! @IBOutlet weak var imageView4: UIImageView! @IBOutlet weak var accessoryImageView: UIImageView! @IBOutlet weak var accessoryImageViewTrailingConstraint: NSLayoutConstraint! private var enabled: Bool = false { willSet { if newValue { iconImageView.tintColor = UIColor.yepTintColor() nameLabel.textColor = UIColor.yepTintColor() accessoryImageView.hidden = false accessoryImageView.tintColor = UIColor.yepCellAccessoryImageViewTintColor() } else { iconImageView.tintColor = SocialAccount.disabledColor nameLabel.textColor = SocialAccount.disabledColor accessoryImageView.hidden = true } } } var feedAttachments: [DiscoveredAttachment?]? { willSet { guard let _attachments = newValue else { return } enabled = !_attachments.isEmpty // 对于从左到右排列,且左边的最新,要处理数量不足的情况 var attachments = _attachments let imageViews = [ imageView4, imageView3, imageView2, imageView1, ] let shortagesCount = max(imageViews.count - attachments.count, 0) // 不足补空 if shortagesCount > 0 { let shortages = Array<DiscoveredAttachment?>(count: shortagesCount, repeatedValue: nil) attachments.insertContentsOf(shortages, at: 0) } for i in 0..<imageViews.count { if i < shortagesCount { imageViews[i].image = nil } else { if let thumbnailImage = attachments[i]?.thumbnailImage { imageViews[i].image = thumbnailImage } else { imageViews[i].image = UIImage.yep_iconFeedText } } } } } override func awakeFromNib() { super.awakeFromNib() enabled = false nameLabel.text = NSLocalizedString("Feeds", comment: "") iconImageViewLeadingConstraint.constant = YepConfig.Profile.leftEdgeInset accessoryImageViewTrailingConstraint.constant = YepConfig.Profile.rightEdgeInset imageView1.contentMode = .ScaleAspectFill imageView2.contentMode = .ScaleAspectFill imageView3.contentMode = .ScaleAspectFill imageView4.contentMode = .ScaleAspectFill let cornerRadius: CGFloat = 2 imageView1.layer.cornerRadius = cornerRadius imageView2.layer.cornerRadius = cornerRadius imageView3.layer.cornerRadius = cornerRadius imageView4.layer.cornerRadius = cornerRadius imageView1.clipsToBounds = true imageView2.clipsToBounds = true imageView3.clipsToBounds = true imageView4.clipsToBounds = true } func configureWithProfileUser(profileUser: ProfileUser?, feedAttachments: [DiscoveredAttachment?]?, completion: ((feeds: [DiscoveredFeed], feedAttachments: [DiscoveredAttachment?]) -> Void)?) { if let feedAttachments = feedAttachments { self.feedAttachments = feedAttachments } else { guard let profileUser = profileUser else { return } feedsOfUser(profileUser.userID, pageIndex: 1, perPage: 20, failureHandler: nil, completion: { validFeeds, _ in println("user's feeds: \(validFeeds.count)") let feedAttachments = validFeeds.map({ feed -> DiscoveredAttachment? in if let attachment = feed.attachment { if case let .Images(attachments) = attachment { return attachments.first } } return nil }) SafeDispatch.async { [weak self] in self?.feedAttachments = feedAttachments completion?(feeds: validFeeds, feedAttachments: feedAttachments) } }) } } }
mit
fd8aa3c3cb2e8e2c7c1ca482e9e0721e
32.126761
197
0.590774
5.653846
false
false
false
false
mfwarren/MWHtmlEscape
MWHtmlEscape/MWHtmlEscape.swift
1
772
// // MWHtmlEscape.swift // MWHtmlEscape // // Created by Matt Warren on 2014-06-12. // Copyright (c) 2014 Matt Warren. All rights reserved. // import Foundation func escape(html: String) -> String{ var result = html.stringByReplacingOccurrencesOfString("&", withString: "&amp;", options: nil, range: nil) result = result.stringByReplacingOccurrencesOfString("\"", withString: "&quot;", options: nil, range: nil) result = result.stringByReplacingOccurrencesOfString("'", withString: "&#39;", options: nil, range: nil) result = result.stringByReplacingOccurrencesOfString("<", withString: "&lt;", options: nil, range: nil) result = result.stringByReplacingOccurrencesOfString(">", withString: "&gt;", options: nil, range: nil) return result }
mit
82b180e4265edf35e0e03efed01f7e6b
41.888889
110
0.708549
4.462428
false
false
false
false
pvbaleeiro/movie-aholic
movieaholic/movieaholic/extension/UIColor+Util.swift
1
3296
// // UIColor+Util.swift // movieaholic // // Created by Victor Baleeiro on 23/09/17. // Copyright © 2017 Victor Baleeiro. All rights reserved. // import UIKit extension UIColor { //------------------------------------------------------------------------------------------------------------- // MARK: Principais tema //------------------------------------------------------------------------------------------------------------- class func primaryColor() -> UIColor { return UIColor(red: 51.0/255.0, green: 190.0/255.0, blue: 242.0/255.0, alpha: 1.0) } class func primaryColorDark() -> UIColor { return UIColor(red: 0.0/255.0, green: 174.0/255.0, blue: 239.0/255.0, alpha: 1.0) } class func secondaryColor() -> UIColor { return UIColor(red: 67.0/255.0, green: 171.0/255.0, blue: 175.0/255.0, alpha: 1.0) } //------------------------------------------------------------------------------------------------------------- // MARK: Vermelho //------------------------------------------------------------------------------------------------------------- class func redClear() -> UIColor { return UIColor(red: 255.0/255.0, green: 90.0/255.0, blue: 95.0/255.0, alpha: 1.0) } convenience init(hex: String) { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString = cString.substring(from: cString.index(cString.startIndex, offsetBy: 1)) } if ((cString.characters.count) != 6) { self.init() } else { var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) self.init( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } } convenience init(r: CGFloat, g: CGFloat, b: CGFloat) { self.init(red: CGFloat(r / 255), green: CGFloat(g / 255), blue: CGFloat(b / 255), alpha: CGFloat(1)) } static func fade(fromColor: UIColor, toColor: UIColor, withPercentage: CGFloat) -> UIColor { var fromRed: CGFloat = 0.0 var fromGreen: CGFloat = 0.0 var fromBlue: CGFloat = 0.0 var fromAlpha: CGFloat = 0.0 fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha) var toRed: CGFloat = 0.0 var toGreen: CGFloat = 0.0 var toBlue: CGFloat = 0.0 var toAlpha: CGFloat = 0.0 toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha) //calculate the actual RGBA values of the fade colour let red = (toRed - fromRed) * withPercentage + fromRed; let green = (toGreen - fromGreen) * withPercentage + fromGreen; let blue = (toBlue - fromBlue) * withPercentage + fromBlue; let alpha = (toAlpha - fromAlpha) * withPercentage + fromAlpha; // return the fade colour return UIColor(red: red, green: green, blue: blue, alpha: alpha) } }
mit
168094f5d865b56a2cca6cb17bf54b8c
37.313953
115
0.489226
4.208174
false
false
false
false
UncleJerry/Filmroom
macOS/Filmroom for Mac/Filters/CustomFilters.swift
1
5091
// // CustomFilter.swift // Filmroom // // Created by 周建明 on 2017/7/8. // Copyright © 2017年 Uncle Jerry. All rights reserved. // import Foundation import CoreImage class GammaAdjust: CIFilter { var inputImage: CIImage? var inputUnit: CGFloat = 0.0 func CustomKernel() -> CIKernel { let url = Bundle.main.url(forResource: "default", withExtension: "metallib") let data = try! Data(contentsOf: url!) let kernel = try! CIKernel(functionName: "gamma", fromMetalLibraryData: data) return kernel } override var outputImage : CIImage! { if let inputImage = inputImage { let arguments = [inputImage, inputUnit] as [Any] let extent = inputImage.extent return CustomKernel().apply(extent: extent, roiCallback: { (index, rect) in return rect }, arguments: arguments) } return nil } override func setDefaults() { inputUnit = 1.0 } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Gamma Filter" as AnyObject, "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputUnit": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 1.0, kCIAttributeDisplayName: "Unit", kCIAttributeMin: 0, kCIAttributeMax: 3, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 3, kCIAttributeType: kCIAttributeTypeScalar] ] } } class GuassianBlur: CIFilter{ var inputImage: CIImage? var sigma: CGFloat = 0.0 override func setDefaults() { sigma = 0.0 } func CustomKernel() -> CIKernel { let url = Bundle.main.url(forResource: "default", withExtension: "metallib") let data = try! Data(contentsOf: url!) let kernel = try! CIKernel(functionName: "gaussianBlur", fromMetalLibraryData: data) return kernel } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "GuassianBlur Filter" as AnyObject, "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "sigma": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.0, kCIAttributeDisplayName: "Unit", kCIAttributeMin: 0, kCIAttributeMax: 100, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 100, kCIAttributeType: kCIAttributeTypeScalar] ] } override var outputImage : CIImage! { if let inputImage = inputImage { let arguments = [inputImage, sigma] as [Any] let extent = inputImage.extent return CustomKernel().apply(extent: extent, roiCallback: { (index, rect) in return rect }, arguments: arguments) } return nil } } class MedianBlur: CIFilter{ var inputImage: CIImage? func CustomKernel() -> CIKernel { let url = Bundle.main.url(forResource: "default", withExtension: "metallib") let data = try! Data(contentsOf: url!) let kernel = try! CIKernel(functionName: "medianBlur", fromMetalLibraryData: data) return kernel } override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Median Filter" as AnyObject, "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage] ] } override var outputImage : CIImage! { if let inputImage = inputImage { let arguments = [inputImage] as [Any] let extent = inputImage.extent return CustomKernel().apply(extent: extent, roiCallback: { (index, rect) in return rect }, arguments: arguments) } return nil } }
apache-2.0
ada7bbcec3d5c412a31f21d12c9c1d81
30.7625
92
0.508855
5.88876
false
false
false
false
ContinuousLearning/PokemonKit
Carthage/Checkouts/PromiseKit/Categories/AddressBook/ABAddressBookRequestAccess+Promise.swift
1
2681
import AddressBook import CoreFoundation import Foundation.NSError #if !COCOAPODS import PromiseKit #endif /** Requests access to the address book. To import `ABAddressBookRequestAccess`: use_frameworks! pod "PromiseKit/AddressBook" And then in your sources: #if !COCOAPODS import PromiseKit #endif @return A promise that fulfills with the ABAuthorizationStatus. */ public func ABAddressBookRequestAccess() -> Promise<ABAuthorizationStatus> { return ABAddressBookRequestAccess().then(on: zalgo) { (_, _) -> ABAuthorizationStatus in return ABAddressBookGetAuthorizationStatus() } } /** Requests access to the address book. To import `ABAddressBookRequestAccess`: pod "PromiseKit/AddressBook" And then in your sources: #if !COCOAPODS import PromiseKit #endif @return A promise that fulfills with the ABAddressBook instance if access was granted. */ public func ABAddressBookRequestAccess() -> Promise<ABAddressBook> { return ABAddressBookRequestAccess().then(on: zalgo) { (granted, book) -> Promise<ABAddressBook> in if granted { return Promise(book) } else { switch ABAddressBookGetAuthorizationStatus() { case .NotDetermined: return Promise(error: "Access to the address book could not be determined.") case .Restricted: return Promise(error: "A head of family must grant address book access.") case .Denied: return Promise(error: "Address book access has been denied.") case .Authorized: return Promise(book) // shouldn’t be possible } } } } extension NSError { private convenience init(CFError error: CoreFoundation.CFError) { let domain = CFErrorGetDomain(error) as String let code = CFErrorGetCode(error) let info = CFErrorCopyUserInfo(error) as [NSObject: AnyObject] self.init(domain: domain, code: code, userInfo: info) } } private func ABAddressBookRequestAccess() -> Promise<(Bool, ABAddressBook)> { var error: Unmanaged<CFError>? = nil let ubook = ABAddressBookCreateWithOptions(nil, &error) if ubook != nil { let book: ABAddressBook = ubook.takeRetainedValue() return Promise { fulfill, reject in ABAddressBookRequestAccessWithCompletion(book) { granted, error in if error == nil { fulfill(granted, book) } else { reject(NSError(CFError: error)) } } } } else { return Promise(NSError(CFError: error!.takeRetainedValue())) } }
mit
9eb380ce95456f9dad430a7b9facba58
28.766667
102
0.652109
5.016854
false
false
false
false
BellAppLab/GradientNavigationBar
GradientNavigationBar/GradientNavigationBar/Classes/GradientNavigationBar.swift
1
2273
// // GradientNavigationBar.swift // Pods // // Created by Bell App Lab on 11/08/2016. // // import UIKit /** */ public class GradientNavigationBar: UINavigationBar { //MARK: Consts public static var defaultOpacity: Float = 0.5 //MARK: Gradient public private(set) weak var gradientLayer: CAGradientLayer? public dynamic var colors: [UIColor]? { didSet { guard let colors = self.colors else { self.gradientLayer?.removeFromSuperlayer(); return } let layer = CAGradientLayer() layer.opacity = self.translucent ? GradientNavigationBar.defaultOpacity : 1.0 self.layer.insertSublayer(layer, atIndex: 1) self.gradientLayer = layer var cgColors = [CGColorRef]() for color in colors { cgColors.append(color.CGColor) } layer.colors = cgColors if let locations = self.locations { layer.locations = locations } layer.startPoint = startPoint layer.endPoint = endPoint } } public dynamic var locations: [Float]? { didSet { guard let layer = self.gradientLayer, let locations = self.locations else { self.gradientLayer?.locations = nil return } layer.locations = locations } } public dynamic var startPoint = CGPointZero { didSet { guard let layer = self.gradientLayer else { return } layer.startPoint = self.startPoint } } public dynamic var endPoint = CGPointZero { didSet { guard let layer = self.gradientLayer else { return } layer.endPoint = self.endPoint } } //MARK: View Life Cycle public override func layoutSubviews() { super.layoutSubviews() guard let layer = self.gradientLayer else { return } let statusBarHeight = UIApplication.sharedApplication().statusBarFrame.size.height layer.frame = CGRectMake(0, 0 - statusBarHeight, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + statusBarHeight) } }
mit
f55b78e5db99cb1ffc47c95cafef9724
27.772152
133
0.575011
5.348235
false
false
false
false
sunnychan626/project-window
Pods/SwiftState/Sources/TransitionChain.swift
1
2140
// // TransitionChain.swift // SwiftState // // Created by Yasuhiro Inami on 2014/08/04. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // /// Group of continuous `Transition`s represented as `.State1 => .State2 => .State3`. public struct TransitionChain<S: StateType> { public private(set) var states: [State<S>] public init(states: [State<S>]) { self.states = states } public init(transition: Transition<S>) { self.init(states: [transition.fromState, transition.toState]) } public var transitions: [Transition<S>] { var transitions: [Transition<S>] = [] for i in 0..<states.count-1 { transitions += [states[i] => states[i+1]] } return transitions } } //-------------------------------------------------- // MARK: - Custom Operators //-------------------------------------------------- // e.g. (.State0 => .State1) => .State public func => <S: StateType>(left: Transition<S>, right: State<S>) -> TransitionChain<S> { return TransitionChain(states: [left.fromState, left.toState]) => right } public func => <S: StateType>(left: Transition<S>, right: S) -> TransitionChain<S> { return left => .Some(right) } public func => <S: StateType>(left: TransitionChain<S>, right: State<S>) -> TransitionChain<S> { return TransitionChain(states: left.states + [right]) } public func => <S: StateType>(left: TransitionChain<S>, right: S) -> TransitionChain<S> { return left => .Some(right) } // e.g. .State0 => (.State1 => .State) public func => <S: StateType>(left: State<S>, right: Transition<S>) -> TransitionChain<S> { return left => TransitionChain(states: [right.fromState, right.toState]) } public func => <S: StateType>(left: S, right: Transition<S>) -> TransitionChain<S> { return .Some(left) => right } public func => <S: StateType>(left: State<S>, right: TransitionChain<S>) -> TransitionChain<S> { return TransitionChain(states: [left] + right.states) } public func => <S: StateType>(left: S, right: TransitionChain<S>) -> TransitionChain<S> { return .Some(left) => right }
apache-2.0
0a9420813205dc1da493c7590dee8098
25.725
94
0.606642
3.522241
false
false
false
false
kissshot13/kissshot-weibo
weibodemo/weibodemo/Classes/home/contorller/KISMyQRCodeViewController.swift
1
3357
// // KISMyQRCodeViewController.swift // weibodemo // // Created by 李威 on 16/8/17. // Copyright © 2016年 李威. All rights reserved. // import UIKit import KGNAutoLayout class KISMyQRCodeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "我的名片" view.backgroundColor = UIColor.init(white:0.85, alpha: 1) view.addSubview(myQRCodeImage) myQRCodeImage.centerInSuperview() myQRCodeImage.sizeToWidthAndHeight(240) myQRCodeImage.image = creatMyQRCode() } /** 创建二维码 */ private func creatMyQRCode() ->UIImage { //1.创建滤镜 let filter = CIFilter.init(name: "CIQRCodeGenerator") //2.还原滤镜的默认属性 filter?.setDefaults() //3.设置需要生成的二维码的数据 filter?.setValue("kissshot".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage") //4.从滤镜中取出图片 let ciImage = filter?.outputImage var image = makeUIImagefromCIImage(ciImage!, size:CGSizeMake(300,300)) image = addIcon(image, icon: UIImage.init(named: "other")!) return image } /** 使模糊图像高清 - parameter image: 二维码图 - parameter size: 生成的图片大小 - returns: 返回清晰的二位码图 */ private func makeUIImagefromCIImage(image:CIImage,size:CGSize) -> UIImage { let extent:CGRect = CGRectIntegral(image.extent) let scale = min(size.width/extent.width, size.height/extent.height) //创建位图上下文 let width = CGRectGetWidth(extent)*scale let height = CGRectGetHeight(extent)*scale let cs:CGColorSpaceRef = CGColorSpaceCreateDeviceGray()! let bitmapcontext = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0) CGContextSetInterpolationQuality(bitmapcontext, CGInterpolationQuality.None) CGContextScaleCTM(bitmapcontext, scale, scale) //创建ci上下文 let context = CIContext.init(options: nil) let bitmapImage :CGImageRef = context.createCGImage(image, fromRect: extent) CGContextDrawImage(bitmapcontext, extent, bitmapImage) let scaleImage :CGImageRef = CGBitmapContextCreateImage(bitmapcontext)! return UIImage(CGImage: scaleImage) } //加入头像合成二维码 private func addIcon(bigImage:UIImage,icon:UIImage) ->UIImage { //开启绘图上下文 UIGraphicsBeginImageContext(bigImage.size) //大图片绘图 bigImage.drawInRect(CGRect.init(origin:CGPointZero, size: bigImage.size)) //头像绘图 let width :CGFloat = 100 let height = width let x = (bigImage.size.width - icon.size.width)/2 let y = (bigImage.size.height - icon.size.height)/2 icon.drawInRect(CGRectMake(x, y, width, height)) //获取图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() //关闭上下文 UIGraphicsEndImageContext() //返回合成图片 return newImage } /// 懒加载图片 private lazy var myQRCodeImage:UIImageView = UIImageView.init() }
apache-2.0
bdc750c88d3b80a7a8b81424ae13086f
30.876289
100
0.640039
4.385816
false
false
false
false
HariniMurali/TestDemoPodSDK
TestDemoPodSDK/Classes/ArticleDetailController.swift
1
23816
// // ArticleDetailController.swift // Pods // // Created by APP DEVELOPEMENT on 07/01/17. // // import UIKit import FMDB import Cosmos class ArticleDetailController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate { var currentArticleID : String = "" @IBOutlet weak var articleTitle: UILabel! @IBOutlet weak var articleRating: CosmosView! @IBOutlet weak var articleViewCount: UILabel! @IBOutlet weak var articleDescription: UILabel! @IBOutlet var scrollView: UIScrollView! @IBOutlet weak var commentsTable: UITableView! @IBOutlet weak var commentText: UITextView! @IBOutlet weak var likeCount: UILabel! @IBOutlet weak var unlikeCount: UILabel! @IBOutlet weak var btnLike: UIButton! @IBOutlet weak var btnUnlike: UIButton! @IBAction func onLikePressed(_ sender: UIButton) { self.likeDislike(flag:"1") { results in } let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) if (dbObj?.open())! { let updateSQL = "UPDATE TABLE_ARTICLE SET article_like_flag = '1' where article_id = '\(self.currentArticleID)'" let result = dbObj?.executeUpdate(updateSQL, withArgumentsIn: nil) if !result! { print("Error: \(dbObj?.lastErrorMessage())") } } else { print("Error: \(dbObj?.lastErrorMessage())") } let frameworkBundle = Bundle(for: TicketHomeController.self) let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent( "TestDemoPodSDK.bundle") btnLike.isEnabled = false btnLike.setImage(UIImage(named: "like.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .disabled) btnUnlike.isEnabled = true btnUnlike.setImage(UIImage(named: "unlike_blur.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .normal) } @IBAction func onUnlikePressed(_ sender: UIButton) { self.likeDislike(flag:"2") { results in } let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) if (dbObj?.open())! { let updateSQL = "UPDATE TABLE_ARTICLE SET article_like_flag = '2' where article_id = '\(self.currentArticleID)'" let result = dbObj?.executeUpdate(updateSQL, withArgumentsIn: nil) if !result! { print("Error: \(dbObj?.lastErrorMessage())") } } else { print("Error: \(dbObj?.lastErrorMessage())") } let frameworkBundle = Bundle(for: TicketHomeController.self) let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent( "TestDemoPodSDK.bundle") btnUnlike.isEnabled = false btnUnlike.setImage(UIImage(named: "unlike.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .disabled) btnLike.isEnabled = true btnLike.setImage(UIImage(named: "like_blur.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .normal) } @IBAction func onAddComment(_ sender: UIButton) { if (commentText.text == "Comment here" || commentText.text.isEmpty) { let alertController:UIAlertController? = UIAlertController(title: "", message: "Please enter the comment", preferredStyle: .alert) let alertAction = UIAlertAction(title: "Okay",style: .default, handler:nil) alertController!.addAction(alertAction) OperationQueue.main.addOperation { self.present(alertController!,animated: true, completion: nil) } return }else { self.addComment(){ results in } } } @IBOutlet weak var headerView: UIView! func textViewDidBeginEditing(_ textView: UITextView) { if textView.textColor == UIColor.lightGray { textView.text = nil textView.textColor = UIColor.black } } func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { textView.text = "Comment here" textView.textColor = UIColor.lightGray } } let defaults = UserDefaults.standard let constants = Constants() var commentData: [[String:String]] = [] override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.scrollView.isScrollEnabled = true self.scrollView.contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height + 120) } override func viewDidLoad() { super.viewDidLoad() commentText.text = "Comment here" commentText.textColor = UIColor.lightGray commentText.layer.borderColor = UIColor(red: CGFloat(204.0 / 255.0), green: CGFloat(204.0 / 255.0), blue: CGFloat(204.0 / 255.0), alpha: CGFloat(1.0)).cgColor commentText.layer.borderWidth = 1.0 commentText.layer.cornerRadius = 5 articleRating.settings.updateOnTouch = false articleRating.settings.fillMode = .precise let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) if (dbObj?.open())! { let querySQL = "SELECT article_id, category_id, subcategory_id, title, description, date, rating ,comment_count, status, totalviews, article_like, article_unlike , article_like_flag FROM TABLE_ARTICLE where article_id = '\(self.currentArticleID)'" let results:FMResultSet? = dbObj?.executeQuery(querySQL, withArgumentsIn: nil) while results?.next() == true { self.articleTitle.text = (results?.string(forColumn: "title"))! self.articleDescription.text = (results?.string(forColumn: "description"))! self.articleViewCount.text = "Views(" + (results?.string(forColumn: "totalviews"))! + ")" var rtng: Double = Double((results?.string(forColumn: "rating"))!)! self.articleRating.rating = rtng self.articleRating.text = String(format: "%.1f", rtng) self.likeCount.text = (results?.string(forColumn: "article_like"))! self.unlikeCount.text = (results?.string(forColumn: "article_unlike"))! let articleFlag = (results?.string(forColumn: "article_like_flag"))! let frameworkBundle = Bundle(for: TicketHomeController.self) let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent( "TestDemoPodSDK.bundle") if (articleFlag == "1") { btnLike.isEnabled = false btnLike.setImage(UIImage(named: "like.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .disabled) btnUnlike.isEnabled = true btnUnlike.setImage(UIImage(named: "unlike_blur.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .normal) } else if (articleFlag == "2") { btnUnlike.isEnabled = false btnUnlike.setImage(UIImage(named: "unlike.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .disabled) btnLike.isEnabled = true btnLike.setImage(UIImage(named: "like_blur.png", in: Bundle(url: bundleURL!), compatibleWith: nil), for: .normal) } } dbObj?.close() } else { print("Error: \(dbObj?.lastErrorMessage())") } let frameworkBundle = Bundle(for: TicketHomeController.self) let bundleURL = frameworkBundle.resourceURL?.appendingPathComponent( "TestDemoPodSDK.bundle") let resourceBundle = Bundle(url: bundleURL!) self.commentsTable.tableFooterView = UIView() self.commentsTable.register(UINib(nibName: "ArticleDetailCell", bundle: resourceBundle), forCellReuseIdentifier: "singleArticleDetailCell") self.commentsTable.estimatedRowHeight = 130.0 if (HSConfig.isInternetAvailable()) { self.downloadArticle(){ results in let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) if (dbObj?.open())! { let querySQL = "SELECT name, date, comment FROM TABLE_ARTICLE_COMMENT where article_id = '\(self.currentArticleID)'" let results:FMResultSet? = dbObj?.executeQuery(querySQL, withArgumentsIn: nil) while results?.next() == true { let jsonObject: [String: String] = [ "Name" : (results?.string(forColumn:"name"))!, "Date" : (results?.string(forColumn: "date"))!, "Comment": (results?.string(forColumn: "comment"))! ] self.commentData.append(jsonObject) } dbObj?.close() } else { print("Error: \(dbObj?.lastErrorMessage())") } DispatchQueue.main.async { self.commentsTable.reloadData() } } }else { let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) if (dbObj?.open())! { let querySQL = "SELECT name, date, comment FROM TABLE_ARTICLE_COMMENT where article_id = '\(self.currentArticleID)'" let results:FMResultSet? = dbObj?.executeQuery(querySQL, withArgumentsIn: nil) while results?.next() == true { let jsonObject: [String: String] = [ "Name" : (results?.string(forColumn:"name"))!, "Date" : (results?.string(forColumn: "date"))!, "Comment": (results?.string(forColumn: "comment"))! ] self.commentData.append(jsonObject) } dbObj?.close() } else { print("Error: \(dbObj?.lastErrorMessage())") } DispatchQueue.main.async { self.commentsTable.reloadData() } } self.scrollView.isScrollEnabled = true self.scrollView.frame = self.view.bounds self.scrollView.contentSize = self.view.bounds.size } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.commentData.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "singleArticleDetailCell", for: indexPath) as! ArticleDetailCell cell.labelName.text = self.commentData[indexPath.row]["Name"] cell.labelCommentedOn.text = self.commentData[indexPath.row]["Date"] cell.labelComment.text = self.commentData[indexPath.row]["Comment"] cell.preservesSuperviewLayoutMargins = false cell.separatorInset = UIEdgeInsets.zero cell.layoutMargins = UIEdgeInsets.zero return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func downloadArticle(completionHandler: @escaping (_ results: String) -> ()) { var lastUpdateDateTime:String = "" let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) if (dbObj?.open())! { let querySQL = "SELECT article_update_time FROM TABLE_ARTICLE WHERE article_id = '\(self.currentArticleID)'" let results:FMResultSet? = dbObj?.executeQuery(querySQL, withArgumentsIn: nil) while results?.next() == true { lastUpdateDateTime = (results?.string(forColumn: "article_update_time"))! } dbObj?.close() } else { print("Error: \(dbObj?.lastErrorMessage())") } let defaultSession = URLSession(configuration: URLSessionConfiguration.ephemeral) let url = URL(string: constants.AppUrl+"article")! var request = URLRequest(url: url) request.addValue("text/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" let jsonObject: [String: String] = [ "apikey": HSConfig.getAPIKey(), "article_id": self.currentArticleID, "action": "comment_list", "modified_date": lastUpdateDateTime ] var data : AnyObject let dict = jsonObject as NSDictionary do { data = try JSONSerialization.data(withJSONObject: dict, options:.prettyPrinted) as AnyObject let strData = NSString(data: (data as! NSData) as Data, encoding: String.Encoding.utf8.rawValue)! as String data = strData.data(using: String.Encoding.utf8)! as AnyObject let task = defaultSession.uploadTask(with: request, from: (data as! NSData) as Data, completionHandler: {(data,response,error) in guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else { return } let json = JSON(data: data!) let dbObj = FMDatabase(path: self.defaults.value(forKey: "databasePath") as! String) for i in 0..<json["response"]["ARTICLE_COMMENT"].count { var name: String! = String(describing: json["response"]["ARTICLE_COMMENT"][i]["first_name"]) + " " + String(describing: json["response"]["ARTICLE_COMMENT"][i]["last_name"]) if (dbObj?.open())! { let insertSQL = "INSERT INTO TABLE_ARTICLE_COMMENT (name, article_id, date, comment) VALUES ('\(name!)','\(self.currentArticleID)','\(String(describing: json["response"]["ARTICLE_COMMENT"][i]["date"]))','\(String(describing: json["response"]["ARTICLE_COMMENT"][i]["article_comments"]))')" let result = dbObj?.executeUpdate(insertSQL, withArgumentsIn: nil) if !result! { print("Error: \(dbObj?.lastErrorMessage())") } } else { print("Error: \(dbObj?.lastErrorMessage())") } } if (dbObj?.open())! { let updatedTime = String(describing: json["response"]["CurrentDateTime"]) do { try dbObj?.executeUpdate("UPDATE TABLE_ARTICLE SET article_update_time=? WHERE article_id=?", withArgumentsIn: [updatedTime, self.currentArticleID]) } catch { } } else { print("Error: \(dbObj?.lastErrorMessage())") } let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) completionHandler(dataString as! String) } ); task.resume() }catch{ } } func addComment(completionHandler: @escaping (_ results: String) -> ()) { let defaultSession = URLSession(configuration: URLSessionConfiguration.ephemeral) let url = URL(string: constants.AppUrl+"article")! var request = URLRequest(url: url) request.addValue("text/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" let jsonObject: [String: String] = [ "apikey": HSConfig.getAPIKey(), "article_id": self.currentArticleID, "action": "comment_add", "email": self.defaults.value(forKey: "userMail") as! String, "article_comments": commentText.text ] var data : AnyObject let dict = jsonObject as NSDictionary do { data = try JSONSerialization.data(withJSONObject: dict, options:.prettyPrinted) as AnyObject let strData = NSString(data: (data as! NSData) as Data, encoding: String.Encoding.utf8.rawValue)! as String data = strData.data(using: String.Encoding.utf8)! as AnyObject let task = defaultSession.uploadTask(with: request, from: (data as! NSData) as Data, completionHandler: {(data,response,error) in guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else { return } let json = JSON(data: data!) let alertController:UIAlertController? = UIAlertController(title: "", message: String(describing: json["SUCCESS"]), preferredStyle: .alert) let alertAction = UIAlertAction(title: "Okay",style: .default, handler:nil) alertController!.addAction(alertAction) OperationQueue.main.addOperation { self.present(alertController!,animated: true, completion: nil) } let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) completionHandler(dataString as! String) } ); task.resume() }catch{ } } func likeDislike(flag: String, completionHandler: @escaping (_ results: String) -> ()) { let defaultSession = URLSession(configuration: URLSessionConfiguration.ephemeral) let url = URL(string: constants.AppUrl+"article")! var request = URLRequest(url: url) request.addValue("text/json", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" let jsonObject: [String: String] = [ "apikey": HSConfig.getAPIKey(), "article_id": self.currentArticleID, "action": "article_feedback", "email": self.defaults.value(forKey: "userMail") as! String, "rating": flag ] var data : AnyObject let dict = jsonObject as NSDictionary do { data = try JSONSerialization.data(withJSONObject: dict, options:.prettyPrinted) as AnyObject let strData = NSString(data: (data as! NSData) as Data, encoding: String.Encoding.utf8.rawValue)! as String data = strData.data(using: String.Encoding.utf8)! as AnyObject let task = defaultSession.uploadTask(with: request, from: (data as! NSData) as Data, completionHandler: {(data,response,error) in guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else { let alertController:UIAlertController? = UIAlertController(title: "", message: "Error check your internet connection", preferredStyle: .alert) let alertAction = UIAlertAction(title: "Okay",style: .default, handler:nil) alertController!.addAction(alertAction) self.present(alertController!,animated: true, completion: nil) return } let json = JSON(data: data!) let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) completionHandler(dataString as! String) } ); task.resume() }catch{ } } }
mit
bdc7caeb5f5efea9403d474ecd8ba3c7
37.289389
316
0.48606
5.844417
false
false
false
false
treejames/firefox-ios
UITests/Global.swift
3
12852
/* 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 Storage import WebKit let LabelAddressAndSearch = "Address and Search" extension XCTestCase { func tester(_ file: String = __FILE__, _ line: Int = __LINE__) -> KIFUITestActor { return KIFUITestActor(inFile: file, atLine: line, delegate: self) } func system(_ file: String = __FILE__, _ line: Int = __LINE__) -> KIFSystemTestActor { return KIFSystemTestActor(inFile: file, atLine: line, delegate: self) } } extension KIFUITestActor { /// Looks for a view with the given accessibility hint. func tryFindingViewWithAccessibilityHint(hint: String) -> Bool { let element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in return element.accessibilityHint == hint } return element != nil } /// Waits for and returns a view with the given accessibility value. func waitForViewWithAccessibilityValue(value: String) -> UIView { var element: UIAccessibilityElement! runBlock { _ in element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in return element.accessibilityValue == value } return (element == nil) ? KIFTestStepResult.Wait : KIFTestStepResult.Success } return UIAccessibilityElement.viewContainingAccessibilityElement(element) } /// Wait for and returns a view with the given accessibility label as an /// attributed string. See the comment in ReadingListPanel.swift about /// using attributed strings as labels. (It lets us set the pitch) func waitForViewWithAttributedAccessibilityLabel(label: NSAttributedString) -> UIView { var element: UIAccessibilityElement! runBlock { _ in element = UIApplication.sharedApplication().accessibilityElementMatchingBlock { element in if let elementLabel = element.valueForKey("accessibilityLabel") as? NSAttributedString { return elementLabel.isEqualToAttributedString(label) } return false } return (element == nil) ? KIFTestStepResult.Wait : KIFTestStepResult.Success } return UIAccessibilityElement.viewContainingAccessibilityElement(element) } /// There appears to be a KIF bug where waitForViewWithAccessibilityLabel returns the parent /// UITableView instead of the UITableViewCell with the given label. /// As a workaround, retry until KIF gives us a cell. /// Open issue: https://github.com/kif-framework/KIF/issues/336 func waitForCellWithAccessibilityLabel(label: String) -> UITableViewCell { var cell: UITableViewCell! runBlock { _ in let view = self.waitForViewWithAccessibilityLabel(label) cell = view as? UITableViewCell return (cell == nil) ? KIFTestStepResult.Wait : KIFTestStepResult.Success } return cell } /** * Finding views by accessibility label doesn't currently work with WKWebView: * https://github.com/kif-framework/KIF/issues/460 * As a workaround, inject a KIFHelper class that iterates the document and finds * elements with the given textContent or title. */ func waitForWebViewElementWithAccessibilityLabel(text: String) { let webView = waitForViewWithAccessibilityLabel("Web content") as! WKWebView // Wait for the webView to stop loading. runBlock({ _ in return webView.loading ? KIFTestStepResult.Wait : KIFTestStepResult.Success }) lazilyInjectKIFHelper(webView) var stepResult = KIFTestStepResult.Wait let escaped = text.stringByReplacingOccurrencesOfString("\"", withString: "\\\"") webView.evaluateJavaScript("KIFHelper.selectElementWithAccessibilityLabel(\"\(escaped)\");", completionHandler: { (result: AnyObject!, error: NSError!) in stepResult = result != nil ? (result as! Bool ? KIFTestStepResult.Success : KIFTestStepResult.Failure) : KIFTestStepResult.Failure }) runBlock({ (error: NSErrorPointer) in if stepResult == KIFTestStepResult.Failure { error.memory = NSError(domain: "KIFHelper", code: 0, userInfo: [NSLocalizedDescriptionKey: "Accessibility label not found in webview: \(escaped)"]) } return stepResult }) } private func lazilyInjectKIFHelper(webView: WKWebView) { var stepResult = KIFTestStepResult.Wait webView.evaluateJavaScript("typeof KIFHelper;", completionHandler: { (result: AnyObject!, error: NSError!) in if result as! String == "undefined" { let bundle = NSBundle(forClass: NavigationTests.self) let path = bundle.pathForResource("KIFHelper", ofType: "js")! let source = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)! webView.evaluateJavaScript(source as String, completionHandler: nil) } stepResult = KIFTestStepResult.Success }) runBlock({ _ in return stepResult }) } public func deleteCharacterFromFirstResponser() { enterTextIntoCurrentFirstResponder("\u{0008}") } // TODO: Click element, etc. } class BrowserUtils { /// Close all tabs to restore the browser to startup state. class func resetToAboutHome(tester: KIFUITestActor) { if tester.tryFindingTappableViewWithAccessibilityLabel("Cancel", error: nil) { tester.tapViewWithAccessibilityLabel("Cancel") } tester.tapViewWithAccessibilityLabel("Show Tabs") let tabsView = tester.waitForViewWithAccessibilityLabel("Tabs Tray").subviews.first as! UICollectionView while tabsView.numberOfItemsInSection(0) > 1 { let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0))! tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester.waitForAbsenceOfViewWithAccessibilityLabel(cell.accessibilityLabel) } // When the last tab is closed, the tabs tray will automatically be closed // since a new about:home tab will be selected. if let cell = tabsView.cellForItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) { tester.swipeViewWithAccessibilityLabel(cell.accessibilityLabel, inDirection: KIFSwipeDirection.Left) tester.waitForTappableViewWithAccessibilityLabel("Show Tabs") } } /// Injects a URL and title into the browser's history database. class func addHistoryEntry(title: String, url: NSURL) { let notificationCenter = NSNotificationCenter.defaultCenter() var info = [NSObject: AnyObject]() info["url"] = url info["title"] = title info["visitType"] = VisitType.Link.rawValue notificationCenter.postNotificationName("LocationChange", object: self, userInfo: info) } private class func clearHistoryItemAtIndex(index: NSIndexPath, tester: KIFUITestActor) { if let row = tester.waitForCellAtIndexPath(index, inTableViewWithAccessibilityIdentifier: "History List") { tester.swipeViewWithAccessibilityLabel(row.accessibilityLabel, value: row.accessibilityValue, inDirection: KIFSwipeDirection.Left) tester.tapViewWithAccessibilityLabel("Remove") } } class func clearHistoryItems(tester: KIFUITestActor, numberOfTests: Int = -1) { resetToAboutHome(tester) tester.tapViewWithAccessibilityLabel("History") let historyTable = tester.waitForViewWithAccessibilityIdentifier("History List") as! UITableView var index = 0 for section in 0 ..< historyTable.numberOfSections() { for rowIdx in 0 ..< historyTable.numberOfRowsInSection(0) { clearHistoryItemAtIndex(NSIndexPath(forRow: 0, inSection: 0), tester: tester) if numberOfTests > -1 && ++index == numberOfTests { return } } } tester.tapViewWithAccessibilityLabel("Top sites") } class func ensureAutocompletionResult(tester: KIFUITestActor, textField: UITextField, prefix: String, completion: String) { // searches are async (and debounced), so we have to wait for the results to appear. tester.waitForViewWithAccessibilityValue(prefix + completion) var range = NSRange() var attribute: AnyObject? let textLength = count(textField.text) attribute = textField.attributedText!.attribute(NSBackgroundColorAttributeName, atIndex: 0, effectiveRange: &range) if attribute != nil { // If the background attribute exists for the first character, the entire string is highlighted. XCTAssertEqual(prefix, "") XCTAssertEqual(completion, textField.text) return } let prefixLength = range.length attribute = textField.attributedText!.attribute(NSBackgroundColorAttributeName, atIndex: textLength - 1, effectiveRange: &range) if attribute == nil { // If the background attribute exists for the last character, the entire string is not highlighted. XCTAssertEqual(prefix, textField.text) XCTAssertEqual(completion, "") return } let completionStartIndex = advance(textField.text.startIndex, prefixLength) let actualPrefix = textField.text.substringToIndex(completionStartIndex) let actualCompletion = textField.text.substringFromIndex(completionStartIndex) XCTAssertEqual(prefix, actualPrefix, "Expected prefix matches actual prefix") XCTAssertEqual(completion, actualCompletion, "Expected completion matches actual completion") } } class SimplePageServer { class func getPageData(name: String, ext: String = "html") -> String { var pageDataPath = NSBundle(forClass: self).pathForResource(name, ofType: ext)! return NSString(contentsOfFile: pageDataPath, encoding: NSUTF8StringEncoding, error: nil)! as String } class func start() -> String { let webServer: GCDWebServer = GCDWebServer() webServer.addHandlerForMethod("GET", path: "/image.png", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in let img = UIImagePNGRepresentation(UIImage(named: "back")) return GCDWebServerDataResponse(data: img, contentType: "image/png") } for page in ["noTitle", "readablePage"] { webServer.addHandlerForMethod("GET", path: "/\(page).html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in return GCDWebServerDataResponse(HTML: self.getPageData(page)) } } // we may create more than one of these but we need to give them uniquie accessibility ids in the tab manager so we'll pass in a page number webServer.addHandlerForMethod("GET", path: "/scrollablePage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var pageData = self.getPageData("scrollablePage") let page = (request.query["page"] as! String).toInt()! pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description) return GCDWebServerDataResponse(HTML: pageData as String) } webServer.addHandlerForMethod("GET", path: "/numberedPage.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var pageData = self.getPageData("numberedPage") let page = (request.query["page"] as! String).toInt()! pageData = pageData.stringByReplacingOccurrencesOfString("{page}", withString: page.description) return GCDWebServerDataResponse(HTML: pageData as String) } webServer.addHandlerForMethod("GET", path: "/readerContent.html", requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in return GCDWebServerDataResponse(HTML: self.getPageData("readerContent")) } if !webServer.startWithPort(0, bonjourName: nil) { XCTFail("Can't start the GCDWebServer") } // We use 127.0.0.1 explicitly here, rather than localhost, in order to avoid our // history exclusion code (Bug 1188626). let webRoot = "http://127.0.0.1:\(webServer.port)" return webRoot } }
mpl-2.0
b96e5725d42232e8b5f6a1d523ad4a9a
44.736655
163
0.676704
5.513514
false
true
false
false
kumabook/MusicFav
MusicFav/StreamTreeViewController.swift
1
22336
// // StreamTreeViewController.swift // MusicFav // // Created by Hiroki Kumamoto on 12/21/14. // Copyright (c) 2014 Hiroki Kumamoto. All rights reserved. // import UIKit import ReactiveSwift import FeedlyKit import MusicFeeder import RATreeView import MBProgressHUD import SoundCloudKit import YouTubeKit class StreamTreeViewController: UIViewController, RATreeViewDelegate, RATreeViewDataSource { enum Section { case globalResource(FeedlyKit.Stream) case feedlyCategory(FeedlyKit.Category) case uncategorizedSubscription(FeedlyKit.Subscription) case favorite case history case youTube case soundCloud case spotify case pocket case twitter var title: String { switch self { case .globalResource(let stream): return stream.streamTitle.localize() case .favorite: return "Favorite".localize() case .history: return "History".localize() case .youTube: return "YouTube" case .soundCloud: return "SoundCloud Timeline" case .spotify: return "Spotify Top Tracks" case .pocket: return "Pocket" case .twitter: return "Twitter" case .feedlyCategory(let category): return category.label case .uncategorizedSubscription(let subscription): return subscription.streamTitle } } func setThumbImage(_ view: UIImageView?) { switch self { case .globalResource(let stream): switch stream.streamTitle { case "All": view?.image = UIImage(named: "home")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) case "Saved": view?.image = UIImage(named: "saved")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) case "Read": view?.image = UIImage(named: "checkmark")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) default: break } case .history: view?.image = UIImage(named: "history")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) case .favorite: view?.image = UIImage(named: "fav_entry")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) case .youTube: view?.image = UIImage(named: "youtube") case .soundCloud: view?.image = UIImage(named: "soundcloud_icon") case .spotify: view?.image = UIImage(named: "spotify") case .pocket: break case .twitter: break case .feedlyCategory: view?.image = UIImage(named: "folder")?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) case .uncategorizedSubscription(let subscription): view?.sd_setImage(with: subscription.thumbnailURL, placeholderImage: UIImage(named: "default_thumb")) } } func child(_ vc: StreamTreeViewController, index: Int) -> Any { switch self { case .globalResource: return [] case .history: return [] case .favorite: return [] case .youTube: let i = vc.youtubeActivityLoader.itemsOfPlaylist.index(vc.youtubeActivityLoader.itemsOfPlaylist.startIndex, offsetBy: index) return vc.youtubeActivityLoader.itemsOfPlaylist.keys[i] case .soundCloud: return [] case .spotify: return [] case .pocket: return [] case .twitter: return [] case .feedlyCategory(let category): if let streams = vc.subscriptionRepository.streamListOfCategory[category] { return streams[index] } else { return [] } case .uncategorizedSubscription: return [] } } func numOfChild(_ vc: StreamTreeViewController) -> Int { switch self { case .globalResource: return 0 case .history: return 0 case .favorite: return 0 case .youTube: return vc.youtubeActivityLoader.itemsOfPlaylist.count case .soundCloud: return 0 case .spotify: return 0 case .pocket: return 0 case .twitter: return 0 case .feedlyCategory(let category): if let streams = vc.subscriptionRepository.streamListOfCategory[category] { return streams.count } else { return 0 } case .uncategorizedSubscription: return 0 } } } var treeView: RATreeView? var sections: [Section] var subscriptionRepository: SubscriptionRepository var observer: Disposable? var refreshDisposable: Disposable? var youtubeActivityLoader: YouTubeActivityLoader var youtubeObserver: Disposable? var apiClient: CloudAPIClient { return CloudAPIClient.shared } var appDelegate: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } var root: UIViewController? { return view.window?.rootViewController } var refreshControl: UIRefreshControl? func defaultSections() -> [Section] { var sections: [Section] = [] if let userId = CloudAPIClient.profile?.id { sections.append(.globalResource(FeedlyKit.Category.all(userId))) sections.append(.globalResource(FeedlyKit.Tag.saved(userId))) sections.append(.globalResource(FeedlyKit.Tag.read(userId))) } sections.append(.favorite) sections.append(.history) sections.append(.youTube) sections.append(.soundCloud) sections.append(.spotify) return sections } init() { sections = [] subscriptionRepository = SubscriptionRepository() youtubeActivityLoader = YouTubeActivityLoader() super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { sections = [] subscriptionRepository = SubscriptionRepository() youtubeActivityLoader = YouTubeActivityLoader() super.init(coder: aDecoder) } deinit {} override func viewDidLoad() { super.viewDidLoad() let settingsButton = UIBarButtonItem(image: UIImage(named: "settings"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(StreamTreeViewController.showPreference)) let addStreamButton = UIBarButtonItem(image: UIImage(named: "add_stream"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(StreamTreeViewController.addStream)) navigationItem.leftBarButtonItems = [settingsButton, addStreamButton] view.backgroundColor = UIColor.white treeView = RATreeView(frame: CGRect(x: 0, y: 0, width: appDelegate.leftVisibleWidth!, height: view.frame.height)) treeView?.backgroundColor = UIColor.white treeView?.delegate = self treeView?.dataSource = self treeView?.register(StreamTreeViewCell.self, forCellReuseIdentifier: "reuseIdentifier") view.addSubview(treeView!) refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action:#selector(StreamTreeViewController.refresh), for:UIControlEvents.valueChanged) treeView?.addResreshControl(refreshControl!) refresh() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() treeView!.frame = CGRect(x: 0, y: 0, width: appDelegate.leftVisibleWidth!, height: view.frame.height) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) Logger.sendScreenView(self) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() observer?.dispose() youtubeObserver?.dispose() } @objc func showPreference() { let prefvc = PreferenceViewController() root?.present(UINavigationController(rootViewController:prefvc), animated: true, completion: nil) } @objc func addStream() { let admvc = AddStreamMenuViewController(subscriptionRepository: subscriptionRepository) root?.present(UINavigationController(rootViewController:admvc), animated: true, completion: nil) } func showDefaultStream() { if let profile = CloudAPIClient.profile { showStream(stream: FeedlyKit.Category.all(profile.id)) } else { let streams: [FeedlyKit.Stream] = subscriptionRepository.streamListOfCategory.values.flatMap { $0 } if streams.count > 0 { showStream(stream: streams[Int(arc4random_uniform(UInt32(streams.count)))]) } else { showStream(stream: RecommendFeed.sampleStream()) } } } func showStream(section: Section) { switch section { case .globalResource(let stream): showStream(stream: stream) case .favorite: showSavedStream() case .history: showHistory() case .soundCloud: if SoundCloudKit.APIClient.shared.isLoggedIn { showSoundCloudActivities() } else { SoundCloudKit.APIClient.authorize() } case .youTube: if YouTubeKit.APIClient.isLoggedIn { return } else { YouTubeKit.APIClient.authorize() } case .spotify: if SpotifyAPIClient.shared.isLoggedIn { showSpotifyTopTracks() } else if let vc = appDelegate.coverViewController { SpotifyAPIClient.shared.startAuthenticationFlow(viewController: vc) } case .pocket: return case .twitter: return case .feedlyCategory: return case .uncategorizedSubscription(let subscription): showStream(stream: subscription) } } func showStream(stream: FeedlyKit.Stream) { let vc = StreamTimelineTableViewController(entryRepository: EntryRepository(stream: stream)) appDelegate.miniPlayerViewController?.setCenterViewController(vc) } func showSavedStream() { let vc = SavedStreamTimelineTableViewController(entryRepository: SavedEntryRepository()) appDelegate.miniPlayerViewController?.setCenterViewController(vc) } func showHistory() { let vc = HistoryTableViewController(entryRepository: HistoryRepository()) appDelegate.miniPlayerViewController?.setCenterViewController(vc) } func showYouTubeActivities(_ playlist: YouTubeKit.Playlist) { let vc = YouTubeActivityTableViewController(activityLoader: youtubeActivityLoader, playlist: playlist) appDelegate.miniPlayerViewController?.setCenterViewController(vc) } func showSoundCloudActivities() { let vc = SoundCloudActivityTableViewController() appDelegate.miniPlayerViewController?.setCenterViewController(vc) } func showSpotifyTopTracks() { let vc = SpotifyTopTracksTableViewController() appDelegate.miniPlayerViewController?.setCenterViewController(vc) } func observeStreamList() { observer?.dispose() observer = subscriptionRepository.signal.observeResult({ result in guard let event = result.value else { return } switch event { case .create(_): self.treeView?.reloadData() MBProgressHUD.hide(for: self.view, animated: true) case .startLoading: self.refreshControl?.beginRefreshing() case .completeLoading: let categories = self.subscriptionRepository.categories.filter({ $0 != self.subscriptionRepository.uncategorized }) self.sections = self.defaultSections() self.sections.append(contentsOf: categories.map({ Section.feedlyCategory($0) })) self.sections.append(contentsOf: self.subscriptionRepository.uncategorizedStreams.map { if let subscription = $0 as? FeedlyKit.Subscription { return Section.uncategorizedSubscription(subscription) } else if let feed = $0 as? Feed { return Section.uncategorizedSubscription(Subscription(feed: feed, categories: [])) } else { return Section.uncategorizedSubscription(Subscription(id: "Unknown", title: "Unknown", categories: []) ) } }) self.refreshControl?.endRefreshing() self.treeView?.reloadData() if let miniPlayerVC = self.appDelegate.miniPlayerViewController { if !miniPlayerVC.hasCenterViewController() { self.showDefaultStream() } } case .failToLoad(let e): let _ = CloudAPIClient.alertController(error: e, handler: { (action) -> Void in }) self.refreshControl?.endRefreshing() case .startUpdating: MBProgressHUD.showAdded(to: self.view, animated: true) case .failToUpdate(let e): let _ = MBProgressHUD.hide(for: self.view, animated: true) let _ = CloudAPIClient.alertController(error: e, handler: { (action) -> Void in }) case .remove(let subscription): MBProgressHUD.hide(for: self.view, animated: true) let _ = MBProgressHUD.showCompletedHUDForView(self.navigationController!.view, animated: true, duration: 1.0, after: { let l = self.subscriptionRepository subscription.categories.forEach { category in if category == l.uncategorized { let i = self.indexOfUncategorizedSubscription(subscription) self.treeView!.deleteItems(at: IndexSet([i]), inParent: nil, with: RATreeViewRowAnimationRight) self.sections.remove(at: i) self.treeView!.reloadData() } else { if let i = self.subscriptionRepository.uncategorizedStreams.index(of: subscription) { self.treeView!.deleteItems(at: IndexSet([i]), inParent: self.treeView!.parent(forItem: subscription), with: RATreeViewRowAnimationRight) self.treeView!.reloadRows(forItems: [self.indexOfCategory(category)], with: RATreeViewRowAnimationRight) } } } }) } }) } func observeYouTubeActivityLoader() { youtubeObserver?.dispose() youtubeObserver = youtubeActivityLoader.signal.observeResult({ result in guard let event = result.value else { return } switch event { case .startLoading: self.treeView?.reloadData() case .completeLoading: self.treeView?.reloadData() case .failToLoad: self.treeView?.reloadData() } }) } func indexOfCategory(_ category: FeedlyKit.Category) -> Int { var i = 0 for section in sections { switch section { case .feedlyCategory(let c): if c == category { return i } default: break } i += 1 } return i } func indexOfUncategorizedSubscription(_ subscription: FeedlyKit.Subscription) -> Int { var i = 0 for section in sections { switch section { case .uncategorizedSubscription(let sub): if sub == subscription { return i } default: break } i += 1 } return i } @objc func refresh() { observer?.dispose() observeStreamList() youtubeObserver?.dispose() observeYouTubeActivityLoader() youtubeActivityLoader.clear() youtubeActivityLoader.fetchChannels() treeView?.reloadData() subscriptionRepository.refresh() } func unsubscribeTo(_ subscription: FeedlyKit.Subscription, index: Int, category: FeedlyKit.Category) { let _ = subscriptionRepository.unsubscribeTo(subscription) } // MARK: - RATreeView data source func treeView(_ treeView: RATreeView!, numberOfChildrenOfItem item: Any!) -> Int { if item == nil { return sections.count } if let index = item as? Int { return sections[index].numOfChild(self) } return 0 } func treeView(_ treeView: RATreeView!, indentationLevelForRowForItem item: Any!) -> Int { if let _ = item as? FeedlyKit.Stream { return 1 } else { return 0 } } func treeView(_ treeView: RATreeView!, shouldIndentWhileEditingRowForItem item: Any!) -> Bool { return true } func treeView(_ treeView: RATreeView!, cellForItem item: Any!) -> UITableViewCell! { let cell = treeView.dequeueReusableCell(withIdentifier: "reuseIdentifier") as! StreamTreeViewCell if let i = self.treeView?.levelForCell(forItem: item) { cell.indent = i } if item == nil { cell.textLabel?.text = "Nothing" } else if let index = item as? Int { let section = sections[index] section.setThumbImage(cell.imageView) let num = section.numOfChild(self) if num > 0 { cell.textLabel?.text = "\(section.title) (\(num))" } else { cell.textLabel?.text = "\(section.title)" } } else if let stream = item as? FeedlyKit.Stream { cell.textLabel?.text = stream.streamTitle if let subscription = stream as? FeedlyKit.Subscription { cell.imageView?.sd_setImage(with: subscription.thumbnailURL, placeholderImage: UIImage(named: "default_thumb")) } } else if let playlist = item as? YouTubeKit.Playlist { cell.textLabel?.text = playlist.title.localize() cell.imageView?.sd_setImage(with: playlist.thumbnailURL, placeholderImage: UIImage(named: "default_thumb")) } return cell } func treeView(_ treeView: RATreeView!, child index: Int, ofItem item: Any!) -> Any! { if item == nil { return index as AnyObject! } if let sectionIndex = item as? Int { return sections[sectionIndex].child(self, index: index) } return "Nothing" as AnyObject! } func treeView(_ treeView: RATreeView!, didSelectRowForItem item: Any!) { Logger.sendUIActionEvent(self, action: "didSelectRowForItem", label: "") if item == nil { } else if let index = item as? Int { showStream(section: sections[index]) } else if let stream = item as? FeedlyKit.Stream { showStream(stream:stream) } else if let playlist = item as? YouTubeKit.Playlist { showYouTubeActivities(playlist) } } func treeView(_ treeView: RATreeView!, canEditRowForItem item: Any!) -> Bool { if let index = item as? Int { switch sections[index] { case Section.uncategorizedSubscription: return true default: return false } } else if let _ = item as? FeedlyKit.Stream { return true } return false } func treeView(_ treeView: RATreeView!, commit editingStyle: UITableViewCellEditingStyle, forRowForItem item: Any!) { Logger.sendUIActionEvent(self, action: "commitEditingStyle", label: "") if let index = item as? Int { switch sections[index] { case Section.uncategorizedSubscription(let subscription): let uncategorized = subscriptionRepository.uncategorized if let i = subscriptionRepository.uncategorizedStreams.index(of: subscription) { unsubscribeTo(subscription, index: i, category: uncategorized) } default: break } } else if let _ = item as? FeedlyKit.Stream { let sectionIndex = treeView.parent(forItem: item) as! Int switch sections[sectionIndex] { case .feedlyCategory(let category): if let streams = subscriptionRepository.streamListOfCategory[category] { let stream = item as! FeedlyKit.Stream if let i = streams.index(of: stream) { if let subscription = item as? FeedlyKit.Subscription { unsubscribeTo(subscription, index: i, category: category) } } } default: break } } } }
mit
f42c254a6ed4d18e849aaecdfb263e3d
41.625954
140
0.573917
5.457122
false
false
false
false
objecthub/swift-lispkit
Sources/LispKit/Runtime/VirtualMachineState.swift
1
2591
// // VirtualMachineState.swift // LispKit // // Created by Matthias Zenger on 02/07/2016. // Copyright © 2016 ObjectHub. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// /// `VirtualMachineState` encapsulates per-continuation state of a virtual machine, such as: /// - the stack /// - the stack pointer /// - the registers /// - the winders stack /// public final class VirtualMachineState: CustomStringConvertible { /// The stack internal let stack: Exprs /// The stack pointer internal let sp: Int /// The set of registers internal let registers: Registers /// The stack of winders internal let winders: VirtualMachine.Winder? /// Creates a new virtual machine state internal init(stack: Exprs, sp: Int, spDelta: Int, ipDelta: Int, registers: Registers, winders: VirtualMachine.Winder?) { var adjustedStack = stack self.sp = sp + spDelta for i in self.sp..<sp { adjustedStack[i] = .undef } self.stack = adjustedStack var adjustedRegisters = registers adjustedRegisters.ip += ipDelta self.registers = adjustedRegisters self.winders = winders } public var description: String { var builder = StringBuilder(prefix: "vmstate {") if self.sp == 0 { builder.append("stack = []") } else if self.sp == 1 { builder.append("stack = [\(self.stack[0])]") } else if self.sp == 2 { builder.append("stack = [\(self.stack[0]), \(self.stack[1])]") } else { builder.append("stack = [..., \(self.stack[self.sp - 3]), \(self.stack[self.sp - 2]), ") builder.append("\(self.stack[self.sp - 1])]") } builder.append(", sp = \(self.sp)") builder.append(", ip = \(self.registers.ip)") builder.append(", fp = \(self.registers.fp)") builder.append(", initialFp = \(self.registers.initialFp)") builder.append(", numWinders = \(self.winders?.count ?? 0)") builder.append("}") return builder.description } }
apache-2.0
5d1ecbeda289e4f7104df0224aee5088
30.975309
94
0.634749
3.93617
false
false
false
false
cclef615/crumbs
crumbs/PostClass.swift
1
558
// // postClass.swift // crumbs // // Created by Colin Kohli on 7/22/15. // Copyright (c) 2015 Colin Kohli. All rights reserved. // import Foundation class Post{ init(myUser: String, myText: String, myLATT: Float, myLONG:Float, myViews: Int, myFlags: Int){ User = myUser Text = myText LATT = myLATT LONG = myLONG Flags = myFlags Views = myViews } var User: String var Text: String var LATT: Float var LONG: Float var Views: Int var Flags: Int }
mit
96131f8059d887e166512754c29572be
15.939394
99
0.569892
3.509434
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Home/View/搜索Cell/BTSearchCategoryTableViewCell.swift
1
1320
// // BTSearchCategoryTableViewCell.swift // BanTang // // Created by 张灿 on 16/6/20. // Copyright © 2016年 张灿. All rights reserved. // import UIKit class BTSearchCategoryTableViewCell: UITableViewCell { /** 标题 */ @IBOutlet weak var nameLabel: UILabel! /** 红色线 */ @IBOutlet weak var redLineView: UIView! /** cell模型 */ var categoryModel: BTSearchDanpinModel? { didSet { guard let categoryModel = categoryModel else { return } nameLabel.text = categoryModel.name } } override func awakeFromNib() { super.awakeFromNib() //取消cell的选中样式 self.selectionStyle = .None } //cell 选中与不选中都会点用这个方法 override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) redLineView.hidden = !selected if selected == true { nameLabel.textColor = UIColor.redColor() self.backgroundColor = UIColor.whiteColor() } else { self.backgroundColor = UIColor(red: 240 / 255.0, green: 240 / 255.0, blue: 240 / 255.0, alpha: 1.0) nameLabel.textColor = UIColor.blackColor() } } }
apache-2.0
098255c33aca6a3b1a6bb74cf6518119
25.104167
111
0.584996
4.381119
false
false
false
false
xingerdayu/dayu
dayu/Comb.swift
1
6824
// // Comb.swift // dayu // // Created by 王毅东 on 15/8/29. // Copyright (c) 2015年 Xinger. All rights reserved. // class Comb: NSObject { var createTime:Int64 = 0 var drawdown:Float = 0.0 var followNum = 0 var grade = 0 var gradego = 0 var id = "" var name = "" var pro:Float = 0.0 var situation:Int = 0 var supportNum:Int = 0 var uid = "" var userName = "" var yesFollow = 0 var yesSupport = 0 var types = 0 var descriptionStr = "" var now_amount : Float = 0.0 var cash_remaining : Float = 0.0 var amount : Float = 0.0 var lever = 0 var modify_time:Int64 = 0 var changeTimes = 0 var recentEarning : Float = 0.0 var recentpro : Float = 0.0 var frequency_rate : Float = 0.0 var grades = Array<Score>() var currencys = Array<Currency>() var contentLabelWidth:CGFloat = 280 var MAXFLOAT = 26; func parse(dict:NSDictionary) { let t: AnyObject? = dict["id"] id = "\(t!)" createTime = (dict["create_time"] as! NSString).longLongValue grade = dict["grade"] as! Int drawdown = dict["drawdown"] as! Float name = dict["name"] as! String let f = dict["follownum"] as? Int if f != nil { followNum = f!} gradego = dict["gradego"] as! Int pro = dict["pro"] as! Float situation = dict["situation"] as! Int let s = dict["supportnum"] as? Int if s != nil { supportNum = s! } uid = dict["uid"] as! String let n = dict["username"] as? String if n != nil {userName = n!} yesFollow = dict["yesfollow"] as! Int yesSupport = dict["yessupport"] as! Int } func parseDetail(dict:NSDictionary) { types = dict["analysis_types"] as! Int descriptionStr = dict["description"] as! String now_amount = dict["now_amount"] as! Float cash_remaining = dict["cash_remaining"] as! Float amount = dict["amount"] as! Float lever = dict["lever"] as! Int modify_time = (dict["modify_time"] as! NSString).longLongValue changeTimes = dict["changetimes"] as! Int //recentEarning = dict["recentearning"] as Float //recentpro = dict["recentpro"] as Float frequency_rate = dict["frequency_rate"] as! Float var gradeStr = ["D", "W", "M", "S"] let json_score = dict["score"] as! NSDictionary for i in 0...3 { let s = Score() let json2 = json_score[gradeStr[i]] as! NSDictionary s.grade = json2["grade"] as! Int s.gradego = json2["gradego"] as! Int s.drawdown_mark_drawdown = json2["drawdown"] as! Double s.drawdown_mark_mark = json2["drawdown_mark"] as! Int s.pro_mark_pro = json2["pro"] as! Double s.pro_mark_mark = json2["pro_mark"] as! Int self.grades.append(s) } self.currencys.removeAll() let json_currency_types = dict["currency_types"] as! NSArray for i in 0..<json_currency_types.count { let c = Currency() let json3 = json_currency_types[i] as! NSDictionary c.value = json3["value"] as! String c.buyRate = json3["buyRate"] as! Float c.operation = json3["operation"] as! String c.key = json3["key"] as! String //c.lots = json3["lots"] as! Float var lots = json3["lots"] as? Float if lots == nil { lots = (json3["lots"] as? NSString)?.floatValue } else { c.lots = lots! } c.earning = json3["earning"] as! Float c.selected = true self.currencys.append(c) } let cash = Currency() cash.value = "可用保证金" cash.buyRate = self.cash_remaining cash.key = "cash_remaining" cash.operation = "" self.currencys.append(cash) } class Score { var grade : Int = 0 var gradego : Int = 0 var drawdown_mark_drawdown : Double = 0 var drawdown_mark_mark : Int = 0 var pro_mark_pro : Double = 0 var pro_mark_mark : Int = 0 } class Currency { var key = "" var value = "" var buyRate : Float = 0.0 var operation = "" var lots : Float = 0.0 var selected : Bool = false var earning : Float = 0.0 } // func getNameWidth() -> CGFloat { // var size = name.textSizeWithFont(UIFont.systemFontOfSize(FONT_SIZE), constrainedToSize: CGSizeMake(20000, 22)) //// CGSize titleSize = [aString sizeWithFont,font constrainedToSize:CGSizeMake(MAXFLOAT, 30)] //// if imageNum > 0 { //// imageGroupHeight = defaultImageGroupHeight //// } //// var text: NSString = NSString(CString: name.cStringUsingEncoding(NSUTF8StringEncoding)!, //// encoding: NSUTF8StringEncoding) //// text.sizeWithAttributes(attrs: [NSObject : AnyObject]!) // // return contentLabelOffsetY + size.height + imageGroupHeight + marginTop * 3 + 30 // } func getColor(s: Int, g: Int) -> [String] { var colors = [String](count: 4, repeatedValue: "") if s < 20 { colors[0] = "comb_circle_1" colors[1] = g > 0 ? "comb_up_1" : "comb_down_1" colors[2] = "#999999" } else if s < 40 { colors[0] = "comb_circle_2" colors[1] = g > 0 ? "comb_up_2" : "comb_down_2" colors[2] = "#397ada" } else if s < 60 { colors[0] = "comb_circle_3" colors[1] = g > 0 ? "comb_up_3" : "comb_down_3" colors[2] = "#44b74f" } else if s < 80 { colors[0] = "comb_circle_4" colors[1] = g > 0 ? "comb_up_4" : "comb_down_4" colors[2] = "#fda126" } else { colors[0] = "comb_circle_5" colors[1] = g > 0 ? "comb_up_5" : "comb_down_5" colors[2] = "#ef5a3a" } return colors } func toCyTypes(comb: Comb) -> Array<CurrencyType> { let all = CurrencyType.createCurrencys() let cacheMap = NSMutableDictionary(); for ct in all { cacheMap[ct.key] = ct } var cs = Array<CurrencyType>() for c in comb.currencys { if c.key != "cash_remaining" { let ct = cacheMap[c.key] as! CurrencyType //ct.key = c.key //ct.value = c.value ct.isSelected = c.selected ct.operation = c.operation ct.tradeNum = CGFloat(c.lots) cs.append(ct) } } return cs } }
bsd-3-clause
c4f2bce28c7a0b61f0406f012bd38618
33.378788
120
0.523362
3.743674
false
false
false
false
danielgindi/Charts
Source/Charts/Components/YAxis.swift
2
6015
// // YAxis.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if canImport(UIKit) import UIKit #endif #if canImport(Cocoa) import Cocoa #endif /// Class representing the y-axis labels settings and its entries. /// Be aware that not all features the YLabels class provides are suitable for the RadarChart. /// Customizations that affect the value range of the axis need to be applied before setting data for the chart. @objc(ChartYAxis) open class YAxis: AxisBase { @objc(YAxisLabelPosition) public enum LabelPosition: Int { case outsideChart case insideChart } /// Enum that specifies the axis a DataSet should be plotted against, either Left or Right. @objc public enum AxisDependency: Int { case left case right } /// indicates if the bottom y-label entry is drawn or not @objc open var drawBottomYLabelEntryEnabled = true /// indicates if the top y-label entry is drawn or not @objc open var drawTopYLabelEntryEnabled = true /// flag that indicates if the axis is inverted or not @objc open var inverted = false /// flag that indicates if the zero-line should be drawn regardless of other grid lines @objc open var drawZeroLineEnabled = false /// Color of the zero line @objc open var zeroLineColor: NSUIColor? = NSUIColor.gray /// Width of the zero line @objc open var zeroLineWidth: CGFloat = 1.0 /// This is how much (in pixels) into the dash pattern are we starting from. @objc open var zeroLineDashPhase = CGFloat(0.0) /// This is the actual dash pattern. /// I.e. [2, 3] will paint [-- -- ] /// [1, 3, 4, 2] will paint [- ---- - ---- ] @objc open var zeroLineDashLengths: [CGFloat]? /// axis space from the largest value to the top in percent of the total axis range @objc open var spaceTop = CGFloat(0.1) /// axis space from the smallest value to the bottom in percent of the total axis range @objc open var spaceBottom = CGFloat(0.1) /// the position of the y-labels relative to the chart @objc open var labelPosition = LabelPosition.outsideChart /// the alignment of the text in the y-label @objc open var labelAlignment: TextAlignment = .left /// the horizontal offset of the y-label @objc open var labelXOffset: CGFloat = 0.0 /// the side this axis object represents private var _axisDependency = AxisDependency.left /// the minimum width that the axis should take /// /// **default**: 0.0 @objc open var minWidth = CGFloat(0) /// the maximum width that the axis can take. /// use Infinity for disabling the maximum. /// /// **default**: CGFloat.infinity @objc open var maxWidth = CGFloat(CGFloat.infinity) public override init() { super.init() self.yOffset = 0.0 } @objc public init(position: AxisDependency) { super.init() _axisDependency = position self.yOffset = 0.0 } @objc open var axisDependency: AxisDependency { return _axisDependency } @objc open func requiredSize() -> CGSize { let label = getLongestLabel() as NSString var size = label.size(withAttributes: [.font: labelFont]) size.width += xOffset * 2.0 size.height += yOffset * 2.0 size.width = max(minWidth, min(size.width, maxWidth > 0.0 ? maxWidth : size.width)) return size } @objc open func getRequiredHeightSpace() -> CGFloat { return requiredSize().height } /// `true` if this axis needs horizontal offset, `false` ifno offset is needed. @objc open var needsOffset: Bool { if isEnabled && isDrawLabelsEnabled && labelPosition == .outsideChart { return true } else { return false } } @objc open var isInverted: Bool { return inverted } open override func calculate(min dataMin: Double, max dataMax: Double) { // if custom, use value as is, else use data value var min = _customAxisMin ? _axisMinimum : dataMin var max = _customAxisMax ? _axisMaximum : dataMax // Make sure max is greater than min // Discussion: https://github.com/danielgindi/Charts/pull/3650#discussion_r221409991 if min > max { switch(_customAxisMax, _customAxisMin) { case(true, true): (min, max) = (max, min) case(true, false): min = max < 0 ? max * 1.5 : max * 0.5 case(false, true): max = min < 0 ? min * 0.5 : min * 1.5 case(false, false): break } } // temporary range (before calculations) let range = abs(max - min) // in case all values are equal if range == 0.0 { max = max + 1.0 min = min - 1.0 } // bottom-space only effects non-custom min if !_customAxisMin { let bottomSpace = range * Double(spaceBottom) _axisMinimum = (min - bottomSpace) } // top-space only effects non-custom max if !_customAxisMax { let topSpace = range * Double(spaceTop) _axisMaximum = (max + topSpace) } // calc actual range axisRange = abs(_axisMaximum - _axisMinimum) } @objc open var isDrawBottomYLabelEntryEnabled: Bool { return drawBottomYLabelEntryEnabled } @objc open var isDrawTopYLabelEntryEnabled: Bool { return drawTopYLabelEntryEnabled } }
apache-2.0
3a2f811321ab3c52db621473e96db5e5
28.199029
112
0.596176
4.588101
false
false
false
false
joerocca/GitHawk
Classes/Systems/NSAttributedStringSizing.swift
1
7791
// // NSAttributedStringSizing.swift // Freetime // // Created by Ryan Nystrom on 5/14/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit extension CGSize { func snapped(scale: CGFloat) -> CGSize { var size = self size.width = ceil(size.width * scale) / scale size.height = ceil(size.height * scale) / scale return size } func resized(inset: UIEdgeInsets) -> CGSize { var size = self size.width += inset.left + inset.right size.height += inset.top + inset.bottom return size } } final class NSAttributedStringSizing: NSObject, ListDiffable { private let textContainer: NSTextContainer private let textStorage: NSTextStorage private let layoutManager: NSLayoutManager let inset: UIEdgeInsets let attributedText: NSAttributedString let screenScale: CGFloat let backgroundColor: UIColor init( containerWidth: CGFloat, attributedText: NSAttributedString, inset: UIEdgeInsets = .zero, backgroundColor: UIColor = .white, exclusionPaths: [UIBezierPath] = [], maximumNumberOfLines: Int = 0, lineFragmentPadding: CGFloat = 0.0, allowsNonContiguousLayout: Bool = false, hyphenationFactor: CGFloat = 0.0, showsInvisibleCharacters: Bool = false, showsControlCharacters: Bool = false, usesFontLeading: Bool = true, screenScale: CGFloat = UIScreen.main.scale ) { self.attributedText = attributedText self.inset = inset self.screenScale = screenScale self.backgroundColor = backgroundColor textContainer = NSTextContainer() textContainer.exclusionPaths = exclusionPaths textContainer.maximumNumberOfLines = maximumNumberOfLines textContainer.lineFragmentPadding = lineFragmentPadding layoutManager = LabelLayoutManager() layoutManager.allowsNonContiguousLayout = allowsNonContiguousLayout layoutManager.hyphenationFactor = hyphenationFactor layoutManager.showsInvisibleCharacters = showsInvisibleCharacters layoutManager.showsControlCharacters = showsControlCharacters layoutManager.usesFontLeading = usesFontLeading layoutManager.addTextContainer(textContainer) // storage implicitly required to use NSLayoutManager + NSTextContainer and find a size textStorage = NSTextStorage(attributedString: attributedText) textStorage.addLayoutManager(layoutManager) super.init() NotificationCenter.default.addObserver( self, selector: #selector(NSAttributedStringSizing.onMemoryWarning), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil ) computeSize(containerWidth) } // MARK: Public API private var _textSize = [CGFloat: CGSize]() func textSize(_ width: CGFloat) -> CGSize { if let cache = _textSize[width] { return cache } return computeSize(width) } func textViewSize(_ width: CGFloat) -> CGSize { return textSize(width).resized(inset: inset) } func rect(_ width: CGFloat) -> CGRect { let size = textSize(width) return CGRect( x: inset.left, y: inset.top, width: size.width - inset.left - inset.right, height: size.height - inset.top - inset.bottom ) } func configure(textView: UITextView) { textView.attributedText = attributedText textView.contentInset = .zero textView.textContainerInset = inset let textContainer = textView.textContainer textContainer.exclusionPaths = self.textContainer.exclusionPaths textContainer.maximumNumberOfLines = self.textContainer.maximumNumberOfLines textContainer.lineFragmentPadding = self.textContainer.lineFragmentPadding let layoutManager = textView.layoutManager layoutManager.allowsNonContiguousLayout = self.layoutManager.allowsNonContiguousLayout layoutManager.hyphenationFactor = self.layoutManager.hyphenationFactor layoutManager.showsInvisibleCharacters = self.layoutManager.showsInvisibleCharacters layoutManager.showsControlCharacters = self.layoutManager.showsControlCharacters layoutManager.usesFontLeading = self.layoutManager.usesFontLeading layoutManager.addTextContainer(textContainer) } private var _contents = [String: CGImage]() func contents(_ width: CGFloat) -> CGImage? { let key = "\(width)" if let contents = _contents[key] { return contents } let size = textSize(width) textContainer.size = size UIGraphicsBeginImageContextWithOptions(size, true, screenScale) backgroundColor.setFill() UIBezierPath(rect: CGRect(origin: .zero, size: size)).fill() let glyphRange = layoutManager.glyphRange(for: textContainer) layoutManager.drawBackground(forGlyphRange: glyphRange, at: .zero) layoutManager.drawGlyphs(forGlyphRange: glyphRange, at: .zero) let contents = UIGraphicsGetImageFromCurrentImageContext()?.cgImage UIGraphicsEndImageContext() // keep only one bitmap at a time _contents.removeAll() _contents[key] = contents return contents } func attributes(point: CGPoint) -> [NSAttributedStringKey: Any]? { var fractionDistance: CGFloat = 1.0 let index = layoutManager.characterIndex(for: point, in: textContainer, fractionOfDistanceBetweenInsertionPoints: &fractionDistance) if index != NSNotFound, fractionDistance < 1.0 { return attributedText.attributes(at: index, effectiveRange: nil) } return nil } // MARK: Private API @discardableResult func computeSize(_ width: CGFloat) -> CGSize { let insetWidth = max(width - inset.left - inset.right, 0) textContainer.size = CGSize(width: insetWidth, height: 0) // find the size of the text now that everything is configured let bounds = layoutManager.usedRect(for: textContainer) // snap to pixel let size = bounds.size.snapped(scale: screenScale) _textSize[width] = size return size } @objc func onMemoryWarning() { _contents.removeAll() } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return attributedText } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { return true } } final class LabelLayoutManager: NSLayoutManager { override func fillBackgroundRectArray(_ rectArray: UnsafePointer<CGRect>, count rectCount: Int, forCharacterRange charRange: NSRange, color: UIColor) { // Get the attributes for the backgroundColor attribute var range = charRange let attributes = textStorage?.attributes(at: charRange.location, effectiveRange: &range) // Ensure that this is one of our labels we're dealing with, ignore basic backgroundColor attributes guard attributes?[MarkdownAttribute.label] != nil else { super.fillBackgroundRectArray(rectArray, count: rectCount, forCharacterRange: charRange, color: color) return } let rawRect = rectArray[0] let rect = CGRect( x: floor(rawRect.origin.x), y: floor(rawRect.origin.y), width: floor(rawRect.size.width), height: floor(rawRect.size.height) ).insetBy(dx: -3, dy: 0) UIBezierPath(roundedRect: rect, cornerRadius: Styles.Sizes.labelCornerRadius).fill() } }
mit
2be4b8bad8735b092b58d3e783e1a22d
33.622222
155
0.671502
5.350275
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift
5
16120
// // ChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation /// Determines how to round DataSet index values for `ChartDataSet.entryIndex(x, rounding)` when an exact x-value is not found. @objc public enum ChartDataSetRounding: Int { case up = 0 case down = 1 case closest = 2 } /// The DataSet class represents one group or type of entries (Entry) in the Chart that belong together. /// It is designed to logically separate different groups of values inside the Chart (e.g. the values for a specific line in the LineChart, or the values of a specific group of bars in the BarChart). open class ChartDataSet: ChartBaseDataSet { public required init() { super.init() _values = [ChartDataEntry]() } public override init(label: String?) { super.init(label: label) _values = [ChartDataEntry]() } @objc public init(values: [ChartDataEntry]?, label: String?) { super.init(label: label) _values = values == nil ? [ChartDataEntry]() : values self.calcMinMax() } @objc public convenience init(values: [ChartDataEntry]?) { self.init(values: values, label: "DataSet") } // MARK: - Data functions and accessors /// the entries that this dataset represents / holds together @objc internal var _values: [ChartDataEntry]! /// maximum y-value in the value array @objc internal var _yMax: Double = -Double.greatestFiniteMagnitude /// minimum y-value in the value array @objc internal var _yMin: Double = Double.greatestFiniteMagnitude /// maximum x-value in the value array @objc internal var _xMax: Double = -Double.greatestFiniteMagnitude /// minimum x-value in the value array @objc internal var _xMin: Double = Double.greatestFiniteMagnitude /// * /// - note: Calls `notifyDataSetChanged()` after setting a new value. /// - returns: The array of y-values that this DataSet represents. @objc open var values: [ChartDataEntry] { get { return _values } set { _values = newValue notifyDataSetChanged() } } /// Use this method to tell the data set that the underlying data has changed open override func notifyDataSetChanged() { calcMinMax() } open override func calcMinMax() { if _values.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude _xMax = -Double.greatestFiniteMagnitude _xMin = Double.greatestFiniteMagnitude for e in _values { calcMinMax(entry: e) } } open override func calcMinMaxY(fromX: Double, toX: Double) { if _values.count == 0 { return } _yMax = -Double.greatestFiniteMagnitude _yMin = Double.greatestFiniteMagnitude let indexFrom = entryIndex(x: fromX, closestToY: Double.nan, rounding: .down) let indexTo = entryIndex(x: toX, closestToY: Double.nan, rounding: .up) if indexTo < indexFrom { return } for i in indexFrom...indexTo { // only recalculate y calcMinMaxY(entry: _values[i]) } } @objc open func calcMinMaxX(entry e: ChartDataEntry) { if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } @objc open func calcMinMaxY(entry e: ChartDataEntry) { if e.y < _yMin { _yMin = e.y } if e.y > _yMax { _yMax = e.y } } /// Updates the min and max x and y value of this DataSet based on the given Entry. /// /// - parameter e: @objc internal func calcMinMax(entry e: ChartDataEntry) { calcMinMaxX(entry: e) calcMinMaxY(entry: e) } /// - returns: The minimum y-value this DataSet holds open override var yMin: Double { return _yMin } /// - returns: The maximum y-value this DataSet holds open override var yMax: Double { return _yMax } /// - returns: The minimum x-value this DataSet holds open override var xMin: Double { return _xMin } /// - returns: The maximum x-value this DataSet holds open override var xMax: Double { return _xMax } /// - returns: The number of y-values this DataSet represents open override var entryCount: Int { return _values?.count ?? 0 } /// - returns: The entry object found at the given index (not x-value!) /// - throws: out of bounds /// if `i` is out of bounds, it may throw an out-of-bounds exception open override func entryForIndex(_ i: Int) -> ChartDataEntry? { guard i >= 0 && i < _values.count else { return nil } return _values[i] } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value according to the rounding. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: determine whether to round up/down/closest if there is no Entry matching the provided x-value open override func entryForXValue( _ xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> ChartDataEntry? { let index = self.entryIndex(x: xValue, closestToY: yValue, rounding: rounding) if index > -1 { return _values[index] } return nil } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, open override func entryForXValue( _ xValue: Double, closestToY yValue: Double) -> ChartDataEntry? { return entryForXValue(xValue, closestToY: yValue, rounding: .closest) } /// - returns: All Entry objects found at the given xIndex with binary search. /// An empty array if no Entry object at that index. open override func entriesForXValue(_ xValue: Double) -> [ChartDataEntry] { var entries = [ChartDataEntry]() var low = 0 var high = _values.count - 1 while low <= high { var m = (high + low) / 2 var entry = _values[m] // if we have a match if xValue == entry.x { while m > 0 && _values[m - 1].x == xValue { m -= 1 } high = _values.count // loop over all "equal" entries while m < high { entry = _values[m] if entry.x == xValue { entries.append(entry) } else { break } m += 1 } break } else { if xValue > entry.x { low = m + 1 } else { high = m - 1 } } } return entries } /// - returns: The array-index of the specified entry. /// If the no Entry at the specified x-value is found, this method returns the index of the Entry at the closest x-value according to the rounding. /// /// - parameter xValue: x-value of the entry to search for /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: Rounding method if exact value was not found open override func entryIndex( x xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> Int { var low = 0 var high = _values.count - 1 var closest = high while low < high { let m = (low + high) / 2 let d1 = _values[m].x - xValue let d2 = _values[m + 1].x - xValue let ad1 = abs(d1), ad2 = abs(d2) if ad2 < ad1 { // [m + 1] is closer to xValue // Search in an higher place low = m + 1 } else if ad1 < ad2 { // [m] is closer to xValue // Search in a lower place high = m } else { // We have multiple sequential x-value with same distance if d1 >= 0.0 { // Search in a lower place high = m } else if d1 < 0.0 { // Search in an higher place low = m + 1 } } closest = high } if closest != -1 { let closestXValue = _values[closest].x if rounding == .up { // If rounding up, and found x-value is lower than specified x, and we can go upper... if closestXValue < xValue && closest < _values.count - 1 { closest += 1 } } else if rounding == .down { // If rounding down, and found x-value is upper than specified x, and we can go lower... if closestXValue > xValue && closest > 0 { closest -= 1 } } // Search by closest to y-value if !yValue.isNaN { while closest > 0 && _values[closest - 1].x == closestXValue { closest -= 1 } var closestYValue = _values[closest].y var closestYIndex = closest while true { closest += 1 if closest >= _values.count { break } let value = _values[closest] if value.x != closestXValue { break } if abs(value.y - yValue) < abs(closestYValue - yValue) { closestYValue = yValue closestYIndex = closest } } closest = closestYIndex } } return closest } /// - returns: The array-index of the specified entry /// /// - parameter e: the entry to search for open override func entryIndex(entry e: ChartDataEntry) -> Int { for i in 0 ..< _values.count { if _values[i] === e { return i } } return -1 } /// Adds an Entry to the DataSet dynamically. /// Entries are added to the end of the list. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter e: the entry to add /// - returns: True open override func addEntry(_ e: ChartDataEntry) -> Bool { if _values == nil { _values = [ChartDataEntry]() } calcMinMax(entry: e) _values.append(e) return true } /// Adds an Entry to the DataSet dynamically. /// Entries are added to their appropriate index respective to it's x-index. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter e: the entry to add /// - returns: True open override func addEntryOrdered(_ e: ChartDataEntry) -> Bool { if _values == nil { _values = [ChartDataEntry]() } calcMinMax(entry: e) if _values.count > 0 && _values.last!.x > e.x { var closestIndex = entryIndex(x: e.x, closestToY: e.y, rounding: .up) while _values[closestIndex].x < e.x { closestIndex += 1 } _values.insert(e, at: closestIndex) } else { _values.append(e) } return true } /// Removes an Entry from the DataSet dynamically. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter entry: the entry to remove /// - returns: `true` if the entry was removed successfully, else if the entry does not exist open override func removeEntry(_ entry: ChartDataEntry) -> Bool { var removed = false for i in 0 ..< _values.count { if _values[i] === entry { _values.remove(at: i) removed = true break } } if removed { calcMinMax() } return removed } /// Removes the first Entry (at index 0) of this DataSet from the entries array. /// /// - returns: `true` if successful, `false` ifnot. open override func removeFirst() -> Bool { let entry: ChartDataEntry? = _values.isEmpty ? nil : _values.removeFirst() let removed = entry != nil if removed { calcMinMax() } return removed } /// Removes the last Entry (at index size-1) of this DataSet from the entries array. /// /// - returns: `true` if successful, `false` ifnot. open override func removeLast() -> Bool { let entry: ChartDataEntry? = _values.isEmpty ? nil : _values.removeLast() let removed = entry != nil if removed { calcMinMax() } return removed } /// Checks if this DataSet contains the specified Entry. /// - returns: `true` if contains the entry, `false` ifnot. open override func contains(_ e: ChartDataEntry) -> Bool { for entry in _values { if (entry.isEqual(e)) { return true } } return false } /// Removes all values from this DataSet and recalculates min and max value. open override func clear() { _values.removeAll(keepingCapacity: true) notifyDataSetChanged() } // MARK: - Data functions and accessors // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! ChartDataSet copy._values = _values copy._yMax = _yMax copy._yMin = _yMin return copy } }
apache-2.0
150a4968faec8489be54f21425c1f360
28.097473
199
0.504591
4.986081
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/FacebookCore/Sources/Core/AppEvents/AppEventsLogger.swift
13
8723
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit.FBSDKAppEvents /** Client-side event logging for specialized application analytics available through Facebook App Insights and for use with Facebook Ads conversion tracking and optimization. The `AppEventsLogger` static class has a few related roles: + Logging predefined and application-defined events to Facebook App Insights with a numeric value to sum across a large number of events, and an optional set of key/value parameters that define "segments" for this event (e.g., 'purchaserStatus' : 'frequent', or 'gamerLevel' : 'intermediate') + Logging events to later be used for ads optimization around lifetime value. + Methods that control the way in which events are flushed out to the Facebook servers. Here are some important characteristics of the logging mechanism provided by `AppEventsLogger`: + Events are not sent immediately when logged. They're cached and flushed out to the Facebook servers in a number of situations: - when an event count threshold is passed (currently 100 logged events). - when a time threshold is passed (currently 15 seconds). - when an app has gone to background and is then brought back to the foreground. + Events will be accumulated when the app is in a disconnected state, and sent when the connection is restored and one of the above 'flush' conditions are met. + The `AppEventsLogger` class is thread-safe in that events may be logged from any of the app's threads. + The developer can set the `flushBehavior` to force the flushing of events to only occur on an explicit call to the `flush` method. + The developer can turn on console debug output for event logging and flushing to the server by using the `FBSDKLoggingBehaviorAppEvents` value in `[FBSettings setLoggingBehavior:]`. Some things to note when logging events: + There is a limit on the number of unique event names an app can use, on the order of 1000. + There is a limit to the number of unique parameter names in the provided parameters that can be used per event, on the order of 25. This is not just for an individual call, but for all invocations for that eventName. + Event names and parameter names (the keys in the Dictionary) must be between 2 and 40 characters, and must consist of alphanumeric characters, _, -, or spaces. + The length of each parameter value can be no more than on the order of 100 characters. */ public class AppEventsLogger { //-------------------------------------- // MARK: - Activate //-------------------------------------- /** Notifies the events system that the app has launched and, when appropriate, logs an "activated app" event. Should typically be placed in the app delegates' `applicationDidBecomeActive()` function. This method also takes care of logging the event indicating the first time this app has been launched, which, among other things, is used to track user acquisition and app install ads conversions. `activate()` will not log an event on every app launch, since launches happen every time the app is backgrounded and then foregrounded. "activated app" events will be logged when the app has not been active for more than 60 seconds. This method also causes a "deactivated app" event to be logged when sessions are "completed", and these events are logged with the session length, with an indication of how much time has elapsed between sessions, and with the number of background/foreground interruptions that session had. This data is all visible in your app's App Events Insights. - parameter application: Optional instance of UIApplication. Default: `UIApplication.sharedApplication()`. */ public static func activate(_ application: UIApplication = UIApplication.shared) { FBSDKAppEvents.activateApp() } //-------------------------------------- // MARK: - Log Events //-------------------------------------- /** Log an app event. - parameter event: The application event to log. - parameter accessToken: Optional access token to use to log the event. Default: `AccessToken.current`. */ public static func log(_ event: AppEventLoggable, accessToken: AccessToken? = AccessToken.current) { let valueToSum = event.valueToSum.map({ NSNumber(value: $0 as Double) }) let parameters = event.parameters.keyValueMap { ($0.0.rawValue as NSString, $0.1.appEventParameterValue) } FBSDKAppEvents.logEvent(event.name.rawValue, valueToSum: valueToSum, parameters: parameters, accessToken: accessToken?.sdkAccessTokenRepresentation) } /** Log an app event. This overload is required, so dot-syntax works in this example: ``` AppEventsLogger().log(.Searched()) ``` - parameter event: The application event to log. - parameter accessToken: Optional access token to use to log the event. Default: `AccessToken.current`. */ public static func log(_ event: AppEvent, accessToken: AccessToken? = AccessToken.current) { log(event as AppEventLoggable, accessToken: accessToken) } /** Log an app event. - parameter eventName: The name of the event to record. - parameter parameters: Arbitrary parameter dictionary of characteristics. - parameter valueToSum: Amount to be aggregated into all events of this eventName, and App Insights will report the cumulative and average value of this amount. - parameter accessToken: The optional access token to log the event as. Default: `AccessToken.current`. */ public static func log(_ eventName: String, parameters: AppEvent.ParametersDictionary = [:], valueToSum: Double? = nil, accessToken: AccessToken? = AccessToken.current) { let event = AppEvent(name: AppEventName(eventName), parameters: parameters, valueToSum: valueToSum) log(event, accessToken: accessToken) } //-------------------------------------- // MARK: - Flush //-------------------------------------- /** The current event flushing behavior specifying when events are sent to Facebook. */ public static var flushBehavior: FlushBehavior { get { return FlushBehavior(sdkFlushBehavior: FBSDKAppEvents.flushBehavior()) } set { FBSDKAppEvents.setFlushBehavior(newValue.sdkFlushBehavior) } } /** Explicitly kick off flushing of events to Facebook. This is an asynchronous method, but it does initiate an immediate kick off. Server failures will be reported through the NotificationCenter with notification ID `FBSDKAppEventsLoggingResultNotification`. */ public static func flush() { FBSDKAppEvents.flush() } //-------------------------------------- // MARK: - Override App Id //-------------------------------------- /** Facebook application id that is going to be used for logging all app events. In some cases, you might want to use one Facebook App ID for login and social presence and another for App Event logging. (An example is if multiple apps from the same company share an app ID for login, but want distinct logging.) By default, this value defers to the `FBSDKAppEventsOverrideAppIDBundleKey` plist value. If that's not set, it defaults to `FBSDKSettings.appId`. */ public static var loggingAppId: String? { get { if let appId = FBSDKAppEvents.loggingOverrideAppID() { return appId } return FBSDKSettings.appID() } set { return FBSDKAppEvents.setLoggingOverrideAppID(newValue) } } }
mit
de8b26e137b4e489d2e59a66cb8dc2a6
44.670157
139
0.706982
4.89781
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Fluent/Model.swift
1
931
public protocol Model: DatabaseModel, JSONRepresentable, StringInitializable { } extension Model { public init?(from string: String) throws { if let model = try Self.find(string) { self = model } else { return nil } } public func makeJSON() -> JSON { var json: [String: JSON] = [:] for (key, value) in serialize() { let jsonValue: JSON if let value = value { switch value.structuredData { case .int(let int): jsonValue = .number(JSON.Number.integer(int)) case .string(let string): jsonValue = .string(string) default: jsonValue = .null } } else { jsonValue = .null } json[key] = jsonValue } return JSON(json) } }
mit
3a8f67cb7e6cef1c8aa29656d96d6dbe
24.861111
80
0.46724
5.032432
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/WallpaperPatternPreviewView.swift
1
4928
// // WallpaperPatternPreview.swift // Telegram // // Created by Mikhail Filimonov on 29/01/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import ThemeSettings import Postbox import SwiftSignalKit class WallpaperPatternView : Control { private var backgroundView: BackgroundView? let imageView = TransformImageView() let checkbox: ImageView = ImageView() private let emptyTextView = TextView() fileprivate(set) var pattern: Wallpaper? required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(imageView) addSubview(checkbox) checkbox.image = theme.icons.chatGroupToggleSelected checkbox.sizeToFit() self.layer?.cornerRadius = .cornerRadius emptyTextView.userInteractionEnabled = false emptyTextView.isSelectable = false } override func layout() { super.layout() imageView.frame = bounds emptyTextView.center() checkbox.setFrameOrigin(NSMakePoint(frame.width - checkbox.frame.width - 5, 5)) backgroundView?.frame = bounds } func update(with pattern: Wallpaper?, isSelected: Bool, account: Account, colors: [NSColor], rotation: Int32?) { checkbox.isHidden = !isSelected self.pattern = pattern let layout = TextViewLayout(.initialize(string: strings().chatWPPatternNone, color: colors.first!.brightnessAdjustedColor, font: .normal(.title))) layout.measure(width: 80) emptyTextView.update(layout) if let pattern = pattern { self.backgroundView?.removeFromSuperview() self.backgroundView = nil emptyTextView.isHidden = true imageView.isHidden = false let emptyColor: TransformImageEmptyColor if colors.count > 1 { let colors = colors.map { return $0.withAlphaComponent($0.alpha == 0 ? 0.5 : $0.alpha) } emptyColor = .gradient(colors: colors, intensity: colors.first!.alpha, rotation: nil) } else if let color = colors.first { emptyColor = .color(color) } else { emptyColor = .color(NSColor(rgb: 0xd6e2ee, alpha: 0.5)) } let arguments = TransformImageArguments(corners: ImageCorners(radius: .cornerRadius), imageSize: pattern.dimensions.aspectFilled(NSMakeSize(300, 300)), boundingSize: bounds.size, intrinsicInsets: NSEdgeInsets(), emptyColor: emptyColor) imageView.set(arguments: arguments) switch pattern { case let .file(_, file, _, _): var representations:[TelegramMediaImageRepresentation] = [] if let dimensions = file.dimensions { representations.append(TelegramMediaImageRepresentation(dimensions: dimensions, resource: file.resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false)) } else { representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(width: 300, height: 300), resource: file.resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false)) } let updateImageSignal = chatWallpaper(account: account, representations: representations, file: file, mode: .thumbnail, isPattern: true, autoFetchFullSize: true, scale: backingScaleFactor, isBlurred: false, synchronousLoad: false, drawPatternOnly: false) imageView.setSignal(signal: cachedMedia(media: file, arguments: arguments, scale: backingScaleFactor), clearInstantly: false) if !imageView.isFullyLoaded { imageView.setSignal(updateImageSignal, animate: true, cacheImage: { result in cacheMedia(result, media: file, arguments: arguments, scale: System.backingScale) }) } default: break } } else { emptyTextView.isHidden = false imageView.isHidden = true if self.backgroundView == nil { let bg = BackgroundView(frame: bounds) self.backgroundView = bg addSubview(bg, positioned: .above, relativeTo: imageView) } if colors.count > 1 { backgroundView?.backgroundMode = .gradient(colors: colors, rotation: rotation) } else { backgroundView?.backgroundMode = .color(color: colors[0]) } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
451d1226048277346cc808fdc6f563e8
40.403361
270
0.604831
5.338028
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/WallpaperColorPicker.swift
1
16684
// // WallpaperColorPicker.swift // Telegram // // Created by Mikhail Filimonov on 29/01/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TGUIKit private let shadowImage: CGImage = { return generateImage(CGSize(width: 45.0, height: 45.0), opaque: false, scale: System.backingScale, rotatedContext: { size, context in context.setBlendMode(.clear) context.setFillColor(NSColor.clear.cgColor) context.fill(CGRect(origin: CGPoint(), size: size)) context.setBlendMode(.normal) context.setShadow(offset: CGSize(width: 0.0, height: 1.5), blur: 4.5, color: NSColor(rgb: 0x000000, alpha: 0.5).cgColor) context.setFillColor(NSColor(rgb: 0x000000, alpha: 0.5).cgColor) context.fillEllipse(in: CGRect(origin: CGPoint(), size: size).insetBy(dx: 3.0 + .borderSize, dy: 3.0 + .borderSize)) })! }() private let smallShadowImage: CGImage = { return generateImage(CGSize(width: 24.0, height: 24.0), opaque: false, scale: System.backingScale, rotatedContext: { size, context in context.setBlendMode(.clear) context.setFillColor(NSColor.clear.cgColor) context.fill(CGRect(origin: CGPoint(), size: size)) context.setBlendMode(.normal) context.setShadow(offset: CGSize(width: 0.0, height: 1.5), blur: 4.5, color: NSColor(rgb: 0x000000, alpha: 0.65).cgColor) context.setFillColor(NSColor(rgb: 0x000000, alpha: 0.5).cgColor) context.fillEllipse(in: CGRect(origin: CGPoint(), size: size).insetBy(dx: 3.0 + .borderSize, dy: 3.0 + .borderSize)) })! }() private let pointerImage: CGImage = { return generateImage(CGSize(width: 12.0, height: 42.0), opaque: false, scale: System.backingScale, rotatedContext: { size, context in context.setBlendMode(.clear) context.setFillColor(NSColor.clear.cgColor) context.fill(CGRect(origin: CGPoint(), size: size)) context.setBlendMode(.normal) let lineWidth: CGFloat = 1.0 context.setFillColor(NSColor.black.cgColor) context.setStrokeColor(NSColor.white.cgColor) context.setLineWidth(lineWidth) context.setLineCap(.round) let pointerHeight: CGFloat = 6.0 context.move(to: CGPoint(x: lineWidth / 2.0, y: lineWidth / 2.0)) context.addLine(to: CGPoint(x: size.width - lineWidth / 2.0, y: lineWidth / 2.0)) context.addLine(to: CGPoint(x: size.width / 2.0, y: lineWidth / 2.0 + pointerHeight)) context.closePath() context.drawPath(using: .fillStroke) context.move(to: CGPoint(x: lineWidth / 2.0, y: size.height - lineWidth / 2.0)) context.addLine(to: CGPoint(x: size.width / 2.0, y: size.height - lineWidth / 2.0 - pointerHeight)) context.addLine(to: CGPoint(x: size.width - lineWidth / 2.0, y: size.height - lineWidth / 2.0)) context.closePath() context.drawPath(using: .fillStroke) })! }() private final class HSVParameter: NSObject { let hue: CGFloat let saturation: CGFloat let value: CGFloat init(hue: CGFloat, saturation: CGFloat, value: CGFloat) { self.hue = hue self.saturation = saturation self.value = value super.init() } } private final class IntensitySliderParameter: NSObject { let bordered: Bool let min: HSVParameter let max: HSVParameter init(bordered: Bool, min: HSVParameter, max: HSVParameter) { self.bordered = bordered self.min = min self.max = max super.init() } } private final class WallpaperColorHueSaturationView: View { var parameters: HSVParameter = HSVParameter(hue: 1.0, saturation: 1.0, value: 1.0) { didSet { self.setNeedsDisplay() } } var value: CGFloat = 1.0 { didSet { parameters = HSVParameter(hue: 1.0, saturation: 1.0, value: self.value) } } override init() { super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override func draw(_ layer: CALayer, in context: CGContext) { let colorSpace = deviceColorSpace let colors = [NSColor(rgb: 0xff0000).cgColor, NSColor(rgb: 0xffff00).cgColor, NSColor(rgb: 0x00ff00).cgColor, NSColor(rgb: 0x00ffff).cgColor, NSColor(rgb: 0x0000ff).cgColor, NSColor(rgb: 0xff00ff).cgColor, NSColor(rgb: 0xff0000).cgColor] var locations: [CGFloat] = [0.0, 0.16667, 0.33333, 0.5, 0.66667, 0.83334, 1.0] let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: &locations)! context.drawLinearGradient(gradient, start: CGPoint(), end: CGPoint(x: bounds.width, y: 0.0), options: CGGradientDrawingOptions()) let overlayColors = [NSColor(rgb: 0xffffff, alpha: 0.0).cgColor, NSColor(rgb: 0xffffff).cgColor] var overlayLocations: [CGFloat] = [0.0, 1.0] let overlayGradient = CGGradient(colorsSpace: colorSpace, colors: overlayColors as CFArray, locations: &overlayLocations)! context.drawLinearGradient(overlayGradient, start: CGPoint(), end: CGPoint(x: 0.0, y: bounds.height), options: CGGradientDrawingOptions()) context.setFillColor(NSColor(rgb: 0x000000, alpha: 1.0 - parameters.value).cgColor) context.fill(bounds) } } private final class WallpaperColorBrightnessView: View { var hsv: (CGFloat, CGFloat, CGFloat) = (0.0, 1.0, 1.0) { didSet { self.setNeedsDisplay() } } override init() { super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } var parameters:HSVParameter { return HSVParameter(hue: self.hsv.0, saturation: self.hsv.1, value: self.hsv.2) } override func draw(_ layer: CALayer, in context: CGContext) { let colorSpace = deviceColorSpace context.setFillColor(NSColor(white: parameters.value, alpha: 1.0).cgColor) context.fill(bounds) let path = NSBezierPath(roundedRect: bounds, xRadius: bounds.height / 2.0, yRadius: bounds.height / 2.0) context.addPath(path.cgPath) context.setFillColor(NSColor.white.cgColor) context.fillPath() let innerPath = NSBezierPath(roundedRect: bounds.insetBy(dx: 1.0, dy: 1.0), xRadius: bounds.height / 2.0, yRadius: bounds.height / 2.0) context.addPath(innerPath.cgPath) context.clip() let color = NSColor(hue: parameters.hue, saturation: parameters.saturation, brightness: 1.0, alpha: 1.0) let colors = [color.cgColor, NSColor.black.cgColor] var locations: [CGFloat] = [0.0, 1.0] let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: &locations)! context.drawLinearGradient(gradient, start: CGPoint(), end: CGPoint(x: bounds.width, y: 0.0), options: CGGradientDrawingOptions()) } } private final class WallpaperColorKnobView: View { var hsv: (CGFloat, CGFloat, CGFloat) = (0.0, 0.0, 1.0) { didSet { if self.hsv != oldValue { self.setNeedsDisplay() } } } var parameters: HSVParameter { return HSVParameter(hue: self.hsv.0, saturation: self.hsv.1, value: self.hsv.2) } override init() { super.init() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override func draw(_ layer: CALayer, in context: CGContext) { // if !isRasterizing { context.setBlendMode(.copy) context.setFillColor(NSColor.clear.cgColor) context.fill(bounds) // } let image = bounds.width > 30.0 ? shadowImage : smallShadowImage context.draw(image, in: bounds) context.setBlendMode(.normal) context.setFillColor(NSColor.white.cgColor) context.fillEllipse(in: bounds.insetBy(dx: 3.0, dy: 3.0)) let color = NSColor(hue: parameters.hue, saturation: parameters.saturation, brightness: parameters.value, alpha: 1.0) context.setFillColor(color.cgColor) let borderWidth: CGFloat = bounds.width > 30.0 ? 5.0 : 5.0 context.fillEllipse(in: bounds.insetBy(dx: borderWidth - .borderSize, dy: borderWidth - .borderSize)) } } private enum PickerChangeValue { case color case brightness } final class WallpaperColorPickerView: View { private let brightnessView: WallpaperColorBrightnessView private let brightnessKnobView: ImageView private let colorView: WallpaperColorHueSaturationView private let colorKnobView: WallpaperColorKnobView private var pickerValue: PickerChangeValue? var colorHSV: (CGFloat, CGFloat, CGFloat) = (0.0, 1.0, 1.0) var color: NSColor { get { return NSColor(hue: self.colorHSV.0, saturation: self.colorHSV.1, brightness: self.colorHSV.2, alpha: 1.0) } set { var hue: CGFloat = 0.0 var saturation: CGFloat = 0.0 var value: CGFloat = 0.0 newValue.getHue(&hue, saturation: &saturation, brightness: &value, alpha: nil) let newHSV: (CGFloat, CGFloat, CGFloat) = (hue, saturation, value) if newHSV != self.colorHSV { self.colorHSV = newHSV self.update() } } } var colorChanged: ((NSColor) -> Void)? var colorChangeEnded: ((NSColor) -> Void)? var adjustingPattern: Bool = false { didSet { let value = self.adjustingPattern self.brightnessView.isHidden = value self.brightnessKnobView.isHidden = value self.needsLayout = true } } override init() { self.brightnessView = WallpaperColorBrightnessView() //self.brightnessView.hitTestSlop = NSEdgeInsetsMake(-16.0, -16.0, -16.0, -16.0) self.brightnessKnobView = ImageView() self.brightnessKnobView.image = pointerImage self.colorView = WallpaperColorHueSaturationView() // self.colorView.hitTestSlop = NSEdgeInsetsMake(-16.0, -16.0, -16.0, -16.0) self.colorKnobView = WallpaperColorKnobView() super.init() self.backgroundColor = .white self.addSubview(self.brightnessView) self.addSubview(self.colorView) self.addSubview(self.colorKnobView) self.addSubview(self.brightnessKnobView) let valueChanged: (CGFloat, Bool) -> Void = { [weak self] value, ended in if let strongSelf = self { let previousColor = strongSelf.color strongSelf.colorHSV.2 = 1.0 - value if strongSelf.color != previousColor || ended { strongSelf.update() if ended { strongSelf.colorChangeEnded?(strongSelf.color) } else { strongSelf.colorChanged?(strongSelf.color) } } } } self.update() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } private func update() { if self.adjustingPattern { self.backgroundColor = .white } else { self.backgroundColor = NSColor(white: self.colorHSV.2, alpha: 1.0) } self.colorView.value = self.colorHSV.2 self.brightnessView.hsv = self.colorHSV self.colorKnobView.hsv = self.colorHSV needsLayout = true } func updateKnobLayout(size: CGSize, panningColor: Bool) { let knobSize = CGSize(width: 45.0, height: 45.0) let colorHeight = size.height - 40 var colorKnobFrame = CGRect(x: -knobSize.width / 2.0 + size.width * self.colorHSV.0, y: -knobSize.height / 2.0 + (colorHeight * (1.0 - self.colorHSV.1)), width: knobSize.width, height: knobSize.height) var origin = colorKnobFrame.origin if !panningColor { origin = CGPoint(x: max(0.0, min(origin.x, size.width - knobSize.width)), y: max(0.0, min(origin.y, colorHeight - knobSize.height))) } else { origin = origin.offsetBy(dx: 0.0, dy: -32.0) } colorKnobFrame.origin = origin self.colorKnobView.frame = colorKnobFrame let inset: CGFloat = 42.0 let brightnessKnobSize = CGSize(width: 12.0, height: 42.0) let brightnessKnobFrame = CGRect(x: inset - brightnessKnobSize.width / 2.0 + (size.width - inset * 2.0) * (1.0 - self.colorHSV.2), y: size.height - 46.0, width: brightnessKnobSize.width, height: brightnessKnobSize.height) self.brightnessKnobView.frame = brightnessKnobFrame } override func layout() { super.layout() let size = frame.size let colorHeight = size.height - 40.0 colorView.frame = CGRect(x: 0.0, y: 0.0, width: size.width, height: colorHeight) let inset: CGFloat = 42.0 brightnessView.frame = CGRect(x: inset, y: size.height - 40, width: size.width - (inset * 2.0), height: 29.0) let slidersInset: CGFloat = 24.0 self.updateKnobLayout(size: size, panningColor: false) } override func mouseDown(with event: NSEvent) { if brightnessView.mouseInside() || brightnessKnobView._mouseInside() { pickerValue = .brightness } else { pickerValue = .color } guard let pickerValue = pickerValue else { return } let size = frame.size let colorHeight = size.height - 40.0 switch pickerValue { case .color: let location = self.convert(event.locationInWindow, from: nil) let newHue = max(0.0, min(1.0, location.x / size.width)) let newSaturation = max(0.0, min(1.0, (1.0 - location.y / colorHeight))) self.colorHSV.0 = newHue self.colorHSV.1 = newSaturation case .brightness: let location = brightnessView.convert(event.locationInWindow, from: nil) let brightnessWidth: CGFloat = brightnessView.frame.width let newValue = max(0.0, min(1.0, 1.0 - location.x / brightnessWidth)) self.colorHSV.2 = newValue } self.updateKnobLayout(size: size, panningColor: false) self.update() self.colorChanged?(self.color) } override func mouseDragged(with event: NSEvent) { let previousColor = self.color let size = frame.size let colorHeight = size.height - 40.0 guard let pickerValue = pickerValue else { return } switch pickerValue { case .color: var location = self.convert(event.locationInWindow, from: nil) location.x = min(max(location.x, 1.0), frame.width) let newHue = max(0.0, min(1.0, location.x / size.width)) let newSaturation = max(0.0, min(1.0, (1.0 - location.y / colorHeight))) self.colorHSV.0 = newHue self.colorHSV.1 = newSaturation case .brightness: let location = brightnessView.convert(event.locationInWindow, from: nil) let brightnessWidth: CGFloat = brightnessView.frame.width let newValue = max(0.0, min(1.0, 1.0 - location.x / brightnessWidth)) self.colorHSV.2 = newValue } self.updateKnobLayout(size: size, panningColor: false) if self.color != previousColor { self.update() self.colorChanged?(self.color) } } override func mouseUp(with event: NSEvent) { self.updateKnobLayout(size: frame.size, panningColor: false) self.colorChanged?(self.color) self.colorChangeEnded?(self.color) pickerValue = nil } }
gpl-2.0
20e70d4527fb19224b26436989cef899
36.155902
245
0.610801
4.093988
false
false
false
false
wwq0327/iOS8Example
TextViewKeyboardDemo/TextViewKeyboardDemo/ViewController.swift
1
3035
// // ViewController.swift // TextViewKeyboardDemo // // Created by wyatt on 15/5/1. // Copyright (c) 2015年 Wanqing Wang. All rights reserved. // import UIKit class ViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! var originalTextViewFrame: CGRect! override func viewDidLoad() { super.viewDidLoad() textView.becomeFirstResponder() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // 获到textView的原始大小 originalTextViewFrame = textView.frame // 注册消息 let defaultCenter = NSNotificationCenter.defaultCenter() // 打开键盘 defaultCenter.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) // 关闭键盘 defaultCenter.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { moveTextviewForKeyboard(notification, up: true) } func keyboardWillHide(notification: NSNotification) { moveTextviewForKeyboard(notification, up: false) } func moveTextviewForKeyboard(notification: NSNotification, up: Bool) { let userInfo = notification.userInfo if let info = userInfo { var animationDuration = (info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue var keyboardEndRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let window = UIApplication.sharedApplication().keyWindow keyboardEndRect = view.convertRect(keyboardEndRect, fromView: window) if up { UIView.animateWithDuration(animationDuration, animations: { var keyboardTop = keyboardEndRect.origin.y var newTextViewFrame = self.textView.frame newTextViewFrame.size.height = keyboardTop - self.textView.frame.origin.y - 20.0 self.textView.frame = newTextViewFrame }) } else { UIView.animateWithDuration(animationDuration, animations: { self.textView.frame = self.originalTextViewFrame }) } UIView.commitAnimations() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textViewShouldBeginEditing(textView: UITextView) -> Bool { textView.resignFirstResponder() return true } }
apache-2.0
1fc20495c7380b2a5fdbd48333b3f01c
30.861702
121
0.621369
5.907298
false
false
false
false
practicalswift/swift
test/SILGen/synthesized_conformance_class.swift
4
4310
// RUN: %target-swift-frontend -emit-silgen %s -swift-version 4 | %FileCheck %s final class Final<T> { var x: T init(x: T) { self.x = x } } // CHECK-LABEL: final class Final<T> { // CHECK: @_hasStorage final var x: T { get set } // CHECK: init(x: T) // CHECK: deinit // CHECK: enum CodingKeys : CodingKey { // CHECK: case x // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Final<T>.CodingKeys, _ b: Final<T>.CodingKeys) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: var stringValue: String { get } // CHECK: init?(stringValue: String) // CHECK: var intValue: Int? { get } // CHECK: init?(intValue: Int) // CHECK: } // CHECK: } class Nonfinal<T> { var x: T init(x: T) { self.x = x } } // CHECK-LABEL: class Nonfinal<T> { // CHECK: @_hasStorage var x: T { get set } // CHECK: init(x: T) // CHECK: deinit // CHECK: enum CodingKeys : CodingKey { // CHECK: case x // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Nonfinal<T>.CodingKeys, _ b: Nonfinal<T>.CodingKeys) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: var stringValue: String { get } // CHECK: init?(stringValue: String) // CHECK: var intValue: Int? { get } // CHECK: init?(intValue: Int) // CHECK: } // CHECK: } // CHECK-LABEL: extension Final : Encodable where T : Encodable { // CHECK: func encode(to encoder: Encoder) throws // CHECK: } // CHECK-LABEL: extension Final : Decodable where T : Decodable { // CHECK: init(from decoder: Decoder) throws // CHECK: } // CHECK-LABEL: extension Nonfinal : Encodable where T : Encodable { // CHECK: func encode(to encoder: Encoder) throws // CHECK: } extension Final: Encodable where T: Encodable {} // CHECK-LABEL: // Final<A>.encode(to:) // CHECK-NEXT: sil hidden [ossa] @$s29synthesized_conformance_class5FinalCAASERzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Encodable> (@in_guaranteed Encoder, @guaranteed Final<T>) -> @error Error { extension Final: Decodable where T: Decodable {} // CHECK-LABEL: // Final<A>.init(from:) // CHECK-NEXT: sil hidden [ossa] @$s29synthesized_conformance_class5FinalCAASeRzlE4fromACyxGs7Decoder_p_tKcfC : $@convention(method) <T where T : Decodable> (@in Decoder, @thick Final<T>.Type) -> (@owned Final<T>, @error Error) { extension Nonfinal: Encodable where T: Encodable {} // CHECK-LABEL: // Nonfinal<A>.encode(to:) // CHECK-NEXT: sil hidden [ossa] @$s29synthesized_conformance_class8NonfinalCAASERzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Encodable> (@in_guaranteed Encoder, @guaranteed Nonfinal<T>) -> @error Error { // Witness tables for Final // CHECK-LABEL: sil_witness_table hidden <T where T : Encodable> Final<T>: Encodable module synthesized_conformance_class { // CHECK-NEXT: method #Encodable.encode!1: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$s29synthesized_conformance_class5FinalCyxGSEAASERzlSE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Final<A> // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable> Final<T>: Decodable module synthesized_conformance_class { // CHECK-NEXT: method #Decodable.init!allocator.1: <Self where Self : Decodable> (Self.Type) -> (Decoder) throws -> Self : @$s29synthesized_conformance_class5FinalCyxGSeAASeRzlSe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance <A> Final<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: } // Witness tables for Nonfinal // CHECK-LABEL: sil_witness_table hidden <T where T : Encodable> Nonfinal<T>: Encodable module synthesized_conformance_class { // CHECK-NEXT: method #Encodable.encode!1: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$s29synthesized_conformance_class8NonfinalCyxGSEAASERzlSE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Nonfinal<A> // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: }
apache-2.0
b32bb331f7c394dc581d0bd567d3d7f2
49.116279
279
0.687471
3.359314
false
false
false
false
jakob-stoeck/speechToText
SpeechToTextAction/Util.swift
1
2786
// // Util.swift // SpeechToText // // Created by Jakob Stoeck on 9/13/17. // Copyright © 2017 Jakob Stoeck. All rights reserved. // import UIKit import MobileCoreServices import Speech import UserNotifications import os.log import Keys class Util { class func post(url: URL, data: Data, completionHandler: @escaping (Data) -> ()) { var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = data request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") let session = URLSession.shared session.dataTask(with: request) {data, response, err in if err != nil { os_log("%@", log: OSLog.default, type: .error, err.debugDescription) } if data != nil { os_log("HTTP response: %@", log: OSLog.default, type: .debug, (String(data: data!, encoding: .utf8)!)) completionHandler(data!) } }.resume() } class func notify(title: String?, body: String, removePending: Bool = false) { let center = UNUserNotificationCenter.current() let options: UNAuthorizationOptions = [.alert] center.requestAuthorization(options: options) { (granted, error) in if !granted { os_log("Something went wrong", log: OSLog.default, type: .error) } } let content = UNMutableNotificationContent() if title != nil { content.title = title! } content.body = body let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false) let identifier = UUID().uuidString let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) if removePending { center.removeAllDeliveredNotifications() center.removeAllPendingNotificationRequests() } center.add(request, withCompletionHandler: { (error) in if error != nil { os_log("Notification went wrong", log: OSLog.default, type: .error) } }) os_log("notification request: \"%@\": \"%@\"", log: OSLog.default, type: .debug, title ?? "", body) } class func errorHandler(_ text: String, title: String = NSLocalizedString("util.error.title", value: "Error", comment: "Title of a generic error message")) { os_log("%@: %@", log: OSLog.default, type: .error, title, text) // notify(title: title, body: text) } class func getCloudSpeechApiKey() -> String? { let keys = SpeechToTextKeys() return keys.googleCloudSpeechApiKey; } }
mit
8da88bd85ba175b45a8ed3c9e84f1d89
37.150685
161
0.606463
4.573071
false
false
false
false
HaliteChallenge/Halite-II
airesources/Swift/Sources/hlt/Game.swift
1
2332
import Foundation public class Game { let botName: String let sendName: Bool let playerId: Int let mapWidth: Int let mapHeight: Int public var map: Map var currentTurn = 0 public var log: FileLogger /// Initialises the game with the given bot name public init(botName: String) { self.botName = botName self.sendName = false self.playerId = Int(Game.getString())! // Set up logging let logFilePath = "\(playerId)_\(botName).log" log = FileLogger(path: logFilePath, logLevel: .info) log.info("Initialized bot \(botName) with id \(playerId)") // Get width and height of map let mapSizeComponents = Game.getString() .trimmingCharacters(in: .whitespacesAndNewlines) .split(separator: " ") .map { Int($0)! } self.mapWidth = mapSizeComponents[0] self.mapHeight = mapSizeComponents[1] log.info("Map size: \(mapWidth) \(mapHeight)") self.map = Map(playerId: playerId, width: 0, height: 0, players: [], planets: []) // Initial map update _ = updateMap() } /// Starts a new turn, returns the updated map public func updateMap() -> Map { // Before the first turn, send the bot name if currentTurn == 1 { sendCommand(self.botName) } log.info("---TURN \(currentTurn)---") let mapList = Game.getString() let tokens = TokenStack(mapList.split(separator: " ").map { String($0) }) self.map = Map.parse(tokens, playerId: playerId, width: mapWidth, height: mapHeight) currentTurn += 1 return self.map } /// Send the given list of moves for a turn public func sendMoves(_ moves: [Move]) { sendCommand(Move.serializeMoves(moves)) } static func getString() -> String { guard let input = readLine(strippingNewline: true) else { fatalError("EOF when expecting input") } return input } func sendCommand(_ cmd: String) { log.info("Sending command: \(cmd)") print(cmd) // Need a flush here. fflush(stdout) } }
mit
3af86d270ed3b6d09f1a499f9b3e7b22
27.096386
92
0.553173
4.554688
false
false
false
false
manuelCarlos/Swift-Playgrounds
ArrayValueVsReference.playground/Contents.swift
1
7954
/*: ____ #### - Arrays holding swift value types. + Array instance declared as constants - `let` example. */ let intLetList = [1,2,3] var intLetListCopy = intLetList /*: ``` intLetListp[1] = -2 // not allowed intLetList.append(4) // not allowed ``` */ /*: + Array instance declared as variable - `var` example. */ var intList: [Int] = [1,2,3] var intListCopy: [Int] = intList /*: Lets place an element of the **inList** array in variable, we'll call it **box**, and change it. */ var box = intList[1] box += 2 /*: **Box** is now 4 but the arrays remain unchanged. */ box intList intListCopy /*: In the same way, modifiying or adding an element to intList has no effect on the copy we made before. */ intList[0] = 100 intList.append(4) intListCopy[0] intListCopy /*: */ intList == intListCopy // intList === intListCopy // not allowd /*: **Conclusion**: Each instance keeps a unique copy of its data. Copying, assigning or passing as argument, creates its own independent instance. ____ */ /*: #### Arrays holding Class instances. */ /*: Let's create a simple class that we can then use to populate an array. */ class C: CustomStringConvertible{ var n: Int var description: String { return "class n is \(self.n) " } init(with: Int){ n = with } } var a = C(with: 1), b = C(with: 2), c = C(with: 3) var classList: [C] = [ a, b, c] let classListCopy: [C] = classList /*: Lets place an element of the **classList** array in variable, we'll call it **classBox**, and change it. */ let classBox: C = classList[1] classBox.n = -30 a = C(with: 20) // This change is reflected in the original array but does not change the copy !!! /*: Modifying **classBox** also changes the array **classList** and **classListCopy** */ classBox classList = [b, a, c] classListCopy /*: Let's try and pass an element of the array to a function. */ func alter(c: C){ c.n = 400 } alter(c: classList[2]) /*: **classList** acts as a reference type. The array and the previously made copy both reflects the changes to **classBox** */ classList classListCopy /*: You can use (===) operator to test whether two object references both refer to the same object instance. */ classBox === classList[1] /*: > **Notice** that we've been declaring all instances of the class ```C``` and the arrays ``` classList: [C]``` and ```classListCopy: [C]``` as let constants and this hasn't stopped the instances from mutating their values. This happens because the array has instances of classes. Changing their value will effect other copies because classes have refrence semantics. */ /*: Let's try yet another situation. This time we declare the array as ```var``` and make a copy. */ var sndClassList: [C] = [ a, b, c] let sndClassListCopy: [C] = sndClassList /*: Being a ```var``` array we can change it's elements. Let's do that and see what happens to the copy: */ sndClassList[0] = b sndClassList sndClassListCopy /*: This time the copy hasn't changed to reflect the original! So what is happening here? What's happening is that when an array is copied, all of the elements of that array are coppied too. Changing the array does not change the elements of any of the copies of the array. But changing an element that has refernce semantics does effect any other copy. The distinction is between changing **the Array** and changing an **element** of the array (when element is a refrence type ). For example, adding an element to ```sndClassList``` or swapping the postition of two elements, would **not** change its copy: */ sndClassList.append(a) sndClassListCopy // swap 1st with last let tmp = sndClassList[0] sndClassList[0] = sndClassList[3] sndClassList[3] = tmp sndClassList sndClassListCopy /*: This is an fine distinction that might go unnoticed at first but is definitly important to be aware of. */ /*: **Conclusion:** Swift Arrays holding reference types allow their elements to keep their reference semantics. After a copy, the two arrays then refer to the same single instances of the elements, so modifying data in one element will also affects that element in the copied array. On the other hand the array retains value semantics when the changes are made to the array itself. ____ */ /*: #### Arrays holding Struct instances. */ /*: Standard Swift Structs are Value types. We begin by creating a simple struct that we'll use to populate an array, which will assign it to another variable to make a copy. */ struct Strkt: CustomStringConvertible{ let c: C // reference type var x: Int // value type init(c: C, x: Int){ self.c = c self.x = x } mutating func change(){ x += 1 c.n += 3 } var description: String { return "\(c) struct x is \(x)"} } var structList: [Strkt] = [Strkt(c: a, x: 0), Strkt(c: b, x: 0), Strkt(c: c, x: 0)] var structListCopy: [Strkt] = structList print(structList) /*: Again let's place an element of the **structList** array in variable, we'll call it **structBox**, and change it. Note that, being a value type, the `structBox` **has** to be a `var` inorder to be mutated. Declaring it as `let` would result in a compiler error as soon as we try to change it. */ var structBox: Strkt = structList[0] structBox.change() /*: Let's check if **structList** as changed */ structList[0] String(describing: structList) structBox String(describing: structListCopy) /*: > **Notice** that in both arrays, the original and the copy, the reference type property of the struct (the c: C) reflects the changes, but the x: Int property of the struct remains unchanged! Now, again, let's try and pass an element of the array out to a function. >Swift structs are full value types when their properties are value types. The example bellow will not compile because function arguments are imutable when they are a value types. We need to change the function declaration to use an `inout` argument. If we make the argument to the function a reference type, it will compile, as we saw in the array of classes example. This is one point of the distinction between structs and classes. ``` func changeStructListElement( c: Strkt) -> Strkt{ return c.change() } // compiler error, c is a let constant!! ``` */ func changeStructListElement( c: inout Strkt){ c.change() } /*: Now lets try to mutate an element of our array in this function. */ changeStructListElement(c: &structBox) String(describing: structList) /*: Like before, the array reflects the changes made to `c: C` but not the ones made to `x: Int` Swift Structs behave much like Arrays. They can be said to have value semantics for their value type properties, but any reference type property they hold will still have reference semantics. So, now its not surprising, that just like in the case of an array of class instances, the array of structs has value semantics when we remove or somehow change the structList array instead of its element. Here's an example: */ structList.removeFirst() String(describing: structList) String(describing: structListCopy) // remains unchanged! /*: **Conclusion:** We can be sure an array will behave as a value type when: All its element are full value types. When that is not the case, those element that are reference types will still have shared references across copies of the array. */ /* Value types (all symbols read-only?) var v:Foo = Foo() // Valucist chooses Foo to var s = v // defend the variable v let v0 = valueOf(v) /* { SideEffector attacks v using only s } */ let v1 = valueOf(v) assert(v0 == v1) // v unchanged? Valucist wins! Mutation Game with NSMutableString var v:NSMutableString = NSMutableString() var s = v let v0 = valueOf(v) s.append("Hello, world") // attempted attack! let v1 = valueOf(v) assert(v0 == v1) // false! SideEffector wins */
mit
91bc1fe9b3caa90cf6aa070c517ac51e
26.811189
437
0.697888
3.64361
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/Serializable.swift
1
4210
// // Serializable.swift // MercadoPagoSDK // // Created by Matias Gualino on 21/4/15. // Copyright (c) 2015 MercadoPago. All rights reserved. // import Foundation public class Serializable: NSObject { /** Converts the class to a dictionary. - returns: The class as an NSDictionary. */ public func toDictionary() -> NSDictionary { let propertiesDictionary = NSMutableDictionary() let mirror = Mirror(reflecting: self) for (propName, propValue) in mirror.children { if let propValue: AnyObject = self.unwrap(propValue) as? AnyObject, propName = propName { if let serializablePropValue = propValue as? Serializable { propertiesDictionary.setValue(serializablePropValue.toDictionary(), forKey: propName) } else if let arrayPropValue = propValue as? [Serializable] { var subArray = [NSDictionary]() for item in arrayPropValue { subArray.append(item.toDictionary()) } propertiesDictionary.setValue(subArray, forKey: propName) } else if propValue is Int || propValue is Double || propValue is Float { propertiesDictionary.setValue(propValue, forKey: propName) } else if let dataPropValue = propValue as? NSData { propertiesDictionary.setValue(dataPropValue.base64EncodedStringWithOptions(.Encoding64CharacterLineLength), forKey: propName) } else if let boolPropValue = propValue as? Bool { propertiesDictionary.setValue(boolPropValue, forKey: propName) } else { propertiesDictionary.setValue(propValue, forKey: propName) } } else if let propValue:Int8 = propValue as? Int8 { propertiesDictionary.setValue(NSNumber(char: propValue), forKey: propName!) } else if let propValue:Int16 = propValue as? Int16 { propertiesDictionary.setValue(NSNumber(short: propValue), forKey: propName!) } else if let propValue:Int32 = propValue as? Int32 { propertiesDictionary.setValue(NSNumber(int: propValue), forKey: propName!) } else if let propValue:Int64 = propValue as? Int64 { propertiesDictionary.setValue(NSNumber(longLong: propValue), forKey: propName!) } else if let propValue:UInt8 = propValue as? UInt8 { propertiesDictionary.setValue(NSNumber(unsignedChar: propValue), forKey: propName!) } else if let propValue:UInt16 = propValue as? UInt16 { propertiesDictionary.setValue(NSNumber(unsignedShort: propValue), forKey: propName!) } else if let propValue:UInt32 = propValue as? UInt32 { propertiesDictionary.setValue(NSNumber(unsignedInt: propValue), forKey: propName!) } else if let propValue:UInt64 = propValue as? UInt64 { propertiesDictionary.setValue(NSNumber(unsignedLongLong: propValue), forKey: propName!) } } return propertiesDictionary } /** Converts the class to JSON. - returns: The class as JSON, wrapped in NSData. */ public func toJson(prettyPrinted : Bool = false) -> NSData? { let dictionary = self.toDictionary() if NSJSONSerialization.isValidJSONObject(dictionary) { do { let json = try NSJSONSerialization.dataWithJSONObject(dictionary, options: (prettyPrinted ? .PrettyPrinted : NSJSONWritingOptions())) return json } catch let error as NSError { print("ERROR: Unable to serialize json, error: \(error)", terminator: "\n") NSNotificationCenter.defaultCenter().postNotificationName("CrashlyticsLogNotification", object: self, userInfo: ["string": "unable to serialize json, error: \(error)"]) } } return nil } /** Converts the class to a JSON string. - returns: The class as a JSON string. */ public func toJsonString(prettyPrinted : Bool = false) -> String? { if let jsonData = self.toJson(prettyPrinted) { return NSString(data: jsonData, encoding: NSUTF8StringEncoding) as String? } return nil } } extension Serializable { /** Unwraps 'any' object. See http://stackoverflow.com/questions/27989094/how-to-unwrap-an-optional-value-from-any-type - returns: The unwrapped object. */ private func unwrap(any: Any) -> Any? { let mi = Mirror(reflecting: any) if mi.displayStyle != .Optional { return any } if mi.children.count == 0 { return nil } let (_, some) = mi.children.first! return some } }
mit
7ec2ecaeac8c66b597fda940dcb3b1d7
32.420635
172
0.716865
3.858845
false
false
false
false
vimeo/VimeoNetworking
Sources/Shared/Models/VideoTranscodeStatus.swift
1
3492
// // VideoTranscodeStatus.swift // VimeoNetworking // // Created by Nicole Lehrer on 12/9/19. // Copyright © 2019 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Representation of a video's transcoding status public struct VideoTranscodeStatus: Decodable { /// Current state of transcoding public var state: TranscodeState /// Percentage of transcoding completed public var progress: Int /// Time in seconds remaining until completion public var timeLeft: TimeInterval /// Current state of the transcoding process /// /// - `active` - Transcoding is active and ongoing /// - `blocked` - Transcoding can't proceed /// - `exceeds_quota` - Transcoding can't proceed because the file size of the transcoded video would exceed the user's weekly quota /// - `exceeds_total_cap` - Transcoding can't proceed because the file size of the transcoded video would exceed the user's storage cap /// - `failed` - Transcoding has failed /// - `finishing` - Transcoding is in the completion stage /// - `internal_error` - Transcoding can't proceed because of an internal error /// - `invalid_file` - Transcoding can't proceed, because the file is invalid /// - `pending` - Transcoding hasn't started yet /// - `ready` - Transcoding is ready to start /// - `retrieved` - Transcoding is finished /// - `standby` - Transcoding is standing by /// - `starting` - Transcoding is in the initialization stage /// - `unknown` - The transcoding status is unknown /// - `upload_complete` - The video has uploaded, but transcoding hasn't started yet /// - `upload_incomplete` - The video upload was incomplete public enum TranscodeState: String, Decodable { case active case blocked case exceedsQuota = "exceeds_quota" case exceedsTotalCap = "exceeds_total_cap" case failed case finishing case internalError = "internal_error" case invalidFile = "invalid_file" case pending case ready case retrieved case standby case starting case unknown case uploadComplete = "upload_complete" case uploadIncomplete = "upload_incomplete" } private enum CodingKeys: String, CodingKey { case state case progress case timeLeft = "time_left" } }
mit
cc7555e4d7a84562790240232350b4c3
41.060241
139
0.689487
4.593421
false
false
false
false
nagra/KNAlertView
KNAlertView.swift
1
17308
// // KNAlertView.swift // KNAlertView // // Created by Kam Nagra on 01/11/2014. // Copyright (c) 2014 Kam Nagra. All rights reserved. // import Foundation import UIKit enum KNAlertViewType { case Default case Error case Warning func getColor() -> UIColor{ switch self { case .Default: return UIColor(red: 60/255, green: 200/255, blue: 0/255, alpha: 1.0) case .Error: return UIColor(red: 220/255, green: 0/255, blue: 0/255, alpha: 1.0) case .Warning: return UIColor(red: 240/255, green: 180/255, blue: 0/255, alpha: 1.0) } } } enum KNAlertActionStyle { case Cancel case Default } enum KNAlertAnimationType { case BounceIn case FadeIn } class KNAlertButton: UIButton { var actionType = KNAlertActionStyle.Default var target: AnyObject! var selector: Selector! var action: (()->Void)! } class KNAlertView : UIView, UIGestureRecognizerDelegate { var titleLabel: UILabel? var messageLabel: UILabel? var alertViewColor: UIColor? var animationType: KNAlertAnimationType = .BounceIn var backgroundView: UIView? var buttons:[KNAlertButton] = [] var cornerRadius: CGFloat = 8.0 { didSet { configureCornerRadius() } } var duration: NSTimeInterval = 0.5 var viewType: KNAlertViewType! // UIKit Dynamics var animator: UIDynamicAnimator! var snapBehavior: UISnapBehavior? var gravityBehavior: UIGravityBehavior! // private properties private let buttonHeight: CGFloat = 44.0 private let maxWidth: CGFloat = 260.0 private let padding: CGFloat = 8.0 private var rootView: UIView! private var rootViewExistingConstraints: [AnyObject] = [] private var rootNavigationController: UINavigationController? private let scaleFactor:CGFloat = 0.66 /** Creates a custom alert view, with optional title and message. You can add actions using the addAction method on the created alert :param: viewController the view controller the alert will be shown in and controlled by :param: title optoinal title for the alert :param: message optional message displayed below the title */ init(viewController: UIViewController, title: String?, message: String?, type: KNAlertViewType){ super.init(frame: viewController.view.frame) hidden = true viewController.view.endEditing(true) // add to root view to take over entire screen if viewController.view != nil { //UIApplication.sharedApplication().keyWindow?.rootViewController if viewController.navigationController != nil { rootNavigationController = viewController.navigationController rootNavigationController?.interactivePopGestureRecognizer.delegate = self rootView = viewController.navigationController!.view } else { // Calculate the view controller rootView = viewController.view } } rootViewExistingConstraints = rootView.constraints() rootView.addSubview(self) if title != nil { titleLabel = UILabel() titleLabel?.text = title } if message != nil { messageLabel = UILabel() messageLabel?.text = message } viewType = type configureAlert() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if rootNavigationController?.interactivePopGestureRecognizer == gestureRecognizer { return false } return true } /** Configures the Background View, UI, Buttons and Gestures */ func configureAlert(){ configureBackgroundView() configureUI() configureGesture() } func isVersionGreaterThan(version: String = "8.0.0") -> Bool { switch UIDevice.currentDevice().systemVersion.compare(version, options: NSStringCompareOptions.NumericSearch) { case .OrderedSame, .OrderedDescending: // is that version return true case .OrderedAscending: // not version return false } } /** Configure the background view which covers the alerts's superview */ func configureBackgroundView(){ if backgroundView == nil { backgroundView = UIView() backgroundView?.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.66) rootView.addSubview(backgroundView!) } backgroundView?.alpha = 0 } /** Configure the titleLabel, messageLabel and alert dimensions */ func configureUI(){ // bring alert in front of the background view rootView.bringSubviewToFront(self) // properties if isVersionGreaterThan(version: "8.0.0") { backgroundColor = .clearColor() let blurView = UIBlurEffect(style: .ExtraLight) let visualEffectView = UIVisualEffectView(effect: blurView) visualEffectView.frame = self.frame addSubview(visualEffectView) } else { backgroundColor = .whiteColor() } alpha = 1 clipsToBounds = true // content // title titleLabel?.numberOfLines = 0 titleLabel?.textAlignment = .Center titleLabel?.font = UIFont(name: "HelveticaNeue-Medium", size: 17.0) if alertViewColor != nil { titleLabel?.textColor = alertViewColor } else { titleLabel?.textColor = viewType.getColor() } if titleLabel != nil { addSubview(titleLabel!) } // message messageLabel?.numberOfLines = 0 messageLabel?.textAlignment = .Center messageLabel?.font = UIFont(name: "HelveticaNeue", size: 13.0) messageLabel?.textColor = UIColor.darkGrayColor() if messageLabel != nil { addSubview(messageLabel!) } configureCornerRadius() } func configureCornerRadius(){ layer.cornerRadius = cornerRadius } /** Configures the pan gesture to allow greater interaction for the user */ func configureGesture(){ animator = UIDynamicAnimator(referenceView: rootView) let panGesture = UIPanGestureRecognizer(target: self, action: Selector("alertDidPan:")) panGesture.delegate = self addGestureRecognizer(panGesture) } /** Add action :param: title String for the title of the button :param: type AlertActionStyle e.g. .Cancel. .Default is the default :param: action The closure to be executed when a button is pressed */ func addAction(title: String, type: KNAlertActionStyle, action:(() -> Void)!) -> KNAlertButton { let btn = KNAlertButton() btn.setTitle(title, forState: .Normal) btn.actionType = type btn.action = action btn.addTarget(self, action:Selector("alertButtonTapped:"), forControlEvents:.TouchUpInside) // cancel button always just primary color btn.setTitleColor(viewType.getColor(), forState: .Normal) if btn.actionType == KNAlertActionStyle.Cancel { btn.layer.borderWidth = 1.0 btn.layer.borderColor = viewType.getColor().CGColor } else if btn.actionType == KNAlertActionStyle.Default { btn.backgroundColor = viewType.getColor() btn.setTitleColor(UIColor.whiteColor(), forState: .Normal) } btn.titleLabel?.font = UIFont(name: "HelveticaNeue", size: 17.0) btn.layer.cornerRadius = cornerRadius / 2 buttons.append(btn) addSubview(btn) //updateConstraints() return btn } /** Method triggered while the alert is panning */ func alertDidPan(panGesture: UIPanGestureRecognizer) { let translation = panGesture.translationInView(rootView) let location = panGesture.locationInView(rootView) let velocity = panGesture.velocityInView(rootView) center = CGPoint(x: rootView.center.x + translation.x, y: rootView.center.y + translation.y) if panGesture.state == .Began { animator.removeAllBehaviors() } if panGesture.state == .Ended { if translation.y > 100 { let gravityBehaviour = UIGravityBehavior(items: [self]) gravityBehaviour.magnitude = 8.0 animator.addBehavior(gravityBehaviour) hide(fadeOut: true) } else if translation.y < -100 { let gravityBehaviour = UIGravityBehavior(items: [self]) gravityBehaviour.magnitude = 8.0 gravityBehaviour.gravityDirection = CGVectorMake(0.0, -8.0) animator.addBehavior(gravityBehaviour) hide(fadeOut: true) } else { snapBehavior = UISnapBehavior(item: self, snapToPoint: rootView.center) animator.addBehavior(snapBehavior) } } } /** Shows the alert depending on the KNAlertAnimationType. Animation options include .FadeIn and .BounceDown */ func show(){ updateConstraints() backgroundView?.layoutIfNeeded() layoutIfNeeded() hidden = false switch animationType { case .FadeIn: UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in self.alpha = 1 self.backgroundView?.alpha = 1 }, completion: nil) case .BounceIn: transform = CGAffineTransformMakeScale(scaleFactor, scaleFactor) UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in self.transform = CGAffineTransformMakeScale(1.0, 1.0) self.alpha = 1 self.backgroundView?.alpha = 1 }, completion: nil) } } /** Hides the alert depending on the KNAlertAnimationType. Options include .AlertAnimationFadeIn and .BounceIn :param: fadeOut Boolean to force fading out of a alert */ func hide(fadeOut:Bool = false){ // can override default animation to fading out if fadeOut == true { animationType = .FadeIn } // renable gesture rootNavigationController?.interactivePopGestureRecognizer.delegate = nil switch animationType { case .FadeIn: UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in self.alpha = 0 self.backgroundView?.alpha = 0 }, { finished in self.removeFromSuperview() self.backgroundView?.removeFromSuperview() }) case .BounceIn: UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: nil, animations: { () -> Void in self.transform = CGAffineTransformMakeScale(self.scaleFactor, self.scaleFactor) self.alpha = 0 self.backgroundView?.alpha = 0 }, completion: { finished in self.removeFromSuperview() self.backgroundView?.removeFromSuperview() }) } } /** Required delegate method passing back the index of the button clicked. */ func alertButtonTapped(btn: KNAlertButton) { if btn.action != nil { btn.action() } hide() } /* MARK: Constraints */ override func updateConstraints() { // background view if backgroundView != nil { backgroundView!.setTranslatesAutoresizingMaskIntoConstraints(false) let backgroundViewConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|[backgroundView]|", options: nil, metrics: nil, views: ["backgroundView": backgroundView!]) let backgroundViewConstraintV = NSLayoutConstraint.constraintsWithVisualFormat("V:|[backgroundView]|", options: nil, metrics: nil, views: ["backgroundView": backgroundView!]) rootView.addConstraints(backgroundViewConstraintH) rootView.addConstraints(backgroundViewConstraintV) } // start of vertical constraints var viewsDictionary = [String: AnyObject]() var verticalConstraintsFormat = "V:|-\(padding)-" // titleLabel if titleLabel != nil { viewsDictionary["titleLabelView"] = titleLabel verticalConstraintsFormat += "[titleLabelView]-\(padding)-" titleLabel!.setTranslatesAutoresizingMaskIntoConstraints(false) let titleLabelConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(padding)-[titleLableView]-\(padding)-|", options: nil, metrics: nil, views: ["titleLableView": titleLabel!]) self.addConstraints(titleLabelConstraintH) } // messageLabel if messageLabel != nil { viewsDictionary["messageLabelView"] = messageLabel verticalConstraintsFormat += "[messageLabelView]-\(padding)-" messageLabel!.setTranslatesAutoresizingMaskIntoConstraints(false) let messageLabelConstraintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(padding)-[messageLabelView]-\(padding)-|", options: nil, metrics: nil, views: ["messageLabelView": messageLabel!]) self.addConstraints(messageLabelConstraintH) } // buttons if buttons.count > 0 { for var i = 0; i < buttons.count; i++ { var button = buttons[i] viewsDictionary["button\(i)"] = button // horizontal button spacing let buttonConstaintH = NSLayoutConstraint.constraintsWithVisualFormat("H:|-\(padding)-[buttonView]-\(padding)-|", options: nil, metrics: nil, views: ["buttonView": button]) button.setTranslatesAutoresizingMaskIntoConstraints(false) self.addConstraints(buttonConstaintH) //vertical button spacing verticalConstraintsFormat += "[button\(i)(40)]-\(padding)-" if (i+1) == buttons.count { // last element close vertical format verticalConstraintsFormat += "|" } } } else { verticalConstraintsFormat += "-|" } // self self.setTranslatesAutoresizingMaskIntoConstraints(false) let alertViewConstraintWidth = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: maxWidth) let alertViewConstraintX = NSLayoutConstraint(item: self, attribute: .CenterX, relatedBy: .Equal, toItem: rootView, attribute: .CenterX, multiplier: 1, constant: 0) let alertViewConstraintY = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: rootView, attribute: .CenterY, multiplier: 1, constant: 0) rootView.addConstraints([alertViewConstraintX, alertViewConstraintY, alertViewConstraintWidth]) // setup entire vertical constraint in one go let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(verticalConstraintsFormat, options: nil, metrics: nil, views: viewsDictionary) rootView.addConstraints(verticalConstraints) super.updateConstraints() } }
mit
d6ab26ff88a3ceb571ce36b8a6ef90ab
32.348748
210
0.583487
5.823688
false
false
false
false
tardieu/swift
test/Inputs/clang-importer-sdk/swift-modules/Foundation.swift
2
9261
@_exported import ObjectiveC @_exported import CoreGraphics @_exported import Foundation @_silgen_name("swift_StringToNSString") internal func _convertStringToNSString(_ string: String) -> NSString @_silgen_name("swift_NSStringToString") internal func _convertNSStringToString(_ nsstring: NSString?) -> String public func == (lhs: NSObject, rhs: NSObject) -> Bool { return lhs.isEqual(rhs) } public let NSUTF8StringEncoding: UInt = 8 // NSArray bridging entry points func _convertNSArrayToArray<T>(_ nsarr: NSArray?) -> [T] { return [T]() } func _convertArrayToNSArray<T>(_ arr: [T]) -> NSArray { return NSArray() } // NSDictionary bridging entry points internal func _convertDictionaryToNSDictionary<Key, Value>( _ d: Dictionary<Key, Value> ) -> NSDictionary { return NSDictionary() } internal func _convertNSDictionaryToDictionary<K: NSObject, V: AnyObject>( _ d: NSDictionary? ) -> Dictionary<K, V> { return Dictionary<K, V>() } // NSSet bridging entry points internal func _convertSetToNSSet<T : Hashable>(_ s: Set<T>) -> NSSet { return NSSet() } internal func _convertNSSetToSet<T : Hashable>(_ s: NSSet?) -> Set<T> { return Set<T>() } extension AnyHashable : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSObject { return NSObject() } public static func _forceBridgeFromObjectiveC(_ x: NSObject, result: inout AnyHashable?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSObject, result: inout AnyHashable? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSObject?) -> AnyHashable { return AnyHashable("") } } extension String : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSString { return NSString() } public static func _forceBridgeFromObjectiveC(_ x: NSString, result: inout String?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSString, result: inout String? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSString?) -> String { return String() } } extension Int : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Int? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Int { return 0 } } extension Bool: _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout Bool? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout Bool? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> Bool { return false } } extension Array : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSArray { return NSArray() } public static func _forceBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSArray, result: inout Array? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSArray? ) -> Array { return Array() } } extension Dictionary : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSDictionary { return NSDictionary() } public static func _forceBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSDictionary, result: inout Dictionary? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSDictionary? ) -> Dictionary { return Dictionary() } } extension Set : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSSet { return NSSet() } public static func _forceBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSSet, result: inout Set? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSSet? ) -> Set { return Set() } } extension CGFloat : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSNumber { return NSNumber() } public static func _forceBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSNumber, result: inout CGFloat? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSNumber? ) -> CGFloat { return CGFloat() } } extension NSRange : _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSValue { return NSValue() } public static func _forceBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) { result = x.rangeValue } public static func _conditionallyBridgeFromObjectiveC( _ x: NSValue, result: inout NSRange? ) -> Bool { self._forceBridgeFromObjectiveC(x, result: &result) return true } public static func _unconditionallyBridgeFromObjectiveC( _ x: NSValue? ) -> NSRange { return NSRange() } } public struct URL : _ObjectiveCBridgeable { public init() { } public init?(string: String) { return nil } public func _bridgeToObjectiveC() -> NSURL { return NSURL() } public static func _forceBridgeFromObjectiveC(_ x: NSURL, result: inout URL?) { } public static func _conditionallyBridgeFromObjectiveC( _ x: NSURL, result: inout URL? ) -> Bool { return true } public static func _unconditionallyBridgeFromObjectiveC(_ x: NSURL?) -> URL { return URL() } } extension NSError : Error { public var _domain: String { return domain } public var _code: Int { return code } } extension NSArray { @objc(methodIntroducedInOverlay) public func introducedInOverlay() { } } @_silgen_name("swift_convertNSErrorToError") func _convertNSErrorToError(_ string: NSError?) -> Error @_silgen_name("swift_convertErrorToNSError") func _convertErrorToNSError(_ string: Error) -> NSError /// An internal protocol to represent Swift error enums that map to standard /// Cocoa NSError domains. public protocol _ObjectiveCBridgeableError : Error { /// Produce a value of the error type corresponding to the given NSError, /// or return nil if it cannot be bridged. init?(_bridgedNSError: NSError) } /// Describes a bridged error that stores the underlying NSError, so /// it can be queried. public protocol _BridgedStoredNSError : _ObjectiveCBridgeableError { /// The type of an error code. associatedtype Code: _ErrorCodeProtocol /// The error code for the given error. var code: Code { get } //// Retrieves the embedded NSError. var _nsError: NSError { get } /// Create a new instance of the error type with the given embedded /// NSError. /// /// The \c error must have the appropriate domain for this error /// type. init(_nsError error: NSError) } public protocol _ErrorCodeProtocol { /// The corresponding error code. associatedtype _ErrorType } public extension _BridgedStoredNSError { public init?(_bridgedNSError error: NSError) { self.init(_nsError: error) } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: SignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: "", code: 0, userInfo: [:])) } /// The user-info dictionary for an error that was bridged from /// NSError. var userInfo: [String : Any] { return [:] } } /// Various helper implementations for _BridgedStoredNSError public extension _BridgedStoredNSError where Code: RawRepresentable, Code.RawValue: UnsignedInteger { // FIXME: Generalize to Integer. public var code: Code { return Code(rawValue: numericCast(_nsError.code))! } /// Initialize an error within this domain with the given ``code`` /// and ``userInfo``. public init(_ code: Code, userInfo: [String : Any] = [:]) { self.init(_nsError: NSError(domain: "", code: 0, userInfo: [:])) } } extension NSDictionary { public subscript(_: Any) -> Any? { @objc(_swift_objectForKeyedSubscript:) get { fatalError() } } public func nonObjCExtensionMethod<T>(_: T) {} } extension NSMutableDictionary { public override subscript(_: Any) -> Any? { get { fatalError() } @objc(_swift_setObject:forKeyedSubscript:) set { } } }
apache-2.0
9b04a2b94098ec12d2d07291c1539187
24.234332
90
0.674441
4.577855
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/Strings.swift
2
5090
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import j2objc public extension String { public var isEmpty: Bool { return self.characters.isEmpty } public var length: Int { return self.characters.count } public func indexOf(str: String) -> Int? { if let range = rangeOfString(str) { return startIndex.distanceTo(range.startIndex) } else { return nil } } public func trim() -> String { return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()); } public subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } public subscript (i: Int) -> String { return String(self[i] as Character) } public func first(count: Int) -> String { let realCount = min(count, length); return substringToIndex(startIndex.advancedBy(realCount)); } public func skip(count: Int) -> String { let realCount = min(count, length); return substringFromIndex(startIndex.advancedBy(realCount)) } public func strip(set: NSCharacterSet) -> String { return componentsSeparatedByCharactersInSet(set).joinWithSeparator("") } public func replace(src: String, dest:String) -> String { return stringByReplacingOccurrencesOfString(src, withString: dest, options: NSStringCompareOptions(), range: nil) } public func toLong() -> Int64? { return NSNumberFormatter().numberFromString(self)?.longLongValue } public func toJLong() -> jlong { return jlong(toLong()!) } public func smallValue() -> String { let trimmed = trim(); if (trimmed.isEmpty){ return "#"; } let letters = NSCharacterSet.letterCharacterSet() let res: String = self[0]; if (res.rangeOfCharacterFromSet(letters) != nil) { return res.uppercaseString; } else { return "#"; } } public func hasPrefixInWords(prefix: String) -> Bool { var components = self.componentsSeparatedByString(" ") for i in 0..<components.count { if components[i].lowercaseString.hasPrefix(prefix.lowercaseString) { return true } } return false } public func contains(text: String) -> Bool { return self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil } public func startsWith(text: String) -> Bool { let range = rangeOfString(text) if range != nil { return range!.startIndex == startIndex } return false } public func rangesOfString(text: String) -> [Range<String.Index>] { var res = [Range<String.Index>]() var searchRange = Range<String.Index>(start: self.startIndex, end: self.endIndex) while true { let found = self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil) if found != nil { res.append(found!) searchRange = Range<String.Index>(start: found!.endIndex, end: self.endIndex) } else { break } } return res } public func repeatString(count: Int) -> String { var res = "" for _ in 0..<count { res += self } return res } public func isValidUrl () -> Bool { if let url = NSURL(string: self) { return UIApplication.sharedApplication().canOpenURL(url) } return false } public var ns: NSString { return self as NSString } public var pathExtension: String? { return ns.pathExtension } public var lastPathComponent: String? { return ns.lastPathComponent } public var asNS: NSString { return (self as NSString) } } public extension NSAttributedString { public func append(text: NSAttributedString) -> NSAttributedString { let res = NSMutableAttributedString() res.appendAttributedString(self) res.appendAttributedString(text) return res } public func append(text: String, font: UIFont) -> NSAttributedString { return append(NSAttributedString(string: text, attributes: [NSFontAttributeName: font])) } public convenience init(string: String, font: UIFont) { self.init(string: string, attributes: [NSFontAttributeName: font]) } } public extension NSMutableAttributedString { public func appendFont(font: UIFont) { self.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, self.length)) } public func appendColor(color: UIColor) { self.addAttribute(NSForegroundColorAttributeName, value: color.CGColor, range: NSMakeRange(0, self.length)) } }
agpl-3.0
f5feeb8baf50c423f6b800bbe179fd64
28.766082
136
0.602947
4.980431
false
false
false
false
riana/NickelSwift
NickelSwift/LocalNotificationFeature.swift
1
3443
// // LocalNotificationFeature.swift // NickelSwift // // Created by Riana Ralambomanana on 05/02/2016. // Copyright © 2016 riana.io. All rights reserved. // import Foundation class LocalNotificationFeature: NickelFeature { init() { } func setupFeature(nickelViewController:NickelWebViewController){ nickelViewController.registerBridgedFunction("scheduleNotification", bridgedMethod: self.scheduleNotification) nickelViewController.registerBridgedFunction("cancelNotification", bridgedMethod: self.cancelNotification) nickelViewController.registerBridgedFunction("getScheduledNotifications", bridgedMethod: self.getScheduledNotifications) } func getScheduledNotifications(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{ var response = [NSObject:AnyObject](); var notifications = [AnyObject]() for notification in UIApplication.sharedApplication().scheduledLocalNotifications! { notifications.append(notification.userInfo!) } response["notifications"] = notifications return response } func cancelNotification(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{ let notificationId = content["id"] as! String for notification in UIApplication.sharedApplication().scheduledLocalNotifications! { let currentId = notification.userInfo!["id"] as! String if(currentId == notificationId){ UIApplication.sharedApplication().cancelLocalNotification(notification) } } return [NSObject:AnyObject]() } func scheduleNotification(operation:String, content:[NSObject:AnyObject]) -> [NSObject:AnyObject]?{ UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound], categories: nil)) if let fireTimeStamp = content["date"] as? NSNumber { let fireDate = NSDate(timeIntervalSince1970: NSTimeInterval(fireTimeStamp.longLongValue / 1000)) let localNotification = UILocalNotification() localNotification.userInfo = content localNotification.fireDate = fireDate localNotification.alertBody = content["message"] as! String? localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.timeZone = NSTimeZone.defaultTimeZone() localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1 if let repeatInterval = content["repeat"] as! String? { if repeatInterval == "Hour"{ localNotification.repeatInterval = NSCalendarUnit.Hour } if repeatInterval == "Minute"{ localNotification.repeatInterval = NSCalendarUnit.Minute } if repeatInterval == "Day"{ localNotification.repeatInterval = NSCalendarUnit.Day } } UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } return [NSObject:AnyObject]() } }
mit
70477e55e5c8ba972823873bf5bf7de3
40.481928
221
0.662115
6.55619
false
false
false
false
hooman/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-enum-1argument-1distinct_use.swift
14
3212
// 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: @"$s4main9NamespaceO5ValueVySS_SiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main9NamespaceO5ValueVySS_SiGWV", i32 0, i32 0) // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.*}}$s4main9NamespaceO5ValueVMn{{.*}} to %swift.type_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* @"$sSSN", // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] enum Namespace<Arg> { struct Value<First> { let first: First } } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture %{{[0-9]+}}, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main9NamespaceO5ValueVySS_SiGMf" // CHECK-SAME: to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) // CHECK-SAME: ) // CHECK: } func doit() { consume( Namespace<String>.Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8* // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, // CHECK-SAME: i8* [[ERASED_TYPE_1]], // CHECK-SAME: i8* [[ERASED_TYPE_2]], // CHECK-SAME: i8* undef, // CHECK-SAME: %swift.type_descriptor* bitcast ( // CHECK-SAME: {{.+}}$s4main9NamespaceO5ValueVMn{{.+}} to %swift.type_descriptor* // CHECK-SAME: ) // CHECK-SAME: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
adfdfd61c0a60dc0ab0125f6fadfe38d
37.698795
157
0.581569
2.993476
false
false
false
false
halonsoluis/MiniRev
MiniRev/MiniRev/ReviewManager/RateHandler.swift
1
2339
// // RateHandler.swift // MiniRev // // Created by Hugo on 7/21/15. // Copyright (c) 2015 Hugo Alonso. All rights reserved. // import Foundation import UIKit /// Rate Functionalities handler public class RateHandler { /** Tries to redirect the user to the rate page, if success, marks the Rate to not appear anymore */ static func goToRate() { if (RatingHandler().rate()) { RateDataManager.doNotPromptAnymore() } } /** This does nothing right now, variable and conditions reset are handled prior in RateDataManager */ static func rememberToRate() { } /** Marks the Rate to not appear anymore */ static func neverRate() { RateDataManager.doNotPromptAnymore() } /** Presents the RateDialog :param: parent the parent of the view to be shown */ public static func presentRateDialog(parent: UIViewController) { /// If there's no parent there's nothing to do //check for connectivity before trying to show the page and ask the RateDataManager if conditions have been meet if /*!Reachability.isConnectedToNetwork() ||*/ !RateDataManager.shouldPrompt() { return } let bundle = NSBundle(forClass: RateHandler.self) //TODO: Add code here to show the view guard let rateVC = UIStoryboard(name: "ReviewFlow", bundle: bundle).instantiateInitialViewController() else { return } rateVC.view.frame = CGRect(x: 0, y: -110, width: parent.view.frame.width, height: 110) parent.addChildViewController(rateVC) parent.view.addSubview(rateVC.view) let topBlackBorder = UIView(frame: CGRect(x: 0, y: 0, width: parent.view.frame.width, height: 20)) topBlackBorder.backgroundColor = UIColor.blackColor() parent.view.addSubview(topBlackBorder) UIView.animateWithDuration(0.35) { () -> Void in rateVC.view.transform = CGAffineTransformTranslate(rateVC.view.transform, 0, 110) } } public static func userHasFulfilledCriteria_A() { RateDataManager.userHasFulfilledCriteria_A() } public static func userHasFulfilledCriteria_B() { RateDataManager.userHasFulfilledCriteria_B() } }
mit
c7fa952d2d0c09438602f59d7733e16e
31.957746
120
0.640872
4.559454
false
false
false
false
AndrewBennet/readinglist
ReadingList/AppDelegate.swift
1
1621
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var launchManager = LaunchManager(window: window) let upgradeManager = UpgradeManager() static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } var tabBarController: TabBarController? { return window?.rootViewController as? TabBarController } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { launchManager.initialise() upgradeManager.performNecessaryUpgradeActions() // Grab any options which we will take action on after the persistent store is initialised let options = launchManager.extractRelevantLaunchOptions(launchOptions) launchManager.initialisePersistentStore(options) // If there were any options, they will be handled once the store is initialised return !options.any() } func applicationDidBecomeActive(_ application: UIApplication) { launchManager.handleApplicationDidBecomeActive() } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let didHandle = launchManager.handleQuickAction(shortcutItem) completionHandler(didHandle) } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { return launchManager.handleOpenUrl(url) } }
gpl-3.0
a5df65c80917021977ccef85b54c7459
37.595238
155
0.735965
5.687719
false
false
false
false
nagyistoce/Kingfisher
Kingfisher/ImageDownloader.swift
1
14547
// // ImageDownloader.swift // Kingfisher // // Created by Wei Wang on 15/4/6. // // Copyright (c) 2015 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. import Foundation /// Progress update block of downloader. public typealias ImageDownloaderProgressBlock = DownloadProgressBlock /// Completion block of downloader. public typealias ImageDownloaderCompletionHandler = ((image: UIImage?, error: NSError?, imageURL: NSURL?) -> ()) /// Download task. public typealias RetrieveImageDownloadTask = NSURLSessionDataTask private let defaultDownloaderName = "default" private let downloaderBarrierName = "com.onevcat.Kingfisher.ImageDownloader.Barrier." private let imageProcessQueueName = "com.onevcat.Kingfisher.ImageDownloader.Process." private let instance = ImageDownloader(name: defaultDownloaderName) /** The error code. - BadData: The downloaded data is not an image or the data is corrupted. - NotModified: The remote server responsed a 304 code. No image data downloaded. - InvalidURL: The URL is invalid. */ public enum KingfisherError: Int { case BadData = 10000 case NotModified = 10001 case InvalidURL = 20000 } /** * Protocol of `ImageDownloader`. */ @objc public protocol ImageDownloaderDelegate { /** Called when the `ImageDownloader` object successfully downloaded an image from specified URL. :param: downloader The `ImageDownloader` object finishes the downloading. :param: image Downloaded image. :param: URL URL of the original request URL. :param: response The response object of the downloading process. */ optional func imageDownloader(downloader: ImageDownloader, didDownloadImage image: UIImage, forURL URL: NSURL, withResponse response: NSURLResponse) } /** * `ImageDownloader` represents a downloading manager for requesting the image with a URL from server. */ public class ImageDownloader: NSObject { class ImageFetchLoad { var callbacks = [CallbackPair]() var responseData = NSMutableData() var shouldDecode = false } // MARK: - Public property /// This closure will be applied to the image download request before it being sent. You can modify the request for some customizing purpose, like adding auth token to the header or do a url mapping. public var requestModifier: (NSMutableURLRequest -> Void)? /// The duration before the download is timeout. Default is 15 seconds. public var downloadTimeout: NSTimeInterval = 15.0 /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this set will be ignored. You can use this set to specify the self-signed site. public var trustedHosts: Set<String>? /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. public weak var delegate: ImageDownloaderDelegate? // MARK: - Internal property let barrierQueue: dispatch_queue_t let processQueue: dispatch_queue_t typealias CallbackPair = (progressBlock: ImageDownloaderProgressBlock?, completionHander: ImageDownloaderCompletionHandler?) var fetchLoads = [NSURL: ImageFetchLoad]() // MARK: - Public method /// The default downloader. public class var defaultDownloader: ImageDownloader { return instance } /** Init a downloader with name. :param: name The name for the downloader. It should not be empty. :returns: The downloader object. */ public init(name: String) { if name.isEmpty { fatalError("[Kingfisher] You should specify a name for the downloader. A downloader with empty name is not permitted.") } barrierQueue = dispatch_queue_create(downloaderBarrierName + name, DISPATCH_QUEUE_CONCURRENT) processQueue = dispatch_queue_create(imageProcessQueueName + name, DISPATCH_QUEUE_CONCURRENT) } func fetchLoadForKey(key: NSURL) -> ImageFetchLoad? { var fetchLoad: ImageFetchLoad? dispatch_sync(barrierQueue, { () -> Void in fetchLoad = self.fetchLoads[key] }) return fetchLoad } } // MARK: - Download method public extension ImageDownloader { /** Download an image with a URL. :param: URL Target URL. :param: progressBlock Called when the download progress updated. :param: completionHandler Called when the download progress finishes. */ public func downloadImageWithURL(URL: NSURL, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) { downloadImageWithURL(URL, options: KingfisherManager.OptionsNone, progressBlock: progressBlock, completionHandler: completionHandler) } /** Download an image with a URL and option. :param: URL Target URL. :param: options The options could control download behavior. See `KingfisherManager.Options` :param: progressBlock Called when the download progress updated. :param: completionHandler Called when the download progress finishes. */ public func downloadImageWithURL(URL: NSURL, options: KingfisherManager.Options, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) { downloadImageWithURL(URL, retrieveImageTask: nil, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } internal func downloadImageWithURL(URL: NSURL, retrieveImageTask: RetrieveImageTask?, options: KingfisherManager.Options, progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?) { let timeout = self.downloadTimeout == 0.0 ? 15.0 : self.downloadTimeout // We need to set the URL as the load key. So before setup progress, we need to ask the `requestModifier` for a final URL. let request = NSMutableURLRequest(URL: URL, cachePolicy: .ReloadIgnoringLocalCacheData, timeoutInterval: timeout) request.HTTPShouldUsePipelining = true self.requestModifier?(request) // There is a possiblility that request modifier changed the url to `nil` if request.URL == nil { completionHandler?(image: nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.InvalidURL.rawValue, userInfo: nil), imageURL: nil) return } setupProgressBlock(progressBlock, completionHandler: completionHandler, forURL: request.URL!) {(session, fetchLoad) -> Void in let task = session.dataTaskWithRequest(request) task.priority = options.lowPriority ? NSURLSessionTaskPriorityLow : NSURLSessionTaskPriorityDefault task.resume() fetchLoad.shouldDecode = options.shouldDecode retrieveImageTask?.downloadTask = task } } // A single key may have multiple callbacks. Only download once. internal func setupProgressBlock(progressBlock: ImageDownloaderProgressBlock?, completionHandler: ImageDownloaderCompletionHandler?, forURL URL: NSURL, started: ((NSURLSession, ImageFetchLoad) -> Void)) { dispatch_barrier_sync(barrierQueue, { () -> Void in var create = false var loadObjectForURL = self.fetchLoads[URL] if loadObjectForURL == nil { create = true loadObjectForURL = ImageFetchLoad() } let callbackPair = (progressBlock: progressBlock, completionHander: completionHandler) loadObjectForURL!.callbacks.append(callbackPair) self.fetchLoads[URL] = loadObjectForURL! if create { let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue:NSOperationQueue.mainQueue()) started(session, loadObjectForURL!) } }) } func cleanForURL(URL: NSURL) { dispatch_barrier_sync(barrierQueue, { () -> Void in self.fetchLoads.removeValueForKey(URL) return }) } } // MARK: - NSURLSessionTaskDelegate extension ImageDownloader: NSURLSessionDataDelegate { /** This method is exposed since the compiler requests. Do not call it. */ public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) { if let URL = dataTask.originalRequest.URL, callbackPairs = fetchLoadForKey(URL)?.callbacks { for callbackPair in callbackPairs { callbackPair.progressBlock?(receivedSize: 0, totalSize: response.expectedContentLength) } } completionHandler(NSURLSessionResponseDisposition.Allow) } /** This method is exposed since the compiler requests. Do not call it. */ public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let URL = dataTask.originalRequest.URL, fetchLoad = fetchLoadForKey(URL) { fetchLoad.responseData.appendData(data) for callbackPair in fetchLoad.callbacks { callbackPair.progressBlock?(receivedSize: Int64(fetchLoad.responseData.length), totalSize: dataTask.response!.expectedContentLength) } } } private func callbackWithImage(image: UIImage?, error: NSError?, imageURL: NSURL) { if let callbackPairs = fetchLoadForKey(imageURL)?.callbacks { self.cleanForURL(imageURL) for callbackPair in callbackPairs { callbackPair.completionHander?(image: image, error: error, imageURL: imageURL) } } } /** This method is exposed since the compiler requests. Do not call it. */ public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let URL = task.originalRequest.URL { if let error = error { // Error happened callbackWithImage(nil, error: error, imageURL: URL) } else { //Download finished without error // We are on main queue when receiving this. dispatch_async(processQueue, { () -> Void in if let fetchLoad = self.fetchLoadForKey(URL) { if let image = UIImage(data: fetchLoad.responseData) { self.delegate?.imageDownloader?(self, didDownloadImage: image, forURL: URL, withResponse: task.response!) if fetchLoad.shouldDecode { self.callbackWithImage(image.kf_decodedImage(), error: nil, imageURL: URL) } else { self.callbackWithImage(image, error: nil, imageURL: URL) } } else { // If server response is 304 (Not Modified), inform the callback handler with NotModified error. // It should be handled to get an image from cache, which is response of a manager object. if let res = task.response as? NSHTTPURLResponse where res.statusCode == 304 { self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.NotModified.rawValue, userInfo: nil), imageURL: URL) return } self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL) } } else { self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: URL) } }) } } } /** This method is exposed since the compiler requests. Do not call it. */ public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { if let trustedHosts = trustedHosts where trustedHosts.contains(challenge.protectionSpace.host) { let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust) completionHandler(.UseCredential, credential) return } } completionHandler(.PerformDefaultHandling, nil) } }
mit
ff713172243129191d89e240e7d20dcf
42.816265
208
0.650856
5.618772
false
false
false
false
SergeMaslyakov/audio-player
app/src/controllers/RootPresenter.swift
1
2018
// // RootPresenter.swift // AudioPlayer // // Created by Serge Maslyakov on 07/07/2017. // Copyright © 2017 Maslyakov. All rights reserved. // import UIKit import Dip import SwiftyBeaver import Reusable class RootPresenter: Loggable, MusicPickerCoordinatable { public func presentTabBarController(_ window: UIWindow) { let tabBarController: UITabBarController = UITabBarController() tabBarController.tabBar.barTintColor = UIColor.TabBar.barTintGray tabBarController.tabBar.tintColor = UIColor.TabBar.itemSelectedTint guard let sourceScene: UIViewController = UIStoryboard(name: StoryboardScenes.source.rawValue, bundle: nil) .instantiateInitialViewController() else { logger!.error("Audio Source scene is absent") return } guard let musicScene: UINavigationController = UIStoryboard(name: StoryboardScenes.musicLib.rawValue, bundle: nil) .instantiateInitialViewController() as? UINavigationController else { logger!.error("Music scene is absent") return } guard let settingsScene: UIViewController = UIStoryboard(name: StoryboardScenes.settings.rawValue, bundle: nil) .instantiateInitialViewController() else { logger!.error("Settings scene is absent") return } musicCoordinator?.musicNavigationController = musicScene let musicState = UserDefaults.standard.getMusicLibraryState() musicScene.setViewControllers([musicState.musicController()], animated: false) tabBarController.viewControllers = [sourceScene, musicScene, settingsScene] tabBarController.selectedIndex = 0 window.rootViewController = tabBarController } public func presentOnboardingController(_ window: UIWindow) { window.rootViewController = UIStoryboard(name: StoryboardScenes.onboarding.rawValue, bundle: nil) .instantiateInitialViewController() } }
apache-2.0
04ff90590d5f4d2d91df5a96979ea08e
34.385965
122
0.704512
5.69774
false
false
false
false
synchromation/Buildasaur
BuildaKit/ConfigTriplet.swift
4
1620
// // ConfigTriplet.swift // Buildasaur // // Created by Honza Dvorsky on 10/10/15. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation import XcodeServerSDK //TODO: remove invalid configs on startup? public struct ConfigTriplet { public var syncer: SyncerConfig public var server: XcodeServerConfig public var project: ProjectConfig public var buildTemplate: BuildTemplate public var triggers: [TriggerConfig] init(syncer: SyncerConfig, server: XcodeServerConfig, project: ProjectConfig, buildTemplate: BuildTemplate, triggers: [TriggerConfig]) { self.syncer = syncer self.server = server self.project = project self.buildTemplate = buildTemplate self.syncer.preferredTemplateRef = buildTemplate.id self.triggers = triggers } public func toEditable() -> EditableConfigTriplet { return EditableConfigTriplet(syncer: self.syncer, server: self.server, project: self.project, buildTemplate: self.buildTemplate, triggers: self.triggers) } } public struct EditableConfigTriplet { public var syncer: SyncerConfig public var server: XcodeServerConfig? public var project: ProjectConfig? public var buildTemplate: BuildTemplate? public var triggers: [TriggerConfig]? public func toFinal() -> ConfigTriplet { var syncer = self.syncer syncer.preferredTemplateRef = self.buildTemplate!.id return ConfigTriplet(syncer: syncer, server: self.server!, project: self.project!, buildTemplate: self.buildTemplate!, triggers: self.triggers!) } }
mit
b6531cd0cab6ccaeb7b18a9e96389f1a
33.446809
161
0.720198
4.818452
false
true
false
false
crazypoo/PTools
PooToolsSource/Animation/PTPurchaseCarAnimationTool.swift
1
2878
// // PTPurchaseCarAnimationTool.swift // Diou // // Created by ken lam on 2021/10/9. // Copyright © 2021 DO. All rights reserved. // import UIKit public typealias AnimationFinishBlock = (_ finish:Bool) -> Void public class PTPurchaseCarAnimationTool: NSObject { public static let shared = PTPurchaseCarAnimationTool.init() public var block:AnimationFinishBlock? public var layer:CALayer? public func startAnimationand(view:UIView,rect:CGRect,finishPoint:CGPoint,handle: AnimationFinishBlock?) { var newRect = rect layer = CALayer() layer?.contents = view.layer.contents layer?.contentsGravity = .resizeAspectFill newRect.size.width = 60 newRect.size.height = 60 layer?.bounds = newRect layer?.cornerRadius = newRect.size.width/2 layer?.masksToBounds = true let keyWindow = AppWindows! keyWindow.layer.addSublayer(layer!) layer?.position = CGPoint.init(x: newRect.origin.x + view.frame.size.width / 2, y: newRect.midY) self.createAnimation(rect: newRect, finishPoint: finishPoint) block = handle } public class func shakeAnimation(view:UIView) { let animation = CABasicAnimation.init(keyPath: "transform.translation.y") animation.duration = 0.25 animation.fromValue = -5 animation.toValue = 5 animation.autoreverses = true view.layer.add(animation, forKey: nil) } public func createAnimation(rect:CGRect,finishPoint:CGPoint) { let path = UIBezierPath() path.move(to: layer!.position) path.addQuadCurve(to: finishPoint, controlPoint: CGPoint.init(x: kSCREEN_WIDTH/2, y: rect.origin.y - 80)) let pathAnimation = CAKeyframeAnimation.init(keyPath: "position") pathAnimation.path = path.cgPath let rotateAnimation = CABasicAnimation.init(keyPath: "transform.rotation") rotateAnimation.isRemovedOnCompletion = true rotateAnimation.fromValue = 0 rotateAnimation.toValue = 12 rotateAnimation.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.easeIn) let groups = CAAnimationGroup() groups.animations = [pathAnimation,rotateAnimation] groups.duration = 1.2 groups.isRemovedOnCompletion = false groups.fillMode = .forwards groups.delegate = self layer?.add(groups, forKey: "group") } } extension PTPurchaseCarAnimationTool:CAAnimationDelegate { public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if anim == layer?.animation(forKey: "group") { layer!.removeFromSuperlayer() layer = nil if block != nil { block!(true) } } } }
mit
8f90c09169f1953b557762a7660cf3ba
32.847059
113
0.64755
4.693312
false
false
false
false
WangCrystal/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsPrivacyViewController.swift
4
4971
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class SettingsPrivacyViewController: AATableViewController { // MARK: - // MARK: Private vars private let CellIdentifier = "CellIdentifier" private var authSessions: [ARApiAuthSession]? // MARK: - // MARK: Constructors init() { super.init(style: UITableViewStyle.Grouped) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("PrivacyTitle", comment: "Controller title") tableView.registerClass(CommonCell.self, forCellReuseIdentifier: CellIdentifier) tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.separatorStyle = UITableViewCellSeparatorStyle.None execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in let list = val as! JavaUtilList self.authSessions = [] for i in 0..<list.size() { self.authSessions!.append(list.getWithInt(jint(i)) as! ARApiAuthSession) } self.tableView.reloadData() }, failureBlock: nil) } // MARK: - // MARK: Getters private func terminateSessionsCell(indexPath: NSIndexPath) -> CommonCell { let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("PrivacyTerminate", comment: "Terminate action")) cell.style = .Normal // cell.showTopSeparator() // cell.showBottomSeparator() return cell } private func sessionsCell(indexPath: NSIndexPath) -> CommonCell { let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell let session = authSessions![indexPath.row] cell.setContent(session.getDeviceTitle()) cell.style = .Normal // if (indexPath.row == 0) { // cell.showTopSeparator() // } else { // cell.hideTopSeparator() // } // cell.showBottomSeparator() return cell } // MARK: - // MARK: UITableView Data Source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if authSessions != nil { if authSessions!.count > 0 { return 2 } } return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { return authSessions!.count } return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 && indexPath.row == 0 { return terminateSessionsCell(indexPath) } else if (indexPath.section == 1) { return sessionsCell(indexPath) } return UITableViewCell() } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section > 0 { return nil } return NSLocalizedString("PrivacyTerminateHint", comment: "Terminate hint") } // MARK: - // MARK: UITableView Delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 0 { execute(Actor.terminateAllSessionsCommand()) } else if (indexPath.section == 1) { execute(Actor.terminateSessionCommandWithId(authSessions![indexPath.row].getId()), successBlock: { (val) -> Void in self.execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in let list = val as! JavaUtilList self.authSessions = [] for i in 0..<list.size() { self.authSessions!.append(list.getWithInt(jint(i)) as! ARApiAuthSession) } self.tableView.reloadData() }, failureBlock: nil) }, failureBlock: nil) } } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel!.textColor = MainAppTheme.list.sectionColor } func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel!.textColor = MainAppTheme.list.hintColor } }
mit
506174b843500f423804c903c46d8e36
34.507143
127
0.617381
5.333691
false
false
false
false
pixlwave/Stingtk-iOS
Source/AppDelegate.swift
1
2099
import UIKit import AVFoundation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // prevent device from going to sleep application.isIdleTimerDisabled = true // applies the included tint colour to UIAlertController (and presumably others) window?.tintColor = .tintColor #if targetEnvironment(macCatalyst) window?.windowScene?.sizeRestrictions?.minimumSize = CGSize(width: 320, height: 568) #endif return true } #warning("Needs testing on device") func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { guard url.isFileURL, let showBrowser = window?.rootViewController as? ShowBrowserViewController else { return false } if let playbackVC = showBrowser.presentedPlaybackViewController { playbackVC.closeShow() } if url.isFileInsideInbox { showBrowser.revealDocument(at: url, importIfNeeded: true) { importedURL, error in guard let importedURL = importedURL else { return } showBrowser.openShow(at: importedURL) } return false } else { showBrowser.openShow(at: url) return true } } func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool { return true } func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool { return true } func applicationDidEnterBackground(_ application: UIApplication) { Engine.shared.isInBackground = true } func applicationDidBecomeActive(_ application: UIApplication) { Engine.shared.isInBackground = false } }
mpl-2.0
4888f1114814f04b2001307b78f6f423
32.854839
145
0.640305
5.703804
false
false
false
false
rusty1s/RSShapeNode
Example/Example/Scene.swift
1
989
// // Scene.swift // Example // // Created by Matthias Fey on 08.09.15. // Copyright © 2015 Matthias Fey. All rights reserved. // import SpriteKit import RSShapeNode class Scene : SKScene { override func didMoveToView(view: SKView) { backgroundColor = SKColor.whiteColor() anchorPoint = CGPoint(x: 0.5, y: 0.5) let vertices = [CGPoint(x: -100, y: 0), CGPoint(x: 0, y: 100), CGPoint(x: 100, y: 0), CGPoint(x: 0, y: -100)] let node = RSShapeNode(points: vertices, closed: true) node.fillColor = SKColor.yellowColor() node.fillTexture = SKTexture(imageNamed: "Stripe") node.fillTextureStyle = .Repeat node.fillTextureOffset = CGPoint(x: 100, y: 100) node.lineWidth = 10 node.strokeColor = SKColor.whiteColor() node.shadowRadius = 10 node.shadowColor = SKColor.blackColor() node.shadowOpacity = 1 addChild(node) } }
mit
dce8ed39bb982bb960b69dcdf09ae225
27.228571
117
0.598178
3.967871
false
false
false
false
kckd/ClassicAppExporter
classicexp-mac/ClassicListExporter/ListNameViewController.swift
1
2174
// // ListNameViewController.swift // ClassicListExporter // // Created by Casey Cady on 2/3/17. // Copyright © 2017 Casey Cady. All rights reserved. // import Cocoa class ListNameViewController: NSViewController { @IBOutlet weak var listNameTextField: NSTextField! public var list: List? public var caches: [String]? override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } override func viewWillAppear() { caches = DatabaseManager.defaultMgr?.getCaches(forList: list!.id!) listNameTextField.stringValue = list!.name! } @IBAction func onOkay(_ sender: Any) { let waitStr = "Please wait. Exporting list." let alert = NSAlert() alert.informativeText = waitStr alert.alertStyle = .informational alert.addButton(withTitle: "Cancel") alert.buttons[0].isHidden = true; alert.beginSheetModal(for: view.window!, completionHandler: { (_) in return }) let task = CreateListAPITask(name: listNameTextField.stringValue) task.execute { (json) in if let code = json["referenceCode"].string { let addTask = AddToListAPITask(listCode: code, cacheCodes: self.caches!) addTask.execute { (result) in DispatchQueue.main.async { alert.buttons[0].performClick(alert) let waitStr = "List Exported" let alert = NSAlert() alert.informativeText = waitStr alert.alertStyle = .informational alert.addButton(withTitle: "Okay") alert.beginSheetModal(for: self.view.window!, completionHandler: { (_) in DispatchQueue.main.async { self.dismiss(nil) } return }) } } } } } @IBAction func onCancel(_ sender: Any) { dismiss(nil) } }
unlicense
059f3218d2232a263e7faa49c755fa65
32.430769
97
0.528302
5.137116
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Edit data/Offline edit and sync/FeatureLayersViewController.swift
1
2463
// // Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class FeatureLayersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView:UITableView! var featureLayerInfos:[AGSIDInfo]! { didSet { self.tableView?.reloadData() } } var selectedLayerIds = [Int]() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.featureLayerInfos?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("FeatureLayerCell")! let layerInfo = self.featureLayerInfos[indexPath.row] cell.textLabel?.text = layerInfo.name //accessory view if self.selectedLayerIds.contains(layerInfo.ID) { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } cell.backgroundColor = UIColor.clearColor() return cell } //MARK: - UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let layerInfo = self.featureLayerInfos[indexPath.row] if let index = self.selectedLayerIds.indexOf(layerInfo.ID) { self.selectedLayerIds.removeAtIndex(index) } else { self.selectedLayerIds.append(layerInfo.ID) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None) } }
apache-2.0
3b0ce4ec3e3e40b594bc790c1461e8cb
30.177215
109
0.662607
5.088843
false
false
false
false
neoneye/SwiftyFORM
Example/Usecases/MaleFemaleViewController.swift
1
1891
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit import SwiftyFORM struct OptionRow { let title: String let identifier: String init(_ title: String, _ identifier: String) { self.title = title self.identifier = identifier } } class MyOptionForm { let optionRows: [OptionRow] let vc0 = ViewControllerFormItem() init(optionRows: [OptionRow]) { self.optionRows = optionRows } func populate(_ builder: FormBuilder) { builder.navigationTitle = "Picker" configureVC0() for optionRow: OptionRow in optionRows { let option = OptionRowFormItem() option.title = optionRow.title builder.append(option) } builder.append(SectionHeaderTitleFormItem().title("Help")) builder.append(vc0) } func configureVC0() { vc0.title = "What is XYZ?" vc0.createViewController = { (dismissCommand: CommandProtocol) in let vc = EmptyViewController() return vc } } } class MaleFemaleViewController: FormViewController, SelectOptionDelegate { var xmyform: MyOptionForm? let dismissCommand: CommandProtocol init(dismissCommand: CommandProtocol) { self.dismissCommand = dismissCommand super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func populate(_ builder: FormBuilder) { let optionRows: [OptionRow] = [ OptionRow("Male", "male"), OptionRow("Female", "female"), OptionRow("It's complicated", "complicated") ] let myform = MyOptionForm(optionRows: optionRows) myform.populate(builder) xmyform = myform } func form_willSelectOption(option: OptionRowFormItem) { print("select option \(option)") dismissCommand.execute(viewController: self, returnObject: option) } } class EmptyViewController: UIViewController { override func loadView() { self.view = UIView() self.view.backgroundColor = UIColor.red } }
mit
3754d955ed77e54a4840d449a86b7ed5
20.247191
74
0.726071
3.567925
false
false
false
false
russelhampton05/MenMew
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/OrderConfirmationViewController.swift
1
2526
// // OrderConfirmationViewController.swift // App_Prototype_Alpha_001 // // Created by Jon Calanio on 9/20/16. // Copyright © 2016 Jon Calanio. All rights reserved. // import UIKit class OrderConfirmationViewController: UIViewController { //Variables var ticket: Ticket? //IBOutlets @IBOutlet weak var orderTitle: UILabel! @IBOutlet var ticketLabel: UILabel! @IBOutlet var dateLabel: UILabel! @IBOutlet weak var ticketTitle: UILabel! @IBOutlet weak var dateTitle: UILabel! @IBOutlet weak var confirmButton: UIButton! @IBOutlet var orderLine: UIView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true //Format date to more human-readable result let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" let currentDate = formatter.date(from: ticket!.timestamp!) formatter.dateStyle = .medium formatter.timeStyle = .short ticketLabel.text = ticket!.desc! dateLabel.text = formatter.string(from: currentDate!) loadTheme() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { } @IBAction func confirmButtonPressed(_ sender: AnyObject) { self.navigationController?.isNavigationBarHidden = false performSegue(withIdentifier: "UnwindToMainSegue", sender: self) } func loadTheme() { //Background and Tint self.view.backgroundColor = currentTheme!.primary! self.view.tintColor = currentTheme!.highlight! //Navigation UINavigationBar.appearance().backgroundColor = currentTheme!.primary! UINavigationBar.appearance().tintColor = currentTheme!.highlight! self.navigationController?.navigationBar.barTintColor = currentTheme!.primary! //Labels orderTitle.textColor = currentTheme!.highlight! ticketTitle.textColor = currentTheme!.highlight! dateTitle.textColor = currentTheme!.highlight! ticketLabel.textColor = currentTheme!.highlight! dateLabel.textColor = currentTheme!.highlight! orderLine.backgroundColor = currentTheme!.highlight! //Buttons confirmButton.backgroundColor = currentTheme!.highlight! confirmButton.setTitleColor(currentTheme!.primary!, for: .normal) } }
mit
4e7eaef1f3111bbd87021eea22c2c5c9
30.5625
86
0.653069
5.44181
false
false
false
false
nanoxd/Bourne
Sources/JSON/JSON.swift
1
4157
import Foundation public struct JSON { private enum Node { case number case string case bool case array case dictionary case null case unknown } public var object: Any? public init() { self.object = nil } /// Initializes an instance with Any object /// /// - Parameter object: Any public init(_ object: Any?) { self.object = object } /// Initializes an instance with another JSON object /// /// - Parameter json: A JSON object public init(json: JSON) { self.object = json.object } public init?(data: Data?) { guard let data = data else { return nil } do { let object: Any = try JSONSerialization.jsonObject(with: data, options: .allowFragments) self.object = object } catch { return nil } } public init?(path: String) { guard FileManager.default.fileExists(atPath: path) else { return nil } let data = try? Data(contentsOf: Foundation.URL(fileURLWithPath: path)) self.init(data: data) } /** Initialize an instance given a JSON file contained within the bundle. - parameter bundle: The bundle to attempt to load from. - parameter string: A string containing the name of the file to load from resources. */ public init?(bundleClass: AnyClass, filename: String) { let bundle = Bundle(for: bundleClass) self.init(bundle: bundle, filename: filename) } public init?(bundle: Bundle, filename: String) { guard let filePath = bundle.path(forResource: filename, ofType: nil) else { return nil } self.init(path: filePath) } public subscript(key: String) -> JSON? { set { if var tempObject = object as? [String : Any] { tempObject[key] = newValue?.object self.object = tempObject } else { var tempObject: [String : Any] = [:] tempObject[key] = newValue?.object self.object = tempObject } } get { return value(for: key) } } /// Retrieve a value from a given keyPath /// /// - Parameter keyPath: A keyPath to where an item could be /// - Returns: Iff an object is found, it will be boxed up in JSON public func value(for keyPath: String) -> JSON? { /** NSDictionary is used because it currently performs better than a native Swift dictionary. The reason for this is that [String : AnyObject] is bridged to NSDictionary deep down the call stack, and this bridging operation is relatively expensive. Until Swift is ABI stable and/or doesn't require a bridge to Objective-C, NSDictionary will be used here */ guard let dictionary = object as? NSDictionary, let value = dictionary.value(forKeyPath: keyPath) else { return nil } return JSON(value) } public var rawString: String { guard let object = object else { return "" } switch type { case .array, .dictionary: guard let data = try? JSONSerialization.data(withJSONObject: object, options: .prettyPrinted) else { return "" } return String(data: data, encoding: String.Encoding.utf8) ?? "" default: return object as? String ?? "" } } private var type: Node { guard let object = object else { return .unknown } switch object { case is String: return .string case is NSArray: return .array case is NSDictionary: return .dictionary case is Int, is Float, is Double: return .number case is Bool: return .bool case is NSNull: return .null default: return .unknown } } }
mit
5cd84169ed736fc90024f749c70a6180
25.819355
112
0.549675
4.937055
false
false
false
false
illescasDaniel/Questions
Questions/ViewControllers/AddContentViewController.swift
1
5242
// // AddContentViewController.swift // Questions // // Created by Daniel Illescas Romero on 08/07/2018. // import UIKit class CustomUITableViewCell: UITableViewCell { @IBInspectable override var imageView: UIImageView? { return self.viewWithTag(1) as? UIImageView } @IBInspectable override var textLabel: UILabel? { return self.viewWithTag(2) as? UILabel } } class PopoverTableViewController: UITableViewController { var parentVC: UITableViewController? override func viewDidLoad() { self.modalPresentationStyle = .popover } func presentOnParent(_ viewController: UIViewController) { self.dismiss(animated: true) { self.parentVC?.present(viewController, animated: true) } } } class AddContentTableVC: PopoverTableViewController { override func viewDidLoad() { super.viewDidLoad() self.tableView.backgroundColor = .popoverVCBackground self.view.backgroundColor = .popoverVCBackground self.tableView.separatorColor = .clear } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: self.addRemoteTopicOrContent() case 1: self.dismiss(animated: true) self.parentVC?.performSegue(withIdentifier: "createNewTopicSegue", sender: nil) case 2: self.dismiss(animated: true) self.parentVC?.performSegue(withIdentifier: "cameraViewSegue", sender: nil) default: break } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.textLabel?.textColor = .white cell.tintColor = .white cell.backgroundColor = .popoverVCBackground } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "addContentCell", for: indexPath) as? CustomUITableViewCell else { return UITableViewCell() } switch indexPath.row { case 0: cell.imageView?.image = #imageLiteral(resourceName: "addTopicRemote") cell.textLabel?.text = L10n.Topics_Saved_Add_Menu_Download cell.textLabel?.adjustsFontSizeToFitWidth = true case 1: cell.imageView?.image = #imageLiteral(resourceName: "addTopicCreate") cell.textLabel?.text = L10n.Topics_Saved_Add_Menu_Create cell.textLabel?.adjustsFontSizeToFitWidth = true case 2: cell.imageView?.image = #imageLiteral(resourceName: "addTopicCamera") cell.textLabel?.text = L10n.Topics_Saved_Add_Menu_Camera cell.textLabel?.adjustsFontSizeToFitWidth = true default: break } let view = UIView() view.backgroundColor = .popoverVCBackgroundSelected cell.selectedBackgroundView = view return cell } // Convenience private func addRemoteTopicOrContent() { let titleText = L10n.Topics_Saved_Add_Download_Title let messageText = L10n.Topics_Saved_Add_Download_Info let newTopicAlert = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert) newTopicAlert.addTextField { textField in textField.placeholder = L10n.Topics_Saved_Add_Download_TopicName textField.keyboardType = .alphabet textField.autocapitalizationType = .sentences textField.autocorrectionType = .yes textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 25)) guard #available(iOS 13, *) else { textField.keyboardAppearance = UserDefaultsManager.darkThemeSwitchIsOn ? .dark : .light return } } newTopicAlert.addTextField { textField in textField.placeholder = L10n.Topics_Saved_Add_Download_TopicContent textField.keyboardType = .URL textField.addConstraint(textField.heightAnchor.constraint(equalToConstant: 25)) guard #available(iOS 13, *) else { textField.keyboardAppearance = UserDefaultsManager.darkThemeSwitchIsOn ? .dark : .light return } } newTopicAlert.addAction(title: L10n.Topics_Saved_Add_Download_Help, style: .default) { _ in if let url = URL(string: "https://github.com/illescasDaniel/Questions#topics-json-format") { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:]) } else { UIApplication.shared.openURL(url) } } } newTopicAlert.addAction(title: L10n.Topics_Saved_Add_Download_Action, style: .default) { _ in if let topicName = newTopicAlert.textFields?.first?.text, let topicURLText = newTopicAlert.textFields?.last?.text, !topicURLText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { DispatchQueue.global().async { let quizContent: String if let topicURL = URL(string: topicURLText), let validTextFromURL = try? String(contentsOf: topicURL) { quizContent = validTextFromURL } else { quizContent = topicURLText } if let validQuiz = SetOfTopics.shared.quizFrom(content: quizContent) { SetOfTopics.shared.save(topic: TopicEntry(name: topicName, content: validQuiz)) DispatchQueue.main.async { self.parentVC?.tableView.reloadData() } } } } } newTopicAlert.addAction(title: L10n.Common_Cancel, style: .cancel) self.presentOnParent(newTopicAlert) } }
mit
8447ede8b6574ff978995cb7c47d7cb2
31.559006
158
0.73884
3.944319
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Effects/Delay/Variable Delay/AKVariableDelay.swift
1
4863
// // AKVariableDelay.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// A delay line with cubic interpolation. /// /// - Parameters: /// - input: Input node to process /// - time: Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. /// - feedback: Feedback amount. Should be a value between 0-1. /// - maximumDelayTime: The maximum delay time, in seconds. /// public class AKVariableDelay: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKVariableDelayAudioUnit? internal var token: AUParameterObserverToken? private var timeParameter: AUParameter? private var feedbackParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. public var time: Double = 1 { willSet { if time != newValue { if internalAU!.isSetUp() { timeParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.time = Float(newValue) } } } } /// Feedback amount. Should be a value between 0-1. public var feedback: Double = 0 { willSet { if feedback != newValue { if internalAU!.isSetUp() { feedbackParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.feedback = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize this delay node /// /// - Parameters: /// - input: Input node to process /// - time: Delay time (in seconds) that can be changed during performance. This value must not exceed the maximum delay time. /// - feedback: Feedback amount. Should be a value between 0-1. /// - maximumDelayTime: The maximum delay time, in seconds. /// public init( _ input: AKNode, time: Double = 1, feedback: Double = 0, maximumDelayTime: Double = 5) { self.time = time self.feedback = feedback var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x76646c61 /*'vdla'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKVariableDelayAudioUnit.self, asComponentDescription: description, name: "Local AKVariableDelay", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKVariableDelayAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } timeParameter = tree.valueForKey("time") as? AUParameter feedbackParameter = tree.valueForKey("feedback") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.timeParameter!.address { self.time = Double(value) } else if address == self.feedbackParameter!.address { self.feedback = Double(value) } } } internalAU?.time = Float(time) internalAU?.feedback = Float(feedback) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
89942649c640d1b6a84288fdee270ea7
32.537931
132
0.59819
5.156946
false
false
false
false
steelwheels/KiwiControls
UnitTest/OSX/UTTable/ViewController.swift
1
4812
// // ViewController.swift // UTTable // // Created by Tomoo Hamada on 2021/05/14. // import KiwiControls import CoconutData import Cocoa class ViewController: KCViewController, KCViewControlEventReceiver { @IBOutlet weak var mTableView: KCTableView! @IBOutlet weak var mAddButton: KCButton! @IBOutlet weak var mSaveButton: KCButton! override func viewDidLoad() { super.viewDidLoad() self.setupTableView() self.setupUpdateButton() self.setupSaveButton() } private func setupTableView() { /* Start logging */ NSLog("Start logging ... begin") let _ = KCLogWindowManager.shared // init CNPreference.shared.systemPreference.logLevel = .debug NSLog("Start logging ... end") /* Set editable */ mTableView.hasGrid = true mTableView.hasHeader = true mTableView.isEnableCallback = { (_ row: Int) -> Bool in let result = (row % 2) == 1 NSLog("isEnable for row \(row) -> \(result)") return result } let table = loadTable(name: "storage") let recnum = table.recordCount NSLog("record count: \(recnum)") NSLog("Set visible fields") mTableView.fieldNames = [ KCTableView.FieldName(field: "c0", title: "col 0"), KCTableView.FieldName(field: "c1", title: "col 1"), KCTableView.FieldName(field: "c2", title: "col 2") ] CNLog(logLevel: .debug, message: "reload data", atFunction: #function, inFile: #file) mTableView.dataTable = table mTableView.filterFunction = { (_ rec: CNRecord) -> Bool in for field in rec.fieldNames { var fval: String = "?" if let fld = rec.value(ofField: field) { fval = fld.description } NSLog("recordMapping: field=\(field), value=\(fval)") } return true } NSLog("reload table") mTableView.reload() } private func setupUpdateButton() { mAddButton.value = .text("Update") mAddButton.buttonPressedCallback = { () -> Void in NSLog("Button pressed callback") let table = self.loadTable(name: "storage2") let recnum = table.recordCount NSLog("record count: \(recnum)") self.mTableView.hasGrid = true CNLog(logLevel: .debug, message: "reload data", atFunction: #function, inFile: #file) self.mTableView.fieldNames = [ KCTableView.FieldName(field: "c0", title: "col 0"), KCTableView.FieldName(field: "c1", title: "col 1"), KCTableView.FieldName(field: "c2", title: "col 2") ] self.mTableView.dataTable = table self.mTableView.reload() } } private func setupSaveButton() { mSaveButton.value = .text("Save") mSaveButton.buttonPressedCallback = { if self.mTableView.dataTable.save() { NSLog("save ... ok") } else { NSLog("save ... error") } } } private func loadTable(name nm: String) -> CNMappingTable { CNLog(logLevel: .debug, message: "setup value table", atFunction: #function, inFile: #file) guard let srcfile = CNFilePath.URLForResourceFile(fileName: nm, fileExtension: "json", subdirectory: "Data", forClass: ViewController.self) else { NSLog("Failed to get URL of storage.json") fatalError("Terminated") } let srcdir = srcfile.deletingLastPathComponent() let cachefile = CNFilePath.URLForApplicationSupportFile(fileName: nm, fileExtension: "json", subdirectory: "Data") let cachedir = cachefile.deletingLastPathComponent() let storage = CNStorage(sourceDirectory: srcdir, cacheDirectory: cachedir, filePath: nm + ".json") switch storage.load() { case .success(_): break case .failure(let err): NSLog("[Error] \(err.toString())") fatalError("Terminated") } let tblpath = CNValuePath(identifier: nil, elements: [.member("data")]) let valtbl = CNStorageTable(path: tblpath, storage: storage) return CNMappingTable(sourceTable: valtbl) } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } public override func viewDidLayout() { /* Init window */ if let win = self.view.window { NSLog("Initialize window attributes") initWindowAttributes(window: win) } else { NSLog("[Error] No window") } } public override func viewDidAppear() { } public func notifyControlEvent(viewControlEvent event: KCViewControlEvent) { switch event { case .none: CNLog(logLevel: .detail, message: "Control event: none", atFunction: #function, inFile: #file) case .updateSize(let targview): CNLog(logLevel: .detail, message: "Update window size: \(targview.description)", atFunction: #function, inFile: #file) case .switchFirstResponder(let newview): if let window = self.view.window { if !window.makeFirstResponder(newview) { CNLog(logLevel: .error, message: "makeFirstResponder -> Fail", atFunction: #function, inFile: #file) } } else { CNLog(logLevel: .error, message: "Failed to switch first responder", atFunction: #function, inFile: #file) } } } }
lgpl-2.1
b234ffbc194563d602f73a5ff21db899
28.163636
148
0.688279
3.417614
false
false
false
false
4074/ExtensionKit
ExtensionKit/UIColor.swift
1
1976
// // Color.swift // ExtensionKitDemo // // Created by wen on 16/7/2. // Copyright © 2016年 wenfeng. All rights reserved. // import UIKit extension UIColor { public class func fromHexString(_ hexString: String, alpha: CGFloat = 1) -> UIColor { let hexString = hexString.trim() let scanner = Scanner(string: hexString) if (hexString.hasPrefix("#")) { scanner.scanLocation = 1 } var color: UInt32 = 0 scanner.scanHexInt32(&color) let red = CGFloat((color & 0xFF0000) >> 16) / 255 let green = CGFloat((color & 0x00FF00) >> 8) / 255 let blue = CGFloat((color & 0x0000FF)) / 255 return UIColor(red: red, green: green, blue: blue, alpha: alpha) } public func toHexString() -> String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) let color: Int = Int(red * 255) << 16 | Int(green * 255) << 8 | Int(blue * 255) << 0 return String(format:"#%06x", color) } public func to(target: UIColor, ratio: CGFloat) -> UIColor { let ratio = min(max(ratio, 0), 1) var s_red: CGFloat = 0, s_green: CGFloat = 0, s_blue: CGFloat = 0, s_alpha: CGFloat = 0 self.getRed(&s_red, green: &s_green, blue: &s_blue, alpha: &s_alpha) var t_red: CGFloat = 0, t_green: CGFloat = 0, t_blue: CGFloat = 0, t_alpha: CGFloat = 0 target.getRed(&t_red, green: &t_green, blue: &t_blue, alpha: &t_alpha) let red = (t_red - s_red) * ratio + s_red let green = (t_green - s_green) * ratio + s_green let blue = (t_blue - s_blue) * ratio + s_blue let alpha = (t_alpha - s_alpha) * ratio + s_alpha return UIColor(red: red, green: green, blue: blue, alpha: alpha) } }
mit
659b5957e253d96379ba2884ad09adf5
33.017241
95
0.543335
3.561372
false
false
false
false
L550312242/SinaWeiBo-Switf
weibo 1/Class/Module(模块)/Home(首页)/View/CZStatusPictureView.swift
1
5259
import UIKit import SDWebImage class CZStatusPictureView: UICollectionView { //MARK: -- 属性 -- /// cell 重用表示 private let StatusPictureViewIdentifier = "StatusPictureViewIdentifier" //微博模型 var status: CZStatus? { didSet { reloadData() } } // // 这个方法是 sizeToFit调用的,而且 返回的 CGSize 系统会设置为当前view的size override func sizeThatFits(size: CGSize) -> CGSize { return calcViewSize() } /// 根据微博模型,计算配图的尺寸 func calcViewSize() -> CGSize { // itemSize let itemSize = CGSize(width: 90, height: 90) // 设置itemSize layout.itemSize = itemSize layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 // 间距 let margin: CGFloat = 10 // 列数 let column = 3 // 根据模型的图片数量来计算尺寸 let count = status?.pictureURLs?.count ?? 0 // 没有图片 if count == 0 { // layout.itemSize = CGSizeZero return CGSizeZero } // 在这个时候需要有图片,才能获取到图片的大小,缓存图片越早越好 if count == 1 { //获取图片url路径 let urlString = status!.pictureURLs![0].absoluteString // 获取缓存好的图片,缓存的图片可能没有成功 let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString) var size = CGSize(width: 150, height: 120) //当有图片的时候来赋值 if image != nil { size = image.size } layout.itemSize = size return size } layout.minimumInteritemSpacing = margin layout.minimumLineSpacing = margin // 4 张图片 if count == 4 { let width = 2 * itemSize.width + margin return CGSize(width: width, height: width) } // 剩下 2, 3, 5, 6, 7, 8, 9 // 计算行数: 公式: 行数 = (图片数量 + 列数 -1) / 列数 let row = (count + column - 1) / column // 宽度公式: 宽度 = (列数 * item的宽度) + (列数 - 1) * 间距 let widht = (CGFloat(column) * itemSize.width) + (CGFloat(column) - 1) * margin // 高度公式: 高度 = (行数 * item的高度) + (行数 - 1) * 间距 let height = (CGFloat(row) * itemSize.height) + (CGFloat(row) - 1) * margin return CGSize(width: widht, height: height) } /// 布局 private var layout = UICollectionViewFlowLayout() // MARK: - 构造函数 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(frame: CGRectZero, collectionViewLayout: layout) // 设置背景 backgroundColor = UIColor.clearColor() // 设置数据源 dataSource = self // 注册cell registerClass(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewIdentifier) } } // MARK: - 扩展 CZStatusPictureView 类,实现 UICollectionViewDataSource协议 extension CZStatusPictureView: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return status?.pictureURLs?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewIdentifier, forIndexPath: indexPath) as! CZStatusPictureViewCell // cell.backgroundColor = UIColor.randomColor() // 模型能直接提供图片的URL数组,外面使用就比较简单 // let url = status?.pic_urls?[indexPath.item]["thumbnail_pic"] as? String cell.imageURL = status?.pictureURLs?[indexPath.item] return cell } } // 自定义cell 显示图片 class CZStatusPictureViewCell: UICollectionViewCell { // MARK: - 属性 var imageURL: NSURL? { didSet { // 设置图片 iconView.cz_setImageWithURL(imageURL) } } // MARK: - 构造函数 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } // MARK: - 准备UI private func prepareUI() { // 添加子控件 contentView.addSubview(iconView) // 添加约束 // 填充父控件 iconView.ff_Fill(contentView) } // MARK: - 懒加载 /// 图片 private lazy var iconView: UIImageView = { let imageView = UIImageView() //设置内容模式 imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.clipsToBounds = true return imageView }() }
apache-2.0
7331331ba1af42d2d8d555e236ebfed2
28.111111
154
0.572216
4.753024
false
false
false
false
sehkai/SKSwiftExtension
Pod/Classes/UIViewController+keyboard.swift
1
9111
// // UIViewController+keyboard.swift // SKSwiftExtension // // Created by Matthew Nguyen on 2/20/15. // Copyright (c) 2015 Solfanto, Inc. All rights reserved. // // add: // override func viewWillAppear(animated: Bool) { // super.viewWillDisappear(animated) // bs_setKeyboardNotifications() // } // // override func viewWillDisappear(animated: Bool) { // super.viewWillDisappear(animated) // bs_unsetKeyboardNotifications() // } #if os(iOS) import UIKit extension UIViewController { private struct Properties { static var keyboardStatus: NSString? static var originalInset: NSValue? static var tabBarHeight: CGFloat = 0.0 static var outsideKeyboardTapRecognizer: UITapGestureRecognizer? } public var keyboardStatus: NSString? { get { return objc_getAssociatedObject(self, &Properties.keyboardStatus) as? NSString } set(newValue) { objc_setAssociatedObject(self, &Properties.keyboardStatus, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } } public var originalInset: NSValue? { get { return objc_getAssociatedObject(self, &Properties.originalInset) as? NSValue } set(newValue) { objc_setAssociatedObject(self, &Properties.originalInset, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } } public var tabBarHeight: CGFloat { get { if let value = objc_getAssociatedObject(self, &Properties.tabBarHeight) as? CGFloat { return value } else { return 0 } } set(newValue) { objc_setAssociatedObject(self, &Properties.tabBarHeight, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY) } } public var outsideKeyboardTapRecognizer: UITapGestureRecognizer? { get { return objc_getAssociatedObject(self, &Properties.outsideKeyboardTapRecognizer) as? UITapGestureRecognizer } set(newValue) { objc_setAssociatedObject(self, &Properties.outsideKeyboardTapRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } public func bs_setKeyboardNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(bs_keyboardWillAppear(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object:nil ) NotificationCenter.default.addObserver(self, selector: #selector(bs_keyboardDidAppear(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object:nil ) NotificationCenter.default.addObserver(self, selector: #selector(bs_keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object:nil ) } public func bs_unsetKeyboardNotifications() { self.dismissKeyboard(nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object:nil ) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object:nil ) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object:nil ) } public func bs_keyboardWillAppear(notification: NSNotification) { if self.outsideKeyboardTapRecognizer == nil { self.outsideKeyboardTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard(_:))) } if let recognizer = self.outsideKeyboardTapRecognizer { self.view.addGestureRecognizer(recognizer) } self.keyboardWillAppear(notification: notification) self.moveScrollViewForKeyboardUp(notification: notification) } public func keyboardWillAppear(notification: NSNotification) { } public func bs_keyboardDidAppear(notification: NSNotification) { self.keyboardDidAppear(notification: notification) } public func keyboardDidAppear(notification: NSNotification) { } public func bs_keyboardWillHide(notification: NSNotification) { if let recognizer = self.outsideKeyboardTapRecognizer { self.view.removeGestureRecognizer(recognizer) } self.keyboardWillDisappear(notification: notification) self.moveScrollViewForKeyboardDown(notification: notification) } public func keyboardWillDisappear(notification: NSNotification) { } public func dismissKeyboard(_ sender: AnyObject?) { self.view.endEditing(true) } public func moveScrollViewForKeyboardUp(notification: NSNotification) { if keyboardStatus == "up" { return } if let scrollView = getScrollView() { originalInset = NSValue(uiEdgeInsets: scrollView.contentInset) var inset = scrollView.contentInset inset.bottom -= tabBarHeight scrollView.contentInset = inset let userInfo = notification.userInfo // Get animation info from userInfo // let animationCurve = (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).integerValue let animationCurve = UIViewAnimationCurve.easeInOut.rawValue let animationDuration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let keyboardSize = (userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size // Animate up or down UIView.beginAnimations(nil, context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: animationCurve)!) var newInset = scrollView.contentInset newInset.bottom += keyboardSize.height scrollView.contentInset = newInset UIView.commitAnimations() scrollView.scrollIndicatorInsets = scrollView.contentInset keyboardStatus = "up" } } public func moveScrollViewForKeyboardDown(notification: NSNotification) { if keyboardStatus == "down" { return } if let scrollView = getScrollView() { let userInfo = notification.userInfo // Get animation info from userInfo // let animationCurve = (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as NSNumber).integerValue let animationCurve = UIViewAnimationCurve.easeInOut.rawValue let animationDuration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue // let keyboardSize = (userInfo?[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size // Animate up or down UIView.beginAnimations(nil, context: nil) UIView.setAnimationBeginsFromCurrentState(true) UIView.setAnimationDuration(animationDuration) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: animationCurve)!) if let inset = self.originalInset { scrollView.contentInset = inset.uiEdgeInsetsValue } var inset = scrollView.contentInset inset.bottom -= tabBarHeight scrollView.contentInset = inset UIView.commitAnimations() if let inset = self.originalInset { scrollView.contentInset = inset.uiEdgeInsetsValue } scrollView.scrollIndicatorInsets = scrollView.contentInset originalInset = nil keyboardStatus = "down" } } public func getScrollView() -> UIScrollView? { if let tc = self as? UITableViewController { return tc.tableView } for subview in self.view.subviews { if subview is UIScrollView { return subview as? UIScrollView } } return nil } } #endif
mit
a4d8ffdc7591c9c03ed533c1152a3278
40.413636
172
0.58841
6.447983
false
false
false
false
BrandonMA/SwifterUI
SwifterUI/SwifterUI/UILibrary/Controllers/SFPDFViewController.swift
1
2263
// // SFPDFViewController.swift // SwifterUI // // Created by brandon maldonado alonso on 15/05/18. // Copyright © 2018 Brandon Maldonado Alonso. All rights reserved. // import UIKit import PDFKit open class SFPDFViewController: SFViewController { // MARK: - Instance Properties public lazy var pdfView: PDFView = { let view = PDFView() return view }() var pdfURL: URL! // MARK: - Initializers public init(data: Data, automaticallyAdjustsColorStyle: Bool = true) { super.init(automaticallyAdjustsColorStyle: automaticallyAdjustsColorStyle) let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(UUID().uuidString) FileManager.default.createFile(atPath: path, contents: data, attributes: nil) pdfURL = URL(fileURLWithPath: path) pdfView.document = PDFDocument(url: pdfURL) } public init(url: URL, automaticallyAdjustsColorStyle: Bool = true) { self.pdfURL = url super.init(automaticallyAdjustsColorStyle: automaticallyAdjustsColorStyle) pdfView.document = PDFDocument(url: pdfURL) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Instance Methods open override func viewWillPrepareSubViews() { view.addSubview(pdfView) pdfView.autoScales = true super.viewWillPrepareSubViews() } open override func viewWillSetConstraints() { pdfView.clipSides() super.viewWillSetConstraints() } open override func prepare(navigationController: UINavigationController) { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(shareButtonDidTouch)) } @objc public final func shareButtonDidTouch() { let activityViewController = UIActivityViewController(activityItems: [pdfURL as Any], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = view // iPads won't crash present(activityViewController, animated: true, completion: nil) } }
mit
0777a92eec320b75fb1a9bc9bf4925ca
33.8
156
0.695402
5.272727
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModelTests/Days/WhenFetchingDaysBeforeRefreshWhenStoreHasConferenceDays.swift
1
694
import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class WhenFetchingDaysBeforeRefreshWhenStoreHasConferenceDays: XCTestCase { func testTheEventsFromTheStoreAreAdapted() { let response = ModelCharacteristics.randomWithoutDeletions let dataStore = InMemoryDataStore(response: response) let context = EurofurenceSessionTestBuilder().with(dataStore).build() let delegate = CapturingEventsScheduleDelegate() let schedule = context.eventsService.makeEventsSchedule() schedule.setDelegate(delegate) DayAssertion() .assertDays(delegate.allDays, characterisedBy: response.conferenceDays.changed) } }
mit
5851bf622fb9d8deb9d469b37680f64c
35.526316
91
0.763689
5.831933
false
true
false
false
ALiOSDev/ALTableView
ALTableViewSwift/Pods/SwipeCellKit/Source/Extensions.swift
1
2604
// // Extensions.swift // // Created by Jeremy Koch // Copyright © 2017 Jeremy Koch. All rights reserved. // import UIKit extension UITableView { var swipeCells: [SwipeTableViewCell] { return visibleCells.compactMap({ $0 as? SwipeTableViewCell }) } func hideSwipeCell() { swipeCells.forEach { $0.hideSwipe(animated: true) } } } extension UICollectionView { var swipeCells: [SwipeCollectionViewCell] { return visibleCells as? [SwipeCollectionViewCell] ?? [] } func hideSwipeCell() { swipeCells.forEach { $0.hideSwipe(animated: true) } } func setGestureEnabled(_ enabled: Bool) { gestureRecognizers?.forEach { guard $0 != panGestureRecognizer else { return } $0.isEnabled = enabled } } } extension UIScrollView { var swipeables: [Swipeable] { switch self { case let tableView as UITableView: return tableView.swipeCells case let collectionView as UICollectionView: return collectionView.swipeCells default: return [] } } func hideSwipeables() { switch self { case let tableView as UITableView: tableView.hideSwipeCell() case let collectionView as UICollectionView: collectionView.hideSwipeCell() default: return } } } extension UIPanGestureRecognizer { func elasticTranslation(in view: UIView?, withLimit limit: CGSize, fromOriginalCenter center: CGPoint, applyingRatio ratio: CGFloat = 0.20) -> CGPoint { let translation = self.translation(in: view) guard let sourceView = self.view else { return translation } let updatedCenter = CGPoint(x: center.x + translation.x, y: center.y + translation.y) let distanceFromCenter = CGSize(width: abs(updatedCenter.x - sourceView.bounds.midX), height: abs(updatedCenter.y - sourceView.bounds.midY)) let inverseRatio = 1.0 - ratio let scale: (x: CGFloat, y: CGFloat) = (updatedCenter.x < sourceView.bounds.midX ? -1 : 1, updatedCenter.y < sourceView.bounds.midY ? -1 : 1) let x = updatedCenter.x - (distanceFromCenter.width > limit.width ? inverseRatio * (distanceFromCenter.width - limit.width) * scale.x : 0) let y = updatedCenter.y - (distanceFromCenter.height > limit.height ? inverseRatio * (distanceFromCenter.height - limit.height) * scale.y : 0) return CGPoint(x: x, y: y) } }
mit
d80c8bf1ffdf8d60045ff01087c1504d
31.135802
156
0.618901
4.574692
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/Pods/CryptoSwift/Sources/CryptoSwift/MD5.swift
9
6120
// // MD5.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 06/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // public final class MD5: DigestType { static let blockSize: Int = 64 static let digestLength: Int = 16 // 128 / 8 fileprivate static let hashInitialValue: Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] fileprivate var accumulated = Array<UInt8>() fileprivate var processedBytesTotalCount: Int = 0 fileprivate var accumulatedHash: Array<UInt32> = MD5.hashInitialValue /** specifies the per-round shift amounts */ private let s: Array<UInt32> = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let k: Array<UInt32> = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] public init() { } public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> { do { return try self.update(withBytes: bytes, isLast: true) } catch { fatalError() } } // mutating currentHash in place is way faster than returning new result fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash: inout Array<UInt32>) { assert(chunk.count == 16 * 4) // Initialize hash value for this chunk: var A: UInt32 = currentHash[0] var B: UInt32 = currentHash[1] var C: UInt32 = currentHash[2] var D: UInt32 = currentHash[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< k.count { var g = 0 var F: UInt32 = 0 switch (j) { case 0 ... 15: F = (B & C) | ((~B) & D) g = j break case 16 ... 31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32 ... 47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48 ... 63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 and get M[g] value let gAdvanced = g << 2 var Mg = UInt32(chunk[chunk.startIndex &+ gAdvanced]) | UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 1]) << 8 | UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 2]) << 16 Mg = Mg | UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 3]) << 24 B = B &+ rotateLeft(A &+ F &+ k[j] &+ Mg, by: s[j]) A = dTemp } currentHash[0] = currentHash[0] &+ A currentHash[1] = currentHash[1] &+ B currentHash[2] = currentHash[2] &+ C currentHash[3] = currentHash[3] &+ D } } extension MD5: Updatable { public func update<T: Collection>(withBytes bytes: T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 { self.accumulated += bytes if isLast { let lengthInBits = (self.processedBytesTotalCount + self.accumulated.count) * 8 let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b // Step 1. Append padding bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8) // Step 2. Append Length a 64-bit representation of lengthInBits self.accumulated += lengthBytes.reversed() } var processedBytes = 0 for chunk in self.accumulated.batched(by: MD5.blockSize) { if (isLast || (self.accumulated.count - processedBytes) >= MD5.blockSize) { self.process(block: chunk, currentHash: &self.accumulatedHash) processedBytes += chunk.count } } self.accumulated.removeFirst(processedBytes) self.processedBytesTotalCount += processedBytes // output current hash var result = Array<UInt8>() result.reserveCapacity(MD5.digestLength) for hElement in self.accumulatedHash { let hLE = hElement.littleEndian result += [UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff)] } // reset hash value for instance if isLast { self.accumulatedHash = MD5.hashInitialValue } return result } }
mit
7d90212df4b779143b3fbfae0d6f80b8
39.236842
180
0.518149
3.660084
false
false
false
false
DaftMobile/ios4beginners_2017
Class 2/Intermediate Swift.playground/Pages/Structs.xcplaygroundpage/Contents.swift
1
1147
//: [Previous](@previous) import Foundation //: ## Basic Structs and mutability struct Point { //: Try changing x and y to let constants and see what happens var x: Double var y: Double init(x: Double, y: Double) { self.x = x self.y = y } } /// This defines a constant point (it cannot be changed) let point1: Point = Point(x: 10.0, y: 10.0) //: Not possible: cannot mutate a let constant //point1.x = 12.0 /// This is a Point variable, so we'll be able to mutate it var point2 = Point(x: 1.0, y: 1.0) point2.x = 15.0 //: ## Initializers, computed properties struct Size { var width: Double var height: Double /// This is the main initializer /// /// - Parameters: /// - width: width of the size /// - height: height of the size init(width: Double, height: Double) { self.width = width self.height = height } /// Initializes a square size /// /// - Parameter side: both width and height of the new size init(side: Double) { self.width = side self.height = side } //: This is a computed property /// Computes the area of the size var area: Double { return width * height } } //: [Next](@next)
apache-2.0
a73f9e4d59577b66ecef24322387a96d
18.116667
63
0.646905
3.1
false
false
false
false
Drakken-Engine/GameEngine
DrakkenEngine_Editor/ProjectFolderView.swift
1
13071
// // ProjectFolderView.swift // DrakkenEngine // // Created by Allison Lindner on 18/10/16. // Copyright © 2016 Drakken Studio. All rights reserved. // import Cocoa public let SCRIPT_PASTEBOARD_TYPE = "drakkenengine.projectfolder.item.script" public let IMAGE_PASTEBOARD_TYPE = "drakkenengine.projectfolder.item.image" public let SPRITEDEF_PASTEBOARD_TYPE = "drakkenengine.projectfolder.item.spritedef" internal class FolderItem: NSObject { var icon: NSImage var name: String var url: URL var children: [FolderItem] internal init(icon: NSImage, name: String, url: URL, children: [FolderItem]) { self.icon = icon self.name = name self.url = url self.children = children super.init() } } fileprivate class RootItem: FolderItem {} class ProjectFolderView: NSOutlineView, NSOutlineViewDataSource, NSOutlineViewDelegate, NSPasteboardItemDataProvider, NSMenuDelegate { let appDelegate = NSApplication.shared().delegate as! AppDelegate var draggedItem: FolderItem? private var itens: [RootItem] = [RootItem]() override func awakeFromNib() { setup() } private func setup() { self.dataSource = self self.delegate = self doubleAction = #selector(self.doubleActionSelector) self.register(forDraggedTypes: [SCRIPT_PASTEBOARD_TYPE, IMAGE_PASTEBOARD_TYPE]) } override func draw(_ dirtyRect: NSRect) { if self.tableColumns[0].headerCell.controlView != nil { if self.tableColumns[0].headerCell.controlView!.frame.width != superview!.frame.width - 3 { self.tableColumns[0].headerCell.controlView!.setFrameSize( NSSize(width: superview!.frame.width - 3, height: self.tableColumns[0].headerCell.controlView!.frame.size.height) ) self.tableColumns[0].sizeToFit() } } super.draw(dirtyRect) } internal func doubleActionSelector() { if let item = self.item(atRow: clickedRow) as? FolderItem { let url = item.url if NSApplication.shared().mainWindow!.contentViewController is EditorViewController { let editorVC = NSApplication.shared().mainWindow!.contentViewController as! EditorViewController if url.pathExtension == "dkscene" { editorVC.currentSceneURL = url editorVC.editorView.scene.DEBUG_MODE = false editorVC.editorView.scene.load(url: url) editorVC.editorView.Init() editorVC.transformsView.reloadData() editorVC.selectedTransform = nil editorVC.inspectorView.reloadData() } else if url.pathExtension == "js" { NSWorkspace.shared().open(url) } else if url.isFileURL { if NSImage(contentsOf: url) != nil { NSWorkspace.shared().open(url) } } } } } internal func loadData(for url: URL) { let rootItens = getItens(from: url) itens.removeAll() for i in rootItens { let rootItem = RootItem(icon: i.icon, name: i.name, url: i.url, children: [FolderItem]()) itens.append(rootItem) loadItem(from: i.url, at: rootItem) } self.reloadData() } private func loadItem(from url: URL, at: FolderItem) { let contentItens = getItens(from: url) for i in contentItens { let item = FolderItem(icon: i.icon, name: i.name, url: i.url, children: [FolderItem]()) at.children.append(item) loadItem(from: i.url, at: item) } } internal func getItens(from url: URL) -> [(icon: NSImage, name: String, url: URL)] { if !url.hasDirectoryPath { return [] } let fileManager = FileManager() var contentItens = [(icon: NSImage, name: String, url: URL)]() let enumerator = fileManager.enumerator(at: url, includingPropertiesForKeys: [URLResourceKey.effectiveIconKey,URLResourceKey.localizedNameKey], options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles .union(FileManager.DirectoryEnumerationOptions.skipsSubdirectoryDescendants) .union(FileManager.DirectoryEnumerationOptions.skipsPackageDescendants), errorHandler: { (u, error) -> Bool in NSLog("URL: \(u.path) - Error: \(error)") return false }) while let u = enumerator?.nextObject() as? URL { do{ let properties = try u.resourceValues(forKeys: [URLResourceKey.effectiveIconKey,URLResourceKey.localizedNameKey]).allValues let icon = properties[URLResourceKey.effectiveIconKey] as? NSImage ?? NSImage() let name = properties[URLResourceKey.localizedNameKey] as? String ?? " " contentItens.append((icon: icon, name: name, url: u)) } catch { NSLog("Error reading file attributes") } } return contentItens } func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { if item != nil { if let i = item as? FolderItem { return i.children.count } } return itens.count } func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { if item != nil { if let i = item as? FolderItem { return i.children[index] } } return itens[index] } func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { if let i = item as? FolderItem { return i.children.count > 0 } return false } func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? { var image:NSImage? var text:String = "" var cellIdentifier: String = "" if let i = item as? FolderItem { if tableColumn == outlineView.tableColumns[0] { image = i.icon text = i.name cellIdentifier = "FolderItemID" } if let cell = outlineView.make(withIdentifier: cellIdentifier, owner: nil) as? PFolderItemCell { cell.textField?.stringValue = text cell.imageView?.image = image ?? nil cell.folderItem = i return cell } } return nil } func outlineViewSelectionDidChange(_ notification: Notification) { if let item = item(atRow: selectedRow) as? FolderItem { if item.url.pathExtension == "dksprite" { appDelegate.editorViewController?.selectedSpriteDef = item.url appDelegate.editorViewController?.selectedTransform = nil appDelegate.editorViewController?.transformsView.deselectAll(nil) appDelegate.editorViewController?.inspectorView.reloadData() } else { if appDelegate.editorViewController?.selectedSpriteDef != nil { appDelegate.editorViewController?.selectedSpriteDef = nil appDelegate.editorViewController?.inspectorView.reloadData() } } } else { if appDelegate.editorViewController?.selectedSpriteDef != nil { appDelegate.editorViewController?.selectedSpriteDef = nil appDelegate.editorViewController?.inspectorView.reloadData() } } if selectedRow >= 0 { if let cell = self.view(atColumn: selectedColumn, row: selectedRow, makeIfNecessary: false) as? PFolderItemCell { appDelegate.editorViewController?.selectedFolderItem = cell.folderItem } } else { appDelegate.editorViewController?.selectedFolderItem = nil } } //MARK: Drag and Drop Setup func outlineView(_ outlineView: NSOutlineView, pasteboardWriterForItem item: Any) -> NSPasteboardWriting? { draggedItem = item as? FolderItem var pbItem: NSPasteboardItem? = nil if draggedItem!.url.pathExtension == "js" { pbItem = NSPasteboardItem() pbItem!.setDataProvider(self, forTypes: [SCRIPT_PASTEBOARD_TYPE]) } else if NSImage(contentsOf: draggedItem!.url) != nil { pbItem = NSPasteboardItem() pbItem!.setDataProvider(self, forTypes: [IMAGE_PASTEBOARD_TYPE]) } else if draggedItem!.url.pathExtension == "dksprite" { pbItem = NSPasteboardItem() pbItem!.setDataProvider(self, forTypes: [SPRITEDEF_PASTEBOARD_TYPE]) } return pbItem } func outlineView(_ outlineView: NSOutlineView, draggingSession session: NSDraggingSession, willBeginAt screenPoint: NSPoint, forItems draggedItems: [Any]) { draggedItem = draggedItems[0] as? FolderItem if draggedItem!.url.pathExtension == "js" { appDelegate.editorViewController?.draggedScript = draggedItem!.url.deletingPathExtension().lastPathComponent session.draggingPasteboard.setString(draggedItem!.url.deletingPathExtension().lastPathComponent, forType: SCRIPT_PASTEBOARD_TYPE) } else if NSImage(contentsOf: draggedItem!.url) != nil { _ = dTexture(draggedItem!.url.lastPathComponent) let spriteDef = dSpriteDef(draggedItem!.url.lastPathComponent, texture: draggedItem!.url.lastPathComponent) DrakkenEngine.Register(sprite: spriteDef) DrakkenEngine.Setup() appDelegate.editorViewController?.draggedImage = draggedItem!.url.lastPathComponent session.draggingPasteboard.setString(draggedItem!.url.lastPathComponent, forType: IMAGE_PASTEBOARD_TYPE) } else if draggedItem!.url.pathExtension == "dksprite" { appDelegate.editorViewController?.draggedSpriteDef = dSpriteDef(json: draggedItem!.url) session.draggingPasteboard.setString(draggedItem!.url.lastPathComponent, forType: SPRITEDEF_PASTEBOARD_TYPE) } } func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: String) { if draggedItem!.url.pathExtension == "js" { item.setString(draggedItem!.url.deletingPathExtension().lastPathComponent, forType: SCRIPT_PASTEBOARD_TYPE) } else if NSImage(contentsOf: draggedItem!.url) != nil { item.setString(draggedItem!.url.lastPathComponent, forType: IMAGE_PASTEBOARD_TYPE) } else if draggedItem!.url.pathExtension == "dksprite" { item.setString(draggedItem!.url.lastPathComponent, forType: SPRITEDEF_PASTEBOARD_TYPE) } } //Mark: Menu override func menu(for event: NSEvent) -> NSMenu? { if becomeFirstResponder() { let point = NSApplication.shared().mainWindow!.contentView!.convert(event.locationInWindow, to: self) let column = self.column(at: point) let row = self.row(at: point) if column >= 0 && row >= 0 { if let cell = self.view(atColumn: column, row: row, makeIfNecessary: false) as? PFolderItemCell { if NSImage(contentsOf: cell.folderItem.url) != nil { NSLog("\(cell.folderItem.name)") if self.selectedRow != row { self.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false) } if let menu = cell.menu as? ImageMenu { menu.selectedFolderItem = cell.folderItem return menu } return nil } } } } return nil } }
gpl-3.0
13199106d71a766f50e5b8ef13292497
39.590062
160
0.56205
5.217565
false
false
false
false
jay18001/brickkit-ios
Source/Behaviors/OffsetLayoutBehavior.swift
1
3719
// // OffsetLayoutBehavior.swift // BrickKit // // Created by Justin Shiiba on 6/8/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // import UIKit public protocol OffsetLayoutBehaviorDataSource: class { func offsetLayoutBehaviorWithOrigin(_ behavior: OffsetLayoutBehavior, originOffsetForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGSize? func offsetLayoutBehavior(_ behavior: OffsetLayoutBehavior, sizeOffsetForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGSize? } open class OffsetLayoutBehavior: BrickLayoutBehavior { weak var dataSource: OffsetLayoutBehaviorDataSource? fileprivate(set) var offsetZIndex = 100 var offsetAttributes: [BrickLayoutAttributes] = [] public init(dataSource: OffsetLayoutBehaviorDataSource) { self.dataSource = dataSource } open override func resetRegisteredAttributes(_ collectionViewLayout: UICollectionViewLayout) { super.resetRegisteredAttributes(collectionViewLayout) offsetAttributes = [] } open override func registerAttributes(_ attributes: BrickLayoutAttributes, for collectionViewLayout: UICollectionViewLayout) { if let _ = dataSource?.offsetLayoutBehaviorWithOrigin(self, originOffsetForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout) { offsetAttributes.append(attributes) } if let _ = dataSource?.offsetLayoutBehavior(self, sizeOffsetForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout) { offsetAttributes.append(attributes) } } open override func invalidateInCollectionViewLayout(_ collectionViewLayout: UICollectionViewLayout, contentSize: inout CGSize, attributesDidUpdate: (_ attributes: BrickLayoutAttributes, _ oldFrame: CGRect?) -> Void) { offsetAttributesInCollectionView(collectionViewLayout, attributesDidUpdate: attributesDidUpdate) } fileprivate func offsetAttributesInCollectionView(_ collectionViewLayout: UICollectionViewLayout, attributesDidUpdate: (_ attributes: BrickLayoutAttributes, _ oldFrame: CGRect?) -> Void) { guard let _ = collectionViewLayout.collectionView , !offsetAttributes.isEmpty else { return } for attributes in offsetAttributes { // Only set attribute's Offset once guard !attributes.isHidden else { continue } let oldFrame = attributes.frame var currentFrame = attributes.originalFrame if let sizeOffset = dataSource?.offsetLayoutBehavior(self, sizeOffsetForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout) { currentFrame?.size = CGSize(width: (currentFrame?.size.width)! + sizeOffset.width, height: (currentFrame?.size.height)! + sizeOffset.height) } if let originOffset = dataSource?.offsetLayoutBehaviorWithOrigin(self, originOffsetForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout) { currentFrame = currentFrame?.offsetBy(dx: originOffset.width, dy: originOffset.height) } if currentFrame != attributes.frame { attributes.frame = currentFrame! attributesDidUpdate(attributes, oldFrame) } } } }
apache-2.0
ba4e1123e02126fb79c2fc95191a84da
47.921053
241
0.741259
6.085106
false
false
false
false
jawwad/swift-algorithm-club
Multiset/Multiset.playground/Sources/Multiset.swift
3
1744
// // Multiset.swift // Multiset // // Created by Simon Whitaker on 28/08/2017. // import Foundation public struct Multiset<T: Hashable> { private var storage: [T: UInt] = [:] public private(set) var count: UInt = 0 public init() {} public init<C: Collection>(_ collection: C) where C.Element == T { for element in collection { self.add(element) } } public mutating func add (_ elem: T) { storage[elem, default: 0] += 1 count += 1 } public mutating func remove (_ elem: T) { if let currentCount = storage[elem] { if currentCount > 1 { storage[elem] = currentCount - 1 } else { storage.removeValue(forKey: elem) } count -= 1 } } public func isSubSet (of superset: Multiset<T>) -> Bool { for (key, count) in storage { let supersetcount = superset.storage[key] ?? 0 if count > supersetcount { return false } } return true } public func count(for key: T) -> UInt { return storage[key] ?? 0 } public var allItems: [T] { var result = [T]() for (key, count) in storage { for _ in 0 ..< count { result.append(key) } } return result } } // MARK: - Equatable extension Multiset: Equatable { public static func == (lhs: Multiset<T>, rhs: Multiset<T>) -> Bool { if lhs.storage.count != rhs.storage.count { return false } for (lkey, lcount) in lhs.storage { let rcount = rhs.storage[lkey] ?? 0 if lcount != rcount { return false } } return true } } // MARK: - ExpressibleByArrayLiteral extension Multiset: ExpressibleByArrayLiteral { public init(arrayLiteral elements: T...) { self.init(elements) } }
mit
a2b9c6c06d072a174c6ec5f4904a8d84
19.761905
70
0.585436
3.648536
false
false
false
false
gcba/hermes
sdks/swift/RatingsSDK/RatingsUser.swift
1
784
// // RatingsUser.swift // RatingsSDK // // Created by Rita Zerrizuela on 10/13/17. // Copyright © 2017 GCBA. All rights reserved. // import Foundation public struct RatingsUser { public let name: String public let email: String? public let mibaId: String? public init(name: String, email: String? = nil, mibaId: String? = nil) { self.name = name self.email = email self.mibaId = mibaId } public func toDict() -> [String: String] { var user: [String: String] = [:] user["name"] = name if let mibaId = mibaId { user["mibaId"] = mibaId } if let email = email { user["email"] = email } return user } }
mit
f3065ee0aef60c5f30763656cc5e55d7
20.162162
76
0.526181
3.764423
false
false
false
false
DAloG/BlueCap
BlueCapKit/Central/BCErrors.swift
1
3167
// // Errors.swift // BlueCap // // Created by Troy Stribling on 7/5/14. // Copyright (c) 2014 Troy Stribling. The MIT License (MIT). // import Foundation public enum CharacteristicError : Int { case ReadTimeout = 1 case WriteTimeout = 2 case NotSerializable = 3 case ReadNotSupported = 4 case WriteNotSupported = 5 } public enum PeripheralError : Int { case DiscoveryTimeout = 20 case Disconnected = 21 case NoServices = 22 } public enum PeripheralManagerError : Int { case IsAdvertising = 40 case IsNotAdvertising = 41 case AddServiceFailed = 42 } public enum CentralError : Int { case IsScanning = 50 } public struct BCError { public static let domain = "BlueCap" public static let characteristicReadTimeout = NSError(domain:domain, code:CharacteristicError.ReadTimeout.rawValue, userInfo:[NSLocalizedDescriptionKey:"Characteristic read timeout"]) public static let characteristicWriteTimeout = NSError(domain:domain, code:CharacteristicError.WriteTimeout.rawValue, userInfo:[NSLocalizedDescriptionKey:"Characteristic write timeout"]) public static let characteristicNotSerilaizable = NSError(domain:domain, code:CharacteristicError.NotSerializable.rawValue, userInfo:[NSLocalizedDescriptionKey:"Characteristic not serializable"]) public static let characteristicReadNotSupported = NSError(domain:domain, code:CharacteristicError.ReadNotSupported.rawValue, userInfo:[NSLocalizedDescriptionKey:"Characteristic read not supported"]) public static let characteristicWriteNotSupported = NSError(domain:domain, code:CharacteristicError.WriteNotSupported.rawValue, userInfo:[NSLocalizedDescriptionKey:"Characteristic write not supported"]) public static let peripheralDisconnected = NSError(domain:domain, code:PeripheralError.Disconnected.rawValue, userInfo:[NSLocalizedDescriptionKey:"Peripheral disconnected timeout"]) public static let peripheralDiscoveryTimeout = NSError(domain:domain, code:PeripheralError.DiscoveryTimeout.rawValue, userInfo:[NSLocalizedDescriptionKey:"Peripheral discovery Timeout"]) public static let peripheralNoServices = NSError(domain:domain, code:PeripheralError.NoServices.rawValue, userInfo:[NSLocalizedDescriptionKey:"Peripheral services not found"]) public static let peripheralManagerIsAdvertising = NSError(domain:domain, code:PeripheralManagerError.IsAdvertising.rawValue, userInfo:[NSLocalizedDescriptionKey:"Peripheral Manager is Advertising"]) public static let peripheralManagerIsNotAdvertising = NSError(domain:domain, code:PeripheralManagerError.IsNotAdvertising.rawValue, userInfo:[NSLocalizedDescriptionKey:"Peripheral Manager is not Advertising"]) public static let peripheralManagerAddServiceFailed = NSError(domain:domain, code:PeripheralManagerError.AddServiceFailed.rawValue, userInfo:[NSLocalizedDescriptionKey:"Add service failed because service peripheral is advertising"]) public static let centralIsScanning = NSError(domain:domain, code:CentralError.IsScanning.rawValue, userInfo:[NSLocalizedDescriptionKey:"Central is scanning"]) }
mit
9e24f86ea4601c00761584c55993e19e
56.581818
236
0.792548
5.441581
false
false
false
false
sina-kh/Swift-Auto-Image-Flipper
AutoImageFlipper/Classes/AutoImageFlipper.swift
1
7497
// // AutoImageFlipper.swift // Auto Image Flipper v0.8.2 // // Created by Sina Khalili on 5/20/16. // Copyright © 2016 Sina Khalili. All rights reserved. // import UIKit public class AutoImageFlipper: UIView { private var imageView1 = UIImageView() private var imageView2 = UIImageView() private var visibleImageView = 1 public private(set) var images = [UIImage]() public private(set) var lastPlayed = -1 public private(set) var showingImage = -1 public var imageViewAlpha: CGFloat = 0.7 private var ratioValue: CGFloat = 4/3 public var ratio : CGFloat { set { ratioValue = newValue setupRatio() } get { return ratioValue } } public var fadeInTimeValue: Double = 3 public var fadeInTime : Double { set { if newValue < showTime - fadeOutTime { fadeInTimeValue = newValue } else { print("`FadeInTime` can't be lower than `ShowTime` - `FadeOutTime`") } } get { return fadeInTimeValue } } public var fadeOutTimeValue: Double = 3 public var fadeOutTime : Double { set { if newValue < showTime - fadeInTime { fadeOutTimeValue = newValue } else { print("`FadeOutTime` can't be lower than `ShowTime` - `FadeInTime`") } } get { return fadeOutTimeValue } } public var showTimeValue: Double = 10 public var showTime : Double { set { if newValue < fadeInTime + fadeOutTime { showTimeValue = newValue } else { print("`ShowTime` can't be lower than `FadeInTime` + `FadeOutTime`") } } get { return showTimeValue } } public var moveDirection = AutoImageFlipperMoveDirection.Left public var delegate: AutoImageFlipperDelegate? override init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { backgroundColor = UIColor.blackColor() addSubview(imageView1) addSubview(imageView2) setupRatio() } private func setupRatio() { imageView1.stopAnimating() imageView1.alpha = 0 imageView2.stopAnimating() imageView2.alpha = 0 imageView1.frame = CGRect(x: 0, y: 0, width: self.frame.height * ratio, height: self.frame.height) imageView2.frame = imageView1.frame } /** Prints Log if isInDebugMode - parameter string: Log */ let isInDebugMode = false private func printIt(string: String) { if isInDebugMode { print(string) } } /** Run something with delay - parameter delay: delay time in seconds - parameter closure: closure */ private func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } /** Plays the animation of the imageView after setting it's image - parameter imageView: imageView to play the animation on - parameter image: the image to show */ private func playImage(imageView: UIImageView, image: UIImage) { // setting properties imageView.image = image if delegate != nil { delegate!.autoImageFlipper?(self, willPlayImage: image, onImageView: imageView) } printIt("AIF: willPlayImage on imageView") // moving animation if moveDirection == .Left { imageView.frame.origin.x = 0 } else { imageView.frame.origin.x = -((self.frame.height * self.ratio) - self.frame.width) } UIView.animateWithDuration(self.showTime, delay: 0.0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in if self.moveDirection == .Left { imageView.frame.origin.x = -((self.frame.height * self.ratio) - self.frame.width) } else { imageView.frame.origin.x = 0 } }, completion: { (finished: Bool) -> Void in }) // fade in animation imageView.alpha = 0 UIView.animateWithDuration(self.fadeInTime, delay: 0.0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in imageView.alpha = self.imageViewAlpha }, completion: nil) delay(self.showTime - fadeOutTime) { // fade out animation UIView.animateWithDuration(self.fadeOutTime, delay: 0, options: UIViewAnimationOptions.TransitionNone, animations: { () -> Void in imageView.alpha = 0 }, completion: { (finished: Bool) -> Void in if finished { if self.delegate != nil { self.delegate!.autoImageFlipper?(self, didPlayImage: image) } } }) // play next self.playNext() } } /** *** PUBLIC API *** Plays next image on the screen (and plays first image on start) */ public func playNext() { // Check if delegate pushes any image to show var image: UIImage? = delegate?.autoImageFlipper(self, lastPlayed: showingImage) // If nothing is pushed from delegate, check for images if image == nil { if images.count == 0 { return } if lastPlayed < images.count - 1 { lastPlayed += 1 } else { lastPlayed = 0 } image = images[lastPlayed] showingImage = lastPlayed } else { showingImage = -1 } // Now play next printIt("AIF now play next") if visibleImageView == 1 { visibleImageView = 2 playImage(imageView2, image: image!) } else { visibleImageView = 1 playImage(imageView1, image: image!) } } /** *** PUBLIC API *** Add image to show - parameter image: image */ public func addImage(image: UIImage) { images.append(image) } /** *** PUBLIC API *** Remove image at index - parameter index: index - returns: Success */ public func removeImageAtIndex(index: Int) -> Bool { if images.count > index { images.removeAtIndex(index) return true } return false } /** *** PUBLIC API *** Remove all images */ public func removeAllImages() { images.removeAll() } } public enum AutoImageFlipperMoveDirection: Int { case Left = -1, Right = 1 }
mit
87d6df963acd366947ee4e6410f83b03
25.121951
142
0.520144
5.082034
false
false
false
false
exoplatform/exo-ios
eXo/Sources/Controllers/HomePage/PreviewController.swift
1
3810
// Copyright (C) 2003-2015 eXo Platform SAS. // // This is free software; you can redistribute it and/or modify it // under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of // the License, or (at your option) any later version. // // This software is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this software; if not, write to the Free // Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA // 02110-1301 USA, or see the FSF site: http://www.fsf.org. import UIKit import WebKit class PreviewController: eXoWebBaseController, WKNavigationDelegate, WKUIDelegate { // Navigation buttons of the webView @IBOutlet weak var goForwardButton: UIBarButtonItem! @IBOutlet weak var goBackButton: UIBarButtonItem! var isStatusBarHidden = true{ didSet{ self.setNeedsStatusBarAppearanceUpdate() } } // MARK: View Controller lifecycle override func viewDidLoad() { super.viewDidLoad() self.setupWebView(self.view) webView?.navigationDelegate = self webView?.uiDelegate = self goBackButton.isEnabled = false goForwardButton.isEnabled = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isStatusBarHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) isStatusBarHidden = false } override var prefersStatusBarHidden: Bool { return isStatusBarHidden } // MARK: Navigation Action: Close, GoBack, GoForward @IBAction func doneAction(_ sender: AnyObject) { self.navigationController?.dismiss(animated: true, completion: nil) } @IBAction func goBackAction(_ sender: AnyObject) { if (webView != nil && webView?.canGoBack == true) { webView?.goBack() } } @IBAction func forwardAction(_ sender: AnyObject) { if (webView != nil && webView?.canGoForward == true) { webView?.goForward() } } // MARK : WKWebViewDelegate func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.updateNavigationStatus() UIApplication.shared.isNetworkActivityIndicatorVisible = false; } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { UIApplication.shared.isNetworkActivityIndicatorVisible = false; } func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { self.updateNavigationStatus() if !UIApplication.shared.isNetworkActivityIndicatorVisible { UIApplication.shared.isNetworkActivityIndicatorVisible = true; } decisionHandler(.allow) } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { UIApplication.shared.isNetworkActivityIndicatorVisible = false; self.updateNavigationStatus() decisionHandler(WKNavigationResponsePolicy.allow) } func updateNavigationStatus () { self.navigationItem.title = webView!.title goBackButton.isEnabled = webView!.canGoBack goForwardButton.isEnabled = webView!.canGoForward } }
lgpl-3.0
f9c9989d0b13761ee548dff4c7b1ef13
34.607477
163
0.686089
5.42735
false
false
false
false
StorageKit/StorageKit
Example/Source/SubExamples/ToDo App/Components/ToDoAppViewController.swift
1
12050
// // ToDoAppViewController.swift // Example // // Created by Marco Santarossa on 16/07/2017. // Copyright © 2017 MarcoSantaDev. All rights reserved. // import UIKit import StorageKit class ToDoAppViewController: UIViewController { internal var storage: Storage? var storageType: StorageKit.StorageType? @IBOutlet weak var todoTV: UITableView! internal var tasks: [Task] = [] internal var doneTasks: [Task] = [] private let sortDescriptor = SortDescriptor(key: "added", ascending: false) override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) customizeUI() fetchAndUpdate() } override func viewDidLoad() { super.viewDidLoad() if let type = storageType { storage = StorageKit.addStorage(type: type) } } func fetchToDoTasks(storage: Storage, context: StorageContext, storageType: StorageKit.StorageType, dispatchGroup: DispatchGroup) { dispatchGroup.enter() storage.performBackgroundTask {[weak self] bckContext in guard let strongSelf = self, let backgroundContext = bckContext else { return } switch storageType { case .CoreData: do { try backgroundContext.fetch(predicate: NSPredicate(format: "done == false"), sortDescriptors: [strongSelf.sortDescriptor], completion: {[weak self] (fetchedTasks: [ToDoTask]?) in guard self != nil else { dispatchGroup.leave() return } guard let fetchedTasks = fetchedTasks else { return } do { try storage.getThreadSafeEntities(for: context, originalContext: backgroundContext, originalEntities: fetchedTasks, completion: { safeFetchedTaks in self?.tasks = safeFetchedTaks DispatchQueue.main.async { dispatchGroup.leave() } }) } catch {} }) } catch {} case .Realm: do { try backgroundContext.fetch(predicate: NSPredicate(format: "done == false"), sortDescriptors: [strongSelf.sortDescriptor], completion: {[weak self] (fetchedTasks: [RTodoTask]?) in guard self != nil else { dispatchGroup.leave() return } guard let fetchedTasks = fetchedTasks else { return } do { try storage.getThreadSafeEntities(for: context, originalContext: backgroundContext, originalEntities: fetchedTasks, completion: { safeFetchedTaks in self?.tasks = safeFetchedTaks DispatchQueue.main.async { dispatchGroup.leave() } }) } catch {} }) } catch {} } } } func fetchDoneTasks(storage: Storage, context: StorageContext, storageType: StorageKit.StorageType, dispatchGroup: DispatchGroup) { dispatchGroup.enter() storage.performBackgroundTask {[weak self] bckContext in guard let strongSelf = self, let backgroundContext = bckContext else { return } switch storageType { case .CoreData: do { try backgroundContext.fetch(predicate: NSPredicate(format: "done == true"), sortDescriptors: [strongSelf.sortDescriptor], completion: {[weak self] (fetchedTasks: [ToDoTask]?) in guard self != nil else { dispatchGroup.leave() return } guard let fetchedTasks = fetchedTasks else { return } do { try storage.getThreadSafeEntities(for: context, originalContext: backgroundContext, originalEntities: fetchedTasks, completion: { safeFetchedTaks in self?.doneTasks = safeFetchedTaks DispatchQueue.main.async { dispatchGroup.leave() } }) } catch {} }) } catch {} case .Realm: do { try backgroundContext.fetch(predicate: NSPredicate(format: "done == true"), sortDescriptors: [strongSelf.sortDescriptor], completion: {[weak self] (fetchedTasks: [RTodoTask]?) in guard self != nil else { dispatchGroup.leave() return } guard let fetchedTasks = fetchedTasks else { return } do { try storage.getThreadSafeEntities(for: context, originalContext: backgroundContext, originalEntities: fetchedTasks, completion: { safeFetchedTaks in self?.doneTasks = safeFetchedTaks DispatchQueue.main.async { dispatchGroup.leave() } }) } catch {} }) } catch {} } } } func fetchAndUpdate() { if let storage = storage, let context = storage.mainContext, let storageType = storageType { let dispatchGroup = DispatchGroup() self.fetchToDoTasks(storage: storage, context: context, storageType: storageType, dispatchGroup: dispatchGroup) self.fetchDoneTasks(storage: storage, context: context, storageType: storageType, dispatchGroup: dispatchGroup) dispatchGroup.notify(queue: .main, execute: { self.todoTV.reloadData() }) } } private func customizeUI() { let addBtn = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(ToDoAppViewController.navigateToAddView)) self.navigationItem.setRightBarButton(addBtn, animated: false) } func navigateToAddView() { self.performSegue(withIdentifier: "goToAddTaskViewController", sender: nil) } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? AddToDoViewController { controller.storage = self.storage controller.storageType = self.storageType } } } // MARK: - UITableViewDataSource extension ToDoAppViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.tasks.count } else { return self.doneTasks.count } } func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "ToDo" } else if section == 1 { return "Done" } return "" } } // MARK: - UITableViewDelegate extension ToDoAppViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCell", for: indexPath) as? ToDoCell { if indexPath.section == 0 { cell.task = self.tasks[indexPath.row] } else { cell.task = self.doneTasks[indexPath.row] } return cell } return UITableViewCell() } // swiftlint:disable cyclomatic_complexity // swiftlint:disable function_body_length func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { if indexPath.section == 0 { // ToDo Tasks let done = UITableViewRowAction(style: .normal, title: "Done") { _, index in if let storage = self.storage, let context = storage.mainContext, let storageType = self.storageType { do { switch storageType { case .CoreData: guard let task = self.tasks[index.row] as? ToDoTask else { return } try context.update { task.done = true } self.fetchAndUpdate() case .Realm: guard let task = self.tasks[index.row] as? RTodoTask else { return } storage.performBackgroundTask { bckContext in guard let backgroundContext = bckContext else { return } do { try storage.getThreadSafeEntities(for: backgroundContext, originalContext: context, originalEntities: [task]) { safeTask in do { try backgroundContext.update { safeTask.first?.done = true } DispatchQueue.main.async { self.fetchAndUpdate() } } catch {} } } catch {} } } } catch { } } } done.backgroundColor = UIColor.darkGray return [done] } else if indexPath.section == 1 { // Done Tasks let delete = UITableViewRowAction(style: .destructive, title: "Delete") { _, index in if let storage = self.storage, let context = storage.mainContext, let storageType = self.storageType { do { switch storageType { case .CoreData: if let task = self.doneTasks[index.row] as? ToDoTask { try context.delete(task) } case .Realm: if let task = self.doneTasks[index.row] as? RTodoTask { try context.delete(task) } } self.fetchAndUpdate() } catch { } } } return [delete] } return [] } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { // you need to implement this method too or you can't swipe to display the actions } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } }
mit
863eaa7dc4f3446b842581e9e4adb195
38.247557
199
0.486098
6.398832
false
false
false
false
yuenhsi/interactive-bridge
Interactive Bridge/Interactive Bridge/CardImageView.swift
1
1319
// // CardImageView.swift // Interactive Bridge // // Created by Yuen Hsi Chang on 1/24/17. // Copyright © 2017 Yuen Hsi Chang. All rights reserved. // import UIKit class CardImageView: UIImageView { var card: Card? { didSet { if card != nil { self.image = UIImage(named: getCardImageName(card!)) } } } func setCard(_ card: Card?) { self.card = card self.contentMode = .scaleAspectFit self.isUserInteractionEnabled = true } func setFacedownCard(rotated: Bool) { if (rotated) { self.image = UIImage(named: "cardBackRotated") self.contentMode = .scaleAspectFit } else { self.image = UIImage(named: "cardBack") self.contentMode = .scaleAspectFit } } func setLabel(labelText: String) { let label = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width)) label.center = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2) label.textAlignment = .center label.text = labelText label.textColor = UIColor.red label.font = UIFont(name: "AvenirNext-Heavy", size: 40) addSubview(label) } }
mit
095c4f29b4ef38d478453cbf75c13983
24.843137
105
0.559939
4.197452
false
false
false
false
josve05a/wikipedia-ios
FeaturedArticleWidget/FeaturedArticleWidget.swift
2
7015
import UIKit import NotificationCenter import WMF private final class EmptyView: SetupView, Themeable { private let label = UILabel() func apply(theme: Theme) { label.textColor = theme.colors.primaryText } override func setup() { super.setup() label.text = WMFLocalizedString("featured-article-empty-title", value: "No featured article available today", comment: "Title that displays when featured article is not available") label.textAlignment = .center label.numberOfLines = 0 updateFonts() wmf_addSubviewWithConstraintsToEdges(label) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateFonts() } private func updateFonts() { label.font = UIFont.wmf_font(.headline, compatibleWithTraitCollection: traitCollection) } } class FeaturedArticleWidget: ExtensionViewController, NCWidgetProviding { let collapsedArticleView = ArticleRightAlignedImageCollectionViewCell() let expandedArticleView = ArticleFullWidthImageCollectionViewCell() var isExpanded = true var currentArticleKey: String? private lazy var emptyView = EmptyView() override func viewDidLoad() { super.viewDidLoad() view.translatesAutoresizingMaskIntoConstraints = false let tapGR = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:))) view.addGestureRecognizer(tapGR) collapsedArticleView.preservesSuperviewLayoutMargins = true collapsedArticleView.frame = view.bounds view.addSubview(collapsedArticleView) expandedArticleView.preservesSuperviewLayoutMargins = true expandedArticleView.saveButton.addTarget(self, action: #selector(saveButtonPressed), for: .touchUpInside) expandedArticleView.frame = view.bounds view.addSubview(expandedArticleView) view.wmf_addSubviewWithConstraintsToEdges(emptyView) } var isEmptyViewHidden = true { didSet { extensionContext?.widgetLargestAvailableDisplayMode = isEmptyViewHidden ? .expanded : .compact emptyView.isHidden = isEmptyViewHidden collapsedArticleView.isHidden = !isEmptyViewHidden expandedArticleView.isHidden = !isEmptyViewHidden } } var dataStore: MWKDataStore? { return SessionSingleton.sharedInstance()?.dataStore } var article: WMFArticle? { guard let dataStore = dataStore, let featuredContentGroup = dataStore.viewContext.newestVisibleGroup(of: .featuredArticle) ?? dataStore.viewContext.newestGroup(of: .featuredArticle), let articleURL = featuredContentGroup.contentPreview as? URL else { return nil } return dataStore.fetchArticle(with: articleURL) } override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } emptyView.apply(theme: theme) collapsedArticleView.apply(theme: theme) collapsedArticleView.tintColor = theme.colors.link expandedArticleView.apply(theme: theme) expandedArticleView.tintColor = theme.colors.link } func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) { defer { updateView() } guard let article = self.article, let articleKey = article.key else { isEmptyViewHidden = false completionHandler(.failed) return } guard articleKey != currentArticleKey else { completionHandler(.noData) return } currentArticleKey = articleKey isEmptyViewHidden = true collapsedArticleView.configure(article: article, displayType: .relatedPages, index: 0, shouldShowSeparators: false, theme: theme, layoutOnly: false) collapsedArticleView.titleTextStyle = .body collapsedArticleView.updateFonts(with: traitCollection) collapsedArticleView.tintColor = theme.colors.link expandedArticleView.configure(article: article, displayType: .pageWithPreview, index: 0, theme: theme, layoutOnly: false) expandedArticleView.tintColor = theme.colors.link expandedArticleView.saveButton.saveButtonState = article.savedDate == nil ? .longSave : .longSaved completionHandler(.newData) } func updateViewAlpha(isExpanded: Bool) { expandedArticleView.alpha = isExpanded ? 1 : 0 collapsedArticleView.alpha = isExpanded ? 0 : 1 } @objc func updateView() { guard viewIfLoaded != nil else { return } var maximumSize = CGSize(width: view.bounds.size.width, height: UIView.noIntrinsicMetric) if let context = extensionContext { isExpanded = context.widgetActiveDisplayMode == .expanded maximumSize = context.widgetMaximumSize(for: context.widgetActiveDisplayMode) } updateViewAlpha(isExpanded: isExpanded) updateViewWithMaximumSize(maximumSize, isExpanded: isExpanded) } func updateViewWithMaximumSize(_ maximumSize: CGSize, isExpanded: Bool) { let sizeThatFits: CGSize if isExpanded { sizeThatFits = expandedArticleView.sizeThatFits(CGSize(width: maximumSize.width, height:UIView.noIntrinsicMetric), apply: true) expandedArticleView.frame = CGRect(origin: .zero, size:sizeThatFits) } else { collapsedArticleView.imageViewDimension = maximumSize.height - 30 //hax sizeThatFits = collapsedArticleView.sizeThatFits(CGSize(width: maximumSize.width, height:UIView.noIntrinsicMetric), apply: true) collapsedArticleView.frame = CGRect(origin: .zero, size:sizeThatFits) } preferredContentSize = CGSize(width: maximumSize.width, height: sizeThatFits.height) } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { debounceViewUpdate() } func debounceViewUpdate() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(updateView), object: nil) perform(#selector(updateView), with: nil, afterDelay: 0.1) } @objc func saveButtonPressed() { guard let article = self.article, let articleKey = article.key else { return } let isSaved = dataStore?.savedPageList.toggleSavedPage(forKey: articleKey) ?? false expandedArticleView.saveButton.saveButtonState = isSaved ? .longSaved : .longSave } @objc func handleTapGesture(_ tapGR: UITapGestureRecognizer) { guard tapGR.state == .recognized else { return } openApp(with: self.article?.url) } }
mit
6c3785ac739c65bcf8e0b7afba83d8f4
37.543956
188
0.678546
5.442203
false
false
false
false
daikiueda/simple-speaking-agent
simple-speaking-agent/src/model/Speakable/AppleSyntheTalker.swift
1
1631
// // SyntheTalkerApple.swift // simple-speaking-agent // // Created by うえでー on 2016/05/04. // Copyright © 2016年 Daiki UEDA. All rights reserved. // import Foundation import AVFoundation class AppleSyntheSpeaker: Speakable { static let talker = AVSpeechSynthesizer() static let voice = AVSpeechSynthesisVoice(language: "ja-JP") private var utterance: AVSpeechUtterance? var pitchMultiplier: Float = 1.0 // 0.5 - 2.0 var rate: Float = 0.5 // 0.0 - 1.0 init() { self.load() } func load() { self.pitchMultiplier = 1.0 self.rate = 0.4 } func save() { } func prepare(string: String?) throws { guard let string = string else { throw AppleSyntheSpeaker.Error.StringRequired } let utterance = AVSpeechUtterance(string: string) utterance.voice = AppleSyntheSpeaker.voice utterance.pitchMultiplier = self.pitchMultiplier utterance.rate = self.rate self.utterance = utterance } func speak() { guard let utterance = self.utterance else { return } if AppleSyntheSpeaker.talker.speaking { return // 発生中にspeakUtteranceを呼ぶと例外発生。 // stopSpeakingAtBoundaryも同様なので、returnするだけで対処 // AppleSyntheSpeaker.talker.stopSpeakingAtBoundary(AVSpeechBoundary.Immediate) } AppleSyntheSpeaker.talker.speakUtterance(utterance) } enum Error: ErrorType { case StringRequired } }
mit
99edac3e707a9053125a5b6f6fa7a449
24.672131
91
0.614943
4.110236
false
false
false
false
cplaverty/KeitaiWaniKani
WaniKaniKit/Database/Table/Schema/VirtualTable.swift
1
2175
// // VirtualTable.swift // WaniKaniKit // // Copyright © 2017 Chris Laverty. All rights reserved. // class VirtualTable { let name: String let schemaType = "table" // We have to make these vars so that we can create the Mirror in the initialiser var columns: [Column]! = nil var prefixIndexes: [Int]! = nil init(name: String, prefixIndexes: [Int]? = nil) { self.name = name let mirror = Mirror(reflecting: self) var columns = [Column]() columns.reserveCapacity(Int(mirror.children.count)) for child in mirror.children { if let column = child.value as? Column { column.table = self columns.append(column) } } self.columns = columns self.prefixIndexes = prefixIndexes } class Column { let name: String let rank: Double weak var table: VirtualTable? init(name: String, rank: Double = 1.0) { self.name = name self.rank = rank } } } // MARK: - CustomStringConvertible extension VirtualTable: CustomStringConvertible { var description: String { return name } } extension VirtualTable.Column: CustomStringConvertible { var description: String { guard let table = table else { return name } return "\(table.name).\(name)" } } // MARK: - TableProtocol extension VirtualTable: TableProtocol { var sqlStatement: String { var query = "CREATE VIRTUAL TABLE \(name) USING fts5(" query += columns.lazy.map({ $0.sqlStatement }).joined(separator: ", ") if let prefixIndexes = prefixIndexes { query += ", prefix = '\(prefixIndexes.lazy.map({ String($0) }).joined(separator: ","))'" } query += ", tokenize = porter);\n" query += "INSERT INTO \(name)(\(name), rank) VALUES('rank', 'bm25(\(columns.lazy.map({ String($0.rank) }).joined(separator: ", ")))');" return query } } // MARK: - ColumnProtocol extension VirtualTable.Column: ColumnProtocol { var sqlStatement: String { return name } }
mit
a672fa592bbceb3216920819e9b490d7
26.871795
143
0.583257
4.409736
false
false
false
false
Burning-Man-Earth/iBurn-iOS
iBurn/BRCDistanceView.swift
1
1359
// // BRCDistanceView.swift // iBurn // // Created by Christopher Ballinger on 8/15/15. // Copyright (c) 2015 Burning Man Earth. All rights reserved. // import UIKit import BButton import PureLayout open class BRCDistanceView: UIView { let distanceLabel: UILabel = UILabel() var destination: CLLocation public init(frame: CGRect, destination aDestination: CLLocation) { destination = aDestination super.init(frame: frame) distanceLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(distanceLabel) distanceLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets.zero) backgroundColor = UIColor.clear distanceLabel.backgroundColor = UIColor.clear } open func updateDistanceFromLocation(_ fromLocation: CLLocation) { let distance = destination.distance(from: fromLocation) let distanceString = TTTLocationFormatter.brc_humanizedString(forDistance: distance) distanceLabel.attributedText = distanceString distanceLabel.sizeToFit() self.frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: distanceLabel.frame.size.width, height: distanceLabel.frame.size.height) } required public init?(coder aDecoder: NSCoder) { destination = CLLocation() super.init(coder: aDecoder) } }
mpl-2.0
87c2c1024a34c7401d9e38ee3700123b
32.146341
145
0.709345
4.80212
false
false
false
false
afnan-ahmad/Swift-Google-Maps-API
Example/Example/ViewController.swift
1
2726
// // ViewController.swift // Example // // Created by Honghao Zhang on 2016-02-12. // Copyright © 2016 Honghao Zhang. All rights reserved. // import UIKit import GoogleMaps import GoogleMapsDirections import GooglePlacesAPI class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Google Maps Directions GoogleMapsDirections.provide(apiKey: "AIzaSyDftpY3fi6x_TL4rntL8pgZb-A8mf6D0Ss") let origin = GoogleMapsDirections.Place.stringDescription(address: "Davis Center, Waterloo, Canada") let destination = GoogleMapsDirections.Place.stringDescription(address: "Conestoga Mall, Waterloo, Canada") // You can also use coordinates or placeID for a place // let origin = Place.Coordinate(coordinate: LocationCoordinate2D(latitude: 43.4697354, longitude: -80.5397377)) // let origin = Place.PlaceID(id: "ChIJb9sw59k0K4gRZZlYrnOomfc") GoogleMapsDirections.direction(fromOrigin: origin, toDestination: destination) { (response, error) -> Void in // Check Status Code guard response?.status == GoogleMapsDirections.StatusCode.ok else { // Status Code is Not OK debugPrint(response?.errorMessage) return } // Use .result or .geocodedWaypoints to access response details // response will have same structure as what Google Maps Directions API returns debugPrint("it has \(response?.routes.count ?? 0) routes") } // Google Places GooglePlaces.provide(apiKey: "A VALID GOOGLE MAPS KEY") GooglePlaces.placeAutocomplete(forInput: "Pub") { (response, error) -> Void in // Check Status Code guard response?.status == GooglePlaces.StatusCode.ok else { // Status Code is Not OK debugPrint(response?.errorMessage) return } // Use .predictions to access response details debugPrint("first matched result: \(response?.predictions.first?.description)") } GooglePlaces.placeDetails(forPlaceID: "ChIJb9sw59k0K4gRZZlYrnOomfc") { (response, error) -> Void in // Check Status Code guard response?.status == GooglePlaces.StatusCode.ok else { // Status Code is Not OK debugPrint(response?.errorMessage) return } // Use .result to access response details debugPrint("the formated address is: \(response?.result?.formattedAddress)") } } }
mit
8b74829183bb10378f5c734651643b69
37.928571
120
0.615046
4.814488
false
false
false
false
icecrystal23/ios-charts
Source/Charts/Data/Implementations/Standard/LineRadarChartDataSet.swift
2
2280
// // LineRadarChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class LineRadarChartDataSet: LineScatterCandleRadarChartDataSet, ILineRadarChartDataSet { // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// The color that is used for filling the line surface area. private var _fillColor = NSUIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0) /// The color that is used for filling the line surface area. open var fillColor: NSUIColor { get { return _fillColor } set { _fillColor = newValue fill = nil } } /// The object that is used for filling the area below the line. /// **default**: nil open var fill: Fill? /// The alpha value that is used for filling the line surface, /// **default**: 0.33 open var fillAlpha = CGFloat(0.33) private var _lineWidth = CGFloat(1.0) /// line width of the chart (min = 0.0, max = 10) /// /// **default**: 1 open var lineWidth: CGFloat { get { return _lineWidth } set { _lineWidth = newValue.clamped(to: 0...10) } } /// Set to `true` if the DataSet should be drawn filled (surface), and not just as a line. /// Disabling this will give great performance boost. /// Please note that this method uses the path clipping for drawing the filled area (with images, gradients and layers). open var drawFilledEnabled = false /// - returns: `true` if filled drawing is enabled, `false` ifnot open var isDrawFilledEnabled: Bool { return drawFilledEnabled } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! LineRadarChartDataSet copy.fillColor = fillColor copy._lineWidth = _lineWidth copy.drawFilledEnabled = drawFilledEnabled return copy } }
apache-2.0
241e49339fcb3529114bddea0394a829
26.46988
124
0.613158
4.606061
false
false
false
false
cmoulton/PullToUpdateDemo
PullToUpdateDemo/ViewController.swift
1
3571
// // ViewController.swift // PullToUpdateDemo // // Created by Christina Moulton on 2015-04-29. // Copyright (c) 2015 Teak Mobile Inc. All rights reserved. // import UIKit enum StockType { case Tech case Cars case Telecom } class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var itemsArray:Array<StockQuoteItem>? @IBOutlet var tableView: UITableView? var stockType: StockType = .Tech var refreshControl = UIRefreshControl() var dateFormatter = NSDateFormatter() override func viewDidLoad() { super.viewDidLoad() self.dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle self.dateFormatter.timeStyle = NSDateFormatterStyle.LongStyle self.refreshControl.backgroundColor = UIColor.clearColor() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged) self.tableView?.addSubview(refreshControl) self.loadStockQuoteItems() } func symbolsStringForCurrentStockType() -> Array<String> { switch self.stockType { case .Tech: return ["AAPL", "GOOG", "YHOO"] case .Cars: return ["GM", "F"] case .Telecom: return ["T", "VZ", "CMCSA"] } } @IBAction func stockTypeSegmentedControlValueChanged(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 0: self.stockType = .Tech case 1: self.stockType = .Cars case 2: self.stockType = .Telecom default: print("Segment index out of known range, do you need to add to the enum or switch statement?") } // load data for our new symbols refresh(sender) } func loadStockQuoteItems() { let symbols = symbolsStringForCurrentStockType() StockQuoteItem.getFeedItems(symbols, completionHandler: { (items, error) in if error != nil { let alert = UIAlertController(title: "Error", message: "Could not load stock quotes :( \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } self.itemsArray = items // update "last updated" title for refresh control let now = NSDate() let updateString = "Last Updated at " + self.dateFormatter.stringFromDate(now) self.refreshControl.attributedTitle = NSAttributedString(string: updateString) if self.refreshControl.refreshing { self.refreshControl.endRefreshing() } self.tableView?.reloadData() }) } func refresh(sender:AnyObject) { self.loadStockQuoteItems() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.itemsArray?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let item = self.itemsArray?[indexPath.row] cell.textLabel?.text = "" cell.detailTextLabel?.text = "" if let symbol = item?.symbol, ask = item?.ask { cell.textLabel?.text = symbol + " @ $" + ask } if let low = item?.yearLow, high = item?.yearHigh { cell.detailTextLabel?.text = "Year: " + low + " - " + high } return cell } }
mit
20444491260624ca847e90c991d34fc7
28.512397
173
0.681042
4.537484
false
false
false
false
WalterCreazyBear/Swifter30
BlueLib/BlueLib/AlbumView.swift
1
1829
// // AlbumView.swift // BlueLibrarySwift // // Created by Yi Gu on 5/6/16. // Copyright © 2016 Raywenderlich. All rights reserved. // import UIKit class AlbumView: UIView { fileprivate var coverImage: UIImageView! fileprivate var indicator: UIActivityIndicatorView! required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! commonInit() } init(frame: CGRect, albumCover: String) { super.init(frame: frame) commonInit() setupNotification(albumCover) } deinit { coverImage.removeObserver(self, forKeyPath: "image") } func commonInit() { setupUI() setupComponents() } func highlightAlbum(_ didHightlightView: Bool) { if didHightlightView { backgroundColor = UIColor.white } else { backgroundColor = UIColor.black } } fileprivate func setupUI() { backgroundColor = UIColor.blue } fileprivate func setupComponents() { coverImage = UIImageView(frame: CGRect(x: 5, y: 5, width: frame.size.width - 10, height: frame.size.height - 10)) addSubview(coverImage) indicator = UIActivityIndicatorView() indicator.center = center indicator.activityIndicatorViewStyle = .whiteLarge indicator.startAnimating() addSubview(indicator) coverImage.addObserver(self, forKeyPath: "image", options: [], context: nil) } fileprivate func setupNotification(_ albumCover: String) { NotificationCenter.default.post(name: Notification.Name(rawValue: downloadImageNotification), object: self, userInfo: ["imageView":coverImage, "coverUrl" : albumCover]) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "image" { indicator.stopAnimating() } } }
mit
b4033653b69527ee0b90b79f0a768428
25.882353
172
0.693654
4.51358
false
false
false
false
RobotsAndPencils/SwiftCharts
SwiftCharts/AxisValues/ChartAxisValueDouble.swift
2
1324
// // ChartAxisValueDouble.swift // SwiftCharts // // Created by ischuetz on 30/08/15. // Copyright © 2015 ivanschuetz. All rights reserved. // import UIKit public class ChartAxisValueDouble: ChartAxisValue { public let formatter: NSNumberFormatter public convenience init(_ int: Int, formatter: NSNumberFormatter = ChartAxisValueDouble.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.init(Double(int), formatter: formatter, labelSettings: labelSettings) } public init(_ double: Double, formatter: NSNumberFormatter = ChartAxisValueDouble.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.formatter = formatter super.init(scalar: double, labelSettings: labelSettings) } override public func copy(scalar: Double) -> ChartAxisValueDouble { return ChartAxisValueDouble(scalar, formatter: self.formatter, labelSettings: self.labelSettings) } static var defaultFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.maximumFractionDigits = 2 return formatter }() // MARK: CustomStringConvertible override public var description: String { return self.formatter.stringFromNumber(self.scalar)! } }
apache-2.0
c4d61e365b0e626fb6a68f2e9cbed192
32.923077
169
0.721844
5.653846
false
false
false
false
debugsquad/Hyperborea
Hyperborea/View/Settings/VSettingsBackground.swift
1
1865
import UIKit class VSettingsBackground:UIView { private let model:MSettingsBackground weak var timer:Timer? private let kTimerInterval:TimeInterval = 0.02 init() { model = MSettingsBackground() super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false isUserInteractionEnabled = false } required init?(coder:NSCoder) { return nil } deinit { timer?.invalidate() } override func layoutSubviews() { let width:CGFloat = bounds.maxX let height:CGFloat = bounds.maxY model.maxWidth = width model.maxHeight = height super.layoutSubviews() } override func draw(_ rect:CGRect) { guard let context:CGContext = UIGraphicsGetCurrentContext() else { return } model.draw(context:context) } //MARK: actions func actionTick(sender timer:Timer) { model.tick() setNeedsDisplay() } //MARK: public func startTimer() { timer?.invalidate() model.loadInitial() DispatchQueue.main.async { [weak self] in guard let strongSelf:VSettingsBackground = self else { return } strongSelf.timer = Timer.scheduledTimer( timeInterval:strongSelf.kTimerInterval, target:strongSelf, selector:#selector(strongSelf.actionTick(sender:)), userInfo:nil, repeats:true) } } }
mit
4a36a58e44b5aa95e244ce819362be0f
19.955056
67
0.510992
5.809969
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Stats/Shared Views/GhostViews/StatsGhostTableViewRows.swift
1
3202
protocol StatsRowGhostable: ImmuTableRow { } extension StatsRowGhostable { var action: ImmuTableAction? { return nil } func configureCell(_ cell: UITableViewCell) { DispatchQueue.main.async { cell.startGhostAnimation(style: GhostCellStyle.muriel) } } } struct StatsGhostGrowAudienceImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostGrowAudienceCell.defaultNib, StatsGhostGrowAudienceCell.self) }() } struct StatsGhostTwoColumnImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTwoColumnCell.defaultNib, StatsGhostTwoColumnCell.self) }() } struct StatsGhostTopImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTopCell.defaultNib, StatsGhostTopCell.self) }() var hideTopBorder = false var hideBottomBorder = false func configureCell(_ cell: UITableViewCell) { DispatchQueue.main.async { cell.startGhostAnimation(style: GhostCellStyle.muriel) } if let detailCell = cell as? StatsGhostTopCell { detailCell.topBorder?.isHidden = hideTopBorder detailCell.bottomBorder?.isHidden = hideBottomBorder } } } struct StatsGhostTopHeaderImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTopHeaderCell.defaultNib, StatsGhostTopHeaderCell.self) }() } struct StatsGhostTabbedImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTabbedCell.defaultNib, StatsGhostTabbedCell.self) }() } struct StatsGhostPostingActivitiesImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostPostingActivityCell.defaultNib, StatsGhostPostingActivityCell.self) }() } struct StatsGhostChartImmutableRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostChartCell.defaultNib, StatsGhostChartCell.self) }() } struct StatsGhostDetailRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostSingleRowCell.defaultNib, StatsGhostSingleRowCell.self) }() var hideTopBorder = false var isLastRow = false var enableTopPadding = false func configureCell(_ cell: UITableViewCell) { DispatchQueue.main.async { cell.startGhostAnimation(style: GhostCellStyle.muriel) } if let detailCell = cell as? StatsGhostSingleRowCell { detailCell.topBorder?.isHidden = hideTopBorder detailCell.isLastRow = isLastRow detailCell.enableTopPadding = enableTopPadding } } } struct StatsGhostTitleRow: StatsRowGhostable { static let cell: ImmuTableCell = { return ImmuTableCell.nib(StatsGhostTitleCell.defaultNib, StatsGhostTitleCell.self) }() } enum GhostCellStyle { static let muriel = GhostStyle(beatStartColor: .placeholderElement, beatEndColor: .placeholderElementFaded) }
gpl-2.0
787e01715fca6b12bc93447eeb9af93c
31.02
111
0.725796
4.600575
false
false
false
false
Eric217/-OnSale
打折啦/打折啦/ResultView.swift
1
3329
// // ResultView.swift // 打折啦 // // Created by Eric on 10/09/2017. // Copyright © 2017 INGStudio. All rights reserved. // import Foundation extension Identifier { static let resultofSearchCellId = "dnakdqweqdkj" } extension ResultController { func setupBar() { view.backgroundColor = UIColor.groupTableViewBackground fd_prefersNavigationBarHidden = true navBar = SearchingNavBar() view.addSubview(navBar) let tap = UITapGestureRecognizer(target: self, action: #selector(didTap)) tap.delegate = self navBar.addGestureRecognizer(tap) navBar.search.delegate = self navBar.cancelButton.addTarget(self, action: #selector(cancel), for: .touchUpInside) navBar.selectButton.addTarget(self, action: #selector(shaixuan), for: .touchUpInside) navBar.all.changeStatus(true) navBar.search.text = keyword } func setupCollection() { let lay = UICollectionViewFlowLayout() collection = UICollectionView(frame: myRect(0, 104, ScreenWidth, ScreenHeight-104), collectionViewLayout: lay) collection.delegate = self collection.dataSource = self collection.register(ELItemViewCell.self, forCellWithReuseIdentifier: Identifier.resultofSearchCellId) view.addSubview(collection) refreshFooter = MJRefreshAutoNormalFooter { self.currPage += 1 self.loadData(page: self.currPage) } collection.showsVerticalScrollIndicator = false collection.backgroundColor = UIColor.groupTableViewBackground } } extension ResultController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifier.resultofSearchCellId, for: indexPath) as! ELItemViewCell cell.fillContents(dataArr[indexPath.item]) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath:IndexPath) { let vc = DetailController() vc.item = dataArr[indexPath.item] as! Good pushWithoutTab(vc) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return lineSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 13, left: lineSpacing, bottom: 0, right: lineSpacing) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: itemCellW, height: itemCellH) } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { if dataArr.count == 0 { collection.mj_footer = nil }else { collection.mj_footer = refreshFooter } return dataArr.count } }
apache-2.0
d3bf22b760c8fd0f38ea3af377703b47
31.891089
175
0.695665
5.445902
false
false
false
false
chinlam91/edx-app-ios
Source/PostsViewController.swift
2
24204
// // PostsViewController.swift // edX // // Created by Tang, Jeff on 5/19/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit public struct DiscussionPostItem { public let title: String public let body: String public let author: String public let authorLabel : AuthorLabelType? public let createdAt: NSDate public let count: Int public let threadID: String public let following: Bool public let flagged: Bool public let pinned : Bool public var voted: Bool public var voteCount: Int public var type : PostThreadType public var read = false public let unreadCommentCount : Int public var closed = false public let groupName : String? public var hasEndorsed = false // Unfortunately there's no way to make the default constructor public public init( title: String, body: String, author: String, authorLabel: AuthorLabelType?, createdAt: NSDate, count: Int, threadID: String, following: Bool, flagged: Bool, pinned: Bool, voted: Bool, voteCount: Int, type : PostThreadType, read : Bool, unreadCommentCount : Int, closed : Bool, groupName : String?, hasEndorsed : Bool ) { self.title = title self.body = body self.author = author self.authorLabel = authorLabel self.createdAt = createdAt self.count = count self.threadID = threadID self.following = following self.flagged = flagged self.pinned = pinned self.voted = voted self.voteCount = voteCount self.type = type self.read = read self.unreadCommentCount = unreadCommentCount self.closed = closed self.groupName = groupName self.hasEndorsed = hasEndorsed } var hasByText : Bool { return following || pinned || self.authorLabel != nil } } class PostsViewControllerEnvironment: NSObject { weak var router: OEXRouter? let networkManager : NetworkManager? let styles : OEXStyles init(networkManager : NetworkManager?, router: OEXRouter?, styles : OEXStyles = OEXStyles.sharedStyles()) { self.networkManager = networkManager self.router = router self.styles = styles } } class PostsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, PullRefreshControllerDelegate { enum Context { case Topic(DiscussionTopic) case Following case Search(String) case AllPosts var allowsPosting : Bool { switch self { case Topic: return true case Following: return true case Search: return false case AllPosts: return true } } var topic : DiscussionTopic? { switch self { case let Topic(topic): return topic case Search(_): return nil case Following(_): return nil case AllPosts(_): return nil } } var navigationItemTitle : String? { switch self { case let Topic(topic): return topic.name case Search(_): return OEXLocalizedString("SEARCH_RESULTS", nil) case Following(_): return OEXLocalizedString("POSTS_IM_FOLLOWING", nil) case AllPosts(_): return OEXLocalizedString("ALL_POSTS",nil) } } } let environment: PostsViewControllerEnvironment var networkPaginator : NetworkPaginator<DiscussionThread>? private let identifierTitleAndByCell = "TitleAndByCell" private let identifierTitleOnlyCell = "TitleOnlyCell" private var tableView: UITableView! private var viewSeparator: UIView! private let loadController : LoadStateViewController private let refreshController : PullRefreshController private let insetsController = ContentInsetsController() private let refineLabel = UILabel() private let headerButtonHolderView = UIView() private let filterButton = UIButton(type: .System) private let sortButton = UIButton(type: .System) private let newPostButton = UIButton(type: .System) private let courseID: String private let contentView = UIView() private let context : Context private var posts: [DiscussionPostItem] = [] private var selectedFilter: DiscussionPostsFilter = .AllPosts private var selectedOrderBy: DiscussionPostsSort = .RecentActivity private var queryString : String? private var refineTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .XSmall, color: OEXStyles.sharedStyles().neutralDark()) } private var filterTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .XSmall, color: self.environment.styles.primaryBaseColor()) } required init(environment : PostsViewControllerEnvironment, courseID : String, context : Context) { self.environment = environment self.courseID = courseID self.context = context loadController = LoadStateViewController(styles: environment.styles) refreshController = PullRefreshController() super.init(nibName: nil, bundle: nil) } convenience init(environment: PostsViewControllerEnvironment, courseID: String, topic : DiscussionTopic) { self.init(environment : environment, courseID : courseID, context : .Topic(topic)) } convenience init(environment: PostsViewControllerEnvironment, courseID: String, queryString : String) { self.init(environment : environment, courseID : courseID, context : .Search(queryString)) } ///Convenience initializer for All Posts and Followed posts convenience init(environment: PostsViewControllerEnvironment, courseID: String, following : Bool) { self.init(environment : environment, courseID : courseID, context : following ? .Following : .AllPosts) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = self.environment.styles.standardBackgroundColor() view.addSubview(contentView) contentView.addSubview(refineLabel) contentView.addSubview(headerButtonHolderView) headerButtonHolderView.addSubview(filterButton) headerButtonHolderView.addSubview(sortButton) self.refineLabel.attributedText = self.refineTextStyle.attributedStringWithText(OEXLocalizedString("REFINE", nil)) contentView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(view) } refineLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(contentView).offset(20) make.top.equalTo(contentView).offset(10) make.height.equalTo(20) } headerButtonHolderView.snp_makeConstraints { (make) -> Void in make.leading.equalTo(refineLabel.snp_trailing) make.trailing.equalTo(contentView) make.height.equalTo(40) make.top.equalTo(contentView) } var buttonTitle = NSAttributedString.joinInNaturalLayout( [Icon.Filter.attributedTextWithStyle(filterTextStyle.withSize(.XSmall)), filterTextStyle.attributedStringWithText(self.titleForFilter(self.selectedFilter))]) filterButton.setAttributedTitle(buttonTitle, forState: .Normal) filterButton.snp_makeConstraints{ (make) -> Void in make.leading.equalTo(headerButtonHolderView) make.top.equalTo(headerButtonHolderView).offset(10) make.height.equalTo(context.allowsPosting ? 20 : 0) make.trailing.equalTo(sortButton.snp_leading) } buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Sort.attributedTextWithStyle(filterTextStyle.withSize(.XSmall)), filterTextStyle.attributedStringWithText(OEXLocalizedString("RECENT_ACTIVITY", nil))]) sortButton.setAttributedTitle(buttonTitle, forState: .Normal) sortButton.snp_makeConstraints{ (make) -> Void in make.trailing.equalTo(headerButtonHolderView).offset(-20) make.top.equalTo(headerButtonHolderView).offset(10) make.height.equalTo(context.allowsPosting ? 20 : 0) make.width.equalTo(filterButton.snp_width) } newPostButton.backgroundColor = self.environment.styles.primaryXDarkColor() let style = OEXTextStyle(weight : .Normal, size: .Small, color: self.environment.styles.neutralWhite()) buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Create.attributedTextWithStyle(style.withSize(.XSmall)), style.attributedStringWithText(OEXLocalizedString("CREATE_A_NEW_POST", nil))]) newPostButton.setAttributedTitle(buttonTitle, forState: .Normal) newPostButton.contentVerticalAlignment = .Center contentView.addSubview(newPostButton) newPostButton.snp_makeConstraints{ (make) -> Void in make.leading.equalTo(view) make.trailing.equalTo(view) make.height.equalTo(context.allowsPosting ? OEXStyles.sharedStyles().standardFooterHeight : 0) make.bottom.equalTo(contentView.snp_bottom) } tableView = UITableView(frame: contentView.bounds, style: .Plain) if let theTableView = tableView { theTableView.registerClass(PostTitleByTableViewCell.classForCoder(), forCellReuseIdentifier: identifierTitleAndByCell) theTableView.registerClass(PostTitleTableViewCell.classForCoder(), forCellReuseIdentifier: identifierTitleOnlyCell) theTableView.dataSource = self theTableView.delegate = self theTableView.tableFooterView = UIView(frame: CGRectZero) contentView.addSubview(theTableView) } if context.allowsPosting { tableView.snp_makeConstraints { (make) -> Void in make.leading.equalTo(view) make.top.equalTo(filterButton).offset(30) make.trailing.equalTo(view) make.bottom.equalTo(newPostButton.snp_top) } viewSeparator = UIView() viewSeparator.backgroundColor = self.environment.styles.neutralXLight() contentView.addSubview(viewSeparator) viewSeparator.snp_makeConstraints{ (make) -> Void in make.leading.equalTo(view) make.trailing.equalTo(view) make.height.equalTo(OEXStyles.dividerSize()) make.top.equalTo(filterButton.snp_bottom).offset(context.allowsPosting ? 12 : 0) } } else { tableView.snp_makeConstraints { (make) -> Void in make.leading.equalTo(view) make.top.equalTo(view) make.trailing.equalTo(view) make.bottom.equalTo(newPostButton.snp_top) } } filterButton.oex_addAction( {[weak self] _ in self?.showFilterPicker() }, forEvents: .TouchUpInside) sortButton.oex_addAction( {[weak self] _ in self?.showSortPicker() }, forEvents: .TouchUpInside) newPostButton.oex_addAction( {[weak self] _ in if let owner = self { owner.environment.router?.showDiscussionNewPostFromController(owner, courseID: owner.courseID, initialTopic: owner.context.topic) } }, forEvents: .TouchUpInside) self.navigationItem.title = context.navigationItemTitle self.navigationItem.backBarButtonItem = UIBarButtonItem(title: " ", style: .Plain, target: nil, action: nil) loadController.setupInController(self, contentView: contentView) insetsController.setupInController(self, scrollView: tableView) refreshController.setupInScrollView(tableView) insetsController.addSource(refreshController) refreshController.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let selectedIndex = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(selectedIndex, animated: false) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) loadContent() } private func loadContent() { switch context { case let .Topic(topic): loadPostsForTopic(topic, filter: selectedFilter, orderBy: selectedOrderBy) case let .Search(query): searchThreads(query) case .Following: loadFollowedPostsForFilter(selectedFilter, orderBy: selectedOrderBy) case .AllPosts: loadPostsForTopic(nil, filter: selectedFilter, orderBy: selectedOrderBy) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() insetsController.updateInsets() } private func loadFollowedPostsForFilter(filter : DiscussionPostsFilter, orderBy: DiscussionPostsSort) { let followedFeed = PaginatedFeed() { i in return DiscussionAPI.getFollowedThreads(courseID: self.courseID, filter: filter, orderBy: orderBy, pageNumber: i) } loadThreadsFromPaginatedFeed(followedFeed) } private func loadThreadsFromPaginatedFeed(feed : PaginatedFeed<NetworkRequest<[DiscussionThread]>>) { self.networkPaginator = NetworkPaginator(networkManager: self.environment.networkManager, paginatedFeed: feed, tableView : self.tableView) self.networkPaginator?.loadDataIfAvailable() {[weak self] discussionThreads in self?.refreshController.endRefreshing() if let threads = discussionThreads { self?.updatePostsFromThreads(threads, removeAll: true) } } } private func searchThreads(query : String) { let apiRequest = DiscussionAPI.searchThreads(courseID: self.courseID, searchText: query) environment.networkManager?.taskForRequest(apiRequest) {[weak self] result in self?.refreshController.endRefreshing() if let threads: [DiscussionThread] = result.data, owner = self { owner.posts.removeAll(keepCapacity: true) for discussionThread in threads { if let item = owner.postItem(fromDiscussionThread : discussionThread) { owner.posts.append(item) } } if owner.posts.count == 0 { var emptyResultSetMessage : NSString = OEXLocalizedString("EMPTY_RESULTSET", nil) emptyResultSetMessage = emptyResultSetMessage.oex_formatWithParameters(["query_string" : query]) owner.loadController.state = LoadState.empty(icon: nil, message: emptyResultSetMessage as String, attributedMessage: nil, accessibilityMessage: nil) } else { owner.loadController.state = .Loaded } owner.tableView.reloadData() } } } private func postItem(fromDiscussionThread thread: DiscussionThread) -> DiscussionPostItem? { if let rawBody = thread.rawBody, let author = thread.author, let createdAt = thread.createdAt, let title = thread.title, let threadID = thread.identifier { return DiscussionPostItem( title: title, body: rawBody, author: author, authorLabel: thread.authorLabel, createdAt: createdAt, count: thread.commentCount, threadID: threadID, following: thread.following, flagged: thread.flagged, pinned: thread.pinned, voted: thread.voted, voteCount: thread.voteCount, type : thread.type ?? .Discussion, read : thread.read, unreadCommentCount : thread.unreadCommentCount, closed : thread.closed, groupName : thread.groupName, hasEndorsed : thread.hasEndorsed ) } return nil } private func loadPostsForTopic(topic : DiscussionTopic?, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort) { let threadsFeed : PaginatedFeed<NetworkRequest<[DiscussionThread]>> threadsFeed = PaginatedFeed() { i in //Topic ID if topic isn't root node var topicIDApiRepresentation : [String]? if let identifier = topic?.id { topicIDApiRepresentation = [identifier] } //Children's topic IDs if the topic is root node else if let discussionTopic = topic { topicIDApiRepresentation = discussionTopic.children.mapSkippingNils { $0.id } } //topicIDApiRepresentation = nil when fetching all posts for a course return DiscussionAPI.getThreads(courseID: self.courseID, topicIDs: topicIDApiRepresentation, filter: filter, orderBy: orderBy, pageNumber: i) } loadThreadsFromPaginatedFeed(threadsFeed) } private func updatePostsFromThreads(threads : [DiscussionThread], removeAll : Bool) { if (removeAll) { self.posts.removeAll(keepCapacity: true) } for thread in threads { if let item = self.postItem(fromDiscussionThread: thread) { self.posts.append(item) } } self.tableView.reloadData() let emptyState = LoadState.Empty(icon: nil, message: OEXLocalizedString("NO_RESULTS_FOUND", nil), attributedMessage: nil, accessibilityMessage: nil) self.loadController.state = self.posts.isEmpty ? emptyState : .Loaded } func titleForFilter(filter : DiscussionPostsFilter) -> String { switch filter { case .AllPosts: return OEXLocalizedString("ALL_POSTS", nil) case .Unread: return OEXLocalizedString("UNREAD", nil) case .Unanswered: return OEXLocalizedString("UNANSWERED", nil) } } func titleForSort(filter : DiscussionPostsSort) -> String { switch filter { case .RecentActivity: return OEXLocalizedString("RECENT_ACTIVITY", nil) case .LastActivityAt: return OEXLocalizedString("MOST_ACTIVITY", nil) case .VoteCount: return OEXLocalizedString("MOST_VOTES", nil) } } func showFilterPicker() { let options = [.AllPosts, .Unread, .Unanswered].map { return (title : self.titleForFilter($0), value : $0) } let controller = PSTAlertController.actionSheetWithItems(options, currentSelection : self.selectedFilter) {filter in self.selectedFilter = filter self.loadContent() let buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Filter.attributedTextWithStyle(self.filterTextStyle.withSize(.XSmall)), self.filterTextStyle.attributedStringWithText(self.titleForFilter(filter))]) self.filterButton.setAttributedTitle(buttonTitle, forState: .Normal) } controller.addAction(PSTAlertAction(title: OEXLocalizedString("CANCEL", nil), style: .Cancel) { _ in }) controller.showWithSender(nil, controller: self, animated: true, completion: nil) } func showSortPicker() { let options = [.RecentActivity, .LastActivityAt, .VoteCount].map { return (title : self.titleForSort($0), value : $0) } let controller = PSTAlertController.actionSheetWithItems(options, currentSelection : self.selectedOrderBy) {sort in self.selectedOrderBy = sort self.loadContent() let buttonTitle = NSAttributedString.joinInNaturalLayout([Icon.Sort.attributedTextWithStyle(self.filterTextStyle.withSize(.XSmall)), self.filterTextStyle.attributedStringWithText(self.titleForSort(sort))]) self.sortButton.setAttributedTitle(buttonTitle, forState: .Normal) } controller.addAction(PSTAlertAction(title: OEXLocalizedString("CANCEL", nil), style: .Cancel) { _ in }) controller.showWithSender(nil, controller: self, animated: true, completion: nil) } // MARK - Pull Refresh func refreshControllerActivated(controller: PullRefreshController) { loadContent() } // Mark - Scroll View Delegate func scrollViewDidScroll(scrollView: UIScrollView) { refreshController.scrollViewDidScroll(scrollView) } // MARK - Table View Delegate func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return posts[indexPath.row].hasByText ? 75 : 50 } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let paginator = self.networkPaginator where tableView.isLastRow(indexPath : indexPath) { paginator.loadDataIfAvailable() {[weak self] discussionThreads in if let threads = discussionThreads { self?.updatePostsFromThreads(threads, removeAll: false) } } } } var cellTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Base, color: self.environment.styles.primaryBaseColor()) } var unreadIconTextStyle : OEXTextStyle { return OEXTextStyle(weight: .Normal, size: .Base, color: self.environment.styles.primaryBaseColor()) } var readIconTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Base, color: self.environment.styles.neutralBase()) } func styledCellTextWithIcon(icon : Icon, text : String?) -> NSAttributedString? { let style = cellTextStyle.withSize(.Small) return text.map {text in return NSAttributedString.joinInNaturalLayout([icon.attributedTextWithStyle(style), style.attributedStringWithText(text)]) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(identifierTitleAndByCell, forIndexPath: indexPath) as! PostTitleByTableViewCell cell.usePost(posts[indexPath.row], selectedOrderBy : selectedOrderBy) cell.applyStandardSeparatorInsets() return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { environment.router?.showDiscussionResponsesFromViewController(self, courseID : courseID, item: posts[indexPath.row]) } } extension UITableView { //Might be worth adding a section argument in the future func isLastRow(indexPath indexPath : NSIndexPath) -> Bool { return indexPath.row == self.numberOfRowsInSection(indexPath.section) - 1 && indexPath.section == self.numberOfSections - 1 } }
apache-2.0
6f0aa4f816ddbae0b548c3c2be26c482
39.272879
168
0.636837
5.391847
false
false
false
false
kickstarter/ios-oss
KsApi/models/Project.Country.swift
1
6869
private let eurMaxPledge: Int = 8_500 private let eurMinPledge: Int = 1 extension Project { public struct Country { public let countryCode: String public let currencyCode: String public let currencySymbol: String public let maxPledge: Int? public let minPledge: Int? public let trailingCode: Bool /* FIXME: The amount for maximum pledge can be found here: https://github.com/kickstarter/kickstarter/blob/master/config/currencies.yml Ideally we should get the amounts from the API. But for now we have to update them manually. */ // swiftformat:disable wrap // swiftformat:disable wrapArguments public static let at = Country(countryCode: "AT", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let au = Country(countryCode: "AU", currencyCode: "AUD", currencySymbol: "$", maxPledge: 13_000, minPledge: 1, trailingCode: true) public static let be = Country(countryCode: "BE", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let ca = Country(countryCode: "CA", currencyCode: "CAD", currencySymbol: "$", maxPledge: 13_000, minPledge: 1, trailingCode: true) public static let ch = Country(countryCode: "CH", currencyCode: "CHF", currencySymbol: "Fr", maxPledge: 9_500, minPledge: 1, trailingCode: true) public static let de = Country(countryCode: "DE", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let dk = Country(countryCode: "DK", currencyCode: "DKK", currencySymbol: "kr", maxPledge: 65_000, minPledge: 5, trailingCode: true) public static let es = Country(countryCode: "ES", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let fr = Country(countryCode: "FR", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let gb = Country(countryCode: "GB", currencyCode: "GBP", currencySymbol: "£", maxPledge: 8_000, minPledge: 1, trailingCode: false) public static let gr = Country(countryCode: "GR", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let hk = Country(countryCode: "HK", currencyCode: "HKD", currencySymbol: "$", maxPledge: 75_000, minPledge: 10, trailingCode: true) public static let ie = Country(countryCode: "IE", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let it = Country(countryCode: "IT", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let jp = Country(countryCode: "JP", currencyCode: "JPY", currencySymbol: "¥", maxPledge: 1_200_000, minPledge: 100, trailingCode: false) public static let lu = Country(countryCode: "LU", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let mx = Country(countryCode: "MX", currencyCode: "MXN", currencySymbol: "$", maxPledge: 200_000, minPledge: 10, trailingCode: true) public static let nl = Country(countryCode: "NL", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let no = Country(countryCode: "NO", currencyCode: "NOK", currencySymbol: "kr", maxPledge: 80_000, minPledge: 5, trailingCode: true) public static let nz = Country(countryCode: "NZ", currencyCode: "NZD", currencySymbol: "$", maxPledge: 14_000, minPledge: 1, trailingCode: true) public static let pl = Country(countryCode: "PL", currencyCode: "PLN", currencySymbol: "zł", maxPledge: 37_250, minPledge: 5, trailingCode: false) public static let se = Country(countryCode: "SE", currencyCode: "SEK", currencySymbol: "kr", maxPledge: 85_000, minPledge: 5, trailingCode: true) public static let sg = Country(countryCode: "SG", currencyCode: "SGD", currencySymbol: "$", maxPledge: 13_000, minPledge: 2, trailingCode: true) public static let si = Country(countryCode: "SI", currencyCode: "EUR", currencySymbol: "€", maxPledge: eurMaxPledge, minPledge: eurMinPledge, trailingCode: false) public static let us = Country(countryCode: "US", currencyCode: "USD", currencySymbol: "$", maxPledge: 10_000, minPledge: 1, trailingCode: true) public static let all: [Country] = [ .au, .at, .be, .ca, .ch, .de, .dk, .es, .fr, .gb, .gr, .hk, .ie, .it, .jp, .lu, .mx, .nl, .no, .nz, .pl, .se, .sg, .si, .us ] // swiftformat:enable wrap // swiftformat:enable wrapArguments } } extension Project.Country: Decodable { enum CodingKeys: String, CodingKey { case countryCode = "country", currency, currencyCode = "currency_code", currencySymbol = "currency_symbol", currencyTrailingCode = "currency_trailing_code", maxPledge = "max_pledge", minPledge = "min_pledge", name, trailingCode = "trailing_code" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { self.countryCode = try container.decode(String.self, forKey: .countryCode) } catch { self.countryCode = try container.decode(String.self, forKey: .name) } do { self.currencyCode = try container.decode(String.self, forKey: .currency) } catch { self.currencyCode = try container.decode(String.self, forKey: .currencyCode) } self.currencySymbol = try container.decode(String.self, forKey: .currencySymbol) self.maxPledge = try? container.decode(Int.self, forKey: .maxPledge) self.minPledge = try? container.decode(Int.self, forKey: .minPledge) do { self.trailingCode = try container.decode(Bool.self, forKey: .currencyTrailingCode) } catch { self.trailingCode = try container.decode(Bool.self, forKey: .trailingCode) } } } extension Project.Country { public init?(currencyCode: String) { guard let country = Project.Country.all.first(where: { $0.currencyCode == currencyCode }) else { return nil } self = country } } extension Project.Country: Equatable {} public func == (lhs: Project.Country, rhs: Project.Country) -> Bool { return lhs.countryCode == rhs.countryCode && lhs.currencySymbol == rhs.currencySymbol && lhs.currencyCode == rhs.currencyCode && lhs.trailingCode == rhs.trailingCode } extension Project.Country: CustomStringConvertible { public var description: String { return "(\(self.countryCode), \(self.currencyCode), \(self.currencySymbol))" } }
apache-2.0
2367b9c3fe41dd4745da5e98a079742b
58
166
0.707335
3.875425
false
false
false
false
younata/RSSClient
TethysKit/Services/ArticleService/ArticleCoordinator.swift
1
2251
import Result import CBGPromise public class ArticleCoordinator { private let localArticleService: ArticleService private let networkArticleService: () -> ArticleService init(localArticleService: ArticleService, networkArticleServiceProvider: @escaping () -> ArticleService) { self.localArticleService = localArticleService self.networkArticleService = networkArticleServiceProvider } private var markArticleSubscriptions: [MarkArticleCall: Subscription<Result<Article, TethysError>>] = [:] public func mark(article: Article, asRead read: Bool) -> Subscription<Result<Article, TethysError>> { let call = MarkArticleCall(articleId: article.identifier, read: read) if let subscription = self.markArticleSubscriptions[call], subscription.isFinished == false { return subscription } let publisher = Publisher<Result<Article, TethysError>>() self.markArticleSubscriptions[call] = publisher.subscription let networkFuture = self.networkArticleService().mark(article: article, asRead: read) self.localArticleService.mark(article: article, asRead: read).then { localResult in publisher.update(with: localResult) networkFuture.then { networkResult in if localResult.error != nil || networkResult.error != nil { publisher.update(with: networkResult) } publisher.finish() self.markArticleSubscriptions.removeValue(forKey: call) } } return publisher.subscription } public func remove(article: Article) -> Future<Result<Void, TethysError>> { return self.localArticleService.remove(article: article) } public func authors(of article: Article) -> String { return self.localArticleService.authors(of: article) } public func date(for article: Article) -> Date { return self.localArticleService.date(for: article) } public func estimatedReadingTime(of article: Article) -> TimeInterval { return self.localArticleService.estimatedReadingTime(of: article) } } private struct MarkArticleCall: Hashable { let articleId: String let read: Bool }
mit
fd70102bc9aa5c4a274bba02d4842e41
39.196429
110
0.689916
4.882863
false
false
false
false
gu704823/ofo
ofo/httpmodel.swift
1
5260
// // httpmodel.swift // ofo // // Created by swift on 2017/5/14. // Copyright © 2017年 swift. All rights reserved. // import UIKit import SwiftyJSON class httpmodel: NSObject { //定义属性 let url = "http://tingapi.ting.baidu.com/v1/restserver/ting?format=json&calback=&from=webapp_music" func onesong(number:Int,json:JSON)->[String:JSON]{ var songdict:[String:JSON] = [:] let title = json["song_list"][number]["title"] let pict = json["song_list"][number]["pic_small"] let author = json["song_list"][number]["author"] let songid = json["song_list"][number]["song_id"] let file_duration = json["song_list"][number]["file_duration"] songdict["title"] = title songdict["pict"] = pict songdict["author"] = author songdict["songid"] = songid songdict["file_duration"] = file_duration return songdict } //电台列表 func onsearhlist(type:String,completion:@escaping (_ albumdict:[String:JSON],_ songdict:[[String:JSON]])->()){ var albumdict:[String:JSON] = [:] var onedict:[String:JSON] = [:] var songdict:[[String:JSON]] = [] let parameters = ["method":"baidu.ting.billboard.billList","type":type,"size":"30","offset":"0"] network.requestdata(url: url, parameters: parameters, method: .get) { (result) in let json = JSON(result) let name = json["billboard"]["name"] let updatatime = json["billboard"]["update_date"] let albumimg = json["billboard"]["pic_s640"] albumdict["name"] = name albumdict["updatatime"] = updatatime albumdict["albumimg"] = albumimg for i in 0..<json["song_list"].count{ onedict = self.onesong(number: i, json: json) songdict.append(onedict) } completion(albumdict, songdict) } } //频道列表 func onsearchchannel(type:Int,completion:@escaping (_ channel:[String:JSON])->()){ var channeldict:[String:JSON] = [:] let parameters = ["method":"baidu.ting.billboard.billList","type":"\(type)","size":"10","offset":"0"] network.requestdata(url: url, parameters: parameters, method: .get) { (result) in let json = JSON(result) let albumimg = json["billboard"]["pic_s210"] let name = json["billboard"]["name"] channeldict["albumimg"] = albumimg channeldict["name"] = name channeldict["id"] = JSON(type) completion(channeldict) } } func onsearchtotalchannel(completion:@escaping (_ dict:[[String:JSON]])->()){ var channelarry:[[String:JSON]] = [] var dict:[String:JSON]?{ didSet{ channelarry.append(dict!) completion(channelarry) } } let arry = [1,2,6,8,9,11,20,21,22,23,24,25,31] for i in arry{ onsearchchannel(type: i) { (data) in dict = data } } } func getmusicdata(songid:String,completion:@escaping (_ filelink:JSON)->()){ let parameters = ["method":"baidu.ting.song.play","songid":songid] network.requestdata(url: url, parameters: parameters, method: .get) { (result) in let json = JSON(result) let filelink = json["bitrate"]["file_link"] completion(filelink) } } } /* http://tingapi.ting.baidu.com/v1/restserver/ting?format=json&calback=&from=webapp_music&method=baidu.ting.billboard.billList&type=6&size=30&offset=0 http://tingapi.ting.baidu.com/v1/restserver/ting?format=json&calback=&from=webapp_music&method=baidu.ting.song.play&songid=826361 一、获取列表 format=json或xml&calback=&from=webapp_music&method= method=baidu.ting.billboard.billList&type=1&size=10&offset=0 参数: type = 1-新歌榜a,2-热歌榜a,11-摇滚榜a,21-欧美金曲榜a,22-经典老歌榜a,23-情歌对唱榜a,24/14-影视金曲榜a,25-网络歌曲榜a,6-ktv热歌榜a ,8-Billboarda,9-雪碧音碰音榜a,20-华语金曲榜a,31-中国好声音榜a size = 10 //返回条目数量 offset = 0 //获取偏移 三、搜索 method=baidu.ting.search.catalogSug&query=海阔天空 四、播放 method=baidu.ting.song.play&songid=877578 method=baidu.ting.song.playAAC&songid=877578 五、LRC歌词 method=baidu.ting.song.lry&songid=877578 六、推荐列表 method=baidu.ting.song.getRecommandSongList&song_id=877578&num=5 七、下载 method=baidu.ting.song.downWeb&songid=877578&bit=24&_t=1393123213 八、获取歌手信息 例:method=baidu.ting.artist.getInfo&tinguid=877578 九、获取歌手歌曲列表 method=baidu.ting.artist.getSongList&tinguid=877578&limits=6&use_cluster=1&order=2 http://c.hiphotos.baidu.com/ting/pic/item/f7246b600c33874495c4d089530fd9f9d62aa0c6.jpg", "pic_s444":"http://d.hiphotos.baidu.com/ting/pic/item/78310a55b319ebc4845c84eb8026cffc1e17169f.jpg", "pic_s260":"http://b.hiphotos.baidu.com/ting/pic/item/e850352ac65c1038cb0f3cb0b0119313b07e894b.jpg", "pic_s210":"http://business.cdn.qianqian.com/qianqian/pic/bos_client_c49310115801d43d42a98fdc357f6057.jpg */
mit
eff5089163ad03f411210d05c0e041fd
38.314961
149
0.626477
3.057563
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieMath/Accelerate/Radix2CooleyTukey/half_cooleytukey_8.swift
1
4889
// // half_cooleytukey_8.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @inlinable @inline(__always) func half_cooleytukey_forward_8<T: BinaryFloatingPoint>(_ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) { var input = input var out_real = out_real var out_imag = out_imag let a1 = input.pointee input += in_stride let e1 = in_count > 1 ? input.pointee : 0 input += in_stride let c1 = in_count > 2 ? input.pointee : 0 input += in_stride let g1 = in_count > 3 ? input.pointee : 0 input += in_stride let b1 = in_count > 4 ? input.pointee : 0 input += in_stride let f1 = in_count > 5 ? input.pointee : 0 input += in_stride let d1 = in_count > 6 ? input.pointee : 0 input += in_stride let h1 = in_count > 7 ? input.pointee : 0 let a3 = a1 + b1 let b3 = a1 - b1 let c3 = c1 + d1 let d3 = c1 - d1 let e3 = e1 + f1 let f3 = e1 - f1 let g3 = g1 + h1 let h3 = g1 - h1 let a5 = a3 + c3 let c5 = a3 - c3 let e5 = e3 + g3 let g5 = e3 - g3 let M_SQRT1_2 = 0.7071067811865475244008443621048490392848359376884740 as T let i = M_SQRT1_2 * (f3 - h3) let j = M_SQRT1_2 * (f3 + h3) out_real.pointee = a5 + e5 out_imag.pointee = a5 - e5 out_real += out_stride out_imag += out_stride out_real.pointee = b3 + i out_imag.pointee = -d3 - j out_real += out_stride out_imag += out_stride out_real.pointee = c5 out_imag.pointee = -g5 out_real += out_stride out_imag += out_stride out_real.pointee = b3 - i out_imag.pointee = d3 - j out_real += out_stride out_imag += out_stride } @inlinable @inline(__always) func half_cooleytukey_inverse_8<T: BinaryFloatingPoint>(_ in_real: UnsafePointer<T>, _ in_imag: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ output: UnsafeMutablePointer<T>, _ out_stride: Int) { var in_real = in_real var in_imag = in_imag var output = output let a1 = in_real.pointee let b1 = in_imag.pointee in_real += in_stride in_imag += in_stride let e1 = in_count > 1 ? in_real.pointee : 0 let e2 = in_count > 1 ? in_imag.pointee : 0 in_real += in_stride in_imag += in_stride let c1 = in_count > 2 ? in_real.pointee : 0 let c2 = in_count > 2 ? in_imag.pointee : 0 in_real += in_stride in_imag += in_stride let g1 = in_count > 3 ? in_real.pointee : 0 let g2 = in_count > 3 ? in_imag.pointee : 0 let a3 = a1 + b1 let b3 = a1 - b1 let c3 = c1 + c1 let d4 = c2 + c2 let e3 = e1 + g1 let e4 = e2 - g2 let f3 = e1 - g1 let f4 = e2 + g2 let g3 = g1 + e1 let g4 = g2 - e2 let h3 = g1 - e1 let h4 = g2 + e2 let a5 = a3 + c3 let b5 = b3 - d4 let c5 = a3 - c3 let d5 = b3 + d4 let e5 = e3 + g3 let f5 = f3 - h4 let f6 = f4 + h3 let g6 = e4 - g4 let h5 = f3 + h4 let h6 = f4 - h3 let M_SQRT1_2 = 0.7071067811865475244008443621048490392848359376884740 as T let i = M_SQRT1_2 * (f5 - f6) let k = M_SQRT1_2 * (h5 + h6) output.pointee = a5 + e5 output += out_stride output.pointee = b5 + i output += out_stride output.pointee = c5 - g6 output += out_stride output.pointee = d5 - k output += out_stride output.pointee = a5 - e5 output += out_stride output.pointee = b5 - i output += out_stride output.pointee = c5 + g6 output += out_stride output.pointee = d5 + k }
mit
957ea559fee7d0c1ea099f967ed573e4
27.097701
212
0.595623
3.096263
false
false
false
false
larryhou/swift
PhotoPreview/PhotoPreview/PageViewController.swift
1
2209
// // ViewController.swift // PhotoPreview // // Created by larryhou on 3/19/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate { let PHOTO_COUNT = 4 private var recycle: [PhotoPreviewController]! private var dataIndex: Int = 0 override func viewDidLoad() { super.viewDidLoad() dataSource = self delegate = self recycle = [] for i in 0..<3 { recycle.append(PhotoPreviewController()) } dataIndex = 0 setViewControllers([getPreviewController(dataIndex: dataIndex)], direction: .Forward, animated: false, completion: nil) } func getPreviewController(dataIndex index: Int) -> PhotoPreviewController { let viewIndex = index % 3 recycle[viewIndex].setImage(UIImage(named: "\(index + 1).jpg")!, dataIndex: index) return recycle[viewIndex] } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let current = viewController as PhotoPreviewController if current.dataIndex + 1 < PHOTO_COUNT { dataIndex = current.dataIndex + 1 return getPreviewController(dataIndex: dataIndex) } return nil } func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let current = viewController as PhotoPreviewController if current.dataIndex > 0 { dataIndex = current.dataIndex - 1 return getPreviewController(dataIndex: dataIndex) } return nil } func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return PHOTO_COUNT } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return dataIndex } // MARK: reset state func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) { var dst = pendingViewControllers.first! as PhotoPreviewController dst.dirty = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
7f9cdfe8612c2cc930b972e140d28221
28.851351
158
0.775464
4.680085
false
false
false
false
lkzhao/Hero
LegacyExamples/Examples/AppleHomePage/AppleProductViewController.swift
1
4543
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Hero let viewControllerIDs = ["iphone", "watch", "macbook"] class AppleProductViewController: UIViewController, HeroViewControllerDelegate { var panGR: UIPanGestureRecognizer! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var primaryLabel: UILabel! @IBOutlet weak var secondaryLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() panGR = UIPanGestureRecognizer(target: self, action: #selector(pan)) view.addGestureRecognizer(panGR) } func applyShrinkModifiers() { view.hero.modifiers = nil primaryLabel.hero.modifiers = [.translate(x:-50, y:(view.center.y - primaryLabel.center.y)/10), .scale(0.9), HeroModifier.duration(0.3)] secondaryLabel.hero.modifiers = [.translate(x:-50, y:(view.center.y - secondaryLabel.center.y)/10), .scale(0.9), HeroModifier.duration(0.3)] imageView.hero.modifiers = [.translate(x:-80), .scale(0.9), HeroModifier.duration(0.3)] } func applySlideModifiers() { view.hero.modifiers = [.translate(x: view.bounds.width), .duration(0.3), .beginWith(modifiers: [.zPosition(2)])] primaryLabel.hero.modifiers = [.translate(x:100), .duration(0.3)] secondaryLabel.hero.modifiers = [.translate(x:100), .duration(0.3)] imageView.hero.modifiers = nil } enum TransitionState { case normal, slidingLeft, slidingRight } var state: TransitionState = .normal weak var nextVC: AppleProductViewController? @objc func pan() { let translateX = panGR.translation(in: nil).x let velocityX = panGR.velocity(in: nil).x switch panGR.state { case .began, .changed: let nextState: TransitionState if state == .normal { nextState = velocityX < 0 ? .slidingLeft : .slidingRight } else { nextState = translateX < 0 ? .slidingLeft : .slidingRight } if nextState != state { Hero.shared.cancel(animate: false) let currentIndex = viewControllerIDs.index(of: self.title!)! let nextIndex = (currentIndex + (nextState == .slidingLeft ? 1 : viewControllerIDs.count - 1)) % viewControllerIDs.count nextVC = self.storyboard!.instantiateViewController(withIdentifier: viewControllerIDs[nextIndex]) as? AppleProductViewController if nextState == .slidingLeft { applyShrinkModifiers() nextVC!.applySlideModifiers() } else { applySlideModifiers() nextVC!.applyShrinkModifiers() } state = nextState hero.replaceViewController(with: nextVC!) } else { let progress = abs(translateX / view.bounds.width) Hero.shared.update(progress) if state == .slidingLeft, let nextVC = nextVC { Hero.shared.apply(modifiers: [.translate(x: view.bounds.width + translateX)], to: nextVC.view) } else { Hero.shared.apply(modifiers: [.translate(x: translateX)], to: view) } } default: let progress = (translateX + velocityX) / view.bounds.width if (progress < 0) == (state == .slidingLeft) && abs(progress) > 0.3 { Hero.shared.finish() } else { Hero.shared.cancel() } state = .normal } } func heroWillStartAnimatingTo(viewController: UIViewController) { if !(viewController is AppleProductViewController) { view.hero.modifiers = [.ignoreSubviewModifiers(recursive: true)] } } }
mit
22acc6d3f29947a5912eb20fb4449e3f
38.850877
144
0.690073
4.206481
false
false
false
false
xuzhuoxi/SearchKit
Source/cs/resource/Resource.swift
1
4311
// // Resource.swift // SearchKit // // Created by 许灼溪 on 15/12/15. // // import Foundation /** * * @author xuzhuoxi * */ open class Resource { fileprivate let name : String fileprivate var keyList : [String] fileprivate var valueList : [String] /** * 键值对数量 * * @return 键值对数量 */ open var size: Int { return keyList.count } fileprivate init(name: String) { self.name = name self.keyList = [] self.valueList = [] } /** * 判断是否为键 * * @param key * 待判断的键 * @return 是true否false */ public final func isKey(_ key : String) ->Bool { return keyList.contains(key) } /** * 取键 * * @param index * 索引 * @return 键 */ public final func getKey(_ index : Int) ->String { return keyList[index] } /** * 取全部键 * * @return 键组成的数组 */ public final func getKeys() ->Array<String> { let rs = keyList return rs } /** * 取值 * * @param index * 索引 * @return 值 */ public final func getValue(_ index : Int) ->String { return valueList[index]; } /** * 取全部值 * * @return 值 */ public final func getValues() ->Array<String> { let rs = valueList return rs } /** * 追加一个资源文件 */ public final func appendFile(_ absoluteFilePath: String) { let nPath = absoluteFilePath let fileManager = FileManager.default if fileManager.fileExists(atPath: nPath) { do { let content = try NSString(contentsOfFile: nPath, encoding: String.Encoding.utf8.rawValue) self.appendDataString(content as String) } catch { } } // let tfr = TextFileReader(path: absoluteFilePath) // while let line = tfr.nextLine() { // self.appendLine(line) // } } /** * 追加字符串数据 */ public final func appendDataString(_ dataString: String) { let dataArray = dataString.components(separatedBy: "\n") for str in dataArray { self.appendLine(str) } } /** * 追加一行数据 */ public final func appendLine(_ lineString: String) { if lineString.isEmpty{ return } let trimLine = lineString.trim() if trimLine.isEmpty { return } if let index = trimLine.characters.index(of: "=") { let key = trimLine.substring(to: index).trimRight() if key.isEmpty { return } let value = trimLine.substring(from: trimLine.index(index, offsetBy: 1)).trimLeft() if value.isEmpty { return } self.keyList.append(key) self.valueList.append(value) } } /** * 追加一对数据 */ public final func appendData(_ key: String, value: String) { if key.isEmpty || value.isEmpty { return } self.keyList.append(key) self.valueList.append(value) } /** * 通过字符串数据创建实例<br> * * @param data * 字符串数据 * @return Resource实例 */ open static func getResourceByData(_ data:String) -> Resource? { if data.isEmpty { return nil } let rs = Resource(name : "\(data.hashValue)") rs.appendDataString(data) return rs } /** * 通过资源的路径创建实例,默认资源编码格式为UTF-8。<br> * * @param absoluteFilePath * 文件路径 * @return * 路径有效且格式正确: Resource实例 * 否则:nil */ open static func getResource(_ absoluteFilePath: String) ->Resource? { let rs = Resource(name: "\(absoluteFilePath.hashValue)") rs.appendFile(absoluteFilePath) if rs.size <= 0 { return nil } return rs } }
mit
c750e8cdde4ed0ca91da524b0395e73a
20.609626
106
0.496164
4.140369
false
false
false
false
shamasshahid/SSCheckBoxButton
SampleProject/SampleProject/SSCheckBoxButton/SSCheckBoxButton.swift
1
3688
// // SSCheckBoxButton.swift // SampleProject // // Created by Al Shamas Tufail on 03/06/2015. // Copyright (c) 2015 Shamas Shahid. All rights reserved. // import UIKit @IBDesignable class SSCheckBoxButton: UIButton { private var tickLayer = CAShapeLayer() private var backLayer = CAShapeLayer() @IBInspectable var checkBoxColor: UIColor = UIColor.redColor() @IBInspectable var insetEdge: CGFloat = 2 { didSet { self.layoutIfNeeded() } } @IBInspectable var lineWidth: CGFloat = 2 @IBInspectable var tickLineWidth: CGFloat = 4 var animationDuration = 0.25 override var selected: Bool { didSet { self.updateState() } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(frame: CGRect) { super.init(frame: frame) initialize() } private func initialize() { var aRect = rectForSquare() backLayer.frame = aRect backLayer.lineWidth = lineWidth backLayer.fillColor = UIColor.clearColor().CGColor backLayer.strokeColor = checkBoxColor.CGColor layer.addSublayer(backLayer) backLayer.path = UIBezierPath(roundedRect: rectForSquare(), cornerRadius: 1).CGPath self.titleEdgeInsets = UIEdgeInsetsMake(0, (aRect.size.width), 0, 0) self.addTarget(self, action: "pressed:", forControlEvents: UIControlEvents.TouchUpInside) updateState() } func pressed(button: UIButton) { if self.selected { self.selected = false } else { self.selected = true } } private func updateState() { if selected { var boundingRect = rectForSquare() backLayer.lineWidth = lineWidth backLayer.path = UIBezierPath(roundedRect: boundingRect, cornerRadius: 1).CGPath backLayer.frame = boundingRect backLayer.strokeColor = checkBoxColor.CGColor var path = UIBezierPath() path.moveToPoint(CGPointMake(tickLineWidth + boundingRect.origin.x + (boundingRect.size.width*0.1), boundingRect.origin.y + boundingRect.size.height/2)) path.addLineToPoint(CGPointMake(boundingRect.origin.x + boundingRect.size.width/2, boundingRect.origin.y + (boundingRect.size.height * 0.9))) path.addLineToPoint(CGPointMake(boundingRect.origin.x + (boundingRect.size.width * 1.2), boundingRect.origin.y + boundingRect.size.height * 0.2)) tickLayer.fillColor = UIColor.clearColor().CGColor tickLayer.path = path.CGPath tickLayer.frame = bounds tickLayer.strokeColor = UIColor.blackColor().CGColor tickLayer.lineWidth = tickLineWidth tickLayer.lineJoin = kCALineJoinBevel layer.addSublayer(tickLayer) var pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = animationDuration pathAnimation.fromValue = NSNumber(float: 0.0) pathAnimation.toValue = NSNumber(float: 1.0) tickLayer.addAnimation(pathAnimation, forKey: "strokeEndAnimation") } else { tickLayer.removeFromSuperlayer() } } private func rectForSquare() ->CGRect { var rect = CGRectMake(insetEdge, insetEdge, (frame.size.width > frame.size.height ? frame.size.height : frame.size.width) - (4 * insetEdge) , (frame.size.width > frame.size.height ? frame.size.height : frame.size.width) - (4 * insetEdge)) return rect } override func prepareForInterfaceBuilder() { initialize() } }
mit
5551f37793d920de064c75c88c597740
35.88
246
0.644252
4.777202
false
false
false
false
bogaara/joke
Joke/Joke/Classes/Tools/NetworkTools.swift
1
1334
// // NetworkTools.swift // Joke // // Created by 董宏 on 16/11/13. // Copyright © 2016年 谭安溪. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { /// 网络请求 /// /// - parameter type: 请求类型 /// - parameter url: 请求地址 /// - parameter parameters: 请求参数 /// - parameter finishedCallBack: 请求完成回调 static func requestData(_ type: MethodType, url: String, parameters:[String: Any]? = nil, finishedCallBack:@escaping (_ result: [String: Any]) -> ()){ //判断请求类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post //发送请求 _ = Alamofire.request(url, method: method, parameters: parameters).responseJSON(completionHandler: { (response) in //判断返回数据 guard let result = response.result.value as? [String: Any] else{ print(response.result.error) return } //判断状态码 guard result["code"] as! Int == 1 else{ print(result["message"] as! String) return } //执行回调 finishedCallBack(result) }) } }
apache-2.0
103ed25dac84e2e232958d8c492ebd6b
27.534884
154
0.535452
4.382143
false
false
false
false
OEASLAN/LetsEat
IOS/Let's Eat/Let's Eat/TabBar VC/Profile Tab/ProfileVC.swift
1
2838
// // ProfileVC.swift // login // // Created by VidalHARA on 5.11.2014. // Copyright (c) 2014 MacBook Retina. All rights reserved. // import UIKit class ProfileVC: UIViewController, FBSDKLoginButtonDelegate { @IBOutlet weak var nameField: UILabel! @IBOutlet weak var surnameField: UILabel! @IBOutlet weak var userNameField: UILabel! @IBOutlet weak var logOutButton: UIButton! @IBOutlet weak var emailField: UILabel! @IBOutlet weak var fLogOutView: FBSDKLoginButton! @IBOutlet weak var changePasswordButton: UIButton! @IBOutlet weak var infoButton: UIButton! var user: [String: NSString]! let alert = Alerts() let apiMethod = ApiMethods() override func viewWillAppear(animated: Bool) { let userDefaults = NSUserDefaults.standardUserDefaults() if let userInfo = userDefaults.objectForKey("userInfo") as? [String: NSString]{ user = userInfo nameField.text = user["name"] as? String surnameField.text = user["surname"] as? String userNameField.text = user["username"] as? String emailField.text = user["email"] as? String } if (FBSDKAccessToken.currentAccessToken() != nil){ changePasswordButton.hidden = true logOutButton.hidden = true fLogOutView.hidden = false }else{ changePasswordButton.hidden = false logOutButton.hidden = false fLogOutView.hidden = true } } func loginButton(fLogOutView: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { println("User Logged In") } func loginButtonDidLogOut(fLogOutView: FBSDKLoginButton!) { println("User Logged Out") let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setInteger(0, forKey: "ISLOGGEDIN") userDefaults.removeObjectForKey("userInfo") userDefaults.removeObjectForKey("Friends") userDefaults.removeObjectForKey("USERNAME") self.tabBarController?.selectedIndex = 0 } @IBAction func logoutTapped() { apiMethod.requestLogout(self) self.tabBarController?.selectedIndex = 0 } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if sender is UIButton{ if sender as! UIButton == infoButton{ let infoVC = segue.destinationViewController as! ChangeInfoVC if user != nil { infoVC.user = user } }else if sender as! UIButton == changePasswordButton{ let passwordVC = segue.destinationViewController as! ChangePasswordVC if user != nil { passwordVC.user = user } } } } }
gpl-2.0
a9a28b06a2ba3fd6ff925d1ff78c1f8e
33.192771
132
0.639535
5.169399
false
false
false
false
domenicosolazzo/practice-swift
CoreLocation/Customizing the View of the Map with a Camera/Customizing the View of the Map with a Camera/ViewController.swift
1
4998
// // ViewController.swift // Customizing the View of the Map with a Camera // // Created by Domenico Solazzo on 19/05/15. // License MIT // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate{ var mapView: MKMapView! var locationManager: CLLocationManager? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) mapView = MKMapView() } /* Set up the map and add it to our view */ override func viewDidLoad() { super.viewDidLoad() mapView.mapType = .standard mapView.frame = view.frame mapView.delegate = self view.addSubview(mapView) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) /* Are location services available on this device? */ if CLLocationManager.locationServicesEnabled(){ /* Do we have authorization to access location services? */ switch CLLocationManager.authorizationStatus(){ case .denied: /* No */ displayAlertWithTitle("Not Determined", message: "Location services are not allowed for this app") case .notDetermined: /* We don't know yet, we have to ask */ locationManager = CLLocationManager() if let manager = locationManager{ manager.delegate = self manager.requestWhenInUseAuthorization() } case .restricted: /* Restrictions have been applied, we have no access to location services */ displayAlertWithTitle("Restricted", message: "Location services are not allowed for this app") default: showUserLocationOnMapView() } } else { /* Location services are not enabled. Take appropriate action: for instance, prompt the user to enable the location services */ print("Location services are not enabled") } } //- MARK: Location Manager func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){ print("Location manager failed with error = \(error)") } /* The authorization status of the user has changed, we need to react to that so that if she has authorized our app to to view her location, we will accordingly attempt to do so */ func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus){ print("The authorization status of location services is changed to: ", terminator: "") switch CLLocationManager.authorizationStatus(){ case .denied: print("Denied") case .notDetermined: print("Not determined") case .restricted: print("Restricted") default: showUserLocationOnMapView() } } //- MARK: MapView func mapView(_ mapView: MKMapView, didFailToLocateUserWithError error: Error) { displayAlertWithTitle("Failed", message: "Could not get the user's location") } func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation){ print("Setting the camera for our map view...") let userCoordinate = userLocation.coordinate /* Assuming my location is hardcoded to lat: 58.592725 and long:16.185962, the following camera angle works perfectly for me */ let eyeCoordinate = CLLocationCoordinate2D( latitude: 58.571647, longitude: 16.234660) let camera = MKMapCamera( lookingAtCenter: userCoordinate, fromEyeCoordinate: eyeCoordinate, eyeAltitude: 400.0) mapView.setCamera(camera, animated: true) } //- MARK: Helper methods /* Just a little method to help us display alert dialogs to the user */ func displayAlertWithTitle(_ title: String, message: String){ let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) present(controller, animated: true, completion: nil) } /* We will call this method when we are sure that the user has given us access to her location */ func showUserLocationOnMapView(){ mapView.showsUserLocation = true mapView.userTrackingMode = .follow } }
mit
8f8edf8274c7c5b7b0297892cb0fb2ef
32.77027
98
0.57623
5.914793
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Transfer/Coordinators/ConfirmCoordinator.swift
1
2365
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import TrustCore import TrustKeystore import Result protocol ConfirmCoordinatorDelegate: class { func didCancel(in coordinator: ConfirmCoordinator) } final class ConfirmCoordinator: RootCoordinator { let navigationController: NavigationController let session: WalletSession let account: Account let keystore: Keystore let configurator: TransactionConfigurator var didCompleted: ((Result<ConfirmResult, AnyError>) -> Void)? let type: ConfirmType let server: RPCServer var coordinators: [Coordinator] = [] weak var delegate: ConfirmCoordinatorDelegate? var rootViewController: UIViewController { return controller } private lazy var controller: ConfirmPaymentViewController = { return ConfirmPaymentViewController( session: session, keystore: keystore, configurator: configurator, confirmType: type, server: server ) }() init( navigationController: NavigationController = NavigationController(), session: WalletSession, configurator: TransactionConfigurator, keystore: Keystore, account: Account, type: ConfirmType, server: RPCServer ) { self.navigationController = navigationController self.navigationController.modalPresentationStyle = .formSheet self.session = session self.configurator = configurator self.keystore = keystore self.account = account self.type = type self.server = server controller.didCompleted = { [weak self] result in guard let `self` = self else { return } switch result { case .success(let data): self.didCompleted?(.success(data)) case .failure(let error): self.didCompleted?(.failure(error)) } } } func start() { controller.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(dismiss)) navigationController.viewControllers = [controller] } @objc func dismiss() { didCompleted?(.failure(AnyError(DAppError.cancelled))) delegate?.didCancel(in: self) } }
gpl-3.0
afa1cf366e60325d05f49574cf4fc54e
29.320513
141
0.658351
5.564706
false
true
false
false
TrustWallet/trust-wallet-ios
Trust/Foundation/QRGenerator.swift
1
677
// Copyright DApps Platform Inc. All rights reserved. import UIKit final class QRGenerator { static func generate(from string: String) -> UIImage? { let context = CIContext() let data = string.data(using: String.Encoding.ascii) if let filter = CIFilter(name: "CIQRCodeGenerator") { filter.setValue(data, forKey: "inputMessage") let transform = CGAffineTransform(scaleX: 7, y: 7) if let output = filter.outputImage?.transformed(by: transform), let cgImage = context.createCGImage(output, from: output.extent) { return UIImage(cgImage: cgImage) } } return nil } }
gpl-3.0
756c6e2712eb824d1b63fea9ed937b19
34.631579
142
0.630724
4.605442
false
false
false
false
Legoless/iOS-Course
2015-1/Lesson10/MyWeather/MyWeather/WeatherIconView.swift
1
1480
// // WeatherIconView.swift // MyWeather // // Created by Dal Rupnik on 11/11/15. // Copyright © 2015 Unified Sense. All rights reserved. // import UIKit enum WeatherIcon : String { case Cloudy = "cloudy" case Fog = "fog" case Frost = "frost" case Rain = "rain" case Showers = "showers" case Snowy = "snowy" case SunRain = "sun-rain" case PartlyCloudy = "sunny-cloudy" case Sunny = "sunny" case Thunder = "thunder" } class WeatherIconView: UIView { var iconType : WeatherIcon = .Sunny { didSet { imageView.image = UIImage(named: iconType.rawValue) } } private var imageView : UIImageView override init(frame: CGRect) { imageView = UIImageView(frame: frame) imageView.image = UIImage(named: WeatherIcon.Sunny.rawValue) super.init(frame: frame) addSubview(imageView) //insertSubview(imageView, atIndex: 0) //bringSubviewToFront(imageView) } required init?(coder aDecoder: NSCoder) { imageView = UIImageView(coder: aDecoder)! imageView.image = UIImage(named: WeatherIcon.Sunny.rawValue) super.init(coder: aDecoder) addSubview(imageView) } override func layoutSubviews() { super.layoutSubviews() imageView.frame = self.bounds } }
mit
ecb67f3e3ac0b32bd7502440a541f787
23.245902
68
0.571332
4.401786
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/Kingfisher/String+MD5.swift
4
8743
// // String+MD5.swift // Kingfisher // // This file is stolen from HanekeSwift: https://github.com/Haneke/HanekeSwift/blob/master/Haneke/CryptoSwiftMD5.swift // which is a modified version of CryptoSwift: // // To date, adding CommonCrypto to a Swift framework is problematic. See: // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework // We're using a subset of CryptoSwift as a (temporary?) alternative. // The following is an altered source version that only includes MD5. The original software can be found at: // https://github.com/krzyzanowskim/CryptoSwift // This is the original copyright notice: /* Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. - This notice may not be removed or altered from any source or binary distribution. */ import Foundation extension String { func kf_MD5() -> String { if let data = dataUsingEncoding(NSUTF8StringEncoding) { let MD5Calculator = MD5(data) let MD5Data = MD5Calculator.calculate() let resultBytes = UnsafeMutablePointer<CUnsignedChar>(MD5Data.bytes) let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: MD5Data.length) var MD5String = "" for c in resultEnumerator { MD5String += String(format: "%02x", c) } return MD5String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (sizeofValue(value) * 8) let valuePointer = UnsafeMutablePointer<T>.alloc(1) valuePointer.memory = value let bytesPointer = UnsafeMutablePointer<UInt8>(valuePointer) var bytes = [UInt8](count: totalBytes, repeatedValue: 0) for j in 0..<min(sizeof(T), totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).memory } valuePointer.destroy() valuePointer.dealloc(1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(totalBytes: Int = sizeof(Int)) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(arrayOfBytes: [UInt8]) { appendBytes(arrayOfBytes, length: arrayOfBytes.count) } } class HashBase { var message: NSData init(_ message: NSData) { self.message = message } /** Common part for hash calculation. Prepare header data. */ func prepare(len: Int = 64) -> NSMutableData { let tmpMessage: NSMutableData = NSMutableData(data: self.message) // Step 1. Append Padding Bits tmpMessage.appendBytes([0x80]) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.length var counter = 0 while msgLength % len != (len - 8) { counter++ msgLength++ } let bufZeros = UnsafeMutablePointer<UInt8>(calloc(counter, sizeof(UInt8))) tmpMessage.appendBytes(bufZeros, length: counter) bufZeros.destroy() bufZeros.dealloc(1) return tmpMessage } } func rotateLeft(value: UInt32, bits: UInt32) -> UInt32 { return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) } class MD5 : HashBase { /** specifies the per-round shift amounts */ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let hashs: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> NSData { let tmpMessage = prepare() // hash values var hh = hashs // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.length * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage.appendBytes(Array(lengthBytes.reverse())) // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 var leftMessageBytes = tmpMessage.length for (var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes) { let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes, leftMessageBytes))) // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M: [UInt32] = [UInt32](count: 16, repeatedValue: 0) let range = NSRange(location:0, length: M.count * sizeof(UInt32)) chunk.getBytes(UnsafeMutablePointer<Void>(M), range: range) // Initialize hash value for this chunk: var A: UInt32 = hh[0] var B: UInt32 = hh[1] var C: UInt32 = hh[2] var D: UInt32 = hh[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< sines.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } let buf: NSMutableData = NSMutableData() hh.forEach({ (item) -> () in var i:UInt32 = item.littleEndian buf.appendBytes(&i, length: sizeofValue(i)) }) return buf.copy() as! NSData } }
apache-2.0
66ecaa2a3ca34c9336fad4189014f7d3
38.529412
213
0.557463
3.880942
false
false
false
false
opentok/opentok-ios-sdk-samples-swift
Custom-Audio-Driver/Custom-Audio-Driver/ViewController.swift
1
4940
// // ViewController.swift // Custom-Audio-Driver // // Created by Roberto Perez Cubero on 11/08/16. // Copyright © 2016 tokbox. All rights reserved. // import UIKit import OpenTok let kWidgetHeight = 240 let kWidgetWidth = 320 // *** Fill the following variables using your own Project info *** // *** https://tokbox.com/account/#/ *** // Replace with your OpenTok API key let kApiKey = "" // Replace with your generated session ID let kSessionId = "" // Replace with your generated token let kToken = "" class ViewController: UIViewController { lazy var session: OTSession = { return OTSession(apiKey: kApiKey, sessionId: kSessionId, delegate: self)! }() var publisher: OTPublisher? var subscriber: OTSubscriber? let customAudioDevice = DefaultAudioDevice() override func viewDidLoad() { super.viewDidLoad() OTAudioDeviceManager.setAudioDevice(customAudioDevice) doConnect() } /** * Asynchronously begins the session connect process. Some time later, we will * expect a delegate method to call us back with the results of this action. */ private func doConnect() { var error: OTError? defer { process(error: error) } session.connect(withToken: kToken, error: &error) } /** * Sets up an instance of OTPublisher to use with this session. OTPubilsher * binds to the device camera and microphone, and will provide A/V streams * to the OpenTok session. */ fileprivate func doPublish() { var error: OTError? = nil defer { process(error: error) } let settings = OTPublisherSettings() settings.name = UIDevice.current.name publisher = OTPublisher(delegate: self, settings: settings) if let pub = publisher, let pubView = pub.view { session.publish(pub, error: &error) pubView.frame = CGRect(x: 0, y: 0, width: kWidgetWidth, height: kWidgetHeight) view.addSubview(pubView) } } fileprivate func doSubscribe(_ stream: OTStream) { var error: OTError? defer { process(error: error) } subscriber = OTSubscriber(stream: stream, delegate: self) session.subscribe(subscriber!, error: &error) } fileprivate func process(error err: OTError?) { if let e = err { showAlert(errorStr: e.localizedDescription) } } fileprivate func showAlert(errorStr err: String) { DispatchQueue.main.async { let controller = UIAlertController(title: "Error", message: err, preferredStyle: .alert) controller.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) self.present(controller, animated: true, completion: nil) } } } // MARK: - OTSession delegate callbacks extension ViewController: OTSessionDelegate { func sessionDidConnect(_ session: OTSession) { print("Session connected") doPublish() } func sessionDidDisconnect(_ session: OTSession) { print("Session disconnected") } func session(_ session: OTSession, streamCreated stream: OTStream) { print("Session streamCreated: \(stream.streamId)") doSubscribe(stream) } func session(_ session: OTSession, streamDestroyed stream: OTStream) { print("Session streamDestroyed: \(stream.streamId)") if let subStream = subscriber?.stream, subStream.streamId == stream.streamId { subscriber?.view?.removeFromSuperview() } } func session(_ session: OTSession, didFailWithError error: OTError) { print("session Failed to connect: \(error.localizedDescription)") } } // MARK: - OTPublisher delegate callbacks extension ViewController: OTPublisherDelegate { func publisher(_ publisher: OTPublisherKit, streamCreated stream: OTStream) { print("Publishing") } func publisher(_ publisher: OTPublisherKit, streamDestroyed stream: OTStream) { } func publisher(_ publisher: OTPublisherKit, didFailWithError error: OTError) { print("Publisher failed: \(error.localizedDescription)") } } // MARK: - OTSubscriber delegate callbacks extension ViewController: OTSubscriberDelegate { func subscriberDidConnect(toStream subscriberKit: OTSubscriberKit) { subscriber?.view?.frame = CGRect(x: 0, y: kWidgetHeight, width: kWidgetWidth, height: kWidgetHeight) if let subsView = subscriber?.view { view.addSubview(subsView) } } func subscriber(_ subscriber: OTSubscriberKit, didFailWithError error: OTError) { print("Subscriber failed: \(error.localizedDescription)") } func subscriberVideoDataReceived(_ subscriber: OTSubscriber) { } }
mit
05456454d49ec0cf13e086b3a91f0c55
30.864516
108
0.64264
4.771981
false
false
false
false