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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fabiomassimo/GAuth | Sources/Models/DeviceAuthorizationToken.swift | 1 | 2120 | //
// UserCode.swift
// GoogleAuthenticator
//
// Created by Fabio Milano on 12/06/16.
// Copyright © 2016 Touchwonders. All rights reserved.
//
import Foundation
// EXAMPLE
//{
// "device_code" : "THE DEVICE CODE",
// "user_code" : "THE USER CODE",
// "verification_url" : "https://www.google.com/device",
// "expires_in" : 1800,
// "interval" : 5
//}
/**
* A DeviceAuthorizationToken struct represents the response object when starting an authentication via device token.
*/
internal struct DeviceAuthorizationToken {
/// The device code related to the authorization request.
let deviceCode: String
/// The user code. This should be shown to the user to complete the authorization process.
let userCode: String
/// The verification URL to which the user should connect to in order to complete the authorization process.
let verificationUrl: NSURL
/// Expiration of the user code expressend in NSTimeInterval
let expiresIn: NSTimeInterval
/// The retry interval to use when polling the authorization against Google
let retryInterval: NSTimeInterval
init?(json: [String: AnyObject]) {
guard let deviceCode = json[UserCodeJSONKey.DeviceCode.rawValue] as? String,
verificationUrl = json[UserCodeJSONKey.VerificationUrl.rawValue] as? String,
userCode = json[UserCodeJSONKey.UserCode.rawValue] as? String,
expiresIn = json[UserCodeJSONKey.ExpiresIn.rawValue] as? NSTimeInterval,
retryInterval = json[UserCodeJSONKey.RetryInterval.rawValue] as? NSTimeInterval else {
return nil
}
self.deviceCode = deviceCode
self.userCode = userCode
self.verificationUrl = NSURL(string: verificationUrl)!
self.expiresIn = expiresIn
self.retryInterval = retryInterval
}
}
private enum UserCodeJSONKey: String {
case DeviceCode = "device_code"
case VerificationUrl = "verification_url"
case UserCode = "user_code"
case ExpiresIn = "expires_in"
case RetryInterval = "interval"
} | mit | 623857e7d3c166596f15f4f89454dda0 | 32.650794 | 118 | 0.677206 | 4.527778 | false | false | false | false |
jterhorst/SwiftParseDemo | SwiftParseExample/DetailViewController.swift | 1 | 2571 | //
// DetailViewController.swift
// SwiftParseExample
//
// Created by Jason Terhorst on 7/14/14.
// Copyright (c) 2014 Jason Terhorst. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UISplitViewControllerDelegate {
@IBOutlet var detailDescriptionLabel: UILabel?
var masterPopoverController: UIPopoverController? = nil
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.valueForKey("name") as NSString
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = "Master" // NSLocalizedString(@"Master", @"Master")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
| mit | f142db6757bcfd8f5299beee13a94766 | 37.373134 | 238 | 0.712563 | 6.092417 | false | false | false | false |
kasei/kineo | Sources/Kineo/SimpleParser/QueryParser.swift | 1 | 16218 | //
// QueryParser.swift
// Kineo
//
// Created by Gregory Todd Williams on 5/10/18.
//
import Foundation
import SPARQLSyntax
// swiftlint:disable:next type_body_length
open class QueryParser<T: LineReadable> {
let reader: T
var stack: [Algebra]
public init(reader: T) {
self.reader = reader
self.stack = []
}
// swiftlint:disable:next cyclomatic_complexity
func parse(line: String) throws -> Algebra? {
let parts = line.components(separatedBy: " ").filter { $0 != "" && !$0.hasPrefix("\t") }
guard parts.count > 0 else { return nil }
if parts[0].hasPrefix("#") { return nil }
let rest = parts.suffix(from: 1).joined(separator: " ")
let op = parts[0]
if op == "project" {
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
let vars = Array(parts.suffix(from: 1))
guard vars.count > 0 else { throw QueryError.parseError("No projection variables supplied") }
return .project(child, Set(vars))
} else if op == "join" {
guard stack.count >= 2 else { throw QueryError.parseError("Not enough operands for \(op)") }
guard let rhs = stack.popLast() else { return nil }
guard let lhs = stack.popLast() else { return nil }
return .innerJoin(lhs, rhs)
} else if op == "union" {
guard stack.count >= 2 else { throw QueryError.parseError("Not enough operands for \(op)") }
guard let rhs = stack.popLast() else { return nil }
guard let lhs = stack.popLast() else { return nil }
return .union(lhs, rhs)
} else if op == "leftjoin" {
guard stack.count >= 2 else { throw QueryError.parseError("Not enough operands for \(op)") }
guard let rhs = stack.popLast() else { return nil }
guard let lhs = stack.popLast() else { return nil }
return .leftOuterJoin(lhs, rhs, .node(.bound(Term.trueValue)))
} else if op == "quad" {
let parser = NTriplesPatternParser(reader: "")
guard let pattern = parser.parseQuadPattern(line: rest) else { return nil }
return .quad(pattern)
} else if op == "triple" {
let parser = NTriplesPatternParser(reader: "")
guard let pattern = parser.parseTriplePattern(line: rest) else { return nil }
return .triple(pattern)
} else if op == "nps" {
let parser = NTriplesPatternParser(reader: "")
let view = AnyIterator(rest.unicodeScalars.makeIterator())
var chars = PeekableIterator(generator: view)
guard let nodes = parser.parseNodes(chars: &chars, count: 2) else { return nil }
guard nodes.count == 2 else { return nil }
let iriStrings = chars.elements().map { String($0) }.joined(separator: "").components(separatedBy: " ")
let iris = iriStrings.map { Term(value: $0, type: .iri) }
return .path(nodes[0], .nps(iris), nodes[1])
} else if op == "path" {
let parser = NTriplesPatternParser(reader: "")
let view = AnyIterator(rest.unicodeScalars.makeIterator())
var chars = PeekableIterator(generator: view)
guard let nodes = parser.parseNodes(chars: &chars, count: 2) else { return nil }
guard nodes.count == 2 else { return nil }
let rest = chars.elements().map { String($0) }.joined(separator: "").components(separatedBy: " ")
guard let pp = try parsePropertyPath(rest) else { throw QueryError.parseError("Failed to parse property path") }
return .path(nodes[0], pp, nodes[1])
} else if op == "agg" { // (SUM(?skey) AS ?sresult) (AVG(?akey) AS ?aresult) ... GROUP BY ?x ?y ?z --> "agg sum sresult ?skey , avg aresult ?akey ; ?x , ?y , ?z"
let pair = parts.suffix(from: 1).split(separator: ";")
guard pair.count >= 1 else { throw QueryError.parseError("Bad syntax for agg operation") }
let aggs = pair[0].split(separator: ",")
guard aggs.count > 0 else { throw QueryError.parseError("Bad syntax for agg operation") }
let groupby = pair.count == 2 ? pair[1].split(separator: ",") : []
var aggregates = [Algebra.AggregationMapping]()
for a in aggs {
let strings = Array(a)
guard strings.count >= 3 else { throw QueryError.parseError("Failed to parse aggregate expression") }
let op = strings[0]
let name = strings[1]
var expr: Expression!
if op != "countall" {
guard let e = try ExpressionParser.parseExpression(Array(strings.suffix(from: 2))) else { throw QueryError.parseError("Failed to parse aggregate expression") }
expr = e
}
var agg: Aggregation
switch op {
case "avg":
agg = .avg(expr, false)
case "sum":
agg = .sum(expr, false)
case "count":
agg = .count(expr, false)
case "countall":
agg = .countAll
default:
throw QueryError.parseError("Unexpected aggregation operation: \(op)")
}
let aggMap = Algebra.AggregationMapping(aggregation: agg, variableName: name)
aggregates.append(aggMap)
}
let groups = try groupby.map { (gstrings) -> Expression in
guard let e = try ExpressionParser.parseExpression(Array(gstrings)) else { throw QueryError.parseError("Failed to parse aggregate expression") }
return e
}
guard let child = stack.popLast() else { return nil }
return .aggregate(child, groups, Set(aggregates))
} else if op == "window" { // window row rowresult , rank rankresult ; ?x , ?y , ?z"
let pair = parts.suffix(from: 1).split(separator: ";")
guard pair.count >= 1 else { throw QueryError.parseError("Bad syntax for window operation") }
let w = pair[0].split(separator: ",")
guard w.count > 0 else { throw QueryError.parseError("Bad syntax for window operation") }
let groupby = pair.count == 2 ? pair[1].split(separator: ",") : []
let groups = try groupby.map { (gstrings) -> Expression in
guard let e = try ExpressionParser.parseExpression(Array(gstrings)) else { throw QueryError.parseError("Failed to parse aggregate expression") }
return e
}
var windows: [Algebra.WindowFunctionMapping] = []
for a in w {
let strings = Array(a)
guard strings.count >= 2 else { throw QueryError.parseError("Failed to parse window expression") }
let op = strings[0]
let name = strings[1]
// var expr: Expression!
var f: WindowFunction
switch op {
case "rank":
f = .rank
case "row":
f = .rowNumber
default:
throw QueryError.parseError("Unexpected window operation: \(op)")
}
let frame = WindowFrame(type: .rows, from: .unbound, to: .unbound)
let windowApp = WindowApplication(windowFunction: f, comparators: [], partition: groups, frame: frame)
let windowMap = Algebra.WindowFunctionMapping(windowApplication: windowApp, variableName: name)
windows.append(windowMap)
}
guard let child = stack.popLast() else { return nil }
return .window(child, windows)
} else if op == "avg" { // (AVG(?key) AS ?name) ... GROUP BY ?x ?y ?z --> "avg key name x y z"
guard parts.count > 2 else { return nil }
let key = parts[1]
let name = parts[2]
let groups = parts.suffix(from: 3).map { (name) -> Expression in .node(.variable(name, binding: true)) }
guard let child = stack.popLast() else { return nil }
let aggMap = Algebra.AggregationMapping(aggregation: .avg(.node(.variable(key, binding: true)), false), variableName: name)
return .aggregate(child, groups, [aggMap])
} else if op == "sum" { // (SUM(?key) AS ?name) ... GROUP BY ?x ?y ?z --> "sum key name x y z"
guard parts.count > 2 else { throw QueryError.parseError("Not enough arguments for \(op)") }
let key = parts[1]
let name = parts[2]
let groups = parts.suffix(from: 3).map { (name) -> Expression in .node(.variable(name, binding: true)) }
guard let child = stack.popLast() else { return nil }
let aggMap = Algebra.AggregationMapping(aggregation: .sum(.node(.variable(key, binding: true)), false), variableName: name)
return .aggregate(child, groups, [aggMap])
} else if op == "count" { // (COUNT(?key) AS ?name) ... GROUP BY ?x ?y ?z --> "count key name x y z"
guard parts.count > 2 else { throw QueryError.parseError("Not enough arguments for \(op)") }
let key = parts[1]
let name = parts[2]
let groups = parts.suffix(from: 3).map { (name) -> Expression in .node(.variable(name, binding: true)) }
guard let child = stack.popLast() else { return nil }
let aggMap = Algebra.AggregationMapping(aggregation: .count(.node(.variable(key, binding: true)), false), variableName: name)
return .aggregate(child, groups, [aggMap])
} else if op == "countall" { // (COUNT(*) AS ?name) ... GROUP BY ?x ?y ?z --> "count name x y z"
guard parts.count > 1 else { throw QueryError.parseError("Not enough arguments for \(op)") }
let name = parts[1]
let groups = parts.suffix(from: 2).map { (name) -> Expression in .node(.variable(name, binding: true)) }
guard let child = stack.popLast() else { return nil }
let aggMap = Algebra.AggregationMapping(aggregation: .countAll, variableName: name)
return .aggregate(child, groups, [aggMap])
} else if op == "limit" {
guard let count = Int(rest) else { return nil }
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
return .slice(child, 0, count)
} else if op == "graph" {
let parser = NTriplesPatternParser(reader: "")
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
guard let graph = parser.parseNode(line: rest) else { return nil }
return .namedGraph(child, graph)
} else if op == "extend" {
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
let name = parts[1]
guard parts.count > 2 else { return nil }
do {
if let expr = try ExpressionParser.parseExpression(Array(parts.suffix(from: 2))) {
return .extend(child, expr, name)
}
} catch {}
fatalError("Failed to parse filter expression: \(parts)")
} else if op == "filter" {
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
do {
if let expr = try ExpressionParser.parseExpression(Array(parts.suffix(from: 1))) {
return .filter(child, expr)
}
} catch {}
fatalError("Failed to parse filter expression: \(parts)")
} else if op == "sort" {
let comparators = try parts.suffix(from: 1).split(separator: ",").map { (stack) -> Algebra.SortComparator in
guard let expr = try ExpressionParser.parseExpression(Array(stack)) else { throw QueryError.parseError("Failed to parse ORDER expression") }
let c = Algebra.SortComparator(ascending: true, expression: expr)
return c
}
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
return .order(child, comparators)
} else if op == "distinct" {
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
return .distinct(child)
} else if op == "reduced" {
guard let child = stack.popLast() else { throw QueryError.parseError("Not enough operands for \(op)") }
return .reduced(child)
}
warn("Cannot parse query line: \(line)")
return nil
}
func parsePropertyPath(_ parts: [String]) throws -> PropertyPath? {
var stack = [PropertyPath]()
var i = parts.makeIterator()
let parser = NTriplesPatternParser(reader: "")
while let s = i.next() {
switch s {
case "|":
guard stack.count >= 2 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") }
let rhs = stack.popLast()!
let lhs = stack.popLast()!
stack.append(.alt(lhs, rhs))
case "/":
guard stack.count >= 2 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") }
let rhs = stack.popLast()!
let lhs = stack.popLast()!
stack.append(.seq(lhs, rhs))
case "^":
guard stack.count >= 1 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") }
let lhs = stack.popLast()!
stack.append(.inv(lhs))
case "+":
guard stack.count >= 1 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") }
let lhs = stack.popLast()!
stack.append(.plus(lhs))
case "*":
guard stack.count >= 1 else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") }
let lhs = stack.popLast()!
stack.append(.star(lhs))
case "nps":
guard let c = i.next() else { throw QueryError.parseError("No count argument given for property path operation: \(s)") }
guard let count = Int(c) else { throw QueryError.parseError("Failed to parse count argument for property path operation: \(s)") }
guard stack.count >= count else { throw QueryError.parseError("Not enough property paths on the stack for \(s)") }
var iris = [Term]()
for _ in 0..<count {
let link = stack.popLast()!
guard case .link(let term) = link else { throw QueryError.parseError("Not an IRI for \(s)") }
iris.append(term)
}
stack.append(.nps(iris))
default:
guard let n = parser.parseNode(line: s) else { throw QueryError.parseError("Failed to parse property path: \(parts.joined(separator: " "))") }
guard case .bound(let term) = n else { throw QueryError.parseError("Failed to parse property path: \(parts.joined(separator: " "))") }
stack.append(.link(term))
}
}
return stack.popLast()
}
public func parse() throws -> Query? {
let lines = try self.reader.lines()
for line in lines {
guard let algebra = try self.parse(line: line) else { continue }
stack.append(algebra)
}
guard let algebra = stack.popLast() else {
return nil
}
let proj = Array(algebra.projectableVariables)
return try Query(form: .select(.variables(proj)), algebra: algebra, dataset: nil)
}
}
| mit | b30e837995de3adaf87b99dfd6a4cbe4 | 55.117647 | 179 | 0.557652 | 4.515033 | false | false | false | false |
szhalf/iepg2ical | iEPG2iCal/Classes/Converter.swift | 1 | 2654 | //
// Converter.swift
// iEPG2iCal
//
// Created by Wataru SUZUKI on 9/23/15.
// Copyright © 2015 sz50.com. All rights reserved.
//
import EventKit
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
class Converter: NSObject {
var stationReplaceMap: [String: String]
var defaultEventAvailability: EKEventAvailability
fileprivate let _eventStore: EKEventStore
fileprivate var _events: [EKEvent]?
fileprivate var _tvProgramInfos: [TVProgramInfo]
init(withEventStore store: EKEventStore) {
_eventStore = store
_events = nil
_tvProgramInfos = [TVProgramInfo]()
stationReplaceMap = [String: String]()
defaultEventAvailability = EKEventAvailability.free
}
fileprivate func convertStationName(_ stationName: String) -> String {
var convertedStationName = stationName
for (original, replaced) in self.stationReplaceMap {
convertedStationName = convertedStationName.replacingOccurrences(of: original, with:replaced)
}
return convertedStationName
}
func addTVPrograms(_ programs: [TVProgramInfo]) {
_tvProgramInfos += programs
}
fileprivate func convert() {
self._events = []
for program in _tvProgramInfos {
let station = self.convertStationName(program.station)
let event = EKEvent(eventStore: self._eventStore)
event.title = !station.isEmpty ? NSString(format: "[%@] ", station) as String + program.title : program.title
event.startDate = program.startDateTime as Date
event.endDate = program.endDateTime as Date
event.availability = self.defaultEventAvailability
event.notes = program.memo.replacingOccurrences(of: "<BR>", with:"\r\n", options: NSString.CompareOptions.caseInsensitive)
self._events! += [event]
}
}
func saveToCalendar(_ calendar: EKCalendar) throws {
if self._events == nil {
self.convert()
}
if (self._events?.count < 1) {
return
}
for event in self._events! {
event.calendar = calendar
try eventStore.save(event, span: EKSpan.thisEvent, commit: false)
}
try eventStore.commit()
}
}
| mit | c0fc4fdc58fb4bc8ae2c53634f4864c0 | 29.147727 | 141 | 0.623068 | 4.542808 | false | false | false | false |
onevcat/Rainbow | Sources/BackgroundColor.swift | 1 | 3231 | //
// BackgroundColor.swift
// Rainbow
//
// Created by Wei Wang on 15/12/22.
//
// Copyright (c) 2018 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.
public enum BackgroundColorType: ModeCode {
case named(BackgroundColor)
case bit8(UInt8)
case bit24(RGB)
@available(*, deprecated, message: "For backward compatibility.")
var namedColor: BackgroundColor? {
switch self {
case .named(let color): return color
default: return nil
}
}
public var value: [UInt8] {
switch self {
case .named(let color): return color.value
case .bit8(let color): return [ControlCode.setBackgroundColor, ControlCode.set8Bit, color]
case .bit24(let rgb): return [ControlCode.setBackgroundColor, ControlCode.set24Bit, rgb.0, rgb.1, rgb.2]
}
}
public var toColor: ColorType {
switch self {
case .named(let color): return .named(color.toColor)
case .bit8(let color): return .bit8(color)
case .bit24(let rgb): return .bit24(rgb)
}
}
}
extension BackgroundColorType: Equatable {
public static func == (lhs: BackgroundColorType, rhs: BackgroundColorType) -> Bool {
switch (lhs, rhs) {
case (.named(let color1), .named(let color2)): return color1 == color2
case (.bit8(let color1), .bit8(let color2)): return color1 == color2
case (.bit24(let color1), .bit24(let color2)): return color1 == color2
default: return false
}
}
}
public typealias BackgroundColor = NamedBackgroundColor
/// Valid background colors to use in `Rainbow`.
public enum NamedBackgroundColor: UInt8, ModeCode, CaseIterable {
case black = 40
case red
case green
case yellow
case blue
case magenta
case cyan
case white
case `default` = 49
case lightBlack = 100
case lightRed
case lightGreen
case lightYellow
case lightBlue
case lightMagenta
case lightCyan
case lightWhite
public var value: [UInt8] {
return [rawValue]
}
public var toColor: NamedColor {
return NamedColor(rawValue: rawValue - 10)!
}
}
| mit | 3a0818113d9e3d70bcd7c73ff9e48e06 | 31.969388 | 112 | 0.679356 | 4.16366 | false | false | false | false |
tiagobsbraga/TBPagarME | Example/Example/ViewController.swift | 1 | 1814 | //
// ViewController.swift
// Example
//
// Created by Tiago Braga on 4/18/16.
// Copyright © 2016 Tiago Braga. All rights reserved.
//
import UIKit
import TBPagarME
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
transaction()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func transaction() {
let pagarME = TBPagarME.sharedInstance
// card
pagarME.card.cardNumber = "xxxxxxxxxxxxxxxx"
pagarME.card.cardHolderName = "Name Owner Card"
pagarME.card.cardExpirationMonth = "12"
pagarME.card.cardExpirationYear = "17"
pagarME.card.cardCVV = "111"
// customer
pagarME.customer.name = "Onwer Card"
pagarME.customer.document_number = "09809889011"
pagarME.customer.email = "[email protected]"
pagarME.customer.street = "Street"
pagarME.customer.neighborhood = "Neightborhood"
pagarME.customer.zipcode = "00000"
pagarME.customer.street_number = "1"
pagarME.customer.complementary = "Apt 805"
pagarME.customer.ddd = "031"
pagarME.customer.number = "986932196"
//transaction
TBPagarME.sharedInstance.transaction("1000", success: { (data) in
print("data transaction \(data)")
})
{ (message) in
print("error message \(message)")
}
//get card hash
TBPagarME.sharedInstance.generateCardHash(success: { (card_hash) in
debugPrint("card_hash: \(card_hash)")
}) { (message) in
debugPrint("error: \(message)")
}
}
}
| mit | cce80bcab01bd1f2ce0591a921caa551 | 26.892308 | 75 | 0.596249 | 4.50995 | false | false | false | false |
Jakobeha/lAzR4t | lAzR4t Shared/Code/Core/List.swift | 1 | 7127 | //
// List.swift
// lAzR4t
//
// Created by Jakob Hain on 9/30/17.
// Copyright © 2017 Jakob Hain. All rights reserved.
//
import Foundation
///A non-empty linked list
enum List<T> {
case empty
indirect case cons(head: T, rest: List<T>)
///Shorthand operator for `cons`
static func +(_ head: T, _ rest: List<T>) -> List<T> {
return .cons(head: head, rest: rest)
}
static func +(_ a: List<T>, _ b: List<T>) -> List<T> {
switch a {
case .empty:
return b
case .cons(let aHead, let aRest):
return .cons(head: aHead, rest: aRest + b)
}
}
var isEmpty: Bool {
switch self {
case .empty:
return true
case .cons(_, _):
return false
}
}
var last: T? {
switch self {
case .empty:
return nil
case .cons(head: let last, rest: .empty):
return last
case .cons(_, let rest):
return rest.last
}
}
var count: Int {
switch self {
case .empty:
return 0
case .cons(_, let rest):
return 1 + rest.count
}
}
var toArray: [T] {
let count = self.count
var curRes = [T]()
curRes.reserveCapacity(count)
var remaining = self
for _ in 0..<count {
switch remaining {
case .empty:
fatalError("Remaining list empty before remaining length 0")
case .cons(head: let next, rest: let newRemaining):
curRes.append(next)
remaining = newRemaining
break
}
}
return curRes
}
///Creates a list with just one item
init(item: T) {
self = .cons(head: item, rest: .empty)
}
init(fromArray array: [T]) {
var curSelf = List.empty
for item in array.reversed() {
curSelf = .cons(head: item, rest: curSelf)
}
self = curSelf
}
func map<T2>(_ transform: (T) throws -> T2) rethrows -> List<T2> {
switch self {
case .empty:
return .empty
case .cons(let head, let rest):
return .cons(head: try transform(head), rest: try rest.map(transform))
}
}
func flatMap<T2>(_ transform: (T) throws -> T2?) rethrows -> List<T2> {
switch self {
case .empty:
return .empty
case .cons(let head, let rest):
let newRest = try rest.flatMap(transform)
switch try transform(head) {
case .none:
return newRest
case .some(let newHead):
return .cons(head: newHead, rest: newRest)
}
}
}
func flatMap<T2>(_ transform: (T) throws -> List<T2>) rethrows -> List<T2> {
switch self {
case .empty:
return .empty
case .cons(let head, let rest):
return try transform(head) + rest.flatMap(transform)
}
}
func filter(_ satisfies: (T) throws -> Bool) rethrows -> List<T> {
switch self {
case .empty:
return .empty
case .cons(let head, let rest):
let newRest = try rest.filter(satisfies)
if try !satisfies(head) {
return newRest
} else {
return .cons(head: head, rest: newRest)
}
}
}
func forEach(_ apply: (T) throws -> Void) rethrows {
switch self {
case .empty:
break
case .cons(let head, let rest):
try apply(head)
try rest.forEach(apply)
break
}
}
func contains(where satisfies: (T) throws -> Bool) rethrows -> Bool {
switch self {
case .empty:
return false
case .cons(let head, let rest):
return try satisfies(head) || rest.contains(where: satisfies)
}
}
///How many items satisfy the condition
func count(onlyWhere satisfies: (T) throws -> Bool) rethrows -> Int {
switch self {
case .empty:
return 0
case .cons(let head, let rest):
return try (satisfies(head) ? 1 : 0) + rest.count(onlyWhere: satisfies)
}
}
func find(where satisfies: (T) throws -> Bool) rethrows -> T? {
switch self {
case .empty:
return nil
case .cons(let head, let rest):
return try satisfies(head) ? head : rest.find(where: satisfies)
}
}
}
extension List where T: Equatable {
static func ==(_ a: List<T>, _ b: List<T>) -> Bool {
switch (a, b) {
case (.empty, .empty):
return true
case (.empty, .cons(_, _)):
return false
case (.cons(_, _), .empty):
return false
case (.cons(head: let aHead, rest: let aRest), .cons(head: let bHead, rest: let bRest)):
return aHead == bHead && aRest == bRest
}
}
static func !=(_ a: List<T>, _ b: List<T>) -> Bool {
return !(a == b)
}
var withoutDuplicates: List<T> {
switch self {
case .empty:
return .empty
case .cons(let head, let rest):
return .cons(head: head, rest: rest.removeAll(head).withoutDuplicates)
}
}
var numDuplicates: Int {
return count - withoutDuplicates.count
}
func contains(_ item: T) -> Bool {
return contains { $0 == item }
}
func count(of item: T) -> Int {
return count(onlyWhere: { $0 == item })
}
///Throws an error if the item isn't removed
func removeOne(_ item: T) throws -> List<T> {
switch self {
case .empty:
throw ListError.itemNotRemoved
case .cons(let head, let rest):
if head == item {
return rest
} else {
return .cons(head: head, rest: try rest.removeOne(item))
}
}
}
//Doesn't care if the item isn't even removed once
func removeAll(_ item: T) -> List<T> {
switch self {
case .empty:
return .empty
case .cons(let head, let rest):
let newRest = rest.removeAll(item)
if head == item {
return newRest
} else {
return .cons(head: head, rest: newRest)
}
}
}
///Throws an error if the item isn't replaced
func replaceOne(_ oldItem: T, with newItem: T) throws -> List<T> {
switch self {
case .empty:
throw ListError.itemNotReplaced
case .cons(let head, let rest):
if head == oldItem {
return .cons(head: newItem, rest: rest)
} else {
return .cons(head: head, rest: try rest.replaceOne(oldItem, with: newItem))
}
}
}
}
enum ListError: Error {
case itemNotRemoved
case itemNotReplaced
}
| mit | 81e960af8faaace8f1c3a5272697cc8d | 26.095057 | 96 | 0.492141 | 4.191765 | false | false | false | false |
aiwalle/LiveProject | LiveProject/Live/View/ChatView/LJEmoticonView.swift | 1 | 2528 | //
// LJEmoticonView.swift
// LiveProject
//
// Created by liang on 2017/8/30.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
class LJEmoticonView: UIView {
var emoticonClickCallback : ((LJEmoticonModel) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension LJEmoticonView {
fileprivate func setupUI() {
var style = LJPageStyle()
style.isShowBottomLine = true
let layout = LJPageCollectionLayout()
layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
layout.cols = 7
layout.rows = 3
layout.lineMargin = 0
layout.itemMargin = 0
let pageCv = LJPageCollectionView(frame: bounds, titles: ["普通", "粉丝专属"], style: style, isTitleInTop: true, layout: layout)
pageCv.register(LJEmoticonViewCell.self, forCellWithReuseIdentifier: kEmoticonViewCellID)
pageCv.dataSource = self
pageCv.delegate = self
addSubview(pageCv)
}
}
extension LJEmoticonView : LJPageCollectionViewDataSource, LJPageCollectionViewDelegate {
func numberOfSectionInPageCollectionView(_ pageCollectionView: LJPageCollectionView) -> Int {
return LJEmoticonViewModel.shareInstance.packags.count
}
func pageCollectionView(_ pageCollectionView: LJPageCollectionView, numberOfItemsInSection section: Int) -> Int {
let count = LJEmoticonViewModel.shareInstance.packags[section].emoticons.count
return count
}
func pageCollectionView(_ pageCollectionView: LJPageCollectionView, _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = LJEmoticonViewCell.cellWithCollectionView(collectionView, indexPath: indexPath as NSIndexPath)
cell.emoticon = LJEmoticonViewModel.shareInstance.packags[indexPath.section].emoticons[indexPath.item]
return cell
}
func pageCollectionView(_ pageCollectionView: LJPageCollectionView, didSelectItemAt indexPath: IndexPath) {
let emoticon = LJEmoticonViewModel.shareInstance.packags[indexPath.section].emoticons[indexPath.item]
if let emoticonClickCallback = emoticonClickCallback {
emoticonClickCallback(emoticon)
}
}
}
| mit | 722c8cfcdfe3809c091dad1214d61d05 | 31.217949 | 169 | 0.684441 | 5.192149 | false | false | false | false |
grogdj/toilet-paper-as-a-service | ios/toilet-service/toilet-service/HomesTableViewController.swift | 1 | 6971 | //
// HomesTableViewController.swift
// toilet-service
//
// Created by Mauricio Salatino on 22/03/2016.
// Copyright © 2016 ToiletService. All rights reserved.
//
import UIKit
let serviceUrl = "http://localhost:8083/api/homes/"
class HomesTableViewController: UITableViewController {
@IBOutlet var homesTable: UITableView!
var homes: NSMutableArray = NSMutableArray();
@IBAction func unwindToHomeList(segue: UIStoryboardSegue){
print("Unwinding.... ")
if(segue.sourceViewController.isKindOfClass(AddHomeViewController)){
if let sourceViewController = segue.sourceViewController as? AddHomeViewController {
let newHome = sourceViewController.newHome
let newIndexPath = NSIndexPath(forRow: homes.count, inSection: 0)
homes.addObject(newHome)
homesTable.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom)
}
}
}
func loadHomesList(){
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: serviceUrl)!) { (data, response, error) -> Void in
if let urlContent = data {
do{
self.homes = try NSJSONSerialization.JSONObjectWithData(urlContent, options: NSJSONReadingOptions.MutableContainers) as! NSMutableArray
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.homesTable.reloadData()
})
} catch {
print("Error parsing JSON")
}
}
}.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
loadHomesList()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
if let homeName = homes[indexPath.row]["name"]{
cell.textLabel?.text = String(homeName!)
} else{
cell.textLabel?.text = String("No Name")
}
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
if let id = homes[indexPath.row]["id"]{
if let finalId = id{
let url = NSURL(string: "\(serviceUrl)\(finalId)")!
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "DELETE"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
// Make the DELETE call and handle it in a completion handler
session.dataTaskWithRequest(request, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure we get an OK response
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 204 else {
print("Not a 204 response")
return
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.homes.removeObjectAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// self.homesTableView.reloadData()
})
}).resume()
}
}else{
print("Wrong ID");
}
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return indexPath;
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if let cell = sender as? UITableViewCell {
let i = homesTable.indexPathForCell(cell)!.row
let vc = segue.destinationViewController as! HomeDetailsTabBarController
print("data here2 -> "+String(homes[i]))
vc.home = NSMutableDictionary(dictionary: homes[i] as! NSDictionary)
}
}
}
| apache-2.0 | 0f400b096a19c17954fe08f06ac2ec78 | 37.508287 | 157 | 0.576327 | 6.097988 | false | false | false | false |
urdnot-ios/ShepardAppearanceConverter | ShepardAppearanceConverter/ShepardAppearanceConverter/Models/GameSequence.swift | 1 | 3732 | //
// CurrentGame.swift
// ShepardAppearanceConverter
//
// Created by Emily Ivie on 8/9/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import Foundation
public struct GameSequence {
public typealias ShepardVersionIdentifier = (uuid: String, gameVersion: GameVersion)
public var allShepards = [FaultedShepard]()
public var uuid = "\(NSUUID().UUIDString)"
public var gameVersion: GameVersion {
return shepard.gameVersion
}
public var shepard: Shepard
public init() {
shepard = Shepard(sequenceUuid: self.uuid, gameVersion: .Game1)
allShepards.append(FaultedShepard(uuid: shepard.uuid, gameVersion: .Game1))
}
public init?(uuid: String) {
guard let game = GameSequence.get(uuid: uuid)
else {
return nil
}
self = game
}
public mutating func changeGameVersion(newGameVersion: GameVersion) {
if newGameVersion == gameVersion {
return
}
// save prior shepard
shepard.saveAnyChanges()
// locate new shepard
if let foundIndex = allShepards.indexOf({ $0.gameVersion == newGameVersion }),
let foundShepard = Shepard.get(uuid: allShepards[foundIndex].uuid) {
shepard = foundShepard
} else {
var newShepard = Shepard(sequenceUuid: uuid, gameVersion: newGameVersion)
// share all data from other game version:
newShepard.setData(shepard.getData(), gameConversion: shepard.gameVersion)
newShepard.saveAnyChanges()
allShepards.append(FaultedShepard(uuid: newShepard.uuid, gameVersion: newGameVersion))
if let foundIndex = App.allGames.indexOf({ $0.uuid == uuid }) {
App.allGames[foundIndex].shepardUuids = allShepards.map { $0.uuid }
}
shepard = newShepard
}
// reset the listeners (new value = new listeners)
App.resetShepardListener()
// save current game and shepard (to mark most recent)
saveAnyChanges()
}
}
//MARK: Saving/Retrieving Data
extension GameSequence: SerializedDataStorable {
public func getData() -> SerializedData {
var list = [String: SerializedDataStorable?]()
list["uuid"] = uuid
list["lastPlayedShepard"] = shepard.uuid
list["allShepards"] = SerializedData(allShepards.map { $0.getData() })
return SerializedData(list)
}
}
extension GameSequence: SerializedDataRetrievable {
public init(serializedData data: String) throws {
self.init()
setData(try SerializedData(serializedData: data))
}
public mutating func setData(data: SerializedData) {
uuid = data["uuid"]?.string ?? uuid
if let lastPlayedShepard = data["lastPlayedShepard"]?.string,
let shepard = Shepard.get(uuid: lastPlayedShepard) {
self.shepard = shepard
changeGameVersion(shepard.gameVersion)
}
if let allShepards = data["allShepards"]?.array {
self.allShepards = []
for faultedShepardData in allShepards {
self.allShepards.append(FaultedShepard(data: faultedShepardData))
}
}
}
}
//MARK: Supporting data type
extension GameSequence {
public enum GameVersion: String {
case Game1 = "1", Game2 = "2", Game3 = "3"
func list() -> [GameVersion] {
return [.Game1, .Game2, .Game3]
}
}
}
extension GameSequence.GameVersion: Equatable {}
public func ==(lhs: GameSequence.GameVersion, rhs: GameSequence.GameVersion) -> Bool {
return lhs.rawValue == rhs.rawValue
}
| mit | 256e9deae172d27145fe09f92b9b4a80 | 29.08871 | 98 | 0.622353 | 4.826649 | false | false | false | false |
silt-lang/silt | Sources/Seismography/ExplicitOwnership.swift | 1 | 4791 | /// ExplicitOwnership.swift
///
/// Copyright 2017-2018, The Silt Language Project.
///
/// This project is released under the MIT license, a copy of which is
/// available in the repository.
import Foundation
/// Holds an unowned reference to a class (this class is necessary for keeping
/// unowned references in collection types.
struct Unowned<T: AnyObject & Hashable>: Hashable {
unowned let value: T
static func == <T>(lhs: Unowned<T>, rhs: Unowned<T>) -> Bool {
return lhs.value == rhs.value
}
func hash(into hasher: inout Hasher) {
self.value.hash(into: &hasher)
}
}
/// A dictionary type that holds unowned references to both keys and values.
public struct UnownedDictionary<
Key: AnyObject & Hashable,
Value: AnyObject & Hashable
>: Collection, Hashable {
public typealias Index = UnownedDictionaryIndex
public struct UnownedDictionaryIndex: Comparable {
// swiftlint:disable syntactic_sugar
let underlying: Dictionary<Unowned<Key>, Unowned<Value>>.Index
public static func < (lhs: UnownedDictionaryIndex,
rhs: UnownedDictionaryIndex) -> Bool {
return lhs.underlying < rhs.underlying
}
public static func == (lhs: UnownedDictionaryIndex,
rhs: UnownedDictionaryIndex) -> Bool {
return lhs.underlying == rhs.underlying
}
}
var storage: [Unowned<Key>: Unowned<Value>]
public init() {
storage = [:]
}
public init(_ values: [Key: Value]) {
var storage = [Unowned<Key>: Unowned<Value>]()
for (k, v) in values {
storage[Unowned(value: k)] = Unowned(value: v)
}
self.storage = storage
}
public var startIndex: Index {
return UnownedDictionaryIndex(underlying: storage.startIndex)
}
public var endIndex: Index {
return UnownedDictionaryIndex(underlying: storage.endIndex)
}
public subscript(position: Index) -> (key: Key, value: Value) {
let bucket = storage[position.underlying]
return (key: bucket.key.value, value: bucket.value.value)
}
public subscript(key: Key) -> Value? {
get {
return storage[Unowned(value: key)]?.value
}
set {
storage[Unowned(value: key)] = newValue.map(Unowned.init)
}
}
public func index(after i: Index) -> Index {
return UnownedDictionaryIndex(underlying:
storage.index(after: i.underlying))
}
public static func == <K, V>(lhs: UnownedDictionary<K, V>,
rhs: UnownedDictionary<K, V>) -> Bool {
return lhs.storage == rhs.storage
}
public func hash(into hasher: inout Hasher) {
for (key, value) in self.storage {
key.hash(into: &hasher)
value.hash(into: &hasher)
}
}
}
/// An array of unowned references to values. Use this in place of an array if
/// you don't want the elements of the array to be owned values.
public struct UnownedArray<
Element: AnyObject & Hashable
>: Collection, Hashable {
var storage: [Unowned<Element>]
public init() {
storage = []
}
public init(values: [Element]) {
self.storage = values.map(Unowned.init)
}
public var startIndex: Int {
return storage.startIndex
}
public var endIndex: Int {
return storage.endIndex
}
public mutating func append(_ element: Element) {
storage.append(Unowned(value: element))
}
public subscript(position: Int) -> Element {
get {
return storage[position].value
}
set {
return storage[position] = Unowned(value: newValue)
}
}
public func index(after i: Int) -> Int {
return storage.index(after: i)
}
public static func == (lhs: UnownedArray, rhs: UnownedArray) -> Bool {
return lhs.storage == rhs.storage
}
public func hash(into hasher: inout Hasher) {
for value in self.storage {
value.hash(into: &hasher)
}
}
}
extension UnownedArray: ManglingEntity where Element: ManglingEntity {
public func mangle<M: Mangler>(into mangler: inout M) {
if self.isEmpty {
mangler.append("y")
} else if self.count == 1 {
self[0].mangle(into: &mangler)
} else {
var isFirst = true
for argument in self {
argument.mangle(into: &mangler)
if isFirst {
mangler.append("_")
isFirst = false
}
}
mangler.append("t")
}
}
}
extension Array: ManglingEntity where Element: ManglingEntity {
public func mangle<M: Mangler>(into mangler: inout M) {
if self.isEmpty {
mangler.append("y")
} else if self.count == 1 {
self[0].mangle(into: &mangler)
} else {
var isFirst = true
for argument in self {
argument.mangle(into: &mangler)
if isFirst {
mangler.append("_")
isFirst = false
}
}
mangler.append("t")
}
}
}
| mit | 813934a44fa7ea934f272125ccbf959c | 24.484043 | 78 | 0.635775 | 4.105398 | false | false | false | false |
lazersly/GithubzToGo | GithubzToGo/UsersJSONParser.swift | 1 | 975 | //
// UsersJSONParser.swift
// GithubzToGo
//
// Created by Brandon Roberts on 4/17/15.
// Copyright (c) 2015 BR World. All rights reserved.
//
import Foundation
class UsersJSONParser {
class func usersFromJSONData(jsonData: NSData) -> [User] {
var users = [User]()
var error : NSError?
if let
root = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.allZeros, error: &error) as? [String : AnyObject],
items = root["items"] as? [[String : AnyObject]]
{
for item in items
{
if let
id = item["id"] as? NSNumber,
htmlURL = item["html_url"] as? String,
avatarURL = item["avatar_url"] as? String,
score = item["score"] as? String
{
let newUser = User(id: id.stringValue, avatarURL: avatarURL, htmlURL: htmlURL, score: score)
users.append(newUser)
}
}
}
return users
}
}
| mit | f5a696dcb8c17a486556b897703b0bd5 | 26.857143 | 142 | 0.582564 | 4.148936 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Tree/297_Serialize and Deserialize Binary Tree.swift | 1 | 3527 | // 297_Serialize and Deserialize Binary Tree
// https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
//
// Created by Honghao Zhang on 10/27/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
//
//Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
//
//Example:
//
//You may serialize the following tree:
//
// 1
// / \
// 2 3
// / \
// 4 5
//
//as "[1,2,3,null,null,4,5]"
//Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
//
//Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
//
import Foundation
class Num297 {
// MARK: - DFS preorder traversal
// For serialization, get the string representation of preorder traversal (leaf node will have 'None' in the string)
// For deserialization, passing the string and mutate it when constructing the tree.
// Generally, construct the root node with the first node and call self to construct left then right tree.
// Python
// # Definition for a binary tree node.
// # class TreeNode(object):
// # def __init__(self, x):
// # self.val = x
// # self.left = None
// # self.right = None
//
// class Codec:
//
// def serialize(self, root):
// """Encodes a tree to a single string.
//
// :type root: TreeNode
// :rtype: str
// """
// def rserialize(root, string):
// """ a recursive helper function for the serialize() function."""
// # check base case
// if root is None:
// return 'None,'
// # string += 'None,'
// else:
// return str(root.val) + ',' + rserialize(root.left, string) + rserialize(root.right, string)
// # string += str(root.val) + ','
// # string = rserialize(root.left, string)
// # string = rserialize(root.right, string)
// # return string
//
// return rserialize(root, '')
//
//
// def deserialize(self, data):
// """Decodes your encoded data to tree.
//
// :type data: str
// :rtype: TreeNode
// """
// def rdeserialize(l):
// """ a recursive helper function for deserialization."""
// if l[0] == 'None':
// l.pop(0)
// return None
//
// root = TreeNode(l[0])
// l.pop(0)
// root.left = rdeserialize(l)
// root.right = rdeserialize(l)
// return root
//
// data_list = data.split(',')
// root = rdeserialize(data_list)
// return root
//
//
// # Your Codec object will be instantiated and called as such:
// # codec = Codec()
// # codec.deserialize(codec.serialize(root))
}
| mit | 6dd174e466daf7877e6ec33025dd2d15 | 36.510638 | 295 | 0.597561 | 3.997732 | false | false | false | false |
classified/Amazons3 | AmazonS3/AmazonUploader.swift | 1 | 11819 | //
// AmazonUploader.swift
// AmazonS3
//
// Created by SOTSYS220 on 05/05/17.
// Copyright © 2017 SOTSYS220. All rights reserved.
//
import UIKit
import AWSS3
import MobileCoreServices
public struct AmazonCredentials {
var bucketName : String?
var accessKey : String?
var secretKey : String?
var region : AWSRegionType?
public init(bucketName : String,accessKey : String, secretKey: String, region : AWSRegionType) {
self.bucketName = bucketName
self.accessKey = accessKey
self.secretKey = secretKey
self.region = region
}
}
public class AmazonUploader {
// public vars
public static let shared = AmazonUploader()
// private vars
fileprivate static var credentials : AmazonCredentials!
fileprivate var fileURL = [String]()
fileprivate var currentIndex = 0
public static func setup(credentials : AmazonCredentials){
AmazonUploader.credentials = credentials
let credentialsProvider: AWSStaticCredentialsProvider = AWSStaticCredentialsProvider(accessKey: credentials.accessKey!, secretKey: credentials.secretKey!)
let configuration: AWSServiceConfiguration = AWSServiceConfiguration(region: credentials.region!, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
AmazonUploader.shared.initializeUploader()
}
private init() {
guard AmazonUploader.credentials != nil,AmazonUploader.credentials.accessKey != nil ,AmazonUploader.credentials.secretKey != nil,AmazonUploader.credentials.bucketName != nil else {
fatalError("Error - you must call setup before accessing AmazonUploader")
}
//Regular initialisation using param
}
//MARK: Intialize local variables
fileprivate func initializeUploader(){
if validateData() {
fileURL.removeAll()
currentIndex = 0
}
}
fileprivate func validateData() -> Bool {
if AmazonUploader.credentials.bucketName?.count == 0 {
fatalError("bucket name can not be blank")
}
if AmazonUploader.credentials.accessKey?.count == 0 {
fatalError("access key can not be blank")
}
if AmazonUploader.credentials.secretKey?.count == 0 {
fatalError("secret key can not be blank")
}
return true
}
//MARK: Upload with normal manager
/**
* url: File URL
* name: File name
**/
public func uploadFile(fileUrl url: URL,keyName name:String , permission ACL:AWSS3ObjectCannedACL , completed: @escaping (_ isSuccess: Bool,_ url: String?, _ error : Error?) -> Void) {
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.bucket = AmazonUploader.credentials.bucketName!
uploadRequest?.acl = ACL
uploadRequest?.key = "\(name)"
uploadRequest?.contentType = mimeTypeFromFileExtension(path: url.lastPathComponent)
uploadRequest?.body = url
// we will track progress through an AWSNetworkingUploadProgressBlock
uploadRequest?.uploadProgress = {(bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
}
let transferManager:AWSS3TransferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest!).continueWith(executor: AWSExecutor.mainThread(), block:{
task -> AnyObject in
if(task.error != nil){
completed(false,nil,task.error)
}else{
completed(true,"https://\(AmazonUploader.credentials.bucketName!).s3.amazonaws.com/\(name)",nil)
}
return "" as AnyObject
})
}
//MARK: Upload with normal manager
public func uploadMultipleFiles(fileUrl urls: [URL], keyName name:[String] , permission ACL:AWSS3ObjectCannedACL , completed: ((_ isSuccess: Bool, _ url: [String]? , _ error : Error?) -> Void)?) {
if AmazonUploader.shared.currentIndex == urls.count {
completed!(true,AmazonUploader.shared.fileURL,nil)
AmazonUploader.shared.initializeUploader()
}else{
uploadMultipleSingleFile(fileUrl: urls[AmazonUploader.shared.currentIndex], keyName: name[AmazonUploader.shared.currentIndex], permission: ACL) { isSuccess in
if isSuccess {
self.uploadMultipleFiles(fileUrl: urls, keyName: name, permission: ACL, completed: completed)
}else{
completed!(true,AmazonUploader.shared.fileURL,nil)
AmazonUploader.shared.initializeUploader()
}
}
}
}
//MARK: Upload with normal manager
fileprivate func uploadMultipleSingleFile(fileUrl url: URL,keyName name:String , permission ACL:AWSS3ObjectCannedACL , completed: @escaping (_ isSuccess: Bool) -> Void) {
let uploadRequest = AWSS3TransferManagerUploadRequest()
uploadRequest?.bucket = AmazonUploader.credentials.bucketName!
uploadRequest?.acl = ACL
uploadRequest?.key = "\(name)"
uploadRequest?.contentType = mimeTypeFromFileExtension(path: url.lastPathComponent)
uploadRequest?.body = url
// we will track progress through an AWSNetworkingUploadProgressBlock
uploadRequest?.uploadProgress = {(bytesSent:Int64, totalBytesSent:Int64, totalBytesExpectedToSend:Int64) in
}
let transferManager:AWSS3TransferManager = AWSS3TransferManager.default()
transferManager.upload(uploadRequest!).continueWith(executor: AWSExecutor.mainThread(), block:{
task -> AnyObject in
if(task.error != nil){
completed(false)
}else{
AmazonUploader.shared.currentIndex += 1
AmazonUploader.shared.fileURL.append("https://\(AmazonUploader.credentials.bucketName!).s3.amazonaws.com/\(name)")
completed(true)
}
return "" as AnyObject
})
}
//MARK: Delete files from S3
public func deleteUploadedFiles(keyName: String , completed: @escaping (_ isSuccess: Bool, _ error : Error?) -> Void){
let s3 = AWSS3.default()
let deleteObjectRequest = AWSS3DeleteObjectRequest()
deleteObjectRequest?.bucket = AmazonUploader.credentials.bucketName!
deleteObjectRequest?.key = keyName
s3.deleteObject(deleteObjectRequest!) { (task, error) in
if error != nil {
completed(false,error)
}else{
completed(true,nil)
}
}
}
//MARK: Upload files with background sessions
public func uploadFileSession(fileUrl url: URL,keyName name:String , completed: @escaping (_ isSuccess: Bool, _ url: URL? , _ error : Error?) -> Void) {
let transferUtility = AWSS3TransferUtility.default()
let expression = AWSS3TransferUtilityUploadExpression()
expression.setValue("public-read", forRequestParameter: "x-amz-acl")
transferUtility.uploadFile(url,
bucket: AmazonUploader.credentials.bucketName!,
key: name,
contentType: mimeTypeFromFileExtension(path: url.lastPathComponent),
expression: expression) { task, maybeError in
if let error = maybeError {
completed(false,nil,error)
} else {
completed(true,URL(string: "https://\(AmazonUploader.credentials.bucketName!).s3.amazonaws.com/\(name)"),nil)
}
}
.continueWith { task in
if task.error != nil {
completed(false,nil,task.error)
}
if let _ = task.result {
}
return nil
}
}
//MARK: Download file for private files
public func downloadFile(keyName name:String ,progressBlock: @escaping (_ task:AWSS3TransferUtilityTask,
_ progress:Progress) -> Void, completed: @escaping (_ isSuccess: Bool, _ url: URL? , _ error : Error?) -> Void) {
let expression = AWSS3TransferUtilityDownloadExpression()
expression.progressBlock = {(task, progress) in DispatchQueue.main.async(execute: {
// Do something e.g. Update a progress bar.
progressBlock(task,progress)
})
}
var completionHandler: AWSS3TransferUtilityDownloadCompletionHandlerBlock?
completionHandler = { (task, URL, data, error) -> Void in
DispatchQueue.main.async(execute: {
// Do something e.g. Alert a user for transfer completion.
// On failed downloads, `error` contains the error object.
completed(error != nil ? false : true, URL,error)
})
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.downloadData(
fromBucket: AmazonUploader.credentials.bucketName!,
key: name,
expression: expression,
completionHandler: completionHandler
).continueWith {
(task) -> AnyObject! in if task.error != nil {
}
if let _ = task.result {
// Do something with downloadTask.
}
return nil
}
}
public func checkPendingUploads(){
let completion: AWSS3TransferUtilityUploadCompletionHandlerBlock = { task, maybeError in
if let error = maybeError {
task.cancel()
// TODO we should re-trigger an upload task for this file
} else {
}
}
let transferUtility = AWSS3TransferUtility.default()
transferUtility.enumerateToAssignBlocks(forUploadTask: { (task, progressPointer, completionPointer) -> Void in
completionPointer?.pointee = completion
}, downloadTask: nil)
transferUtility.getUploadTasks().continueWith { task in
if let tasks = task.result as? [AWSS3TransferUtilityUploadTask] {
if tasks.isEmpty {
} else {
for task in tasks {
task.resume()
}
}
}
return nil
}
}
fileprivate func mimeTypeFromFileExtension(path: String) -> String {
let url = NSURL(fileURLWithPath: path)
let pathExtension = url.pathExtension
if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension! as NSString, nil)?.takeRetainedValue() {
if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
return mimetype as String
}
}
return "application/octet-stream"
}
}
| apache-2.0 | 3706e1e71885b52344f1ea9546e27877 | 36.51746 | 200 | 0.576917 | 5.836049 | false | false | false | false |
lukemetz/Paranormal | Paranormal/Paranormal/Panels/ToolSettings/ToolSettingsViewController.swift | 3 | 2629 | import Foundation
import Cocoa
import AppKit
public class ToolSettingsViewController: PNViewController {
@IBOutlet weak var sizeSlider: NSSlider!
@IBOutlet weak var strengthSlider: NSSlider!
@IBOutlet weak var hardnessSlider: NSSlider!
@IBOutlet weak var colorPickerView: NSView!
var colorPickerViewController: ColorPickerViewController?
public var toolSettingsTitle: String = ""
var toolType: ActiveTool = ActiveTool.Tilt
init?(nibName: NSString, bundle: NSBundle?, toolType : ActiveTool) {
super.init(nibName: nibName, bundle: bundle)
self.toolType = toolType
switch toolType {
case .Smooth:
toolSettingsTitle = "Smooth Tool Settings"
case .Sharpen:
toolSettingsTitle = "Sharpen Tool Settings"
case .Flatten:
toolSettingsTitle = "Flatten Tool Settings"
case .Emphasize:
toolSettingsTitle = "Emphasize Tool Settings"
case .Plane:
toolSettingsTitle = "Plane Tool Settings"
case .Tilt:
toolSettingsTitle = "Tilt Tool Settings"
case .Invert:
toolSettingsTitle = "Invert Tool Settings"
default:
toolSettingsTitle = ""
}
}
override public func loadView() {
super.loadView()
if (toolType == ActiveTool.Plane || toolType == ActiveTool.Tilt) {
colorPickerViewController =
ColorPickerViewController(nibName: "ColorPicker", bundle: nil)
addViewController(colorPickerViewController)
if let view = colorPickerViewController?.view {
ViewControllerUtils.insertSubviewIntoParent(colorPickerView, child: view)
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
updateSettingsSliders()
}
@IBAction func updateSize(sender: NSSlider) {
document?.toolSettings.size = sizeSlider.floatValue
}
@IBAction func updateStrength(sender: NSSlider) {
document?.toolSettings.strength = strengthSlider.floatValue
}
@IBAction func updateHardness(sender: NSSlider) {
document?.toolSettings.hardness = hardnessSlider.floatValue
}
public func updateSettingsSliders() {
if let doc = document {
sizeSlider.floatValue = doc.toolSettings.size
strengthSlider.floatValue = doc.toolSettings.strength
hardnessSlider.floatValue = doc.toolSettings.hardness
}
if let cpController = colorPickerViewController? {
cpController.updateColorPicker()
}
}
}
| mit | c649ec7f34a4b0bbf54be8181f6d267c | 31.45679 | 89 | 0.649677 | 5.465696 | false | false | false | false |
cornerstonecollege/402 | Jorge_Juri/MyExercises/GestureRecognizers/CustomViews/FirstCustomView.swift | 2 | 1342 | //
// FirstCustomView.swift
// CustomViews
//
// Created by Luiz on 2016-10-13.
// Copyright © 2016 Ideia do Luiz. All rights reserved.
//
import UIKit
class FirstCustomView: UIView {
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
self.center = touches.first!.location(in: self.superview)
//es porque se debe invocar al padre no a si mismo
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.red // default background color
let label = UILabel()
label.text = "Name"
label.sizeToFit()
label.center = CGPoint(x: self.frame.size.width / 2, y: 10)
self.addSubview(label)
let txtFrame = CGRect(x: (self.frame.size.width - 40) / 2, y: 50, width: 40, height: 20)
let textView = UITextField(frame: txtFrame)
textView.backgroundColor = UIColor.white
self.addSubview(textView)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| gpl-3.0 | 42ecebce92273c2fec0a36849cf62c90 | 25.82 | 96 | 0.604773 | 4.203762 | false | false | false | false |
aoifukuoka/XMLModelizer | XMLModelizer/XMLModelizerModel.swift | 1 | 1290 | //
// XMLModelizerModel.swift
// XMLModelizer
//
// Created by aoponaopon on 2016/09/22.
// Copyright © 2016年 aoponapopon. All rights reserved.
//
import UIKit
open class XMLModelizerModel: NSObject {
var _title: [String]!
var _link: [String]!
var _guid: [String]!
var _description: [String]!
open class func xmlModelizerXpathKeyMap() -> [String:String] {
return [
"_title":"//item/title",
"_link":"//item/link",
"_guid":"//item/guid",
"_description":"//item/description",
]
}
open class var classProperties: [String] {
var resultSet: [String] = []
var count: UInt32 = 0
let properties = class_copyPropertyList(self, &count)
for i in 0..<Int(count) {
let propName = String(utf8String: property_getName(properties?[i]))
resultSet.append(propName!)
}
return resultSet
}
open class func hasDifferentXpathTop() -> Bool {
return Set(// remove duplicates
Array(
xmlModelizerXpathKeyMap().values
).map{$0.components(separatedBy: "/")
.filter{$0 != ""}.first!}
).count
!= 1
}
}
| mit | a950552db1de7344f5fe980e06ef5ed4 | 24.74 | 79 | 0.529915 | 4.275748 | false | false | false | false |
sonsongithub/spbuilder | main.swift | 1 | 11797 | //
// main.swift
// spbuilder
//
// Created by sonson on 2016/06/22.
// Copyright © 2016年 sonson. All rights reserved.
//
import Foundation
extension NSError {
class func error(description: String) -> NSError {
return NSError(domain:"com.sonson.spbuilder", code: 0, userInfo:["description":description])
}
}
struct Book {
let name: String
let version: String
let contentIdentifier: String
let contentVersion: String
var imageReference: String?
let deploymentTarget: String
var chapters: [Chapter]
init(name aName: String, version aVersion: String, contentIdentifier aContentIdentifier: String, contentVersion aContentVersion: String, imageReference anImageReference: String? = nil, deploymentTarget aDeploymentTarget: String, chapters arrayChapters: [String] = []) {
name = aName
version = aVersion
contentIdentifier = aContentVersion
contentVersion = aContentVersion
imageReference = anImageReference
deploymentTarget = aDeploymentTarget
chapters = arrayChapters.map({ (name) -> Chapter in
let title = name.replacingOccurrences(of: ".playgroundchapter", with: "")
print("\(name) => \(title)")
return Chapter(name: title)
})
}
func getChapter(name: String) throws -> Chapter {
for i in 0..<chapters.count {
if chapters[i].name == name {
return chapters[i]
}
}
throw NSError.error(description: "Not found")
}
mutating func add(chapter: Chapter) throws {
if chapters.map({$0.name}).index(of: chapter.name) != nil {
throw NSError.error(description: "Already page has been added.")
}
chapters.append(chapter)
do {
try writeManifest()
} catch {
throw error
}
}
func manifest() -> [String:AnyObject] {
var dict: [String:AnyObject] = [
"Name" : name,
"Version" : version,
"ContentIdentifier" : contentIdentifier,
"ContentVersion" : contentVersion,
"DeploymentTarget" : deploymentTarget,
"Chapters" : chapters.map({ $0.name + ".playgroundchapter" }) as [String]
]
if let imageReference = imageReference {
dict["ImageReference"] = imageReference
}
return dict
}
func writeManifest(at: String = "./Contents/Manifest.plist") throws {
let nsdictionary = manifest() as NSDictionary
if !nsdictionary.write(toFile: at, atomically: false) {
throw NSError.error(description: "Can not write plist.")
}
}
func parepareDefaultFiles() throws {
let path = "./\(name).playgroundbook"
let sourcesPath = "./\(path)/Contents/Sources"
let resourcesPath = "./\(path)/Contents/Resources"
do {
try FileManager.default().createDirectory(atPath: sourcesPath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: resourcesPath, withIntermediateDirectories: true, attributes: nil)
} catch {
throw error
}
}
func create() throws {
// create book
do {
let path = "./\(name).playgroundbook"
let contentsPath = "./\(path)/Contents"
try FileManager.default().createDirectory(atPath: contentsPath, withIntermediateDirectories: true, attributes: nil)
try writeManifest(at: "./\(path)/Contents/Manifest.plist")
try parepareDefaultFiles()
} catch {
throw error
}
}
}
struct Chapter {
let name: String
var pages: [Page]
let version: String
init(name aName: String, version aVersion: String = "1.0") {
print("Chapter name = \(aName)")
name = aName
version = aVersion
pages = []
let at = "./Contents/Chapters/\(name).playgroundchapter"
let chapterManifestPath = "\(at)/Manifest.plist"
if FileManager.default().isReadableFile(atPath: chapterManifestPath) {
if let dict = NSDictionary(contentsOfFile: chapterManifestPath) {
if let name = dict["Name"] as? String,
version = dict["Version"] as? String {
let pageNames = dict["Pages"] as? [String] ?? [] as [String]
pages = pageNames.map({ (name) -> Page in
let title = name.replacingOccurrences(of: ".playgroundpage", with: "")
return Page(name: title, chapterName: name)
})
}
}
}
}
func manifest() -> [String:AnyObject] {
let dict: [String:AnyObject] = [
"Name" : name,
"Version" : version,
"Pages" : pages.map({ $0.name + ".playgroundpage" }) as [String]
]
return dict
}
mutating func add(page: Page) throws {
if pages.map({$0.name}).index(of: page.name) != nil {
throw NSError.error(description: "Already page has been added.")
}
pages.append(page)
do {
try writeManifest()
} catch {
throw error
}
}
func writeManifest() throws {
let at = "./Contents/Chapters/\(name).playgroundchapter"
let sourcesPath = "./\(at)/Sources"
let resourcesPath = "./\(at)/Resources"
do {
try FileManager.default().createDirectory(atPath: at, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: sourcesPath, withIntermediateDirectories: true, attributes: nil)
try FileManager.default().createDirectory(atPath: resourcesPath, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
let nsdictionary = manifest() as NSDictionary
print(nsdictionary)
print(at)
if !nsdictionary.write(toFile: at + "/Manifest.plist", atomically: false) {
throw NSError.error(description: "Chapter: Can not write plist.")
}
}
}
struct Page {
let name: String
let version: String
let chapterName: String
init(name aName: String, version aVersion: String = "1.0", chapterName aChapterName: String) {
name = aName
version = aVersion
chapterName = aChapterName
}
func manifest() -> [String:AnyObject] {
let dict: [String:AnyObject] = [
"Name" : name,
"Version" : version,
"LiveViewMode" : "HiddenByDefault"
]
return dict
}
func parepareDefaultFiles() throws {
let liveViewPath = "./Contents/Chapters/\(chapterName).playgroundchapter/Pages/\(name).playgroundpage/LiveView.swift"
let contentsPath = "./Contents/Chapters/\(chapterName).playgroundchapter/Pages/\(name).playgroundpage/Contents.swift"
let liveViewTemplate = "// LiveView.swift"
let contentsTemplate = "// Contents.swift"
do {
try liveViewTemplate.write(toFile: liveViewPath, atomically: false, encoding: .utf8)
try contentsTemplate.write(toFile: contentsPath, atomically: false, encoding: .utf8)
} catch {
throw error
}
}
func writeManifest() throws {
let at = "./Contents/Chapters/\(chapterName).playgroundchapter/Pages/\(name).playgroundpage/"
do {
try FileManager.default().createDirectory(atPath: at, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
let nsdictionary = manifest() as NSDictionary
if !nsdictionary.write(toFile: at + "/Manifest.plist", atomically: false) {
throw NSError.error(description: "Page : Can not write plist.")
}
}
}
func bookExists(bookName: String) -> Bool {
return FileManager.default().fileExists(atPath: "./\(bookName).playgroundbook")
}
func loadBook() throws -> Book {
let bookManifestPath = "./Contents/Manifest.plist"
if FileManager.default().isReadableFile(atPath: bookManifestPath) {
// open
guard let dict = NSDictionary(contentsOfFile: bookManifestPath) else { throw NSError.error(description: "Can not parse Manifest.plist.") }
if let name = dict["Name"] as? String,
version = dict["Version"] as? String,
contentIdentifier = dict["ContentIdentifier"] as? String,
contentVersion = dict["ContentVersion"] as? String,
deploymentTarget = dict["DeploymentTarget"] as? String {
let imageReference = dict["ImageReference"] as? String
let chapters = dict["Chapters"] as? [String] ?? [] as [String]
return Book(name: name, version: version, contentIdentifier: contentIdentifier, contentVersion: contentVersion, imageReference: imageReference, deploymentTarget: deploymentTarget, chapters: chapters)
} else {
throw NSError.error(description: "Manifest.plist is malformed.")
}
} else {
throw NSError.error(description: "Can not find Manifest.plist. Moved inside playgroundbook's directory.")
}
}
func createBook(argc: Int, arguments: [String]) throws {
if argc == 3 {
if bookExists(bookName: arguments[1]) {
throw NSError.error(description: "Book already exsits.")
} else {
do {
try Book(name: arguments[1], version: "1.0", contentIdentifier: arguments[2], contentVersion: "1.0", deploymentTarget: "ios10.10").create()
} catch {
throw error
}
}
} else {
throw NSError.error(description: "Arguments is less.")
}
}
func addChapter(argc: Int, arguments: [String]) throws {
if argc == 2 {
do {
var book = try loadBook()
let chapter = Chapter(name: arguments[1])
try book.add(chapter: chapter)
try book.writeManifest()
try chapter.writeManifest()
} catch {
throw error
}
} else {
throw NSError.error(description: "Arguments is less.")
}
}
func addPage(argc: Int, arguments: [String]) throws {
if argc == 3 {
do {
let book = try loadBook()
var chapter = try book.getChapter(name: arguments[1])
let page = Page(name: arguments[2], chapterName: chapter.name)
try chapter.add(page: page)
try page.writeManifest()
try page.parepareDefaultFiles()
} catch {
throw error
}
} else {
throw NSError.error(description: "Arguments is less.")
}
}
func parseArguments() throws {
var arguments :[String] = ProcessInfo.processInfo().arguments
print(arguments.first)
let argc = arguments.count - 1
if argc >= 1 {
arguments.removeFirst() // remove own path
switch arguments[0] {
case "create":
do { try createBook(argc: argc, arguments: arguments) } catch { throw error }
case "chapter":
do { try addChapter(argc: argc, arguments: arguments) } catch { throw error }
case "page":
do { try addPage(argc: argc, arguments: arguments) } catch { throw error }
case "rm":
print(argc)
default:
print(argc)
}
} else {
throw NSError.error(description: "Arguments are less.")
}
}
func main() {
do {
try parseArguments()
} catch {
print(error)
}
}
main()
| mit | 03f1bec4b2f9239cdbc8aba0de1c2e8a | 34.20597 | 273 | 0.585806 | 4.796259 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | MarsImagesIOS/Mission.swift | 1 | 5075 | //
// Mission.swift
// MarsImagesIOS
//
// Created by Mark Powell on 7/27/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import Foundation
class Mission {
static let names = [ OPPORTUNITY, SPIRIT, CURIOSITY ]
static let missionKey = "mission"
static let OPPORTUNITY = "Opportunity"
static let SPIRIT = "Spirit"
static let CURIOSITY = "Curiosity"
let EARTH_SECS_PER_MARS_SEC = 1.027491252
static let missions:[String:Mission] = [OPPORTUNITY: Opportunity(), SPIRIT: Spirit(), CURIOSITY: Curiosity()]
static let slashAndDot = CharacterSet(charactersIn: "/.")
var epoch:Date?
var formatter:DateFormatter
var eyeIndex = 0
var instrumentIndex = 0
var sampleTypeIndex = 0
var cameraFOVs = [String:Double]()
static func currentMission() -> Mission {
return missions[currentMissionName()]!
}
static func currentMissionName() -> String {
let userDefaults = UserDefaults.standard
if userDefaults.value(forKey: missionKey) == nil {
userDefaults.set(OPPORTUNITY, forKey: missionKey)
userDefaults.synchronize()
}
return userDefaults.value(forKey: missionKey) as! String
}
static func imageId(url:String) -> String {
let tokens = url.components(separatedBy: slashAndDot)
let numTokens = tokens.count
let imageId = tokens[numTokens-2]
return imageId.removingPercentEncoding ?? ""
}
func urlPrefix() -> String {
return ""
}
func sol(_ title: String) -> Int {
let tokens = title.components(separatedBy: " ")
if tokens.count >= 2 {
return Int(tokens[1])!
}
return 0;
}
init() {
self.formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .long
}
func rowTitle(_ title: String) -> String {
return title
}
func subtitle(_ title: String) -> String {
let marstime = tokenize(title).marsLocalTime
return "\(marstime) LST"
}
func caption(_ title: String) -> String {
let t = tokenize(title)
return "\(t.instrumentName) image taken on Sol \(t.sol)."
}
func tokenize(_ title: String) -> Title {
return Title()
}
func getSortableImageFilename(url: String) -> String {
return url
}
func solAndDate(sol:Int) -> String {
let interval = Double(sol*24*60*60)*EARTH_SECS_PER_MARS_SEC
let imageDate = Date(timeInterval: interval, since: epoch!)
let formattedDate = formatter.string(from: imageDate)
return "Sol \(sol) \(formattedDate)"
}
func imageName(imageId: String) -> String {
print("You should never call me: override me in a subclass instead.")
return ""
}
func stereoImageIndices(imageIDs: [String]) -> (Int,Int)? {
print("You should never call me: override me in a subclass instead.")
return nil
}
func getInstrument(imageId:String) -> String {
let irange = imageId.index(imageId.startIndex, offsetBy: instrumentIndex)..<imageId.index(imageId.startIndex, offsetBy: instrumentIndex+1)
return String(imageId[irange])
}
func getEye(imageId:String) -> String {
let erange = imageId.index(imageId.startIndex, offsetBy: eyeIndex)..<imageId.index(imageId.startIndex, offsetBy:eyeIndex+1)
return String(imageId[erange])
}
func getCameraId(imageId: String) -> String {
print("You should never call me: override me in a subclass instead.")
return ""
}
func getCameraFOV(cameraId:String) -> Double {
let fov = cameraFOVs[cameraId]
guard fov != nil else {
print("Brown alert: requested camera FOV for unrecognized camera id: \(cameraId)")
return 0.0
}
return fov!
}
func layer(cameraId:String) -> Int {
if cameraId.hasPrefix("N") {
return 2;
} else {
return 1;
}
}
func mastPosition() -> [Double] {
print("You should never call me: override me in a subclass instead.")
return [0,0,0]
}
}
class Title {
var sol = 0
var imageSetID = ""
var instrumentName = ""
var marsLocalTime = ""
var siteIndex = 0
var driveIndex = 0
}
// http://www.dracotorre.com/blog/swift-substrings/
// extend String to enable sub-script with Int to get Character or sub-string
extension String
{
subscript (i: Int) -> Character {
return self[self.index(self.startIndex, offsetBy: i)]
}
// for convenience we should include String return
subscript (i: Int) -> String {
return String(self[i] as Character)
}
subscript (r: Range<Int>) -> String {
let start = self.index(self.startIndex, offsetBy: r.lowerBound)
let end = self.index(self.startIndex, offsetBy: r.upperBound)
return String(self[start...end])
}
}
| apache-2.0 | 7df5d7221be61be72aa1e50399e9163c | 28.5 | 146 | 0.606622 | 4.193388 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp | HTWDresden_old/HTWDresden/MPMainXMLParser.swift | 1 | 3361 | //
// MPMainXMLParser.swift
// HTWDresden
//
// Created by Benjamin Herzog on 27.08.14.
// Copyright (c) 2014 Benjamin Herzog. All rights reserved.
//
import UIKit
class MPMainXMLParser: NSObject, NSXMLParserDelegate {
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!
var completion: ((success: Bool, error: String!) -> Void)!
// MARK: - XMLHelper
var currentItem: String!
var speiseDic: [String:String]!
var inItem = false
var newSpeise: Speise!
override init() {
super.init()
let request = NSFetchRequest(entityName: "Speise")
let tempArray = context.executeFetchRequest(request, error: nil) as [Speise]
for speise in tempArray {
context.deleteObject(speise)
}
context.save(nil)
}
func parseWithCompletion(handler: (success: Bool, error: String?) -> Void) {
completion = handler
println("== Lade Mensenfeed...")
let request = NSURLRequest(URL: NSURL(string: MENSA_URL)!)
setNetworkIndicator(true)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {
response, data, error in
if data == nil {
self.completion(success: false, error: "Verbindung fehlgeschlagen.")
return
}
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
})
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError!) {
completion(success: false, error: parseError.localizedDescription)
}
func parser(parser: NSXMLParser, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
if elementName == "item" {
inItem = true
newSpeise = NSEntityDescription.insertNewObjectForEntityForName("Speise", inManagedObjectContext: context) as Speise
speiseDic = [String: String]()
}
currentItem = elementName
}
func parser(parser: NSXMLParser, foundCharacters string: String!) {
if string == "\n" { return }
if inItem {
if let temp = speiseDic[currentItem] {
var tempString = temp
tempString += string
speiseDic[currentItem] = tempString
}
else {
speiseDic[currentItem] = string
}
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
if elementName == "item" {
inItem = false
newSpeise.title = speiseDic["title"]?.componentsSeparatedByString("(").first
newSpeise.desc = speiseDic["description"]
newSpeise.link = speiseDic["link"]
newSpeise.mensa = speiseDic["author"]
context.save(nil)
}
}
func parserDidEndDocument(parser: NSXMLParser) {
dispatch_async(MAIN_QUEUE) {
setNetworkIndicator(false)
MENSA_LAST_REFRESH = NSDate()
self.completion(success: true, error: nil)
}
}
}
| gpl-2.0 | cdda53593a6b1bc3a7094a408cec9187 | 32.949495 | 180 | 0.599524 | 5.162826 | false | false | false | false |
zouguangxian/VPNOn | VPNOnKit/VPNKeychainWrapper.swift | 1 | 1669 | //
// VPNKeychainWrapper.swift
// VPNOn
//
// Created by Lex Tang on 12/12/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import Foundation
//let kKeychainServiceName = NSBundle.mainBundle().bundleIdentifier!
let kKeychainServiceName = "com.LexTang.VPNOn"
@objc(VPNKeychainWrapper)
class VPNKeychainWrapper
{
class func setPassword(password: String, forVPNID VPNID: String) -> Bool {
KeychainWrapper.serviceName = kKeychainServiceName
KeychainWrapper.removeObjectForKey(VPNID)
return KeychainWrapper.setString(password, forKey: VPNID)
}
class func setSecret(secret: String, forVPNID VPNID: String) -> Bool {
KeychainWrapper.serviceName = kKeychainServiceName
KeychainWrapper.removeObjectForKey("\(VPNID)psk")
return KeychainWrapper.setString(secret, forKey: "\(VPNID)psk")
}
class func setPassword(password: String, andSecret secret: String, forVPNID VPNID: String) -> Bool {
return setPassword(password, forVPNID: VPNID) && setSecret(secret, forVPNID: VPNID)
}
class func passwordForVPNID(VPNID: String) -> NSData? {
KeychainWrapper.serviceName = kKeychainServiceName
return KeychainWrapper.dataForKey(VPNID)
}
class func secretForVPNID(VPNID: String) -> NSData? {
KeychainWrapper.serviceName = kKeychainServiceName
return KeychainWrapper.dataForKey("\(VPNID)psk")
}
class func destoryKeyForVPNID(VPNID: String) {
KeychainWrapper.serviceName = kKeychainServiceName
KeychainWrapper.removeObjectForKey(VPNID)
KeychainWrapper.removeObjectForKey("\(VPNID)psk")
}
} | mit | a59066990d0c3f20fa1c723acecbdd5a | 33.791667 | 104 | 0.710006 | 4.967262 | false | false | false | false |
spacedrabbit/100-days | One00Days/One00Days/IntroSpriteKit/IntroSpriteKit/StarNode.swift | 1 | 904 | //
// StarNode.swift
// IntroSpriteKit
//
// Created by Louis Tur on 3/2/16.
// Copyright © 2016 SRLabs. All rights reserved.
// https://spin.atomicobject.com/2014/12/29/spritekit-physics-tutorial-swift/
import Foundation
import UIKit
import SpriteKit
class StarNode: SKSpriteNode {
class func star(location: CGPoint) -> StarNode {
let starSprite: StarNode = StarNode(imageNamed: "star.png")
starSprite.xScale = 0.075
starSprite.yScale = 0.075
starSprite.position = location
starSprite.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "star.png"), size: starSprite.size)
if let physics = starSprite.physicsBody {
physics.affectedByGravity = true
physics.allowsRotation = true
physics.dynamic = true
physics.linearDamping = 0.75
physics.angularDamping = 0.75
physics.restitution = 0.5
}
return starSprite
}
} | mit | 69c812bef7f3b3663ec5ea988e258b28 | 27.25 | 109 | 0.702104 | 4.142202 | false | false | false | false |
benlangmuir/swift | benchmark/single-source/DictionarySwap.swift | 10 | 2966 | //===--- DictionarySwap.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Dictionary element swapping benchmark
// rdar://problem/19804127
import TestsUtils
let size = 100
let numberMap = Dictionary(uniqueKeysWithValues: zip(1...size, 1...size))
let boxedNums = (1...size).lazy.map { Box($0) }
let boxedNumMap = Dictionary(uniqueKeysWithValues: zip(boxedNums, boxedNums))
let t: [BenchmarkCategory] = [.validation, .api, .Dictionary, .cpubench]
public let benchmarks = [
BenchmarkInfo(name: "DictionarySwap",
runFunction: swap, tags: t, legacyFactor: 4),
BenchmarkInfo(name: "DictionarySwapOfObjects",
runFunction: swapObjects, tags: t, legacyFactor: 40),
BenchmarkInfo(name: "DictionarySwapAt",
runFunction: swapAt, tags: t, legacyFactor: 4),
BenchmarkInfo(name: "DictionarySwapAtOfObjects",
runFunction: swapAtObjects, tags: t, legacyFactor: 11),
]
// Return true if correctly swapped, false otherwise
func swappedCorrectly(_ swapped: Bool, _ p25: Int, _ p75: Int) -> Bool {
return swapped && (p25 == 75 && p75 == 25) ||
!swapped && (p25 == 25 && p75 == 75)
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
func swap(n: Int) {
var dict = numberMap
var swapped = false
for _ in 1...2500*n {
(dict[25], dict[75]) = (dict[75]!, dict[25]!)
swapped = !swapped
check(swappedCorrectly(swapped, dict[25]!, dict[75]!))
}
}
func swapObjects(n: Int) {
var dict = boxedNumMap
var swapped = false
for _ in 1...250*n {
let b1 = Box(25)
let b2 = Box(75)
(dict[b1], dict[b2]) = (dict[b2]!, dict[b1]!)
swapped = !swapped
check(swappedCorrectly(swapped,
dict[Box(25)]!.value, dict[Box(75)]!.value))
}
}
func swapAt(n: Int) {
var dict = numberMap
var swapped = false
for _ in 1...2500*n {
let i25 = dict.index(forKey: 25)!
let i75 = dict.index(forKey: 75)!
dict.values.swapAt(i25, i75)
swapped = !swapped
check(swappedCorrectly(swapped, dict[25]!, dict[75]!))
}
}
func swapAtObjects(n: Int) {
var dict = boxedNumMap
var swapped = false
for _ in 1...1000*n {
let i25 = dict.index(forKey: Box(25))!
let i75 = dict.index(forKey: Box(75))!
dict.values.swapAt(i25, i75)
swapped = !swapped
check(swappedCorrectly(swapped,
dict[Box(25)]!.value, dict[Box(75)]!.value))
}}
| apache-2.0 | fa5f5eed099ea4cee6d8b2dac7f694bc | 28.078431 | 80 | 0.622387 | 3.556355 | false | false | false | false |
benlangmuir/swift | validation-test/compiler_crashers_fixed/01640-swift-typebase-getcanonicaltype.swift | 65 | 571 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
protocol A : A {
typealias A {
func b: C {
func b) -> String {
}
}
extension Array {
}
class A {
}
private class B == B<c) {
}
let f == .B {
var b = {
}
}
}
}
extension A =
| apache-2.0 | 49fd3e14f295849da6f3e5d931722003 | 20.148148 | 79 | 0.686515 | 3.300578 | false | false | false | false |
xuyazhong/SunnyNavigation | Pod/Classes/SunnyNaviItem.swift | 1 | 4396 | //
// FishNaviItem.swift
// Pods
//
// Created by amaker on 16/4/15.
//
//
import Foundation
import UIKit
public enum ItemType {
case left,center,right
}
let Default_Offset:CGFloat = 10.0
let TitleViewSize = CGSize(width: 120, height: 40)//用NSString设置item时 item的尺寸
let LeftViewSize = CGSize(width: 50, height: 40)//用NSString设置item时 item的尺寸
open class SunnyNaviItem: NSObject {
open var fixBarItem:UIBarButtonItem?
open var contentBarItem:UIButton?
open var items:NSMutableArray?
open var itemType:ItemType!
open var customView:UIView?
open var isCustomView:Bool?
func initCustomItemWithType(_ type : ItemType, size : CGSize) {
self.isCustomView = false
self.itemType = type
self.items = NSMutableArray()
self.contentBarItem = UIButton(type: .custom)
self.contentBarItem?.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
self.items?.add(self.contentBarItem!)
}
open static func itemWithTitle(_ title : String,
textColor : UIColor,
fontSize : CGFloat,
itemType : ItemType) -> SunnyNaviItem{
let item = SunnyNaviItem()
if itemType == .center {
item.initCustomItemWithType(itemType, size: TitleViewSize)
} else {
item.initCustomItemWithType(itemType, size: LeftViewSize)
}
item.setItemContetnWithType(itemType)
item.contentBarItem?.setTitle(title, for: UIControlState())
item.contentBarItem?.setTitleColor(textColor, for: UIControlState())
item.contentBarItem?.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
return item
}
open static func itemWithImage(_ itemWithImage : String,
size : CGSize,
type : ItemType) -> SunnyNaviItem{
let item = SunnyNaviItem()
item.initCustomItemWithType(type, size: size)
item.setItemContetnWithType(type)
item.contentBarItem?.setImage(UIImage(named: itemWithImage) , for: UIControlState())
return item
}
open static func itemWithCustomeView(_ customView : UIView,
type : ItemType) -> SunnyNaviItem{
let item = SunnyNaviItem()
item.initCustomItemWithType(type, size: customView.frame.size)
item.isCustomView = true
item.customView = customView
customView.frame = (item.contentBarItem?.bounds)!
item.contentBarItem?.addSubview(customView)
item.setItemContetnWithType(type)
return item
}
open func addTarget(_ target : AnyObject,
selector : Selector,
event : UIControlEvents) {
self.contentBarItem?.addTarget(target, action: selector, for: event)
}
/**
*设置item偏移量
*@param offSet 正值向左偏,负值向右偏
*/
open func setOffset(_ offSet : CGFloat) {
if (self.isCustomView != nil) {
var customViewFrame = self.customView?.frame
customViewFrame?.origin.x = offSet
self.customView?.frame = customViewFrame!
}
else{
self.contentBarItem?.contentEdgeInsets = UIEdgeInsetsMake(0, offSet, 0, -offSet)
}
}
open func setItemContetnWithType(_ type : ItemType){
if type == .right {
self.contentBarItem?.contentHorizontalAlignment = .right
self.setOffset(Default_Offset)
}else if type == .left{
self.contentBarItem?.contentHorizontalAlignment = .left
self.setOffset(Default_Offset)
}
}
open func setItemWithNavigationItem(_ navigationItem: UINavigationItem, type : ItemType){
if type == .center {
navigationItem.titleView = self.contentBarItem
} else if type == .left{
navigationItem.setLeftBarButton(UIBarButtonItem(customView: self.contentBarItem! ), animated: false)
} else if type == .right{
navigationItem.setRightBarButton(UIBarButtonItem(customView: self.contentBarItem! ), animated: false)
}
}
}
| mit | f81a4400bf7e78de4e78e47e1d660bb9 | 31.848485 | 113 | 0.5994 | 5.077283 | false | false | false | false |
ZackKingS/Tasks | task/Classes/Others/Lib/TakePhoto/photoCollectionViewCell.swift | 2 | 3515 |
//
// photoCollectionViewCell.swift
// PhotoPicker
//
// Created by liangqi on 16/3/6.
// Copyright © 2016年 dailyios. All rights reserved.
//
import UIKit
import Photos
protocol PhotoCollectionViewCellDelegate: class {
func eventSelectNumberChange(number: Int);
}
class photoCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var thumbnail: UIImageView!
@IBOutlet weak var imageSelect: UIImageView!
@IBOutlet weak var selectButton: UIButton!
weak var delegate: PhotoCollectionViewController?
weak var eventDelegate: PhotoCollectionViewCellDelegate?
var representedAssetIdentifier: String?
var model : PHAsset?
override func awakeFromNib() {
super.awakeFromNib()
self.thumbnail.contentMode = .scaleAspectFill
self.thumbnail.clipsToBounds = true
}
func updateSelected(select:Bool){
self.selectButton.isSelected = select
self.imageSelect.isHidden = !select
if select {
self.selectButton.setImage(nil, for: UIControlState.normal)
} else {
self.selectButton.setImage(UIImage(named: "picture_unselect"), for: UIControlState.normal)
}
}
@IBAction func eventImageSelect(sender: UIButton) {
if sender.isSelected {
sender.isSelected = false
self.imageSelect.isHidden = true
sender.setImage(UIImage(named: "picture_unselect"), for: UIControlState.normal)
if delegate != nil {
if let index = PhotoImage.instance.selectedImage.index(of: self.model!) {
PhotoImage.instance.selectedImage.remove(at: index)
}
if self.eventDelegate != nil {
self.eventDelegate!.eventSelectNumberChange(number: PhotoImage.instance.selectedImage.count)
}
}
} else {
if delegate != nil {
if PhotoImage.instance.selectedImage.count >= PhotoPickerController.imageMaxSelectedNum - PhotoPickerController.alreadySelectedImageNum {
self.showSelectErrorDialog() ;
return;
} else {
PhotoImage.instance.selectedImage.append(self.model!)
if self.eventDelegate != nil {
self.eventDelegate!.eventSelectNumberChange(number: PhotoImage.instance.selectedImage.count)
}
}
}
sender.isSelected = true
self.imageSelect.isHidden = false
sender.setImage(nil, for: UIControlState.normal)
self.imageSelect.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 6, options: [UIViewAnimationOptions.curveEaseIn], animations: { () -> Void in
self.imageSelect.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
}, completion: nil)
}
}
private func showSelectErrorDialog() {
if self.delegate != nil {
let less = PhotoPickerController.imageMaxSelectedNum - PhotoPickerController.alreadySelectedImageNum
let range = PhotoPickerConfig.ErrorImageMaxSelect.range(of:"#")
var error = PhotoPickerConfig.ErrorImageMaxSelect
error.replaceSubrange(range!, with: String(less))
let alert = UIAlertController.init(title: nil, message: error, preferredStyle: UIAlertControllerStyle.alert)
let confirmAction = UIAlertAction(title: PhotoPickerConfig.ButtonConfirmTitle, style: .default, handler: nil)
alert.addAction(confirmAction)
self.delegate?.present(alert, animated: true, completion: nil)
}
}
}
| apache-2.0 | f650385cbfaa6af538b0905b73a8f026 | 34.836735 | 176 | 0.68992 | 4.549223 | false | false | false | false |
tinysun212/swift-windows | test/APINotes/versioned.swift | 1 | 3554 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 4 | %FileCheck -check-prefix=CHECK-SWIFT-4 %s
// RUN: %target-swift-ide-test -F %S/Inputs/custom-frameworks -print-module -source-filename %s -module-to-print=APINotesFrameworkTest -function-definitions=false -print-regular-comments -swift-version 3 | %FileCheck -check-prefix=CHECK-SWIFT-3 %s
// CHECK-SWIFT-4: func jumpTo(x: Double, y: Double, z: Double)
// CHECK-SWIFT-3: func jumpTo(x: Double, y: Double, z: Double)
// CHECK-SWIFT-4: func accept(_ ptr: UnsafeMutablePointer<Double>)
// CHECK-SWIFT-3: func acceptPointer(_ ptr: UnsafeMutablePointer<Double>?)
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 4 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-4 %s
// RUN: not %target-swift-frontend -typecheck -F %S/Inputs/custom-frameworks -swift-version 3 %s 2>&1 | %FileCheck -check-prefix=CHECK-DIAGS -check-prefix=CHECK-DIAGS-3 %s
import APINotesFrameworkTest
func testRenamedTopLevel() {
var value = 0.0
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
accept(&value)
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:3: error: 'accept' has been renamed to 'acceptPointer(_:)'
// CHECK-DIAGS-3: note: 'accept' was introduced in Swift 4
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]:
acceptPointer(&value)
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:3: error: 'acceptPointer' has been renamed to 'accept(_:)'
// CHECK-DIAGS-4: note: 'acceptPointer' was obsoleted in Swift 4
acceptDoublePointer(&value)
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'acceptDoublePointer' has been renamed to
// CHECK-DIAGS-4-SAME: 'accept(_:)'
// CHECK-DIAGS-3-SAME: 'acceptPointer(_:)'
// CHECK-DIAGS: note: 'acceptDoublePointer' was obsoleted in Swift 3
oldAcceptDoublePointer(&value)
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:3: error: 'oldAcceptDoublePointer' has been renamed to
// CHECK-DIAGS-4-SAME: 'accept(_:)'
// CHECK-DIAGS-3-SAME: 'acceptPointer(_:)'
// CHECK-DIAGS: note: 'oldAcceptDoublePointer' has been explicitly marked unavailable here
_ = SomeCStruct()
// CHECK-DIAGS: versioned.swift:[[@LINE-1]]:7: error: 'SomeCStruct' has been renamed to
// CHECK-DIAGS-4-SAME: 'VeryImportantCStruct'
// CHECK-DIAGS-3-SAME: 'ImportantCStruct'
// CHECK-DIAGS: note: 'SomeCStruct' was obsoleted in Swift 3
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]:
_ = ImportantCStruct()
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:7: error: 'ImportantCStruct' has been renamed to 'VeryImportantCStruct'
// CHECK-DIAGS-4: note: 'ImportantCStruct' was obsoleted in Swift 4
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
_ = VeryImportantCStruct()
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:7: error: 'VeryImportantCStruct' has been renamed to 'ImportantCStruct'
// CHECK-DIAGS-3: note: 'VeryImportantCStruct' was introduced in Swift 4
// CHECK-DIAGS-3-NOT: versioned.swift:[[@LINE+1]]:
_ = InnerInSwift4()
// CHECK-DIAGS-4: versioned.swift:[[@LINE-1]]:7: error: 'InnerInSwift4' has been renamed to 'Outer.Inner'
// CHECK-DIAGS-4: note: 'InnerInSwift4' was obsoleted in Swift 4
// CHECK-DIAGS-4-NOT: versioned.swift:[[@LINE+1]]:
_ = Outer.Inner()
// CHECK-DIAGS-3: versioned.swift:[[@LINE-1]]:13: error: 'Inner' has been renamed to 'InnerInSwift4'
}
| apache-2.0 | 306fb627726f9f5aa08cb72b612057a5 | 52.044776 | 248 | 0.705121 | 3.460565 | false | true | false | false |
ksco/swift-algorithm-club-cn | Topological Sort/Topological Sort.playground/Sources/Graph.swift | 1 | 1169 | public class Graph: CustomStringConvertible {
public typealias Node = String
private(set) public var adjacencyLists: [Node : [Node]]
public init() {
adjacencyLists = [Node : [Node]]()
}
public func addNode(value: Node) -> Node {
adjacencyLists[value] = []
return value
}
public func addEdge(fromNode from: Node, toNode to: Node) -> Bool {
adjacencyLists[from]?.append(to)
return adjacencyLists[from] != nil ? true : false
}
public var description: String {
return adjacencyLists.description
}
public func adjacencyList(forNode node: Node) -> [Node]? {
for (key, adjacencyList) in adjacencyLists {
if key == node {
return adjacencyList
}
}
return nil
}
}
extension Graph {
typealias InDegree = Int
func calculateInDegreeOfNodes() -> [Node : InDegree] {
var inDegrees = [Node : InDegree]()
for (node, _) in adjacencyLists {
inDegrees[node] = 0
}
for (_, adjacencyList) in adjacencyLists {
for nodeInList in adjacencyList {
inDegrees[nodeInList] = (inDegrees[nodeInList] ?? 0) + 1
}
}
return inDegrees
}
}
| mit | 50319f88328bb0979a2afeec233ac383 | 21.921569 | 69 | 0.62361 | 4.297794 | false | false | false | false |
ksco/swift-algorithm-club-cn | Fizz Buzz/FizzBuzz.swift | 1 | 296 | func fizzBuzz(numberOfTurns: Int) {
for i in 1...numberOfTurns {
var result = ""
if i % 3 == 0 {
result += "Fizz"
}
if i % 5 == 0 {
result += (result.isEmpty ? "" : " ") + "Buzz"
}
if result.isEmpty {
result += "\(i)"
}
print(result)
}
}
| mit | 872ea94a35d9614fdf036cc1bf44d0ac | 14.578947 | 52 | 0.449324 | 3.288889 | false | false | false | false |
hoowang/WKRefreshDemo | WKRefreshDemo/Controller/WKExampleViewController.swift | 1 | 1633 | //
// WKExampleViewController.swift
// WKRefreshDemo
//
// Created by hooge on 16/5/5.
// Copyright © 2016年 hooge. All rights reserved.
//
import UIKit
class WKExampleViewController: UITableViewController {
let exampleCount = 10
let cellIdentify = "WKExampleCellID"
let titles = ["WKRichRefreshHeader ---下拉刷新", "TableView ---上拉刷新",
"WKPureRefreshHeader ---下拉刷新","collectionView ---上拉刷新"]
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: cellIdentify)
}
}
extension WKExampleViewController{
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentify)
cell?.textLabel?.text = self.titles[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0:
self.navigationController?.pushViewController(WKExampleTableViewController(), animated: true)
break
case 1:
break
case 2:
self.navigationController?.pushViewController(WKPureHeaderExampleController(), animated: true)
break
case 3:
break
default:
break
}
}
}
| mit | 3eb96ef5d8073d906c167d5e975f3f28 | 30.333333 | 118 | 0.66771 | 5.30897 | false | false | false | false |
spearal/SpearalIOS | SpearalIOS/SpearalPrinter.swift | 1 | 6728 | /**
* == @Spearal ==>
*
* Copyright (C) 2014 Franck WOLFF & William DRAI (http://www.spearal.io)
*
* 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.
*/
// author: Franck WOLFF
import Foundation
public protocol SpearalPrinterOutput {
func print(value:String) -> SpearalPrinterOutput
}
public class SpearalPrinterStringOutput: SpearalPrinterOutput {
private var _value:String = ""
public var value:String {
return _value
}
public init() {
}
public func print(value:String) -> SpearalPrinterOutput {
_value += value
return self
}
}
public protocol SpearalPrinter {
var output:SpearalPrinterOutput { get }
init(_ output:SpearalPrinterOutput)
func printNil()
func printBoolean(value:Bool)
func printIntegral(value:Int)
func printBigIntegral(value:String)
func printFloating(value:Double)
func printBigFloating(value:String)
func printString(value:String)
func printByteArrayReference(referenceIndex:Int)
func printByteArray(value:[UInt8], referenceIndex:Int)
func printDateTime(value:NSDate)
func printCollectionReference(referenceIndex:Int)
func printStartCollection(referenceIndex:Int)
func printEndCollection()
func printMapReference(referenceIndex:Int)
func printStartMap(referenceIndex:Int)
func printEndMap()
func printEnum(className:String, valueName:String)
func printClass(value:String)
func printBeanReference(referenceIndex:Int)
func printStartBean(className:String, referenceIndex:Int)
func printBeanProperty(name:String)
func printEndBean()
}
public class SpearalDefaultPrinter: SpearalPrinter {
private class Context {
var first:Bool = true
}
private class Collection: Context {
}
private class Bean: Context {
var name:Bool = true
}
private class Map: Context {
var key:Bool = true
}
public let output:SpearalPrinterOutput
private var contexts = [Context]()
public required init(_ output:SpearalPrinterOutput) {
self.output = output
}
public func printNil() {
indentValue("nil")
}
public func printBoolean(value:Bool) {
indentValue("\(value)")
}
public func printIntegral(value:Int) {
indentValue("\(value)")
}
public func printBigIntegral(value:String) {
indentValue(value)
}
public func printFloating(value:Double) {
indentValue("\(value)")
}
public func printBigFloating(value:String) {
indentValue(value)
}
public func printString(value:String) {
indentValue("\"\(value)\"")
}
public func printByteArrayReference(referenceIndex:Int) {
indentValue("@\(referenceIndex)")
}
public func printByteArray(value:[UInt8], referenceIndex:Int) {
indentValue("#\(referenceIndex) \(value)")
}
public func printDateTime(value:NSDate) {
indentValue("\(value)")
}
public func printCollectionReference(referenceIndex:Int) {
indentValue("@\(referenceIndex)")
}
public func printStartCollection(referenceIndex:Int) {
indentValue("#\(referenceIndex) [")
contexts.append(Collection())
}
public func printEndCollection() {
contexts.removeLast()
indentEnd("]")
}
public func printMapReference(referenceIndex:Int) {
indentValue("@\(referenceIndex)")
}
public func printStartMap(referenceIndex:Int) {
indentValue("#\(referenceIndex) {")
contexts.append(Map())
}
public func printEndMap() {
contexts.removeLast()
indentEnd("}")
}
public func printEnum(className:String, valueName:String) {
indentValue("\(className).\(valueName)")
}
public func printClass(value:String) {
indentValue(value)
}
public func printBeanReference(referenceIndex:Int) {
indentValue("@\(referenceIndex)")
}
public func printStartBean(className:String, referenceIndex:Int) {
indentValue("#\(referenceIndex) \(className) {")
contexts.append(Bean())
}
public func printBeanProperty(name:String) {
indentValue(name)
}
public func printEndBean() {
contexts.removeLast()
indentEnd("}")
}
private func indentValue(value:String) {
if contexts.isEmpty {
output.print(value)
return
}
switch contexts.last {
case let collection as Collection:
if collection.first {
collection.first = false
}
else {
output.print(",")
}
output.print("\n\(spaces())\(value)")
case let bean as Bean:
if bean.name {
if bean.first {
bean.first = false
}
else {
output.print(",")
}
output.print("\n\(spaces())\(value): ")
}
else {
output.print(value)
}
bean.name = !bean.name
case let map as Map:
if map.key {
if map.first {
map.first = false
}
else {
output.print(",")
}
output.print("\n\(spaces())")
}
output.print(value)
if map.key {
output.print(": ")
}
map.key = !map.key
default:
println("[SpearalPrinterImpl] Unexpected context: \(contexts.last)")
break
}
}
private func spaces() -> String {
return String(count: contexts.count, repeatedValue: Character("\t"))
}
private func indentEnd(value:String) {
output.print("\n")
output.print(String(count: contexts.count, repeatedValue: Character("\t")))
output.print(value)
}
}
| apache-2.0 | f63f98e992bd556500e2a42969bca5d2 | 24.976834 | 83 | 0.583532 | 4.943424 | false | false | false | false |
Pluto-tv/RxSwift | RxCocoa/iOS/UITableView+Rx.swift | 1 | 8735 | //
// UITableView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/2/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
// Items
extension UITableView {
/**
Binds sequences of elements to table view rows.
- parameter source: Observable sequence of items.
- parameter cellFactory: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithCellFactory<S: SequenceType, O: ObservableType where O.E == S>
(source: O)
(cellFactory: (UITableView, Int, S.Generator.Element) -> UITableViewCell)
-> Disposable {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory)
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
/**
Binds sequences of elements to table view rows.
- parameter cellIdentifier: Identifier used to dequeue cells.
- parameter source: Observable sequence of items.
- parameter configureCell: Transform between sequence elements and view cells.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithCellIdentifier<S: SequenceType, Cell: UITableViewCell, O : ObservableType where O.E == S>
(cellIdentifier: String)
(source: O)
(configureCell: (Int, S.Generator.Element, Cell) -> Void)
-> Disposable {
let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper<S> { (tv, i, item) in
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let cell = tv.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! Cell
configureCell(i, item, cell)
return cell
}
return self.rx_itemsWithDataSource(dataSource)(source: source)
}
/**
Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation.
- parameter dataSource: Data source used to transform elements to view cells.
- parameter source: Observable sequence of items.
- returns: Disposable object that can be used to unbind.
*/
public func rx_itemsWithDataSource<DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>, S: SequenceType, O: ObservableType where DataSource.Element == S, O.E == S>
(dataSource: DataSource)
(source: O)
-> Disposable {
return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: false) { [weak self] (_: RxTableViewDataSourceProxy, event) -> Void in
guard let tableView = self else {
return
}
dataSource.tableView(tableView, observedEvent: event)
}
}
}
extension UITableView {
/**
Factory method that enables subclasses to implement their own `rx_delegate`.
- returns: Instance of delegate proxy that wraps `delegate`.
*/
override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy {
return RxTableViewDelegateProxy(parentObject: self)
}
/**
Reactive wrapper for `dataSource`.
For more information take a look at `DelegateProxyType` protocol documentation.
*/
public var rx_dataSource: DelegateProxy {
return proxyForObject(self) as RxTableViewDataSourceProxy
}
/**
Installs data source as forwarding delegate on `rx_dataSource`.
It enables using normal delegate mechanism with reactive delegate mechanism.
- parameter dataSource: Data source object.
- returns: Disposable object that can be used to unbind the data source.
*/
public func rx_setDataSource(dataSource: UITableViewDataSource)
-> Disposable {
let proxy: RxTableViewDataSourceProxy = proxyForObject(self)
return installDelegate(proxy, delegate: dataSource, retainDelegate: false, onProxyForObject: self)
}
// events
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
*/
public var rx_itemSelected: ControlEvent<NSIndexPath> {
let source = rx_delegate.observe("tableView:didSelectRowAtIndexPath:")
.map { a in
return a[1] as! NSIndexPath
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var rx_itemInserted: ControlEvent<NSIndexPath> {
let source = rx_dataSource.observe("tableView:commitEditingStyle:forRowAtIndexPath:")
.filter { a in
return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Insert
}
.map { a in
return (a[2] as! NSIndexPath)
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`.
*/
public var rx_itemDeleted: ControlEvent<NSIndexPath> {
let source = rx_dataSource.observe("tableView:commitEditingStyle:forRowAtIndexPath:")
.filter { a in
return UITableViewCellEditingStyle(rawValue: (a[1] as! NSNumber).integerValue) == .Delete
}
.map { a in
return (a[2] as! NSIndexPath)
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`.
*/
public var rx_itemMoved: ControlEvent<ItemMovedEvent> {
let source: Observable<ItemMovedEvent> = rx_dataSource.observe("tableView:moveRowAtIndexPath:toIndexPath:")
.map { a in
return ((a[1] as! NSIndexPath), (a[2] as! NSIndexPath))
}
return ControlEvent(source: source)
}
/**
Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`.
It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence.
If custom data source is being bound, new `rx_modelSelected` wrapper needs to be written also.
public func rx_myModelSelected<T>() -> ControlEvent<T> {
let source: Observable<T> = rx_itemSelected.map { indexPath in
let dataSource: MyDataSource = self.rx_dataSource.forwardToDelegate() as! MyDataSource
return dataSource.modelAtIndex(indexPath.item)!
}
return ControlEvent(source: source)
}
*/
public func rx_modelSelected<T>() -> ControlEvent<T> {
let source: Observable<T> = rx_itemSelected.flatMap { [weak self] indexPath -> Observable<T> in
guard let view = self else {
return empty()
}
return just(try view.rx_modelAtIndexPath(indexPath))
}
return ControlEvent(source: source)
}
/**
Synchronous helper method for retrieving a model at indexPath through a reactive data source
*/
public func rx_modelAtIndexPath<T>(indexPath: NSIndexPath) throws -> T {
let dataSource: RxCollectionViewReactiveArrayDataSource<T> = castOrFatalError(self.rx_dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx_items*` methods was used.")
guard let element = dataSource.modelAtIndex(indexPath.item) else {
throw rxError(.InvalidOperation, "Items not set yet.")
}
return element
}
}
#endif
#if os(tvOS)
extension UITableView {
/**
Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`.
*/
public var rx_didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> {
let source = rx_delegate.observe("tableView:didUpdateFocusInContext:withAnimationCoordinator:")
.map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in
let context = a[1] as! UIFocusUpdateContext
let animationCoordinator = a[2] as! UIFocusAnimationCoordinator
return (context: context, animationCoordinator: animationCoordinator)
}
return ControlEvent(source: source)
}
}
#endif
| mit | 042ab9f02ce84e29b20b1d8f4e7de9f0 | 36.012712 | 209 | 0.648884 | 5.352328 | false | false | false | false |
zeroc-ice/ice | swift/test/Ice/retry/AllTests.swift | 3 | 4121 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
import PromiseKit
import TestCommon
public func allTests(helper: TestHelper, communicator2: Ice.Communicator, ref: String) throws -> RetryPrx {
func test(_ value: Bool, file: String = #file, line: Int = #line) throws {
try helper.test(value, file: file, line: line)
}
let output = helper.getWriter()
let communicator = helper.communicator()
output.write("testing stringToProxy... ")
let base1 = try communicator.stringToProxy(ref)!
let base2 = try communicator.stringToProxy(ref)!
output.writeLine("ok")
output.write("testing checked cast... ")
let retry1 = try checkedCast(prx: base1, type: RetryPrx.self)!
try test(retry1 == base1)
var retry2 = try checkedCast(prx: base2, type: RetryPrx.self)!
try test(retry2 == base2)
output.writeLine("ok")
output.write("calling regular operation with first proxy... ")
try retry1.op(false)
output.writeLine("ok")
output.write("calling operation to kill connection with second proxy... ")
do {
try retry2.op(true)
try test(false)
} catch is Ice.UnknownLocalException {
// Expected with collocation
} catch is Ice.ConnectionLostException {}
output.writeLine("ok")
output.write("calling regular operation with first proxy again... ")
try retry1.op(false)
output.writeLine("ok")
output.write("calling regular AMI operation with first proxy... ")
try retry1.opAsync(false).wait()
output.writeLine("ok")
output.write("calling AMI operation to kill connection with second proxy... ")
do {
try retry2.opAsync(true).wait()
} catch is Ice.ConnectionLostException {} catch is Ice.UnknownLocalException {}
output.writeLine("ok")
output.write("calling regular AMI operation with first proxy again... ")
try retry1.opAsync(false).wait()
output.writeLine("ok")
output.write("testing idempotent operation... ")
try test(retry1.opIdempotent(4) == 4)
try test(retry1.opIdempotentAsync(4).wait() == 4)
output.writeLine("ok")
output.write("testing non-idempotent operation... ")
do {
try retry1.opNotIdempotent()
try test(false)
} catch is Ice.LocalException {}
do {
try retry1.opNotIdempotentAsync().wait()
try test(false)
} catch is Ice.LocalException {}
output.writeLine("ok")
if try retry1.ice_getConnection() != nil {
output.write("testing system exception... ")
do {
try retry1.opSystemException()
try test(false)
} catch {}
do {
try retry1.opSystemExceptionAsync().wait()
try test(false)
} catch {}
output.writeLine("ok")
}
output.write("testing invocation timeout and retries... ")
retry2 = try checkedCast(prx: communicator2.stringToProxy(retry1.ice_toString())!,
type: RetryPrx.self)!
do {
// No more than 2 retries before timeout kicks-in
_ = try retry2.ice_invocationTimeout(500).opIdempotent(4)
try test(false)
} catch is Ice.InvocationTimeoutException {
_ = try retry2.opIdempotent(-1) // Reset the counter
}
do {
// No more than 2 retries before timeout kicks-in
_ = try retry2.ice_invocationTimeout(500).opIdempotentAsync(4).wait()
try test(false)
} catch is Ice.InvocationTimeoutException {
_ = try retry2.opIdempotent(-1) // Reset the counter
}
if try retry1.ice_getConnection() != nil {
// The timeout might occur on connection establishment or because of the sleep. What's
// important here is to make sure there are 4 retries and that no calls succeed to
// ensure retries with the old connection timeout semantics work.
let retryWithTimeout = retry1.ice_invocationTimeout(-2).ice_timeout(200)
do {
try retryWithTimeout.sleep(1000)
try test(false)
} catch is Ice.TimeoutException {}
}
output.writeLine("ok")
return retry1
}
| gpl-2.0 | 769484fa022898f73da39270c33298d4 | 32.504065 | 107 | 0.643776 | 4.239712 | false | true | false | false |
buttacciot/Hiragana | Hiragana/Theme.swift | 1 | 2473 | //
// Theme.swift
// Hiragana
//
// Created by Travis Buttaccio on 6/26/16.
// Copyright © 2016 LangueMatch. All rights reserved.
//
import Foundation
import ChameleonFramework
enum ViewControllerType {
case Splash
case Master
case Practice
case Drawing
}
enum ViewType {
case MenuItem(idx: Int)
}
protocol Theme {
func themeViewController(controller: UIViewController, type: ViewControllerType)
func themeView(view: UIView, type: ViewType)
}
class DefaultTheme: Theme {
static let sharedAPI = DefaultTheme()
func themeViewController(controller: UIViewController, type: ViewControllerType) {
switch type {
case .Splash:
let c = controller as! SplashController
c.view.backgroundColor = UIColor.SkyBlueGradient(c.view.frame)
case .Master:
let c = controller as! MasterController
guard let nav = c.navigationController else { return }
nav.navigationBar.barStyle = UIBarStyle.Black
nav.navigationBar.tintColor = UIColor.flatWhiteColor()
nav.navigationBar.barTintColor = UIColor.Salmon()
nav.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.flatWhiteColor()];
case .Practice:
let c = controller as! PracticeController
c.titleView.label.textColor = UIColor.flatWhiteColor()
case .Drawing:
let c = controller as! DrawingViewController
c.hiddenSymbol.layer.borderColor = UIColor.whiteColor().CGColor
}
}
func themeView(view: UIView, type: ViewType) {
switch type {
case .MenuItem(let idx):
let view = view as! MenuItemCell
view.titleLabel.textColor = UIColor.flatWhiteColor()
view.subtitleLabel.textColor = UIColor.flatWhiteColor()
switch idx {
case 0:
view.titleLabel.text = "Practice"
view.subtitleLabel.text = "Draw - Listen - Repeat"
view.backgroundColor = UIColor.flatCoffeeColor()
view.customImageView.image = UIImage(named: "")
case 1:
view.titleLabel.text = "Play"
view.backgroundColor = UIColor.flatGrayColor()
case 2:
view.titleLabel.text = "Play"
view.backgroundColor = UIColor.flatBlueColor()
default: break
}
}
}
} | mit | a1ba13d5188e8c399b19850580c631fc | 31.973333 | 112 | 0.621359 | 5.034623 | false | false | false | false |
Furzoom/swift-OC | src/swift/constant_variable/set.swift | 1 | 1070 | var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items")
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
print("union")
let set1 = oddDigits.union(evenDigits).sorted()
for v in set1 {
print("\(v) ", terminator: "")
}
print()
print("intersection")
let set2 = evenDigits.intersection(singleDigitPrimeNumbers).sorted()
for v in set2 {
print("\(v) ", terminator: "")
}
print()
print("subtracting")
let set3 = oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
for v in set3 {
print("\(v) ", terminator: "")
}
print()
print("symmetricDifference")
let set4 = oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
for v in set4 {
print("\(v) ", terminator: "")
}
print()
print(oddDigits == evenDigits)
print(Set<Int>(set2).isSubset(of: evenDigits))
// isSubset(of:)
// isSuperset(of:)
// isStrictSubset(of:)
// isStrictSuperset(of:)
// isDisJoint(with:)
| mit | c789b7b76cd5cc53a340ed0398cd70ac | 24.47619 | 74 | 0.681308 | 3.322981 | false | false | false | false |
water2891/Pudding-JS | PuddingJS/PuddingJS/Pudding-Core/PuddingPage.swift | 1 | 2437 | //
// PuddingPage.swift
// Pudding-JS
//
// Created by 苏打水 on 16/1/1.
// Copyright © 2016年 苏打水. All rights reserved.
//
import UIKit
public class PuddingPage: UIViewController {
public func fromUrlOrFile(urlOrFile:String){
print(urlOrFile)
if nil == self.template {
self.template = SamuraiTemplate();
self.template.responder = self;
}
if urlOrFile.hasPrefix("http") {
self.template.loadURL(urlOrFile, type: nil)
}else{
self.template.loadFile(urlOrFile)
}
}
}
extension UIAlertController {
class func showAlert(
presentController: UIViewController!,
title: String!,
message: String!,
cancelButtonTitle: String? = "cancel",
okButtonTitle: String? = "ok") {
let alert = UIAlertController(title: title!, message: message!, preferredStyle: UIAlertControllerStyle.Alert)
if (cancelButtonTitle != nil) {
alert.addAction(UIAlertAction(title: cancelButtonTitle!, style: UIAlertActionStyle.Default, handler: nil))// do not handle cancel, just dismiss
}
if (okButtonTitle != nil) {
alert.addAction(UIAlertAction(title: okButtonTitle!, style: UIAlertActionStyle.Default, handler: nil))// do not handle cancel, just dismiss
}
presentController!.presentViewController(alert, animated: true, completion: nil)
}
class func showAlert(
presentController: UIViewController!,
title: String!,
message: String!,
cancelButtonTitle: String? = "cancel",
okButtonTitle: String? = "ok",
okHandler: ((UIAlertAction!) -> Void)!) {
let alert = UIAlertController(title: title!, message: message!, preferredStyle: UIAlertControllerStyle.Alert)
if (cancelButtonTitle != nil) {
alert.addAction(UIAlertAction(title: cancelButtonTitle!, style: UIAlertActionStyle.Default, handler: nil))// do not handle cancel, just dismiss
}
if (okButtonTitle != nil) {
alert.addAction(UIAlertAction(title: okButtonTitle!, style: UIAlertActionStyle.Default, handler: okHandler))// do not handle cancel, just dismiss
}
presentController!.presentViewController(alert, animated: true, completion: nil)
}
} | mit | fdadad7b4267428908b564ef123bc565 | 37.460317 | 161 | 0.620562 | 5.077568 | false | false | false | false |
nostramap/nostra-sdk-sample-ios | SearchSample/Swift/SearchSample/CategoryViewController.swift | 1 | 1976 | //
// CategoryViewcontroller.swift
// SearchSample
//
// Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
class CategoryViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var categories: [NTCategoryResult]! = nil;
override func viewDidLoad() {
NTCategoryService.executeAsync { (resultSet, error) in
DispatchQueue.main.async(execute: {
if error == nil {
self.categories = resultSet?.results!;
}
else {
print("error \(error?.description)");
}
self.tableView.reloadData();
});
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "categorytoResultSegue" {
let resultViewController = segue.destination as! ResultViewController;
resultViewController.searchByCategory(sender as? String);
}
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
let category = categories[indexPath.row];
self.performSegue(withIdentifier: "categorytoResultSegue", sender: category.code);
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell");
let category = categories[indexPath.row];
cell?.textLabel?.text = category.name_E;
return cell!;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories != nil ? (categories?.count)! : 0;
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return 1
}
}
| apache-2.0 | 49ed34904e447a3bd7a7f82264856e3a | 26.816901 | 109 | 0.585823 | 5.642857 | false | false | false | false |
melling/SwiftCookBook | Dates/lastDayOfMonth.swift | 1 | 1097 | import Foundation
func lastDayOfMonth(_ aDate:Date) -> Date {
let calendar = Calendar(identifier: .gregorian)
var components = calendar.dateComponents([.year , .month , .day],
from:aDate)
components.month = components.month! + 1 // Next month
components.day = 0 // Set the day to zero to get last day of prior month
let aDate = calendar.date(from: components)
return aDate!
}
let now = Date()
let day = lastDayOfMonth(now)
print("Last day of this month: \(day)\n")
/*
Give a year, return the last day of each month
*/
func lastDayOfMonthList(year:Int) -> [Date] {
var result:[Date] = []
var components = DateComponents()
components.year = year
components.day = 1
for month in 1...12 {
components.month = month
let aDate = Calendar(identifier: .gregorian).date(from: components)
let d = lastDayOfMonth(aDate!)
result += [d]
}
return result
}
let x = lastDayOfMonthList(year: 2016)
x.forEach({print("\($0)")})
| cc0-1.0 | 9b3d577af02338ee1dcebd6f04863a49 | 22.847826 | 76 | 0.594348 | 4.203065 | false | false | false | false |
joakim666/chainbuilderapp | chainbuilder/ChainConfigurationViewModel.swift | 1 | 1846 | //
// ChainConfigurationViewModel.swift
// chainbuilder
//
// Created by Joakim Ek on 2017-06-21.
// Copyright © 2017 Morrdusk. All rights reserved.
//
import UIKit
class ChainConfigurationViewModel {
var configurationMode = false
var chain: Chain?
var callback: (() -> Void)?
var name: String?
var startDateEnabled: Bool?
var startDate: Date?
var color: UIColor?
init() {
}
/**
Configures the view model
- Parameter chain: The chain to configure
- Parameter callback: The callback to call when the configuration action is finished (i.e. to refresh the parent ui)
*/
func configure(_ chain: Chain, callback: @escaping () -> Void) {
self.chain = chain
self.callback = callback
self.configurationMode = true
if let n = chain.name {
self.name = n
}
self.startDateEnabled = chain.startDateEnabled
self.startDate = chain.startDate
self.color = UIColor(hexString: chain.color)
}
func save() {
self.configurationMode = false
guard let chain = self.chain else {
log.error("No chain set")
return
}
do {
let realm = try RealmUtils.create()
try realm.write {
chain.name = self.name
if let startDateEnabled = self.startDateEnabled {
chain.startDateEnabled = startDateEnabled
}
chain.startDate = self.startDate
if let color = self.color {
chain.color = color.toHexString()
}
}
}
catch {
log.error("Failed to modify chain: \(error.localizedDescription))")
}
}
}
| apache-2.0 | 3c1babae264d944d7f4e4f4b6cb68f39 | 24.273973 | 122 | 0.543089 | 4.959677 | false | true | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Sources/RandomizedQueueObserver.swift | 2 | 1854 | //
// RandomizedQueueObserver.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
public class RandomizedQueueObserver: CommandQueueDelegate {
/// The counter which grabs a random Int from the provided range to determine when the handler should be called.
var counter: Int
let desiredRange: ClosedRange<Int>
unowned var gridWorld: GridWorld
let handler: (GridWorld) -> Void
/// The range within which the action should be invoked. Since the range refers to the world's action queue, only positive (unsigned) ranges are supported.
public init(randomRange: ClosedRange<Int> = 1...6, world: GridWorld, commandHandler: (GridWorld) -> Void) {
gridWorld = world
desiredRange = randomRange
handler = commandHandler
// Set an initial value for the counter.
counter = randomNumber(fromRange: desiredRange)
gridWorld.commandQueue.delegate = self
}
// MARK: CommandQueueDelegate
func commandQueue(_ queue: CommandQueue, added _: Command) {
let queueCount = queue.count
if queueCount > counter {
counter = queueCount + randomNumber(fromRange: desiredRange)
// Ignore queue callbacks for any commands that are produced
// as part of the handler.
queue.delegate = nil
handler(gridWorld)
queue.delegate = self
}
}
func commandQueue(_ queue: CommandQueue, willPerform _: Command) {}
func commandQueue(_ queue: CommandQueue, didPerform _: Command) {}
}
private func randomNumber(fromRange range: ClosedRange<Int>) -> Int {
let min = range.lowerBound > 0 ? range.lowerBound : 1
let max = range.upperBound
return Int(arc4random_uniform(UInt32(max - min))) + min
}
| mit | accfea323a08ea8d3a1b72015333a19b | 32.709091 | 159 | 0.653722 | 4.753846 | false | false | false | false |
ontouchstart/swift3-playground | Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Exercise4.playgroundpage/Sources/Assessments.swift | 1 | 1126 | //
// Assessments.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
let success = "### Fantastic! \nComparing a [variable](glossary://variable) to a [constant](glossary://constant) is done frequently in code. As you continue practicing this skill, it will start to seem as commonplace as writing a command. \n\n[**Next Page**](@next)"
let hints = [
"Byte should continue to collect gems until your `gemCounter` value matches your `switchCounter` value.",
"Use a [comparison operator](glossary://comparison%20operator) to write a [Boolean](glossary://Boolean) condition comparing your `gemCounter` value with your `switchCounter` value. \nExample: `while a != b`"
]
let solution = "```swift\nlet switchCounter = numberOfSwitches\nvar gemCounter = 0\n\nwhile gemCounter < switchCounter {\n if isOnGem {\n collectGem()\n gemCounter = gemCounter + 1\n }\n if isBlocked {\n turnRight()\n }\n moveForward()\n}\n```"
public func assessmentPoint() -> AssessmentResults {
return updateAssessment(successMessage: success, failureHints: hints, solution: solution)
}
| mit | fa63b5df28abb19b2e5e0af61cdfbc7a | 61.555556 | 280 | 0.705151 | 3.923345 | false | false | false | false |
soffes/HotKey | Sources/HotKey/NSEventModifierFlags+HotKey.swift | 1 | 1303 | import AppKit
import Carbon
extension NSEvent.ModifierFlags {
public var carbonFlags: UInt32 {
var carbonFlags: UInt32 = 0
if contains(.command) {
carbonFlags |= UInt32(cmdKey)
}
if contains(.option) {
carbonFlags |= UInt32(optionKey)
}
if contains(.control) {
carbonFlags |= UInt32(controlKey)
}
if contains(.shift) {
carbonFlags |= UInt32(shiftKey)
}
return carbonFlags
}
public init(carbonFlags: UInt32) {
self.init()
if carbonFlags & UInt32(cmdKey) == UInt32(cmdKey) {
insert(.command)
}
if carbonFlags & UInt32(optionKey) == UInt32(optionKey) {
insert(.option)
}
if carbonFlags & UInt32(controlKey) == UInt32(controlKey) {
insert(.control)
}
if carbonFlags & UInt32(shiftKey) == UInt32(shiftKey) {
insert(.shift)
}
}
}
extension NSEvent.ModifierFlags: CustomStringConvertible {
public var description: String {
var output = ""
if contains(.control) {
output += Key.control.description
}
if contains(.option) {
output += Key.option.description
}
if contains(.shift) {
output += Key.shift.description
}
if contains(.command) {
output += Key.command.description
}
return output
}
}
| mit | 285a9851394383a52f5477ae794e158f | 17.614286 | 61 | 0.615503 | 3.64986 | false | false | false | false |
ufogxl/MySQLTest | Sources/getAllScore.swift | 1 | 2495 | //
// getMoreScore.swift
// GoodStudent
//
// Created by ufogxl on 2016/12/27.
//
//
import Foundation
import PerfectLib
import PerfectHTTP
import MySQL
import ObjectMapper
fileprivate let container = ResponseContainer()
fileprivate let errorContent = ErrorContent()
fileprivate var user_info = NSDictionary()
func getAllScore(_ request:HTTPRequest,response:HTTPResponse){
let params = request.params()
phaseParams(params: params)
if !paramsValid(){
errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue
container.data = errorContent
container.result = false
container.message = "参数错误"
response.appendBody(string: container.toJSONString(prettyPrint: true)!)
response.completed()
return
}
if let scores = makeAllScores(){
container.data = scores
container.result = true
container.message = "获取成功!"
}else{
errorContent.code = ErrCode.SERVER_ERROR.hashValue
container.data = errorContent
container.result = false
container.message = "获取失败,稍后再试!"
}
response.appendBody(string: container.toJSONString(prettyPrint: true)!)
response.completed()
}
fileprivate func phaseParams(params: [(String,String)]){
let info = NSMutableDictionary()
for pair in params{
info.setObject(pair.1, forKey: NSString(string:pair.0))
}
user_info = info as NSDictionary
}
fileprivate func makeAllScores() -> AllScores?{
let scores = AllScores()
var scoreInfo = [Score]()
let mysql = MySQL()
let connected = mysql.connect(host: db_host, user: db_user, password: db_password, db: database,port:db_port)
guard connected else {
print(mysql.errorMessage())
return nil
}
defer {
mysql.close()
}
let statement = "SELECT c_name,score FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time<=\(getWhichExam() - 3) order by exam_time"
let querySuccess = mysql.query(statement: statement)
guard querySuccess else{
return nil
}
let results = mysql.storeResults()!
while let row = results.next(){
let score = Score()
score.name = row[0]
score.score = row[1]
scoreInfo.append(score)
}
scores.scores = scoreInfo
return scores
}
fileprivate func paramsValid() -> Bool{
return true
}
| apache-2.0 | e4a69628b953430c2791cbfc0ec8d974 | 24.112245 | 167 | 0.641609 | 4.294939 | false | false | false | false |
google/JacquardSDKiOS | JacquardSDK/Classes/Internal/Connection/ProtocolInitializationStateMachine.swift | 1 | 11239 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Combine
import Foundation
class ProtocolInitializationStateMachine {
private enum Constants {
static let requestTimeout = 2.0
}
static let initialState: State = .paired
// This will need to be refactored when we support > 1 protocol.
static let supportedProtocol = ProtocolSpec.version2
private let stateSubject = CurrentValueSubject<State, Never>(
ProtocolInitializationStateMachine.initialState)
lazy var statePublisher: AnyPublisher<State, Never> = stateSubject.eraseToAnyPublisher()
private let marshalQueue = DispatchQueue(
label: "ProtocolInitializationStateMachine marshaling queue")
private var context: Context
private let sdkConfig: SDKConfig
private var observations = [Cancellable]()
private var state: State = ProtocolInitializationStateMachine.initialState {
didSet {
stateSubject.send(state)
}
}
enum State {
case paired
case helloSent
case beginSent
case componentInfoSent
case creatingTagInstance
case tagInitialized(ConnectedTag)
case error(Error)
var isTerminal: Bool {
switch self {
case .tagInitialized, .error: return true
default: return false
}
}
}
private enum Event {
case startNegotiation
case didWriteValue(Error?)
case didReceiveResponse(Google_Jacquard_Protocol_Response)
case didReceiveResponseError(Error)
case validateHelloResponse(Google_Jacquard_Protocol_HelloResponse)
case validateBeginResponse(Data)
case createdConnectedTagInstance(ConnectedTag)
}
private struct Context {
/// This state machine is the first time commands are sent, so we commence with fresh transport state.
let transport: Transport
/// We need to keep a reference to the requested user publish queue to create the ConnectedTag instance with.
let userPublishQueue: DispatchQueue
let characteristics: RequiredCharacteristics
}
init(
peripheral: Peripheral,
characteristics: RequiredCharacteristics,
userPublishQueue: DispatchQueue,
sdkConfig: SDKConfig
) {
let transport = TransportV2Implementation(
peripheral: peripheral, characteristics: characteristics)
self.sdkConfig = sdkConfig
self.context = Context(
transport: transport, userPublishQueue: userPublishQueue, characteristics: characteristics)
}
}
//MARK: - External event methods.
extension ProtocolInitializationStateMachine {
func startNegotiation() {
// Setup transport didWrite event observer.
context.transport.didWriteCommandPublisher
.buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest)
.receive(on: marshalQueue)
.sink { error in
self.handleEvent(.didWriteValue(error))
}.addTo(&observations)
marshalQueue.async {
self.handleEvent(.startNegotiation)
}
}
}
//MARK: - Internal event methods & helpers.
extension ProtocolInitializationStateMachine {
private func handleResponseResult(_ responseResult: Transport.ResponseResult) {
self.marshalQueue.async {
switch responseResult {
case .success(let packet):
do {
let response = try Google_Jacquard_Protocol_Response(
serializedData: packet, extensions: Google_Jacquard_Protocol_Jacquard_Extensions)
self.handleEvent(.didReceiveResponse(response))
} catch (let error) {
self.handleEvent(.didReceiveResponseError(error))
}
case .failure(let error):
self.handleEvent(.didReceiveResponseError(error))
}
}
}
private func sendHello() throws {
let helloRequest = Google_Jacquard_Protocol_Request.with {
$0.domain = .base
$0.opcode = .hello
}
context.transport.enqueue(
request: helloRequest,
type: .withoutResponse,
retries: 2,
requestTimeout: Constants.requestTimeout,
callback: handleResponseResult
)
}
private func sendBegin() throws {
let beginRequest = Google_Jacquard_Protocol_Request.with {
$0.domain = .base
$0.opcode = .begin
$0.Google_Jacquard_Protocol_BeginRequest_begin.protocol = ProtocolSpec.version2.rawValue
}
context.transport.enqueue(
request: beginRequest,
type: .withoutResponse,
retries: 2,
requestTimeout: Constants.requestTimeout,
callback: handleResponseResult)
}
private func sendComponentInfo() {
let componentInfoRequest = ComponentInfoCommand(
componentID: TagConstants.FixedComponent.tag.rawValue)
context.transport.enqueue(
request: componentInfoRequest.request,
type: .withoutResponse,
retries: 2,
requestTimeout: Constants.requestTimeout,
callback: handleResponseResult
)
}
private func createConnectedTagInstance(
componentInfoResponse: Google_Jacquard_Protocol_Response
) {
let info = componentInfoResponse.Google_Jacquard_Protocol_DeviceInfoResponse_deviceInfo
let product = GearMetadata.GearData.Product.with {
$0.id = ComponentImplementation.convertToHex(info.productID)
$0.name = TagConstants.product
$0.image = "JQTag"
$0.capabilities = [.led]
}
let vendor = GearMetadata.GearData.Vendor.with {
$0.id = ComponentImplementation.convertToHex(info.vendorID)
$0.name = info.vendor
$0.products = [product]
}
let firmwareVersion = Version(
major: info.firmwareMajor, minor: info.firmwareMinor, micro: info.firmwarePoint)
let tagComponet = ComponentImplementation(
componentID: TagConstants.FixedComponent.tag.rawValue,
vendor: vendor,
product: product,
isAttached: true,
version: firmwareVersion,
uuid: info.uuid
)
let connectedTag = ConnectedTagModel(
transport: context.transport,
userPublishQueue: context.userPublishQueue,
tagComponent: tagComponet,
sdkConfig: sdkConfig)
marshalQueue.async {
self.handleEvent(.createdConnectedTagInstance(connectedTag))
}
}
}
//MARK: - Transitions.
// Legend of comments that cross reference the Dot Statechart at the end of this file.
// (labels) cross reference individual transitions
// case where clauses represent [guard] statements
// / Actions are labelled with comments in the case bodies.
extension ProtocolInitializationStateMachine {
/// Examines events and current state to apply transitions.
private func handleEvent(_ event: Event) {
dispatchPrecondition(condition: .onQueue(marshalQueue))
if state.isTerminal {
jqLogger.info("State machine is already terminal, ignoring event: \(event)")
}
jqLogger.debug("Entering \(self).handleEvent(\(state), \(event)")
switch (state, event) {
// (e1)
case (_, .didWriteValue(let error)) where error != nil:
state = .error(error!)
// (e2)
case (_, .didReceiveResponseError(let error)):
state = .error(error)
// (t3)
case (.paired, .startNegotiation):
do {
try sendHello()
state = .helloSent
} catch (let error) {
state = .error(error)
}
// (t4)
case (.helloSent, .didReceiveResponse(let response))
where
response.hasGoogle_Jacquard_Protocol_HelloResponse_hello
&& response.Google_Jacquard_Protocol_HelloResponse_hello.protocolMin >= 2
&& response.Google_Jacquard_Protocol_HelloResponse_hello.protocolMax <= 2:
do {
try sendBegin()
state = .beginSent
} catch (let error) {
state = .error(error)
}
// (e5)
case (.helloSent, .didReceiveResponse(_)):
state = .error(TagConnectionError.malformedResponseError)
// (t6)
case (.beginSent, .didReceiveResponse(let response))
where response.hasGoogle_Jacquard_Protocol_BeginResponse_begin:
sendComponentInfo()
state = .componentInfoSent
// (e7)
case (.beginSent, .didReceiveResponse(_)):
state = .error(TagConnectionError.malformedResponseError)
// (t8)
case (.componentInfoSent, .didReceiveResponse(let response))
where response.hasGoogle_Jacquard_Protocol_DeviceInfoResponse_deviceInfo:
// TODO(b/193370260): Handle bad firmware use case.
state = .creatingTagInstance
createConnectedTagInstance(componentInfoResponse: response)
// (e9)
case (.componentInfoSent, .didReceiveResponse(_)):
state = .error(TagConnectionError.malformedResponseError)
// (t10)
case (.creatingTagInstance, .createdConnectedTagInstance(let tag)):
state = .tagInitialized(tag)
// No valid transition found.
default:
jqLogger.error("No transition found for (\(state), \(event))")
state = .error(TagConnectionError.internalError)
}
jqLogger.debug("Exiting \(self).handleEvent() new state: \(state)")
}
}
//MARK: - Dot Statechart
// Note that the order is important - the transition events/guards will be evaluated in order and
// only the first matching transition will have effect.
// digraph {
// node [shape=point] start, complete;
// node [shape=Mrecord]
// edge [decorate=1, minlen=2]
//
// start -> paired;
//
// // Note that unlike regular commands after initialization is complete, throughout this
// // state machine we request write responses from CoreBluetooth.
//
// "*" -> error
// [label="(e1)
// didWriteValue(error)
// [error != nil]"];
//
// "* " -> error
// [label="(e2) didReceiveResponseError(error)"];
//
// paired -> helloSent
// [label="(t3)
// startNegotiation
// / sendHello (with 2 seconds request timeout)"];
//
// helloSent -> beginSent
// [label="(t4)
// didReceiveResponse(data)
// [response.hasHelloResponse && (resp.minProtocol ≤ 2 ≤ resp.maxProtocol)]
// / sendBegin() (with 2 seconds request timeout)"];
//
// helloSent -> error
// [label="(e5)
// didReceiveResponse(_)"];
//
// beginSent -> componentInfoSent
// [label="(t6)
// didReceiveResponse(_)
// [response.hasBeginResponse)]
// / sendComponentInfo() (with 2 seconds request timeout)"];
//
// beginSent -> error
// [label="(e7)
// didReceiveResponse(_)"];
//
// componentInfoSent -> creatingTagInstance
// [label="(t8)
// didReceiveResponse(_)
// [response.hasDeviceInfoResponse)]
// / createConnectedTagInstance(resp)"];
// componentInfoSent -> error
// [label="(e9)
// didReceiveResponse(_)"];
//
// creatingTagInstance -> tagInitialized
// [label="(t10) createdTagInstance(tag)"];
//
// tagInitialized -> complete;
//}
| apache-2.0 | 3bf3e7144fb936f2a12de705031ae896 | 29.447154 | 113 | 0.680552 | 4.543065 | false | false | false | false |
xiaoxinghu/OrgMarker | Tests/OrgMarkerTests/InlineTests.swift | 1 | 1095 | //
// InlineTests.swift
// OrgMarker
//
// Created by Xiaoxing Hu on 27/03/17.
//
//
import XCTest
@testable import OrgMarker
class InlineTests: XCTestCase {
var text: String!
var lines: [String]!
override func setUp() {
super.setUp()
}
func testBasicSyntax() throws {
let syntax = [
("~awesome~", "code"),
("=awesome=", "verbatim"),
("*awesome*", "bold"),
("/awesome/", "italic"),
("_awesome_", "underline"),
("+awesome+", "strikeThrough"),
("[[awesome][www.orgmode.org]]", "link"),
]
for (text, name) in syntax {
let line = "org-mode is \(text). smiley face 😀."
expect(mark(line)[0],
to: haveMark(name, to: haveValue(text, on: line)))
}
}
func testComplexLink() {
let text = "This is an [[awesome website][www.orgmode.org/awesome/tool]]."
let m = mark(text)[0]
XCTAssertEqual(1, m.marks.count)
expect(m, to: haveMark("link"))
}
}
| mit | 0bcf29c0d3e4965059c11bf3be0e8ea0 | 23.818182 | 82 | 0.496337 | 3.858657 | false | true | false | false |
almachelouche/Alien-Adventure | Alien Adventure/MostCommonCharacter.swift | 1 | 1140 | //
// MostCommonCharacter.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/4/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func mostCommonCharacter(inventory: [UDItem]) -> Character? {
var charact = [Character:Int]()
if inventory.isEmpty {
return nil
} else {
for item in inventory {
for i in item.name.lowercased().characters {
print (i)
if let value = charact[i] {
let count = value + 1
charact[i] = count
} else {
charact[i] = 1
}
}
}
var highestCount : Int = 0
var mostCommonChar : Character = "a"
for (i,count) in charact {
if count > highestCount {
highestCount = count
mostCommonChar = i
print ("Most common character is \(mostCommonChar) it occured \(highestCount)")
}
}
print (mostCommonChar)
return mostCommonChar
}
}
}
| mit | 894b6f97ca5eb8db15706705fdb0ae5c | 25.488372 | 95 | 0.480246 | 4.867521 | false | false | false | false |
Tulakshana/FileCache | FileCache/Example/FileCache/Users/User.swift | 1 | 1997 | //
// User.swift
// FileCacheExample
//
// Created by Weerasooriya, Tulakshana on 5/14/17.
// Copyright © 2017 Tulakshana. All rights reserved.
//
import Foundation
class User {
var username: NSString?
var name: NSString?
var imageURL: NSString?
var thumbURL: NSString?
var sampleWorkURL: NSString?
var categoriesArray: NSArray = NSArray()
var unsplashLink: NSString?
init(dictionary: [String:AnyObject]) {
if let user: [String:AnyObject] = dictionary["user"] as? [String : AnyObject] {
if let uname: NSString = user["username"] as? NSString {
self.username = uname
}
if let name: NSString = user["name"] as? NSString {
self.name = name
}
if let imageDic: [String:AnyObject] = user["profile_image"] as? [String:AnyObject] {
if let url: NSString = imageDic["large"] as? NSString {
self.imageURL = url
}
if let url: NSString = imageDic["small"] as? NSString {
self.thumbURL = url
}
}
}
if let cArray: [[String:AnyObject]] = dictionary["categories"] as? [[String:AnyObject]] {
let categories: NSMutableArray = NSMutableArray()
for object in cArray {
let cat: Category = Category.init(dictionary: object)
categories.add(cat)
}
categoriesArray = categories
}
if let links: [String:AnyObject] = dictionary["links"] as? [String:AnyObject] {
if let url: NSString = links["html"] as? NSString {
self.unsplashLink = url
}
}
if let urls: [String:AnyObject] = dictionary["urls"] as? [String:AnyObject] {
if let url: NSString = urls["full"] as? NSString {
self.sampleWorkURL = url
}
}
}
}
| mit | 8befcfe917a7d40b4e3e6f8083698045 | 31.721311 | 97 | 0.531062 | 4.62037 | false | false | false | false |
AndreasRicci/firebase-continue | samples/ios/Continote/Continote/MyNotesTableViewDataSource.swift | 2 | 2037 | //
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebaseDatabase
import FirebaseDatabaseUI
import MaterialComponents.MaterialSnackbar
/**
The data source used for the TableView in MyNotesViewController.
We need to override FUITableViewDataSource in order to allow the user to edit
(and then subsequently delete) rows (i.e. Notes) within the table.
*/
class MyNotesTableViewDataSource: FUITableViewDataSource {
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Allow the user to edit any row in the table.
return true
}
override func tableView(_ tableView: UITableView,
commit editingStyle: UITableViewCellEditingStyle,
forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
// Attempt to delete the corresponding Note from the Firebase Realtime Database.
if (UInt(indexPath.row) < count) {
snapshot(at: indexPath.row).ref.removeValue { (error, ref) in
guard error == nil else {
MDCSnackbarManager.show(Constants.AppError.couldNotDeleteNote.rawValue)
return
}
}
}
}
}
/**
These local constants are organized as a private extension to the global Constants struct
for clarity and a cleaner namespace.
*/
private extension Constants {
enum AppError: String, Error {
case couldNotDeleteNote = "Could not delete note. Please try again."
}
}
| apache-2.0 | 89e79d6179be02e0581725dc544a0205 | 32.95 | 96 | 0.713795 | 4.608597 | false | false | false | false |
KyoheiG3/PagingView | PagingView/CellReuseQueue.swift | 1 | 739 | //
// CellReuseQueue.swift
// Pods
//
// Created by Kyohei Ito on 2015/10/09.
//
//
struct CellReuseQueue {
private var queue: [String: [PagingViewCell]] = [:]
func dequeue(_ identifier: String) -> PagingViewCell? {
return queue[identifier]?.filter { $0.superview == nil }.first
}
mutating func append(_ view: PagingViewCell, forQueueIdentifier identifier: String) {
if queue[identifier] == nil {
queue[identifier] = []
}
queue[identifier]?.append(view)
}
mutating func remove(_ identifier: String) {
queue[identifier] = nil
}
func count(_ identifier: String) -> Int {
return queue[identifier]?.count ?? 0
}
}
| mit | 7342dd02d673daa57730cb7750bf73df | 22.83871 | 89 | 0.580514 | 4.198864 | false | false | false | false |
floriankrueger/SHOUTCLOUD_IOS | EXAMPLE/User Interface/ViewController.swift | 1 | 3067 | //
// ViewController.swift
// EXAMPLE
//
// Created by Florian Krüger on 03/06/15.
// Copyright (c) 2015 projectserver.org. All rights reserved.
//
import UIKit
import Manuscript
import SHOUTCLOUD
class ViewController: UIViewController {
let inputTextField = UITextField(frame: CGRectZero)
let sendButton = UIButton.buttonWithType(.System) as! UIButton
// MARK: - Init
init() {
super.init(nibName: nil, bundle: nil)
self.setup()
}
required init(coder aDecoder: NSCoder) {
fatalError("storyboards are incompatible with truth and beauty")
}
// MARK: - View
override func loadView() {
super.loadView()
self.setupView()
self.setupSubviews()
self.setupLayout()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
// MARK: - Target
func shout() {
let client = SHOUTCLOUD.Client.sharedClient
client.shout(self.inputTextField.text,
success: { message in
dispatch_async(dispatch_get_main_queue()) {
UIAlertView(title: "RESPONSE", message: message, delegate: nil, cancelButtonTitle: "OK").show()
}
},
failure: { error in
dispatch_async(dispatch_get_main_queue()) {
UIAlertView(title: "ERROR", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show()
}
}
)
}
// MARK: - Setup & Layout
private func setup() {
self.title = "SHOUTCLOUD"
}
private func setupView() {
self.view.backgroundColor = UIColor.whiteColor()
}
private func setupSubviews() {
self.inputTextField.backgroundColor = UIColor.whiteColor()
self.inputTextField.placeholder = "put some text here"
self.inputTextField.font = UIFont(name: "AvenirNext", size: 16.0)
self.inputTextField.textColor = SHOUTCLOUD.Constants.Colors.black
self.inputTextField.textAlignment = .Center
self.inputTextField.layer.borderColor = SHOUTCLOUD.Constants.Colors.black.CGColor
self.inputTextField.layer.borderWidth = 1.5
self.inputTextField.layer.cornerRadius = 3.0
self.inputTextField.clearButtonMode = .WhileEditing;
self.view.addSubview(self.inputTextField)
self.sendButton.setTitleColor(SHOUTCLOUD.Constants.Colors.red, forState: .Normal)
self.sendButton.setTitle("SHOUT", forState: .Normal)
self.sendButton.addTarget(self, action: "shout", forControlEvents: .TouchUpInside)
self.view.addSubview(self.sendButton)
}
private func setupLayout() {
Manuscript.layout(self.inputTextField) { c in
c.make(.Left, equalTo: self.view, s: .Left, plus: 20.0)
c.make(.Right, equalTo: self.view, s: .Right, minus: 20.0)
c.make(.Top, equalTo: self.topLayoutGuide, s: .Baseline, plus: 20.0)
c.set(.Height, to: 44.0)
}
Manuscript.layout(self.sendButton) { c in
c.make(.Left, equalTo: self.view, s: .Left, plus: 20.0)
c.make(.Right, equalTo: self.view, s: .Right, minus: 20.0)
c.make(.Top, equalTo: self.inputTextField, s: .Bottom, plus: 20.0)
c.set(.Height, to: 44.0)
}
}
}
| mit | ffdb52adbf0a6333a27ff62107715e4a | 28.2 | 121 | 0.677104 | 3.890863 | false | false | false | false |
vokal/Xcode-Template | Vokal-Swift.xctemplate/TokenStorageHelper.swift | 2 | 2762 | //
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// ___COPYRIGHT___
//
import Foundation
import SwiftKeychainWrapper
/**
Facilitates the storage of a single user's credentials in the keychain.
*/
struct TokenStorageHelper {
// MARK: - Keychain enums
private enum KeychainKey: String {
case username = "___PACKAGENAME___.keychain.username"
}
// MARK: - Authorization methods
/**
Stores the authorization token for a given user's email in the keychain.
- parameter email: The user's email address.
- parameter authToken: The current auth token.
*/
static func store(authorizationToken: String, forEmail email: String) {
// See if the token matches existing:
// There is a stored username, and it is not the email you are using right now
if let username = getUserName(), username != email {
//This is a differnt user, nuke the auth token.
nukeAuthorizationToken()
}
if !KeychainWrapper.standard.set(email, forKey: KeychainKey.username.rawValue) {
DLog("Username could not be stored. Bailing out!")
//Bail out since you'll never be able to get the token back.
return
}
if !KeychainWrapper.standard.set(authorizationToken, forKey: email) {
DLog("Auth token could not be stored!")
}
}
/**
Removes both the authorization token and the current stored username, if they exist.
*/
static func nukeAuthorizationToken() {
guard let username = getUserName() else {
//Nothin' to do, nowhere to go.
return
}
//Remove the auth token
if !KeychainWrapper.standard.removeObject(forKey: username) {
DLog("Auth token not removed!")
}
//Remove the username.
if !KeychainWrapper.standard.removeObject(forKey: KeychainKey.username.rawValue) {
DLog("Username not removed!")
}
}
/**
Retrieves the authorization token for the current user.
- returns: The token, or nil if either the username or token isn't properly stored.
*/
static func getAuthorizationToken() -> String? {
guard let username = getUserName(),
let authToken = KeychainWrapper.standard.string(forKey: username) else {
return nil
}
return authToken
}
static func getUserName() -> String? {
guard let username = KeychainWrapper.standard.string(forKey: KeychainKey.username.rawValue) else {
return nil
}
return username
}
}
| mit | 62e42dea8c0323df22a79d71da3b1294 | 29.688889 | 106 | 0.597031 | 5.133829 | false | false | false | false |
cxchope/NyaaCatAPP_iOS | nyaacatapp/WikiAnalysis.swift | 1 | 3729 | //
// WikiAnalysis.swift
// dynmapanalysistest
//
// Created by 神楽坂雅詩 on 16/3/26.
// Copyright © 2016年 KagurazakaYashi. All rights reserved.
//
import UIKit
class WikiAnalysis: NSObject {
var html:String? = nil
var 解析:Analysis = Analysis()
let 页面特征:String = "[Nyaa Wiki]"
func 有效性校验() -> Bool {
if (html?.range(of: 页面特征) != nil) {
return true
}
return false
}
func 维基主菜单() -> [[String]] {
var 主菜单:[[String]] = [[String()]]
let 主菜单区间:String = 解析.抽取区间(html!, 起始字符串: "<!-- ********** ASIDE ********** -->", 结束字符串: "<!-- /aside -->", 包含起始字符串: false, 包含结束字符串: false)
let 主菜单分割:[String] = 主菜单区间.components(separatedBy: "<li ")
for 当前主菜单分割:String in 主菜单分割 {
if (当前主菜单分割.characters.count > 10) {
let 超链接:String = 解析.抽取区间(当前主菜单分割, 起始字符串: "<a href=\"", 结束字符串: "\"", 包含起始字符串: false, 包含结束字符串: false)
let 名称串:String = 解析.抽取区间(当前主菜单分割, 起始字符串: "title=\"", 结束字符串: "</a>", 包含起始字符串: false, 包含结束字符串: true)
let 名称:String = 解析.抽取区间(名称串, 起始字符串: ">", 结束字符串: "</a>", 包含起始字符串: false, 包含结束字符串: false)
var 缩进:String = 解析.抽取区间(当前主菜单分割, 起始字符串: "class=\"level", 结束字符串: "\">", 包含起始字符串: false, 包含结束字符串: false)
let 缩进分割:[String] = 缩进.components(separatedBy: " ")
if (缩进分割.count > 0) {
缩进 = 缩进分割[0]
}
/*
if (缩进.characters.count > 0) {
let 缩进量:Int = Int(缩进)! - 1
var 空格:String = ""
for i in 0...缩进量 {
if (i > 0) {
空格 = " " + 空格
}
}
名称 = 空格 + 名称 //空格 + "·" + 名称
}
*/
if (名称.characters.count > 0 && 超链接.characters.count > 0) {
let 当前菜单项:[String] = [名称,超链接,缩进]
主菜单.append(当前菜单项)
//print("\(缩进) \(名称) (\(超链接))")
}
}
}
return 主菜单
}
func 维基内容(_ 域名:String) -> String {
var 内容区间:String = 解析.抽取区间(html!, 起始字符串: "<!-- wikipage start -->", 结束字符串: "<!-- wikipage stop -->", 包含起始字符串: false, 包含结束字符串: false)
if (内容区间.characters.count == 0) {
内容区间 = "未能读取这个维基页面。"
} else {
//var filtered = url.stringByReplacingOccurrencesOfString("/", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
内容区间 = 内容区间.replacingOccurrences(of: "<a href=\"/", with: "<a href=\"\(域名)/", options: NSString.CompareOptions.literal, range: nil)
}
let 返回网页:String = "<!DOCTYPE html><html lang=\"zh\" dir=\"ltr\" class=\"no-js\"><head><meta charset=\"utf-8\" /><title>wikipage</title></head><body>\(内容区间)</body></html>"
//print(返回网页)
return 返回网页
}
}
| gpl-3.0 | 69563cb99dcc4fd9ba0dcf55a09affaf | 39.375 | 178 | 0.47678 | 3.712644 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Message/ZMAssetClientMessage+UpdateEvent.swift | 1 | 1853 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
extension ZMAssetClientMessage {
override open func update(with updateEvent: ZMUpdateEvent, initialUpdate: Bool) {
guard let message = GenericMessage(from: updateEvent) else { return }
do {
try setUnderlyingMessage(message)
} catch {
assertionFailure("Failed to set generic message: \(error.localizedDescription)")
return
}
version = 3 // We assume received assets are V3 since backend no longer supports sending V2 assets.
guard
let assetData = message.assetData,
let status = assetData.status
else {
return
}
switch status {
case .uploaded(let data) where data.hasAssetID:
updateTransferState(.uploaded, synchronize: false)
case .notUploaded where transferState != .uploaded:
switch assetData.notUploaded {
case .cancelled:
managedObjectContext?.delete(self)
case .failed:
updateTransferState(.uploadingFailed, synchronize: false)
}
default: break
}
}
}
| gpl-3.0 | 393d8dc96d8cdcc436e289d39efb2768 | 33.314815 | 107 | 0.654074 | 4.863517 | false | false | false | false |
czechboy0/swift-package-crawler | Sources/AnalyzerLib/Aliases.swift | 1 | 838 | //
// Aliases.swift
// swift-package-crawler
//
// Created by Honza Dvorsky on 8/16/16.
//
//
private let authorAliases: [String: String] = [
"qutheory": "vapor"
]
/// Useful for when authors/orgs get renamed, e.g. qutheory -> vapor,
/// so that both vapor and qutheory are aliased as one author for the stats.
func resolveAuthorAlias(_ name: String) -> String {
guard let resolved = authorAliases[name] else { return name }
return resolved
}
extension String {
/// For github name strings e.g. "/czechboy0/Jay", we need to run
/// the author through the alias resolved
func authorAliasResolved() -> String {
var comps = self.components(separatedBy: "/")
precondition(comps.count == 3)
comps[1] = resolveAuthorAlias(comps[1])
return comps.joined(separator: "/")
}
}
| mit | db1ef3344eedaa71ba8224e856138f3a | 26.032258 | 76 | 0.651551 | 3.774775 | false | false | false | false |
priya273/stockAnalyzer | Stock Analyzer/Stock Analyzer/PriceChartViewController.swift | 1 | 8275 | //
// PriceChartViewController.swift
// Stock Analyzer
//
// Created by Naga sarath Thodime on 11/30/15.
// Copyright © 2015 Priyadarshini Ragupathy. All rights reserved.
//
import UIKit
import Charts
import Foundation
class PriceChartViewController: UIViewController, ChartViewDelegate, ChartConsumerDelegate
{
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sept", "Oct", "Nov", "Dec"]
@IBOutlet weak var chartView: UIView!
@IBOutlet weak var priceInformation: UILabel!
var stock : Stock!
var dateComponentList : [NSDateComponents] = []
var dataAvailable : Bool = false
var lineChartView : LineChartView!
var ChartModel : ChartContract?
override func viewDidLoad()
{
super.viewDidLoad()
let parentController = (self.parentViewController as! ChartTabViewController)
self.stock = parentController.stock
let service = ChartConsumer();
service.delegate = self;
service.Run(self.stock.symbol!, id: (UIApplication.sharedApplication().delegate as! AppDelegate).userID!)
//DoAllNetworkCalls()
}
func ServiceFailed(message: String, exception: Bool)
{
if(exception == false)
{
self.priceInformation.text = message
}
else
{
self.alertTheUserSomethingWentWrong("Problem loading graph", message: message, actionTitle: "okay")
}
}
func ServicePassed(chart: ChartContract, dataAvailable: Bool)
{
self.dataAvailable = dataAvailable;
self.ChartModel = chart;
ParseAndUpdateDate()
self.setChart((self.ChartModel?.Positions)!, value: (self.ChartModel?.Prices)!)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func ParseAndUpdateDate()
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let calender = NSCalendar.currentCalendar()
for( var i = 0; i < self.ChartModel?.Dates.count; i++)
{
if let date : NSDate = dateFormatter.dateFromString( (self.ChartModel?.Dates[i])!)!
{
let dateComponent : NSDateComponents = calender.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
dateComponentList.append(dateComponent)
}
}
}
func setChart(dataPoints: [Double], value: [Double])
{
self.lineChartView = LineChartView()
self.lineChartView.delegate = self
self.lineChartView.noDataText = "You need to provide data for the chart."
self.lineChartView.backgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
var dataEntriesYaxisForEachX :[ChartDataEntry] = []
for (var i = 0; i < dataPoints.count; i++)
{
let dataEntry = ChartDataEntry(value: value[i], xIndex: i)
dataEntriesYaxisForEachX.append(dataEntry)
}
let lineChartDateSet = LineChartDataSet(yVals: dataEntriesYaxisForEachX, label: "Price for the last one year")
lineChartDateSet.axisDependency = .Left
lineChartDateSet.colors = [UIColor.blueColor()]
lineChartDateSet.drawCirclesEnabled = false
let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDateSet)
self.lineChartView.data = lineChartData
let minVal = value.minElement()!
let maxVal = value.maxElement()!
var intervalCount = Int(maxVal - minVal)
lineChartView.leftAxis.customAxisMin = min(minVal - 2, lineChartView.data!.yMin - 1)
lineChartView.leftAxis.customAxisMax = max(maxVal + 2, lineChartView.data!.yMax + 1)
if(intervalCount / 5 != 0 && intervalCount / 5 > 2)
{
intervalCount = intervalCount / 5
}
lineChartView.leftAxis.labelCount = intervalCount
lineChartView.leftAxis.startAtZeroEnabled = false
lineChartView.rightAxis.drawLabelsEnabled = false
lineChartView.descriptionText = ""
lineChartView.scaleXEnabled = false
lineChartView.scaleYEnabled = false
lineChartView.xAxis.gridColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
lineChartView.leftAxis.gridColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
// lineChartView.drawGridBackgroundEnabled = false
lineChartView.frame = CGRectMake(0, 0, self.chartView.frame.width, self.chartView.frame.height)
self.chartView.addSubview(self.lineChartView)
self.priceInformation.text = "Interactive Chart"
}
// MARK: - ChartViewDelegate
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight)
{
self.priceInformation.text = "\(self.months[self.dateComponentList[entry.xIndex].month - 1]) \(self.dateComponentList[entry.xIndex].day), \(self.dateComponentList[entry.xIndex].year) Price : \(entry.value)"
}
// MARK: - Alert Controller
func alertTheUserSomethingWentWrong(titleforController: String, message : String, actionTitle: String)
{
let controller = UIAlertController(title: titleforController , message: message, preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: actionTitle, style: UIAlertActionStyle.Cancel, handler: nil)
controller.addAction(action)
self.presentViewController(controller, animated: true, completion: nil)
}
/*
func DoAllNetworkCalls()
{
let parentVC = self.parentViewController as! ChartTabViewController
self.stock = parentVC.stock
print("Printing before view load")
print(stock.symbol!)
let params = "{\"Normalized\":false,\"NumberOfDays\":365,\"DataPeriod\":\"Day\",\"Elements\":[{\"Symbol\":\"\(stock.symbol!)\",\"Type\":\"price\",\"Params\":[\"c\"]}]}"
//let escapedParams = params.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
Alamofire.request(.GET, "http://dev.markitondemand.com/Api/v2/InteractiveChart/json", parameters: ["parameters" : params]).responseJSON {
JSON in
// print(JSON)
do
{
let serialization = try NSJSONSerialization.JSONObjectWithData(JSON.data! as NSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary;
if(serialization.valueForKey("Elements")?.count > 0)
{
self.dataAvailable = true
self.Positions = serialization.valueForKey("Positions") as! [Double]
self.Dates = serialization.valueForKey("Dates") as! [String]
self.setDateComponent()
let value = (((serialization.valueForKey("Elements") as! NSArray).valueForKey("DataSeries") as! NSArray ).valueForKey("close") as! NSArray).valueForKey("values") as! NSArray
self.prices = value[0] as! [Double]
self.setChart(self.Positions, value: self.prices)
}
else
{
self.priceInformation.text = "No data availabe to load"
}
}
catch
{
self.alertTheUserSomethingWentWrong("Problem loading graph", message: "something went wrong, could be the network", actionTitle: "okay")
}
}
}
func setDateComponent()
{
/* let dateFormatter = NSDateFormatter()
//dateFormatter.locale = NSLocale(localeIdentifier: "")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let calender = NSCalendar.currentCalendar()
for( var i = 0; i < Dates.count; i++)
{
if let date : NSDate = dateFormatter.dateFromString(Dates[i])!
{
let dateComponent : NSDateComponents = calender.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: date)
dateComponentList.append(dateComponent)
}
}*/
}
*/
}
| apache-2.0 | c4468287f00a021abecf37827ddd5b4d | 31.703557 | 217 | 0.636693 | 4.816065 | false | false | false | false |
iSapozhnik/FamilyPocket | FamilyPocket/Utility/KeyboardUtility.swift | 1 | 1528 | //
// KeyboardUtility.swift
// FamilyPocket
//
// Created by Ivan Sapozhnik on 5/14/17.
// Copyright © 2017 Ivan Sapozhnik. All rights reserved.
//
import UIKit
class KeyboardUtility: NSObject {
typealias KeyboardHandler = (_ height: CGFloat, _ duration: TimeInterval) -> ()
var keyboardHandler: KeyboardHandler?
init(withHandler handler: KeyboardHandler?) {
super.init()
keyboardHandler = handler
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardUtility.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardUtility.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func keyboardWillShow(notification: NSNotification) {
if
let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue,
let duration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) {
keyboardHandler?((keyboardSize.height, duration))
}
}
func keyboardWillHide(notification: NSNotification) {
if
let duration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval) {
keyboardHandler?(0.0, duration)
}
}
}
| mit | ba71eaea260cd16603df4eb4cdd464f1 | 32.933333 | 166 | 0.678454 | 5.572993 | false | false | false | false |
milseman/swift | benchmark/single-source/DictionaryGroup.swift | 8 | 1335 | //===--- DictionaryGroup.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
let count = 10_000
let result = count / 10
@inline(never)
public func run_DictionaryGroup(_ N: Int) {
for _ in 1...N {
let dict = Dictionary(grouping: 0..<count, by: { $0 % 10 })
CheckResults(dict.count == 10)
CheckResults(dict[0]!.count == result)
}
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
var hashValue: Int {
return value.hashValue
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionaryGroupOfObjects(_ N: Int) {
let objects = (0..<count).map { Box($0) }
for _ in 1...N {
let dict = Dictionary(grouping: objects, by: { Box($0.value % 10) })
CheckResults(dict.count == 10)
CheckResults(dict[Box(0)]!.count == result)
}
}
| apache-2.0 | e73d4fa41580e1e3eb5db7ccd84c1f0b | 25.176471 | 80 | 0.582772 | 3.814286 | false | false | false | false |
younata/RSSClient | TethysKitSpecs/Services/FeedService/LocalRealmFeedServiceSpec.swift | 1 | 27911 | import Quick
import Nimble
import Result
import CBGPromise
import RealmSwift
@testable import TethysKit
final class LocalRealmFeedServiceSpec: QuickSpec {
override func spec() {
let realmConf = Realm.Configuration(inMemoryIdentifier: "RealmFeedServiceSpec")
var realm: Realm!
var mainQueue: FakeOperationQueue!
var workQueue: FakeOperationQueue!
var subject: LocalRealmFeedService!
var realmFeed1: RealmFeed!
var realmFeed2: RealmFeed!
var realmFeed3: RealmFeed!
func write(_ transaction: () -> Void) {
realm.beginWrite()
transaction()
do {
try realm.commitWrite()
} catch let exception {
dump(exception)
fail("Error writing to realm: \(exception)")
}
}
beforeEach {
let realmProvider = DefaultRealmProvider(configuration: realmConf)
realm = realmProvider.realm()
try! realm.write {
realm.deleteAll()
}
mainQueue = FakeOperationQueue()
mainQueue.runSynchronously = true
workQueue = FakeOperationQueue()
workQueue.runSynchronously = true
subject = LocalRealmFeedService(
realmProvider: realmProvider,
mainQueue: mainQueue,
workQueue: workQueue
)
write {
realmFeed1 = RealmFeed()
realmFeed2 = RealmFeed()
realmFeed3 = RealmFeed()
for (index, feed) in [realmFeed1, realmFeed2, realmFeed3].enumerated() {
feed?.title = "Feed\(index + 1)"
feed?.url = "https://example.com/feed/feed\(index + 1)"
realm.add(feed!)
}
}
}
describe("as a FeedService") {
describe("feeds()") {
var future: Future<Result<AnyCollection<Feed>, TethysError>>!
context("when none of the feeds have unread articles associated with them") {
beforeEach {
future = subject.feeds()
}
it("resolves the future with all stored feeds, ordered by the title of the feed") {
expect(future).to(beResolved())
guard let result = future.value?.value else {
fail("Expected to have the list of feeds, got \(String(describing: future.value))")
return
}
let expectedFeeds = [
feedFactory(title: realmFeed1.title, url: URL(string: realmFeed1.url)!, summary: "",
tags: [], unreadCount: 0, image: nil),
feedFactory(title: realmFeed2.title, url: URL(string: realmFeed2.url)!, summary: "",
tags: [], unreadCount: 0, image: nil),
feedFactory(title: realmFeed3.title, url: URL(string: realmFeed3.url)!, summary: "",
tags: [], unreadCount: 0, image: nil),
]
expect(Array(result)).to(equal(expectedFeeds))
}
}
context("when some of the feeds have unread articles associated with them") {
beforeEach {
write {
let unreadArticle = RealmArticle()
unreadArticle.title = "article1"
unreadArticle.link = "https://example.com/article/article1"
unreadArticle.read = false
unreadArticle.feed = realmFeed2
realm.add(unreadArticle)
let readArticle = RealmArticle()
readArticle.title = "article2"
readArticle.link = "https://example.com/article/article2"
readArticle.read = true
readArticle.feed = realmFeed3
realm.add(readArticle)
}
future = subject.feeds()
}
it("resolves the future with all stored feeds, ordered first by unread count, then by the title of the feed") {
expect(future).to(beResolved())
guard let result = future.value?.value else {
fail("Expected to have the list of feeds, got \(String(describing: future.value))")
return
}
let expectedFeeds = [
feedFactory(title: realmFeed2.title, url: URL(string: realmFeed2.url)!, summary: "",
tags: [], unreadCount: 1, image: nil),
feedFactory(title: realmFeed1.title, url: URL(string: realmFeed1.url)!, summary: "",
tags: [], unreadCount: 0, image: nil),
feedFactory(title: realmFeed3.title, url: URL(string: realmFeed3.url)!, summary: "",
tags: [], unreadCount: 0, image: nil)
]
expect(Array(result)).to(equal(expectedFeeds))
}
}
context("when there are no feeds in the database") {
beforeEach {
try! realm.write {
realm.deleteAll()
}
future = subject.feeds()
}
it("resolves the future with .success([])") {
expect(future.value).toNot(beNil(), description: "Expected to resolve the future")
expect(future.value?.error).to(beNil(), description: "Expected to resolve successfully")
expect(future.value?.value).to(beEmpty(), description: "Expected to successfully resolve with no feeds")
}
}
}
describe("articles(of:)") {
var future: Future<Result<AnyCollection<Article>, TethysError>>!
context("when the feed doesn't exist in the database") {
beforeEach {
future = subject.articles(of: feedFactory())
}
it("resolves saying it couldn't find the feed in the database") {
expect(future.value?.error).to(equal(.database(.entryNotFound)))
}
}
context("and the feed exists in the database") {
var articles: [RealmArticle] = []
beforeEach {
write {
articles = (0..<10).map { index in
let article = RealmArticle()
article.title = "article\(index)"
article.link = "https://example.com/article/article\(index)"
article.read = false
article.feed = realmFeed1
article.published = Date(timeIntervalSinceReferenceDate: TimeInterval(index))
realm.add(article)
return article
}
}
future = subject.articles(of: Feed(realmFeed: realmFeed1))
}
it("resolves the future with the articles, ordered most recent to least recent") {
guard let result = future.value?.value else {
fail("Expected to have the list of feeds, got \(String(describing: future.value))")
return
}
expect(Array(result)).to(equal(
articles.reversed().map { Article(realmArticle: $0) }
))
}
}
}
describe("subscribe(to:)") {
var future: Future<Result<Feed, TethysError>>!
let url = URL(string: "https://example.com/feed")!
context("if a feed with that url already exists in the database") {
var existingFeed: RealmFeed!
beforeEach {
write {
existingFeed = RealmFeed()
existingFeed.title = "Feed"
existingFeed.url = "https://example.com/feed"
realm.add(existingFeed)
}
future = subject.subscribe(to: url)
}
it("resolves the promise with the feed") {
expect(future.value?.value).to(equal(Feed(realmFeed: existingFeed)))
}
}
context("if no feed with that url exists in the database") {
beforeEach {
future = subject.subscribe(to: url)
}
it("creates a feed with that url as it's only contents") {
expect(realm.objects(RealmFeed.self)).to(haveCount(4))
let feed = realm.objects(RealmFeed.self).first { $0.url == url.absoluteString }
expect(feed).toNot(beNil())
expect(feed?.title).to(equal(""))
expect(feed?.summary).to(equal(""))
}
it("resolves the future with that feed") {
expect(future).to(beResolved())
expect(future.value?.value).to(equal(
feedFactory(title: "", url: url, summary: "", tags: [], unreadCount: 0, image: nil)
))
}
}
}
describe("tags()") {
it("immediately resolves with error notSupported") {
let future = subject.tags()
expect(future).to(beResolved())
expect(future.value?.error).to(equal(.notSupported))
}
}
describe("set(tags:of:)") {
it("immediately resolves with error notSupported") {
let future = subject.set(tags: [], of: feedFactory())
expect(future).to(beResolved())
expect(future.value?.error).to(equal(.notSupported))
}
}
describe("set(url:on:)") {
it("immediately resolves with error notSupported") {
let future = subject.set(url: URL(string: "https://example.com/whatever")!, on: feedFactory())
expect(future).to(beResolved())
expect(future.value?.error).to(equal(.notSupported))
}
}
describe("readAll(of:)") {
var future: Future<Result<Void, TethysError>>!
context("when the feed doesn't exist in the database") {
beforeEach {
future = subject.readAll(of: feedFactory())
}
it("resolves saying it couldn't find the feed in the database") {
expect(future.value?.error).to(equal(.database(.entryNotFound)))
}
}
context("when the feed exists in the database") {
var articles: [RealmArticle] = []
var otherArticles: [RealmArticle] = []
beforeEach {
write {
articles = (0..<10).map { index in
let article = RealmArticle()
article.title = "article\(index)"
article.link = "https://example.com/article/article\(index)"
article.read = false
article.feed = realmFeed1
article.published = Date(timeIntervalSinceReferenceDate: TimeInterval(index))
realm.add(article)
return article
}
otherArticles = (0..<10).map { index in
let article = RealmArticle()
article.title = "article\(index)"
article.link = "https://example.com/article/article\(index)"
article.read = false
article.feed = realmFeed2
article.published = Date(timeIntervalSinceReferenceDate: TimeInterval(index))
realm.add(article)
return article
}
}
future = subject.readAll(of: Feed(realmFeed: realmFeed1))
}
it("marks all articles of the feed as read") {
for article in articles {
expect(article.read).to(beTrue())
}
}
it("doesnt mark articles of other feeds as read") {
for article in otherArticles {
expect(article.read).to(beFalse())
}
}
it("resolves the future") {
expect(future.value?.value).to(beVoid())
}
}
}
describe("remove(feed:)") {
var future: Future<Result<Void, TethysError>>!
context("when the feed doesn't exist in the database") {
beforeEach {
future = subject.remove(feed: feedFactory())
}
it("resolves successfully because there's nothing to do") {
expect(future.value?.value).to(beVoid())
}
}
context("when the feed exists in the database") {
var identifier: String!
beforeEach {
identifier = realmFeed1.id
future = subject.remove(feed: Feed(realmFeed: realmFeed1))
}
it("deletes the feed") {
expect(realm.object(ofType: RealmFeed.self, forPrimaryKey: identifier)).to(beNil())
}
it("resolves the future") {
expect(future.value?.value).to(beVoid())
}
}
}
}
describe("as a LocalFeedService") {
describe("updateFeeds(with:)") {
let feeds = [
feedFactory(title: "Updated 1", url: URL(string: "https://example.com/feed/feed1")!, summary: "Updated Summary 1",
tags: ["a", "b", "c"], unreadCount: 3, image: nil),
feedFactory(title: "Feed3", url: URL(string: "https://example.com/feed/feed3")!, summary: "Feed with no read articles",
unreadCount: 0, image: nil),
feedFactory(title: "Brand New Feed", url: URL(string: "https://example.com/brand_new_feed")!,
summary: "some summary", tags: [], unreadCount: 5, image: nil)
]
var future: Future<Result<AnyCollection<Feed>, TethysError>>!
beforeEach {
write {
let unreadArticle = RealmArticle()
unreadArticle.title = "article1"
unreadArticle.link = "https://example.com/article/article1"
unreadArticle.read = false
unreadArticle.feed = realmFeed2
realm.add(unreadArticle)
let unreadArticle2 = RealmArticle()
unreadArticle2.title = "article2"
unreadArticle2.link = "https://example.com/article/article2"
unreadArticle2.read = false
unreadArticle2.feed = realmFeed3
realm.add(unreadArticle2)
}
future = subject.updateFeeds(with: AnyCollection(feeds))
}
it("updates the existing feeds that match (based off URL) with the new data") {
realmFeed1 = realm.object(ofType: RealmFeed.self, forPrimaryKey: realmFeed1.id)
expect(realmFeed1.title).to(equal("Updated 1"))
expect(realmFeed1.summary).to(equal("Updated Summary 1"))
expect(Array(realmFeed1.tags.map { $0.string })).to(equal(["a", "b", "c"]))
}
it("does not delete other feeds that weren't in the network list") {
expect(realm.object(ofType: RealmFeed.self, forPrimaryKey: realmFeed2.id)).toNot(beNil())
expect(realm.object(ofType: RealmFeed.self, forPrimaryKey: realmFeed3.id)).toNot(beNil())
}
it("inserts new feeds that the updated list found") {
let newFeed = realm.objects(RealmFeed.self).first { $0.url == "https://example.com/brand_new_feed" }
expect(newFeed).toNot(beNil())
expect(newFeed?.title).to(equal("Brand New Feed"))
expect(newFeed?.summary).to(equal("some summary"))
expect(newFeed?.tags).to(beEmpty())
}
it("marks as read all articles for a feed if that feed had an unread count of 0") {
expect(realmFeed3.articles).to(haveCount(1))
expect(realmFeed3.articles.first?.read).to(beTrue(), description: "realmFeed3 had a single article, and it should be marked as read")
expect(realmFeed2.articles).to(haveCount(1))
expect(realmFeed2.articles.first?.read).to(beFalse(), description: "realmFeed2's update didn't have an unread count of 0, so all articles should be left alone")
}
it("resolves the promise with the new set of feeds, using the unread counts from the given feeds") {
expect(future).to(beResolved())
guard let receivedFeeds = future.value?.value else {
return fail("Future did not resolve successfully")
}
expect(Array(receivedFeeds)).to(haveCount(4))
expect(Array(receivedFeeds)).to(contain(
feedFactory(title: realmFeed2.title, url: URL(string: realmFeed2.url)!, summary: "",
tags: [], unreadCount: 1, image: nil),
feedFactory(title: "Brand New Feed", url: URL(string: "https://example.com/brand_new_feed")!,
summary: "some summary", tags: [], unreadCount: 5, image: nil),
feedFactory(title: realmFeed3.title, url: URL(string: realmFeed3.url)!, summary: "Feed with no read articles",
tags: [], unreadCount: 0, image: nil),
feedFactory(title: "Updated 1", url: URL(string: realmFeed1.url)!, summary: "Updated Summary 1",
tags: ["a", "b", "c"], unreadCount: 3, image: nil)
))
}
}
describe("updateFeed(from:)") {
var future: Future<Result<Feed, TethysError>>!
context("when that feed's url does not exist in the database") {
beforeEach {
future = subject.updateFeed(from: feedFactory())
}
it("resolves with an entryNotFound error") {
expect(future).to(beResolved())
expect(future.value?.error).to(equal(.database(.entryNotFound)))
}
}
context("when that feed's url exists in the database") {
let updatedFeed = feedFactory(
title: "Updated 1", url: URL(string: "https://example.com/feed/feed1")!,
summary: "Updated Summary 1", tags: ["a", "b", "c"], unreadCount: 10, image: nil)
beforeEach {
future = subject.updateFeed(from: updatedFeed)
}
it("inserts new feeds that the updated list found") {
let newFeed = realm.objects(RealmFeed.self).first { $0.url == "https://example.com/feed/feed1" }
expect(newFeed).toNot(beNil())
expect(newFeed?.title).to(equal("Updated 1"))
expect(newFeed?.summary).to(equal("Updated Summary 1"))
expect(newFeed?.tags.map { $0.string }.sorted()).to(equal(["a", "b", "c"]))
}
it("resolves the promise with the updated feed, using the unread count from the given feed") {
expect(future).to(beResolved())
expect(future.value?.value).to(equal(updatedFeed))
}
}
}
describe("updateArticles(with:feed:)") {
var future: Future<Result<AnyCollection<Article>, TethysError>>!
context("and the feed is not in realm") {
it("resolves with an entry not found error") {
future = subject.updateArticles(with: AnyCollection([]), feed: feedFactory())
expect(future).to(beResolved())
expect(future.value?.error).to(equal(.database(.entryNotFound)))
}
}
context("and the feed is in realm") {
let dateFormatter = ISO8601DateFormatter()
let updatedArticles = [
articleFactory(title: "article 0", link: URL(string: "https://example.com/article/article0")!,
published: dateFormatter.date(from: "2019-03-18T09:15:00-0800")!),
articleFactory(title: "article 1, updated", link: URL(string: "https://example.com/article/article1")!,
summary: "hello", authors: [Author("foo"), Author("bar")], published: dateFormatter.date(from: "2017-08-14T09:00:00-0700")!, updated: dateFormatter.date(from: "2019-01-11T16:45:00-0800")!),
articleFactory(title: "article 2", link: URL(string: "https://example.com/article/article2")!,
published: dateFormatter.date(from: "2017-07-21T18:00:00-0700")!),
articleFactory(title: "article 3", link: URL(string: "https://example.com/article/article3")!,
published: dateFormatter.date(from: "2015-06-14T10:15:00-0700")!),
]
beforeEach {
write {
let article1 = RealmArticle()
article1.title = "article1"
article1.link = "https://example.com/article/article1"
article1.feed = realmFeed1
article1.authors.append(RealmAuthor(name: "buk", email: nil))
article1.authors.append(RealmAuthor(name: "baz", email: nil))
article1.published = updatedArticles[1].published
realm.add(article1)
let article2 = RealmArticle()
article2.title = "article 2"
article2.link = "https://example.com/article/article2"
article2.feed = realmFeed1
article2.published = updatedArticles[2].published
realm.add(article2)
}
let feed = Feed(realmFeed: realmFeed1)
future = subject.updateArticles(with: AnyCollection(updatedArticles), feed: feed)
}
it("stores up to the first unmodified article in the datastore") {
expect(realmFeed1.articles).to(haveCount(3))
let allArticles = realm.objects(RealmArticle.self).sorted(by: [
SortDescriptor(keyPath: "published", ascending: false)
])
expect(allArticles).to(haveCount(3))
expect(allArticles[0].title).to(equal("article 0"))
expect(allArticles[0].link).to(equal("https://example.com/article/article0"))
expect(allArticles[0].published).to(equal(updatedArticles[0].published))
expect(allArticles[0].feed).to(equal(realmFeed1))
expect(allArticles[1].title).to(equal(updatedArticles[1].title))
expect(allArticles[1].link).to(equal(updatedArticles[1].link.absoluteString))
expect(allArticles[1].summary).to(equal(updatedArticles[1].summary))
expect(allArticles[1].published).to(equal(updatedArticles[1].published))
expect(allArticles[1].updatedAt).to(equal(updatedArticles[1].updated))
expect(allArticles[1].feed).to(equal(realmFeed1))
expect(allArticles[2].title).to(equal(updatedArticles[2].title))
expect(allArticles[2].link).to(equal(updatedArticles[2].link.absoluteString))
expect(allArticles[2].published).to(equal(updatedArticles[2].published))
expect(allArticles[2].feed).to(equal(realmFeed1))
}
it("resolves the future with the stored articles") {
expect(future).to(beResolved())
guard let articles = future.value?.value else {
return expect(future.value?.error).to(beNil())
}
expect(Array(articles)).to(equal([
articleFactory(title: "article 0", link: URL(string: "https://example.com/article/article0")!, published: updatedArticles[0].published, updated: updatedArticles[0].updated),
articleFactory(title: "article 1, updated", link: URL(string: "https://example.com/article/article1")!, summary: "hello", authors: [Author("foo"), Author("bar")], published: updatedArticles[1].published, updated: updatedArticles[1].updated),
articleFactory(title: "article 2", link: URL(string: "https://example.com/article/article2")!, published: updatedArticles[2].published, updated: updatedArticles[2].updated),
]))
}
}
}
}
}
}
| mit | eb4a1c3078c048aba898296ecf6b583b | 46.957045 | 269 | 0.470137 | 5.639725 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/UIColorExtension.swift | 5 | 846 | //
// Created by Tom Baranes on 09/02/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public extension UIColor {
public convenience init(hexString: String) {
let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
var int = UInt32()
Scanner(string: hex).scanHexInt32(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3:
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6:
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8:
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
| gpl-3.0 | 78dab597704c2f29ccb98244c340686d | 29.178571 | 110 | 0.56213 | 2.864407 | false | false | false | false |
dingbat/nsrails | demos/swift/SwiftDemo/ReponsesTableViewController.swift | 1 | 5342 | //
// ReponsesTableViewController.swift
// SwiftDemo
//
// Created by Dan Hassin on 8/21/14.
// Copyright (c) 2014 Dan Hassin. All rights reserved.
//
import UIKit
class ReponsesTableViewController: UITableViewController {
var post:Post!
func reply() {
// When the + button is hit, display an InputViewController (this is the shared input view for both posts and responses)
// It has an init method that accepts a completion block - this block of code will be executed when the user hits "save"
let newReplyVC = InputViewController(completionHandler: { author, content in
let newResp = Response()
newResp.author = author
newResp.content = content
newResp.post = self.post //check out Response.swift for more detail on how this line is possible
newResp.remoteCreateAsync() { error in
if error != nil {
AppDelegate.alertForError(error)
} else {
self.post.responses.append(newResp)
self.tableView.reloadData()
self.dismissViewControllerAnimated(true, completion: nil)
}
}
/*
Instead of line 23 (the belongs_to trick), you could also add the new response to the post's "responses" array and then update it:
post.responses.append(newResp)
post.remoteUpdateAsync()...
Doing this may be tempting since it'd already be in post's "responses" array, BUT: you'd have to take into account the Response validation failing (you'd then have to remove it from the array). Also, creating the Response rather than updating the Post will set newResp's remoteID, so we can do remote operations on it later!
Of course, if you have CoreData enabled, this is all handled for you as soon as you set the response's post (the post's reponses array will automatically update), or vice versa (adding the response to the post's array will set the response's post property)
*/
})
newReplyVC.header = "Write your response to \(post.author)"
newReplyVC.messagePlaceholder = "Your response"
self.presentViewController(UINavigationController(rootViewController: newReplyVC), animated: true, completion: nil)
}
func deleteResponseAtIndexPath(indexPath:NSIndexPath) {
let response = post.responses[indexPath.row]
response.remoteDestroyAsync { error in
if error != nil {
AppDelegate.alertForError(error)
} else {
self.post.responses.removeAtIndex(indexPath.row) // Remember to delete the object from our local array too
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
if (self.post.responses.count == 0) {
self.tableView.reloadSections(NSIndexSet(index:0), withRowAnimation:.Automatic)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Posts"
self.tableView.rowHeight = 60
// Add reply button
let reply = UIBarButtonItem(barButtonSystemItem:.Reply, target:self, action:"reply")
self.navigationItem.rightBarButtonItem = reply
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
return 1
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return post.responses.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let CellIdentifier = "CellIdentifier"
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style:.Subtitle, reuseIdentifier:CellIdentifier)
cell.selectionStyle = .None
}
let response = post.responses[indexPath.row]
cell.textLabel.text = response.content
cell.detailTextLabel.text = response.author
return cell
}
override func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
return "“\(post.content)”"
}
override func tableView(tableView: UITableView!, titleForFooterInSection section: Int) -> String! {
let formatter = NSDateFormatter()
formatter.dateFormat = "MM/dd/yy"
var footer = "(Posted on \(formatter.stringFromDate(post.createdAt)))"
if (post.responses.count == 0) {
footer = "There are no responses to this post.\nSay something!\n\n"+footer
}
return footer
}
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
deleteResponseAtIndexPath(indexPath)
}
}
| mit | fb3803a9f21d3e1582eb3d6374b03b77 | 40.379845 | 336 | 0.636568 | 5.375629 | false | false | false | false |
apozdeyev/ReactiveEureka | ReactiveEureka/Classes/Eureka/BaseRow+Lifetime.swift | 1 | 4017 | //
// BaseRow+Lifetime.swift
// EurekaPrototype
//
// Created by anatoliy on 11/08/2017.
//
import Foundation
import Eureka
import ReactiveSwift
/// Holds the `Lifetime` of the object.
fileprivate let isSwizzledKey = AssociationKey<Bool>(default: false)
/// Holds the `Lifetime` of the object.
fileprivate let lifetimeKey = AssociationKey<Lifetime?>(default: nil)
/// Holds the `Lifetime.Token` of the object.
fileprivate let lifetimeTokenKey = AssociationKey<Lifetime.Token?>(default: nil)
// TODO: move to separate file.
internal func lifetime(of object: AnyObject) -> Lifetime {
// describe why we use here BaseRow instead of BaseRowType. BaseRowType can not be extending by ReactiveExtensionsProvider.
if let object = object as? BaseRow {
return object.reactive.lifetime
} else if let object = object as? Form {
return object.reactive.lifetime
}
return synchronized(object) {
let associations = Associations(object)
if let lifetime = associations.value(forKey: lifetimeKey) {
return lifetime
}
let (lifetime, token) = Lifetime.make()
associations.setValue(token, forKey: lifetimeTokenKey)
associations.setValue(lifetime, forKey: lifetimeKey)
return lifetime
}
}
extension Reactive where Base: BaseRowType {
/// Returns a lifetime that ends when the object is deallocated.
@nonobjc public var lifetime: Lifetime {
return base.synchronized {
if let lifetime = base.associations.value(forKey: lifetimeKey) {
return lifetime
}
let (lifetime, token) = Lifetime.make()
let objcClass: AnyClass = (base as AnyObject).objcClass
let objcClassAssociations = Associations(objcClass as AnyObject)
let deallocSelector = sel_registerName("dealloc")
// Swizzle `-dealloc` so that the lifetime token is released at the
// beginning of the deallocation chain, and only after the KVO `-dealloc`.
synchronized(objcClass) {
// Swizzle the class only if it has not been swizzled before.
if !objcClassAssociations.value(forKey: isSwizzledKey) {
objcClassAssociations.setValue(true, forKey: isSwizzledKey)
var existingImpl: IMP? = nil
let newImplBlock: @convention(block) (UnsafeRawPointer) -> Void = { objectRef in
// A custom trampoline of `objc_setAssociatedObject` is used, since
// the imported version has been inserted with ARC calls that would
// mess with the object deallocation chain.
// Release the lifetime token.
unsafeSetAssociatedValue(nil, forKey: lifetimeTokenKey, forObjectAt: objectRef)
let impl: IMP
// Call the existing implementation if one has been caught. Otherwise,
// call the one first available in the superclass hierarchy.
if let existingImpl = existingImpl {
impl = existingImpl
} else {
let superclass: AnyClass = class_getSuperclass(objcClass)!
impl = class_getMethodImplementation(superclass, deallocSelector)!
}
typealias Impl = @convention(c) (UnsafeRawPointer, Selector) -> Void
unsafeBitCast(impl, to: Impl.self)(objectRef, deallocSelector)
}
let newImpl = imp_implementationWithBlock(newImplBlock as Any)
if !class_addMethod(objcClass, deallocSelector, newImpl, "v@:") {
// The class has an existing `dealloc`. Preserve that as `existingImpl`.
let deallocMethod = class_getInstanceMethod(objcClass, deallocSelector)!
// Store the existing implementation to `existingImpl` to ensure it is
// available before our version is swapped in.
existingImpl = method_getImplementation(deallocMethod)
// Store the swapped-out implementation to `existingImpl` in case
// the implementation has been changed concurrently.
existingImpl = method_setImplementation(deallocMethod, newImpl)
}
}
}
base.associations.setValue(token, forKey: lifetimeTokenKey)
base.associations.setValue(lifetime, forKey: lifetimeKey)
return lifetime
}
}
}
| mit | 56dc8c0c3682182d5416f1ccb2244555 | 33.930435 | 125 | 0.712472 | 4.380589 | false | false | false | false |
tatowilson/ZTDropDownNotification | Demo-Swift/Demo-Swift/ViewController.swift | 1 | 3442 | //
// ViewController.swift
// Demo-Swift
//
// Created by Zhang Tao on 2017/8/26.
// Copyright © 2017年 Zhang Tao. All rights reserved.
//
import UIKit
import ZTDropDownNotification
let NotificationRegisteredIconKey = "NotificationRegisteredIconKey"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
ZTDropDownNotification.registerIcons([
NotificationRegisteredIconKey: #imageLiteral(resourceName:"registered_blue"),
ZTNSuccessIconKey: #imageLiteral(resourceName:"check_green")])
}
@IBAction func notifyMessageOnly(_ button: UIButton) {
ZTDropDownNotification.notifyMessage(button.titleLabel!.text!, withIcon: nil)
}
@IBAction func notifySuccessMessage(_ button: UIButton) {
ZTDropDownNotification.notifySuccessMessage(button.titleLabel!.text!)
}
@IBAction func notifyMessageWithRegisteredIcon(_ button: UIButton) {
ZTDropDownNotification.notifyMessage(button.titleLabel!.text!, withIconKey: NotificationRegisteredIconKey)
}
@IBAction func notifyMessageWithIconOnce(_ button: UIButton) {
ZTDropDownNotification.notifyMessage(button.titleLabel!.text!, withIcon: #imageLiteral(resourceName:"thumbs_up_blue"))
}
@IBAction func setCustomLayout(_ button: UIButton) {
ZTDropDownNotification.setCustomLayoutGenerator { () -> UIView in
return CustomRectangleLayout.init()
}
}
@IBAction func resetLayoutToBuiltIns(_ button: UIButton) {
ZTDropDownNotification.setCustomLayoutGenerator(nil)
}
@IBAction func notifyCustomTemporaryView(_ button: UIButton) {
let view = UIView.init()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.layer.cornerRadius = 5
view.layer.shadowOffset = CGSize(width: 0, height: 1)
view.layer.shadowRadius = 5
view.layer.shadowOpacity = 0.9
view.addConstraint(
NSLayoutConstraint.init(item: view,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: UIScreen.main.bounds.size.width * 0.6))
let label = UILabel.init()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .orange
label.text = button.titleLabel!.text!
label.shadowOffset = CGSize(width: 1, height: 0)
label.shadowColor = .lightGray
view.addSubview(label)
let icon = UIImageView.init()
icon.translatesAutoresizingMaskIntoConstraints = false
icon.image = #imageLiteral(resourceName:"check_green")
view.addSubview(icon)
view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "|-[label]-[icon]-|",
options: .alignAllCenterY,
metrics: nil,
views: ["label": label, "icon": icon]))
view.addConstraints(
NSLayoutConstraint.constraints(withVisualFormat: "V:|-(28)-[label(==44)]|",
options: .directionLeadingToTrailing,
metrics: nil,
views: ["label": label]))
icon.setContentHuggingPriority(UILayoutPriorityDefaultLow + 1, for: .horizontal)
ZTDropDownNotification.notify(view)
}
}
| mit | 4c0df3dfbaca037ae9f7d8ccc9ed1b74 | 35.585106 | 122 | 0.656295 | 5.218513 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Main/Coordinators/MainSwitchCoordinator.swift | 1 | 5092 | //
// MainSwitchCoordinator.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/10/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import RxSwift
protocol MainSwitchCoordinator {
@discardableResult
func `switch`(to position: MainSwitchCoordinatorPosition, animated: Bool) -> Observable<Void>
}
class MAMainSwitchCoordinator: MainSwitchCoordinator {
private weak var mainViewController: MainViewController?
private var childViewControllers: [UIViewController]?
func setMainViewController(_ main: MainViewController) {
self.mainViewController = main
self.childViewControllers = main.childViewControllers
}
@discardableResult
func `switch`(to position: MainSwitchCoordinatorPosition, animated: Bool) -> Observable<Void> {
switch position {
case .left: return switchToFirstController(animated: animated)
case .right: return switchToSecondController(animated: animated)
}
}
@discardableResult
func switchToFirstController(animated: Bool) -> Observable<Void> {
if animated {
return switchSmoothToController(at: 0)
} else {
return switchToController(at: 0)
}
}
@discardableResult
func switchToSecondController(animated: Bool) -> Observable<Void>{
if animated {
return switchSmoothToController(at: 1)
} else {
return switchToController(at: 1)
}
}
@discardableResult
private func switchToController(at index: Int) -> Observable<Void> {
let subject = PublishSubject<Void>()
guard let containerView = mainViewController?.containerView,
let childView = childViewControllers?[index].view else { return .empty() }
containerView.removeAllSubviews()
childView.frame = containerView.bounds
containerView.addSubview(childView)
subject.onCompleted()
return subject.asObservable()
.take(1)
.ignoreElements()
}
@discardableResult
private func switchSmoothToController(at index: Int) -> Observable<Void> {
let subject = PublishSubject<Void>()
guard let containerView = mainViewController?.containerView,
let firstView = childViewControllers?[0].view,
let secondView = childViewControllers?[1].view else { return .empty() }
containerView.removeAllSubviews()
let duration: TimeInterval = 0.25
let startAlpha: Float = 0
let endAlpha: Float = 1
let offset: CGFloat = containerView.bounds.size.width / 2
// switch from left to right
if index == 0 {
firstView.layer.opacity = startAlpha
firstView.layer.transform = CATransform3DMakeTranslation(-offset, 0, 0)
firstView.frameEqual(with: containerView, originX: -offset)
secondView.layer.opacity = endAlpha
secondView.layer.transform = CATransform3DIdentity
secondView.frameEqual(with: containerView)
containerView.addSubview(firstView)
containerView.addSubview(secondView)
UIView.animate(
withDuration: duration,
animations: {
firstView.layer.opacity = endAlpha
firstView.layer.transform = CATransform3DIdentity
secondView.layer.opacity = startAlpha
secondView.layer.transform = CATransform3DMakeTranslation(offset, 0, 0)
}, completion: { _ in
secondView.removeFromSuperview()
subject.onCompleted()
}
)
}
// switch from right to left
if index == 1 {
firstView.layer.opacity = endAlpha
firstView.layer.transform = CATransform3DIdentity
firstView.frameEqual(with: containerView)
secondView.layer.opacity = startAlpha
secondView.layer.transform = CATransform3DMakeTranslation(offset, 0, 0)
secondView.frameEqual(with: containerView, originX: offset)
containerView.addSubview(firstView)
containerView.addSubview(secondView)
UIView.animate(
withDuration: duration,
animations: {
firstView.layer.opacity = startAlpha
firstView.layer.transform = CATransform3DMakeTranslation(-offset, 0, 0)
secondView.layer.opacity = endAlpha
secondView.layer.transform = CATransform3DIdentity
}, completion: { _ in
firstView.removeFromSuperview()
subject.onCompleted()
}
)
}
return subject.asObservable()
.take(1)
.ignoreElements()
}
}
| mit | 3cc72a24874c88e630a24be7b1c4a65e | 33.14094 | 99 | 0.593474 | 5.901392 | false | false | false | false |
dander521/ShareTest | Uhome/Classes/Module/Login/Controller/Model/UhomeNetManager.swift | 1 | 5030 | //
// UhomeNetManager.swift
// Uhome
//
// Created by 倩倩 on 2017/8/10.
// Copyright © 2017年 menhao. All rights reserved.
//
import UIKit
import Alamofire
import KRProgressHUD
private let UhomeNetManagerShareInstance = UhomeNetManager()
class UhomeNetManager: NSObject {
class var sharedInstance : UhomeNetManager {
return UhomeNetManagerShareInstance
}
}
extension UhomeNetManager {
func getRequest(urlString: String, params : [String : Any], success : @escaping (_ response : String)->(), failure : @escaping (_ error : String)->()) {
Alamofire.request(urlString, method: .get, parameters: params)
.responseString { (string) in/*这里使用了闭包*/
let startRange = string.description.range(of:"{") //正向检索
let endRange = string.description.range(of:"}", options: .backwards)//反向检索
let searchRange = (startRange?.lowerBound)! ..< (endRange?.upperBound)!
let resultString = string.description.substring(with: searchRange)
let dic = UhomeFunctionTools.getDictionaryFromJSONString(jsonString: resultString)
print("Get Json >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n \(dic)")
if dic.count > 0 {
let succcess = dic["succcess"] as! String
let errorMsg = dic["msg"] as! String
if succcess == "true" {
success(resultString)
} else {
failure(errorMsg)
}
} else {
print(">>>>>>>>>>>>>服务器数据异常>>>>>>>>>>>>>>>>")
}
}
}
//MARK: - POST 请求
func postRequest(urlString : String, params : [String : Any], success : @escaping (_ response : String)->(), failure : @escaping (_ error : String)->()) {
Alamofire.request(urlString, method: HTTPMethod.post, parameters: params).responseString { (string) in
let startRange = string.description.range(of:"{") //正向检索
let endRange = string.description.range(of:"}", options: .backwards)//反向检索
let searchRange = (startRange?.lowerBound)! ..< (endRange?.upperBound)!
let resultString = string.description.substring(with: searchRange)
let dic = UhomeFunctionTools.getDictionaryFromJSONString(jsonString: resultString)
print("Post Json >>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n \(dic)")
if dic.count == 0 {
print(">>>>>>>>>>>>服务器数据错误>>>>>>>>>>>>>>>>>")
} else {
let succcess = dic["succcess"] as! String
let errorMsg = dic["msg"] as! String
if succcess == "true" {
success(resultString)
} else {
failure(errorMsg)
}
}
}
}
//MARK: - 照片上传
///
/// - Parameters:
/// - urlString: 服务器地址
/// - params: ["flag":"","userId":""] - flag,userId 为必传参数
/// flag - 666 信息上传多张 -999 服务单上传 -000 头像上传
/// - data: image转换成Data
/// - name: fileName
/// - success:
/// - failture:
func upLoadImageRequest(urlString : String, params:[String:String], data: [Data], name: [String],success : @escaping (_ response : [String : AnyObject])->(), failture : @escaping (_ error : Error)->()){
let headers = ["content-type":"multipart/form-data"]
Alamofire.upload(
multipartFormData: { multipartFormData in
//666多张图片上传
let flag = params["flag"]
let userId = params["userId"]
multipartFormData.append((flag?.data(using: String.Encoding.utf8)!)!, withName: "flag")
multipartFormData.append( (userId?.data(using: String.Encoding.utf8)!)!, withName: "userId")
for i in 0..<data.count {
multipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png")
}
},
to: urlString,
headers: headers,
encodingCompletion: { encodingResult in
// switch encodingResult {
// case .success(let upload, _, _):
// upload.responseJSON { response in
// if let value = response.result.value as? [String: AnyObject]{
// success(value)
// let json = JSON(value)
// PrintLog(json)
// }
// }
// case .failure(let encodingError):
// PrintLog(encodingError)
// failture(encodingError)
// }
}
)
}
}
| mit | c2388a51cf7c96c81e7c3730483b0339 | 38.552846 | 206 | 0.502158 | 4.949135 | false | false | false | false |
xedin/swift | stdlib/public/core/CommandLine.swift | 1 | 1937 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// Command-line arguments for the current process.
@frozen // namespace
public enum CommandLine {
/// The backing static variable for argument count may come either from the
/// entry point or it may need to be computed e.g. if we're in the REPL.
@usableFromInline
internal static var _argc: Int32 = Int32()
/// The backing static variable for arguments may come either from the
/// entry point or it may need to be computed e.g. if we're in the REPL.
///
/// Care must be taken to ensure that `_swift_stdlib_getUnsafeArgvArgc` is
/// not invoked more times than is necessary (at most once).
@usableFromInline
internal static var _unsafeArgv:
UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>
= _swift_stdlib_getUnsafeArgvArgc(&_argc)
/// Access to the raw argc value from C.
public static var argc: Int32 {
_ = CommandLine.unsafeArgv // Force evaluation of argv.
return _argc
}
/// Access to the raw argv value from C. Accessing the argument vector
/// through this pointer is unsafe.
public static var unsafeArgv:
UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> {
return _unsafeArgv
}
/// Access to the swift arguments, also use lazy initialization of static
/// properties to safely initialize the swift arguments.
public static var arguments: [String]
= (0..<Int(argc)).map { String(cString: _unsafeArgv[$0]!) }
}
| apache-2.0 | d9a61a934f25ccbe36068a8cf6cfdbf6 | 37.74 | 80 | 0.659783 | 4.690073 | false | false | false | false |
QuarkX/Quark | Sources/Quark/Core/File/File.swift | 1 | 11050 | import CLibvenice
public enum FileMode {
case read
case createWrite
case truncateWrite
case appendWrite
case readWrite
case createReadWrite
case truncateReadWrite
case appendReadWrite
}
extension FileMode {
var value: Int32 {
switch self {
case .read: return O_RDONLY
case .createWrite: return (O_WRONLY | O_CREAT | O_EXCL)
case .truncateWrite: return (O_WRONLY | O_CREAT | O_TRUNC)
case .appendWrite: return (O_WRONLY | O_CREAT | O_APPEND)
case .readWrite: return (O_RDWR)
case .createReadWrite: return (O_RDWR | O_CREAT | O_EXCL)
case .truncateReadWrite: return (O_RDWR | O_CREAT | O_TRUNC)
case .appendReadWrite: return (O_RDWR | O_CREAT | O_APPEND)
}
}
}
public final class File : Stream {
fileprivate var file: mfile?
public fileprivate(set) var closed = false
public fileprivate(set) var path: String? = nil
public func cursorPosition() throws -> Int {
let position = Int(filetell(file))
try ensureLastOperationSucceeded()
return position
}
public func seek(cursorPosition: Int) throws -> Int {
let position = Int(fileseek(file, off_t(cursorPosition)))
try ensureLastOperationSucceeded()
return position
}
public var length: Int {
return Int(filesize(self.file))
}
public var cursorIsAtEndOfFile: Bool {
return fileeof(file) != 0
}
public lazy var fileExtension: String? = {
guard let path = self.path else {
return nil
}
guard let fileExtension = path.split(separator: ".").last else {
return nil
}
if fileExtension.split(separator: "/").count > 1 {
return nil
}
return fileExtension
}()
init(file: mfile) {
self.file = file
}
public convenience init(path: String, mode: FileMode = .read) throws {
let file = fileopen(path, mode.value, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
try ensureLastOperationSucceeded()
self.init(file: file!)
self.path = path
}
deinit {
if let file = file, !closed {
fileclose(file)
}
}
}
extension File {
public func write(_ data: Data, length: Int, deadline: Double) throws -> Int {
try ensureFileIsOpen()
let bytesWritten = data.withUnsafeBytes {
filewrite(file, $0, length, deadline.int64milliseconds)
}
if bytesWritten == 0 {
try ensureLastOperationSucceeded()
}
return bytesWritten
}
public func read(into buffer: inout Data, length: Int, deadline: Double) throws -> Int {
try ensureFileIsOpen()
let bytesRead = buffer.withUnsafeMutableBytes {
filereadlh(file, $0, 1, length, deadline.int64milliseconds)
}
if bytesRead == 0 {
try ensureLastOperationSucceeded()
}
return bytesRead
}
// public func read(_ byteCount: Int, deadline: Double = .never) throws -> Data {
// try ensureFileIsOpen()
//
// var data = Data(count: byteCount)
// let received = data.withUnsafeMutableBytes {
// fileread(file, $0, data.count, deadline.int64milliseconds)
// }
//
// let receivedData = Data(data.prefix(received))
// try ensureLastOperationSucceeded()
//
// return receivedData
// }
public func readAll(bufferSize: Int = 2048, deadline: Double = .never) throws -> Data {
var inputBuffer = Data(count: bufferSize)
var outputBuffer = Data()
while true {
let inputRead = try read(into: &inputBuffer, deadline: deadline)
if inputRead == 0 || cursorIsAtEndOfFile {
break
}
inputBuffer.withUnsafeBytes {
outputBuffer.append($0, count: inputRead)
}
}
return outputBuffer
}
public func flush(deadline: Double) throws {
try ensureFileIsOpen()
fileflush(file, deadline.int64milliseconds)
try ensureLastOperationSucceeded()
}
public func close() {
if !closed {
fileclose(file)
}
closed = true
}
private func ensureFileIsOpen() throws {
if closed {
throw StreamError.closedStream(data: Data())
}
}
}
extension File {
public static var workingDirectory: String {
var buffer = [Int8](repeating: 0, count: Int(MAXNAMLEN))
let workingDirectory = getcwd(&buffer, buffer.count)
return String(cString: workingDirectory!)
}
public static func changeWorkingDirectory(path: String) throws {
if chdir(path) == -1 {
try ensureLastOperationSucceeded()
}
}
public static func contentsOfDirectory(path: String) throws -> [String] {
var contents: [String] = []
guard let dir = opendir(path) else {
try ensureLastOperationSucceeded()
return []
}
defer {
closedir(dir)
}
let excludeNames = [".", ".."]
while let file = readdir(dir) {
let entry: UnsafeMutablePointer<dirent> = file
if let entryName = withUnsafeMutablePointer(to: &entry.pointee.d_name, { (ptr) -> String? in
let entryPointer = unsafeBitCast(ptr, to: UnsafePointer<CChar>.self)
return String(validatingUTF8: entryPointer)
}) {
if !excludeNames.contains(entryName) {
contents.append(entryName)
}
}
}
return contents
}
public static func fileExists(path: String) -> Bool {
var s = stat()
return lstat(path, &s) >= 0
}
public static func isDirectory(path: String) -> Bool {
var s = stat()
if lstat(path, &s) >= 0 {
if (s.st_mode & S_IFMT) == S_IFLNK {
if stat(path, &s) >= 0 {
return (s.st_mode & S_IFMT) == S_IFDIR
}
return false
}
return (s.st_mode & S_IFMT) == S_IFDIR
}
return false
}
public static func createDirectory(path: String, withIntermediateDirectories createIntermediates: Bool = false) throws {
if createIntermediates {
let (exists, directory) = (fileExists(path: path), isDirectory(path: path))
if !exists {
let parent = path.dropLastPathComponent()
if !fileExists(path: parent) {
try createDirectory(path: parent, withIntermediateDirectories: true)
}
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) == -1 {
try ensureLastOperationSucceeded()
}
} else if directory {
return
} else {
throw SystemError.fileExists
}
} else {
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) == -1 {
try ensureLastOperationSucceeded()
}
}
}
public static func removeFile(path: String) throws {
if unlink(path) != 0 {
try ensureLastOperationSucceeded()
}
}
public static func removeDirectory(path: String) throws {
if fileremove(path) != 0 {
try ensureLastOperationSucceeded()
}
}
}
// Warning: We're gonna need this when we split Venice from Quark in the future
// extension String {
// func split(separator: Character, maxSplits: Int = .max, omittingEmptySubsequences: Bool = true) -> [String] {
// return characters.split(separator: separator, maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences).map(String.init)
// }
//
// public func has(prefix: String) -> Bool {
// return prefix == String(self.characters.prefix(prefix.characters.count))
// }
//
// public func has(suffix: String) -> Bool {
// return suffix == String(self.characters.suffix(suffix.characters.count))
// }
//}
extension String {
func dropLastPathComponent() -> String {
let string = self.fixSlashes()
if string == "/" {
return string
}
switch string.startOfLastPathComponent {
// relative path, single component
case string.startIndex:
return ""
// absolute path, single component
case string.index(after: startIndex):
return "/"
// all common cases
case let startOfLast:
return String(string.characters.prefix(upTo: string.index(before: startOfLast)))
}
}
func fixSlashes(compress: Bool = true, stripTrailing: Bool = true) -> String {
if self == "/" {
return self
}
var result = self
if compress {
result.withMutableCharacters { characterView in
let startPosition = characterView.startIndex
var endPosition = characterView.endIndex
var currentPosition = startPosition
while currentPosition < endPosition {
if characterView[currentPosition] == "/" {
var afterLastSlashPosition = currentPosition
while afterLastSlashPosition < endPosition && characterView[afterLastSlashPosition] == "/" {
afterLastSlashPosition = characterView.index(after: afterLastSlashPosition)
}
if afterLastSlashPosition != characterView.index(after: currentPosition) {
characterView.replaceSubrange(currentPosition ..< afterLastSlashPosition, with: ["/"])
endPosition = characterView.endIndex
}
currentPosition = afterLastSlashPosition
} else {
currentPosition = characterView.index(after: currentPosition)
}
}
}
}
if stripTrailing && result.has(suffix: "/") {
result.remove(at: result.characters.index(before: result.characters.endIndex))
}
return result
}
var startOfLastPathComponent: String.CharacterView.Index {
precondition(!has(suffix: "/") && characters.count > 1)
let characterView = characters
let startPos = characterView.startIndex
let endPosition = characterView.endIndex
var currentPosition = endPosition
while currentPosition > startPos {
let previousPosition = characterView.index(before: currentPosition)
if characterView[previousPosition] == "/" {
break
}
currentPosition = previousPosition
}
return currentPosition
}
}
| mit | 47709c8ea665135cf3c6da9a6d56924f | 29.273973 | 149 | 0.56543 | 5.011338 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/NavigationBarController.swift | 1 | 10369 | //
// NavigationBarController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by nakamuxu on 2005-08-22.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2022 1024jp
//
// 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
//
// https://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 Combine
import Cocoa
final class NavigationBarController: NSViewController {
// MARK: Public Properties
weak var textView: NSTextView?
var outlineItems: [OutlineItem]? {
didSet {
if self.isViewShown {
self.updateOutlineMenu()
}
}
}
// MARK: Private Properties
private var splitViewObservers: Set<AnyCancellable> = []
private var orientationObserver: AnyCancellable?
private var selectionObserver: AnyCancellable?
@objc private dynamic var showsCloseButton = false
@objc private dynamic var showsOutlineMenu = false
@objc private dynamic var isParsingOutline = false
@IBOutlet private weak var leftButton: NSButton?
@IBOutlet private weak var rightButton: NSButton?
@IBOutlet private weak var outlineMenu: NSPopUpButton?
@IBOutlet private weak var openSplitButton: NSButton?
@IBOutlet private var editorSplitMenu: NSMenu?
// MARK: -
// MARK: View Controller Methods
override func viewDidLoad() {
super.viewDidLoad()
// set accessibility
self.view.setAccessibilityElement(true)
self.view.setAccessibilityRole(.group)
self.view.setAccessibilityLabel("navigation bar".localized)
self.outlineMenu?.setAccessibilityLabel("outline menu".localized)
}
override func viewWillAppear() {
super.viewWillAppear()
guard
let splitViewController = self.splitViewController,
let textView = self.textView
else { return assertionFailure() }
splitViewController.$isVertical
.map { $0 ? "split.add-vertical" : "split.add" }
.map { NSImage(named: $0) }
.assign(to: \.image, on: self.openSplitButton!)
.store(in: &self.splitViewObservers)
splitViewController.$canCloseSplitItem
.sink { [weak self] in self?.showsCloseButton = $0 }
.store(in: &self.splitViewObservers)
self.orientationObserver = textView.publisher(for: \.layoutOrientation, options: .initial)
.sink { [weak self] in self?.updateTextOrientation(to: $0) }
self.selectionObserver = NotificationCenter.default.publisher(for: NSTextView.didChangeSelectionNotification, object: textView)
.map { $0.object as! NSTextView }
.filter { !$0.hasMarkedText() }
// avoid updating outline item selection before finishing outline parse
// -> Otherwise, a wrong item can be selected because of using the outdated outline ranges.
// You can ignore text selection change at this time point as the outline selection will be updated when the parse finished.
.filter { $0.textStorage?.editedMask.contains(.editedCharacters) == false }
.debounce(for: .seconds(0.05), scheduler: RunLoop.main)
.sink { [weak self] _ in self?.invalidateOutlineMenuSelection() }
self.updateOutlineMenu()
}
override func viewDidDisappear() {
super.viewDidDisappear()
self.splitViewObservers.removeAll()
self.orientationObserver = nil
self.selectionObserver = nil
}
// MARK: Public Methods
/// Can select the previous item in outline menu?
var canSelectPrevItem: Bool {
guard let textView = self.textView else { return false }
return self.outlineItems?.previousItem(for: textView.selectedRange) != nil
}
/// Can select the next item in outline menu?
var canSelectNextItem: Bool {
guard let textView = self.textView else { return false }
return self.outlineItems?.nextItem(for: textView.selectedRange) != nil
}
/// Show the menu items of the outline menu.
func openOutlineMenu() {
guard let popUpButton = self.outlineMenu else { return }
popUpButton.menu?.popUp(positioning: nil, at: .zero, in: popUpButton)
}
// MARK: Action Messages
/// Select outline item from the popup menu.
@IBAction func selectOutlineMenuItem(_ sender: NSMenuItem) {
guard
let textView = self.textView,
let range = sender.representedObject as? NSRange
else { return assertionFailure() }
textView.select(range: range)
}
// MARK: Private Methods
private lazy var menuItemParagraphStyle: NSParagraphStyle = {
let paragraphStyle = NSParagraphStyle.default.mutable
paragraphStyle.tabStops = []
paragraphStyle.defaultTabInterval = 2.0 * self.outlineMenu!.menu!.font.width(of: " ")
paragraphStyle.lineBreakMode = .byTruncatingMiddle
paragraphStyle.tighteningFactorForTruncation = 0 // don't tighten
return paragraphStyle
}()
/// The split view controller managing editor split.
private var splitViewController: SplitViewController? {
guard let parent = self.parent else { return nil }
return sequence(first: parent, next: \.parent)
.first { $0 is SplitViewController } as? SplitViewController
}
private var prevButton: NSButton? {
return (self.textView?.layoutOrientation == .vertical) ? self.rightButton : self.leftButton
}
private var nextButton: NSButton? {
return (self.textView?.layoutOrientation == .vertical) ? self.leftButton : self.rightButton
}
/// Build outline menu from `outlineItems`.
private func updateOutlineMenu() {
self.isParsingOutline = (self.outlineItems == nil)
self.showsOutlineMenu = (self.outlineItems?.isEmpty == false)
guard let outlineItems = self.outlineItems else { return }
guard let outlineMenu = self.outlineMenu?.menu else { return assertionFailure() }
outlineMenu.items = outlineItems
.flatMap { (outlineItem) -> [NSMenuItem] in
switch outlineItem.title {
case .separator:
// dummy item to avoid merging sequential separators into a single separator
let dummyItem = NSMenuItem()
dummyItem.view = NSView()
dummyItem.setAccessibilityElement(false)
return [.separator(), dummyItem]
default:
let menuItem = NSMenuItem()
menuItem.attributedTitle = outlineItem.attributedTitle(for: outlineMenu.font, attributes: [.paragraphStyle: self.menuItemParagraphStyle])
menuItem.representedObject = outlineItem.range
return [menuItem]
}
}
self.invalidateOutlineMenuSelection()
}
/// Select the proper item in outline menu based on the current selection in the text view.
private func invalidateOutlineMenuSelection() {
guard
self.showsOutlineMenu,
let location = self.textView?.selectedRange.location,
let popUp = self.outlineMenu, popUp.isEnabled
else { return }
let selectedItem = popUp.itemArray.last { menuItem in
guard
menuItem.isEnabled,
let itemRange = menuItem.representedObject as? NSRange
else { return false }
return itemRange.location <= location
} ?? popUp.itemArray.first
popUp.select(selectedItem)
self.prevButton?.isEnabled = self.canSelectPrevItem
self.nextButton?.isEnabled = self.canSelectNextItem
}
/// Update the direction of the menu item arrows.
///
/// - Parameter orientation: The text orientation in the text view.
private func updateTextOrientation(to orientation: NSLayoutManager.TextLayoutOrientation) {
switch orientation {
case .horizontal:
self.leftButton?.image = Chevron.up.image
self.rightButton?.image = Chevron.down.image
case .vertical:
self.leftButton?.image = Chevron.left.image
self.rightButton?.image = Chevron.right.image
@unknown default:
fatalError()
}
self.prevButton?.action = #selector(EditorViewController.selectPrevItemOfOutlineMenu)
self.prevButton?.target = self.parent
self.prevButton?.toolTip = "Jump to previous outline item".localized
self.prevButton?.isEnabled = self.canSelectPrevItem
self.nextButton?.action = #selector(EditorViewController.selectNextItemOfOutlineMenu)
self.nextButton?.target = self.parent
self.nextButton?.toolTip = "Jump to next outline item".localized
self.nextButton?.isEnabled = self.canSelectNextItem
}
}
private enum Chevron: String {
case left
case right
case up
case down
var image: NSImage {
NSImage(systemSymbolName: "chevron." + self.rawValue, accessibilityDescription: self.rawValue)!
}
}
| apache-2.0 | b7bac10c3289a41f29ab2d1b84b2eb18 | 32.550162 | 161 | 0.604707 | 5.385455 | false | false | false | false |
robpeach/test | SwiftPages/OffersVC.swift | 1 | 4121 | //
// OffersVC.swift
// Britannia v2
//
// Created by Rob Mellor on 09/08/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import SafariServices
class OffersVC: UIViewController {
@IBOutlet weak var tableView: UITableView!
private var items = [OffersItem]()
private var offersnetwork: OffersNetworkCalls!
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.reloadData()
offersnetwork = OffersNetworkCalls()
tableView.registerNib(UINib(nibName: "OffersTableViewCell", bundle: nil), forCellReuseIdentifier: "OffersCell")
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OffersVC.loadData), name: UIApplicationWillEnterForegroundNotification, object: nil)
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
loadData()
self.view.layoutIfNeeded()
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func loadData() {
offersnetwork.items { (items) in
if items.count > 0 {
self.items = items
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: - TableView Data Source
extension OffersVC: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("OffersCell", forIndexPath: indexPath) as! OffersTableViewCell
let item = items[indexPath.row]
cell.contentView.alpha = 1
cell.descriptionLabel.text = item.des
cell.titleLabel.text = item.title
cell.photoView.sd_setImageWithURL(item.imageURL)
cell.descriptionLabel.textColor = UIColor.lightGrayColor()
return cell
}
}
// MARK: - TableView Delegate
extension OffersVC: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = items[indexPath.row]
if #available(iOS 9.0, *) {
let safariVC = SFSafariViewController(URL: item.pageURL!)
safariVC.delegate = self
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.view.window!.rootViewController?.presentViewController(safariVC, animated: true, completion: nil)
})
} else {
// Fallback on earlier versions
}
// performSegueWithIdentifier("detailsSegue", sender: item)
// print("null")
}
}
@available(iOS 9.0, *)
extension OffersVC: SFSafariViewControllerDelegate
{
func safariViewControllerDidFinish(controller: SFSafariViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 7d74e64bafb46664006d2b9ac93f8971 | 27.413793 | 167 | 0.59466 | 5.819209 | false | false | false | false |
SwiftORM/SQLite-StORM | Sources/SQLiteStORM/Delete.swift | 1 | 1486 | //
// Delete.swift
// SQLiteStORM
//
// Created by Jonathan Guthrie on 2016-10-07.
//
//
import PerfectLib
import StORM
import PerfectLogger
/// Performs delete-specific functions as an extension
extension SQLiteStORM {
func deleteSQL(_ table: String, idName: String = "id") -> String {
return "DELETE FROM \(table) WHERE \(idName) = :1"
}
/// Deletes one row, with an id as an integer
@discardableResult
public func delete(_ id: Int, idName: String = "id") throws -> Bool {
do {
try exec(deleteSQL(self.table(), idName: idName), params: [String(id)])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
self.error = StORMError.error("\(error)")
throw error
}
return true
}
/// Deletes one row, with an id as a String
@discardableResult
public func delete(_ id: String, idName: String = "id") throws -> Bool {
do {
try exec(deleteSQL(self.table(), idName: idName), params: [id])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
self.error = StORMError.error("\(error)")
throw error
}
return true
}
/// Deletes one row, with an id as a UUID
@discardableResult
public func delete(_ id: UUID, idName: String = "id") throws -> Bool {
do {
try exec(deleteSQL(self.table(), idName: idName), params: [id.string])
} catch {
LogFile.error("Error msg: \(error)", logFile: "./StORMlog.txt")
self.error = StORMError.error("\(error)")
throw error
}
return true
}
}
| apache-2.0 | c47bb900a7b852e46be125cf46e73e22 | 24.186441 | 74 | 0.65074 | 3.346847 | false | false | false | false |
crossroadlabs/Boilerplate | Sources/Boilerplate/Result+.swift | 1 | 1514 | //===--- Result+.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import Result
public func materializeAny<T>(_ f:() throws -> T) -> Result<T, AnyError> {
return materializeAny(try f())
}
public func materializeAny<T>(_ f:@autoclosure () throws -> T) -> Result<T, AnyError> {
do {
return .success(try f())
} catch let e as AnyError {
return .failure(e)
} catch let e {
return .failure(AnyError(e))
}
}
public extension Result where Error : AnyErrorProtocol {
public init(error: Swift.Error) {
self.init(error: Error(error))
}
public func dematerializeAny() throws -> T {
switch self {
case let .success(value):
return value
case let .failure(error):
throw error.error
}
}
}
| apache-2.0 | 49509f502571a92e1437929c47e10467 | 31.212766 | 87 | 0.597754 | 4.466077 | false | false | false | false |
64characters/Telephone | Telephone/ApplicationUserAttentionRequest.swift | 1 | 1716 | //
// ApplicationUserAttentionRequest.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import AppKit
final class ApplicationUserAttentionRequest {
private var request: Int?
private let application: NSApplication
private let center: NotificationCenter
init(application: NSApplication, center: NotificationCenter) {
self.application = application
self.center = center
center.addObserver(
self,
selector: #selector(didBecomeAcitve),
name: NSApplication.didBecomeActiveNotification,
object: application
)
}
deinit {
center.removeObserver(self)
}
@objc private func didBecomeAcitve(_ notification: Notification) {
request = nil
}
}
extension ApplicationUserAttentionRequest: UserAttentionRequest {
func start() {
if !application.isActive && request == nil {
request = application.requestUserAttention(.criticalRequest)
}
}
func stop() {
if let request = request {
application.cancelUserAttentionRequest(request)
}
request = nil
}
}
| gpl-3.0 | 587468ad2ae43c7bc3a1f13e9abb493a | 27.566667 | 72 | 0.677363 | 4.939481 | false | false | false | false |
vmachiel/swift | LearningSwift.playground/Pages/Array, Dict and Range extra.xcplaygroundpage/Contents.swift | 1 | 4269 | import Foundation
// A range is basically a struct that specifies a start and end index
// The generic type can be Int, double etc, but must be comparable!
// Range needs to make sure the start index < endindex
struct Range2<T> {
var startIndex: T
var endIndex: T
}
// Range<Int> could be used to specify the slice of an array!
// Slicing time!
// ..< is start excluding upper and ... is start including upper:
let array1 = ["a", "b", "c", "d", "e"]
let slice1 = array1[2...3]
let slice2 = array1[2..<3]
// Slicing out of bounds [6...8] or reversed [4...1] will cause a runtime crash
// If it's a Range with lower and upperbounds of type Int, like above,
// it's actually the more capable CountableRange type, or a sequence. You can
// then use the for in syntax, like seen in control flow:
for index in 0...4 {
print(array1[index])
}
// You can't do this with floating numbers: they aren't CountableRange, but simple
// Range. If you want to do this, use builtin function stride like so.
// So this takes a type that can be used in a Range and returns a CountableRange
for index in stride(from: 0.5, to: 15.21, by: 0.3) {
print(index)
}
// important: a stringsubrange is NOT Range<Int> but technically Range<String.Index>
// Remove items from array
var characters = ["Lana", "Pam", "Ray", "Sterling"]
print(characters.count)
characters.remove(at: 2)
print(characters.count)
characters.removeAll()
print(characters.count)
// Sort and reverse
let cities = ["London", "Tokyo", "Rome", "Budapest"]
let citiesSorted = cities.sorted()
let citiesBackwards = cities.reversed() // Special type!
// Arrays are sequences that can be iterated over:
let animals = ["Giraffe", "Cow", "Doggie", "Bird"]
for animal in animals {
print(animal)
}
// Dicts as well, using tuples:
var pac12teamRankings = ["Stanford": 1, "USC": 11, "Cal": 12]
for (key, value) in pac12teamRankings {
print("Team \(key) is ranked number \(value)")
}
// Also, when you access dict using keys, they return optionals of their value
// in case the key isn't in the dict.
let test1 = pac12teamRankings["Cal"] // Int? with value 12
let test2 = pac12teamRankings["Snor"] // Int? with value nil
// User a default value:
let test3 = pac12teamRankings["blabla", default: 0] // THIS IS NOT AN OPTIONAL ANYMORE
// There will either be a value, or the default int.
// Arrays have closure method like filter:
// def filter is : filter(includeElement: (T) -> Bool) -> [T]
// filter takes one argument: a function that takes on element of the same type as
// the array, and returns if that should be included. filter returns an array with
// only the included items
let bigNumbers = [2, 47, 118, 5, 9].filter({ $0 > 20 })
// $0 > 20 is the includedElement function. Again, swift knows it returns a bool,
// knows that $0 is supposed to be only argument T
print(bigNumbers)
// Anotherone map: transforms each element into something different.
// map(transform: (T) -> U) -> [U] so takes one parameter: a function that takes
// one and returns a transformed one. Applied on the whole array, transforms all
// of the elements. What the transformation function is can be passed as a closure:
let stringified = [1, 2, 3].map{ String($0) }
print(stringified)
// NOTICE THE LACK OF (): You can leave those at: see trailing closure syntax.
// Finally: reduce takes all the elements and reduces them to a single value.
// reduce takes two arguments: one "answer so far" and one function of what to do.
// THAT function takes two arguments: the "answer so far" and en element from the
// array and returns the new "answer so far". Finally, the whole thing returns a
// final answer: one value. U is "answer so far"'s type (inferred) and T
// is the current array element's type (can be different, is not in example)
// reduce(initial: U, combine: (U, T) -> U) -> U
let sum: Int = [1, 2, 3].reduce(0, { $0 + $1 })
// since + is a valid function it can be simply that instead of closure
let sum2 = [1, 2, 3].reduce(0, +)
let product = [1, 2, 3, 4].reduce(1, *)
// Useful method of dictionary: flatmap!
// let dictTest = ["M": 4, "N": 5, "X": 48]
// let joinedKeysAndValues = dictTest.flatMap{"\($0), \($1)"}
// let jKAVInOneString = joinedKeysAndValues.joined(separator: ", ")
| mit | b7beae90cb83d2787e87ccba1f4c8272 | 37.116071 | 87 | 0.696416 | 3.525186 | false | false | false | false |
gradyzhuo/Acclaim | Sources/Logger/Stream.swift | 1 | 1446 | //
// File.swift
//
//
// Created by Grady Zhuo on 2021/2/27.
//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
import Darwin
let systemStderr = Darwin.stderr
let systemStdout = Darwin.stdout
#elseif os(Windows)
import MSVCRT
let systemStderr = MSVCRT.stderr
let systemStdout = MSVCRT.stdout
#else
import Glibc
let systemStderr = Glibc.stderr!
let systemStdout = Glibc.stdout!
#endif
public protocol WritableStreamer: TextOutputStream{
func flush()
func writeAndFlush(_ string: String)
}
public struct ConsoleOutputStream: WritableStreamer{
internal let filePointer: UnsafeMutablePointer<FILE>
public func write(_ string: String) {
string.withCString { ptr in
#if os(Windows)
_lock_file(self.filePointer)
#else
flockfile(self.filePointer)
#endif
defer {
#if os(Windows)
_unlock_file(self.filePointer)
#else
funlockfile(self.filePointer)
#endif
}
fputs(ptr, self.filePointer)
}
}
public func flush(){
fflush(self.filePointer)
}
public func writeAndFlush(_ string: String){
self.write(string)
self.flush()
}
public static let stderr = Self.init(filePointer: systemStderr)
public static let stdout = Self.init(filePointer: systemStdout)
}
| mit | 0d71d9bf28ed65ad87ee9284f5512687 | 22.704918 | 67 | 0.605118 | 4.290801 | false | false | false | false |
grandiere/box | box/Metal/Spatial/MetalSpatialBase.swift | 1 | 1209 | import Foundation
import MetalKit
class MetalSpatialBase
{
let vertexBuffer:MTLBuffer
init(vertexBuffer:MTLBuffer)
{
self.vertexBuffer = vertexBuffer
}
init(
device:MTLDevice,
width:Float,
height:Float)
{
let width_2:Float = width / 2.0
let height_2:Float = height / 2.0
let top:Float = height_2
let bottom:Float = -height_2
let left:Float = -width_2
let right:Float = width_2
let topLeft:MetalVertex = MetalVertex(
positionX:left,
positionY:top)
let topRight:MetalVertex = MetalVertex(
positionX:right,
positionY:top)
let bottomLeft:MetalVertex = MetalVertex(
positionX:left,
positionY:bottom)
let bottomRight:MetalVertex = MetalVertex(
positionX:right,
positionY:bottom)
let vertexFace:MetalVertexFace = MetalVertexFace(
topLeft:topLeft,
topRight:topRight,
bottomLeft:bottomLeft,
bottomRight:bottomRight)
vertexBuffer = device.generateBuffer(bufferable:vertexFace)
}
}
| mit | 5c3b1441b5596d4a9f5fe0b8c94a384c | 25.282609 | 67 | 0.578164 | 4.914634 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/TXTReader/Reader/Service/ZSReaderWebService.swift | 1 | 2275 | //
// QSTextInteractor.swift
// zhuishushenqi
//
// Created by Nory Cao on 2017/4/14.
// Copyright © 2017年 QS. All rights reserved.
//
/*
chapters:
{
chapterCover = "";
currency = 0;
isVip = 0;
link = "http://book.my716.com/getBooks.aspx?method=content&bookId=2201994&chapterFile=U_2201994_201806182043464927_0420_600.txt";
order = 0;
partsize = 0;
title = "\U7b2c\U4e94\U4e5d\U516b\U7ae0 \U8d8a\U5357\U5144\U5f1f\Uff08\U8865\U66f44\Uff09";
totalpage = 0;
unreadble = 0;
}
*/
import Foundation
import HandyJSON
import ZSAPI
class ZSReaderWebService:ZSBaseService {
//MARK: - 请求所有的来源,key为book的id
func fetchAllResource(key:String,_ callback:ZSBaseCallback<[ResourceModel]>?){
let api = ZSAPI.allResource(key: key)
zs_get(api.path, parameters: api.parameters) { (response) in
if let resources = [ResourceModel].deserialize(from: response as? [Any]) as? [ResourceModel] {
callback?(resources)
}else{
callback?(nil)
}
}
}
//MARK: - 请求所有的章节,key为book的id
func fetchAllChapters(key:String,_ callback:ZSBaseCallback<[ZSChapterInfo]>?){
let api = ZSAPI.allChapters(key: key)
let url:String = api.path
zs_get(url, parameters: api.parameters) { (response) in
if let chapters = [ZSChapterInfo].deserialize(from: response?["chapters"] as? [Any]) as? [ZSChapterInfo]{
QSLog("Chapters:\(chapters)")
callback?(chapters)
}else{
callback?(nil)
}
}
}
//MARK: - 请求当前章节的信息,key为当前章节的link,追书正版则为id
func fetchChapter(key:String,_ callback:ZSBaseCallback<ZSChapterBody>?){
var link:NSString = key as NSString
link = link.urlEncode() as NSString
let api = ZSAPI.chapter(key: link as String, type: .chapter)
zs_get(api.path) { (response) in
QSLog("JSON:\(String(describing: response))")
if let body = ZSChapterBody.deserialize(from: response?["chapter"] as? NSDictionary) {
callback?(body)
} else {
callback?(nil)
}
}
}
}
| mit | 8823d418abec4512a81b68e187276bbc | 30.342857 | 130 | 0.602097 | 3.493631 | false | false | false | false |
luispadron/UICircularProgressRing | Example/UICircularProgressRingExample/Examples/IndeterminateExample.swift | 1 | 2433 | //
// IndeterminateExample.swift
// UICircularProgressRingExample
//
// Created by Luis on 5/30/20.
// Copyright © 2020 Luis. All rights reserved.
//
import Combine
import UICircularProgressRing
import SwiftUI
struct IndeterminateExample: View {
@State private var progress: RingProgress = .percent(0)
private let onDidTapSubject = PassthroughSubject<Void, Never>()
private var onDidTapPublisher: AnyPublisher<Void, Never> {
onDidTapSubject.eraseToAnyPublisher()
}
private let onDidTapIndeterminateSubject = PassthroughSubject<Void, Never>()
private var onDidTapIndeterminatePublisher: AnyPublisher<Void, Never> {
onDidTapIndeterminateSubject.eraseToAnyPublisher()
}
private var progressPublisher: AnyPublisher<RingProgress, Never> {
onDidTapPublisher
.map {
self.progress == .percent(1) || self.progress.isIndeterminate ?
RingProgress.percent(0) :
RingProgress.percent(1)
}
.merge(with: onDidTapIndeterminateSubject.map { RingProgress.indeterminate })
.prepend(progress)
.eraseToAnyPublisher()
}
var body: some View {
VStack {
ProgressRing(progress: $progress)
.animation(.easeInOut(duration: 5))
.padding(32)
HStack {
Button(action: { self.onDidTapSubject.send(()) }) {
buttonLabel
}
.padding(16)
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
.offset(y: -32)
Button(action: { self.onDidTapIndeterminateSubject.send(()) }) {
Text("Make Indeterminate")
}
.padding(16)
.foregroundColor(.white)
.background(Color.red)
.cornerRadius(8)
.offset(y: -32)
}
}
.navigationBarTitle("Indeterminate")
.onReceive(progressPublisher) { progress in
self.progress = progress
}
}
private var buttonLabel: some View {
if progress == .percent(1) || progress.isIndeterminate {
return Text("Restart Progress")
} else {
return Text("Start Progress")
}
}
}
| mit | 96043a9fbe23860b8e8d32c021c753f3 | 30.179487 | 89 | 0.558388 | 5.286957 | false | false | false | false |
devcarlos/RappiApp | RappiApp/Classes/Transitions/CustomInteractionController.swift | 1 | 1815 | //
// CustomInteractionController.swift
// CustomTransitions
//
// Created by Carlos Alcala on 7/3/16.
// Copyright (c) 2015 Appcoda. All rights reserved.
//
import UIKit
class CustomInteractionController: UIPercentDrivenInteractiveTransition {
var navigationController: UINavigationController!
var shouldCompleteTransition = false
var transitionInProgress = false
var completionSeed: CGFloat {
return 1 - percentComplete
}
func attachToViewController(viewController: UIViewController) {
navigationController = viewController.navigationController
setupGestureRecognizer(viewController.view)
}
private func setupGestureRecognizer(view: UIView) {
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(CustomInteractionController.handlePanGesture(_:))))
}
func handlePanGesture(gestureRecognizer: UIPanGestureRecognizer) {
let viewTranslation = gestureRecognizer.translationInView(gestureRecognizer.view!.superview!)
switch gestureRecognizer.state {
case .Began:
transitionInProgress = true
navigationController.popViewControllerAnimated(true)
case .Changed:
let const = CGFloat(fminf(fmaxf(Float(viewTranslation.x / 200.0), 0.0), 1.0))
shouldCompleteTransition = const > 0.5
updateInteractiveTransition(const)
case .Cancelled, .Ended:
transitionInProgress = false
if !shouldCompleteTransition || gestureRecognizer.state == .Cancelled {
cancelInteractiveTransition()
} else {
finishInteractiveTransition()
}
default:
print("Swift switch must be exhaustive, thus the default")
}
}
}
| mit | 24c653d17cdafb9636afe1f62074202d | 36.040816 | 144 | 0.683196 | 5.95082 | false | false | false | false |
newtonstudio/cordova-plugin-device | imgly-sdk-ios-master/imglyKit/Frontend/Editor/IMGLYTextColorSelectorView.swift | 1 | 3505 | //
// IMGLYTextColorSelectorView.swift
// imglyKit
//
// Created by Carsten Przyluczky on 05/03/15.
// Copyright (c) 2015 9elements GmbH. All rights reserved.
//
import UIKit
public protocol IMGLYTextColorSelectorViewDelegate: class {
func textColorSelectorView(selectorView: IMGLYTextColorSelectorView, didSelectColor color: UIColor)
}
public class IMGLYTextColorSelectorView: UIScrollView {
public weak var menuDelegate: IMGLYTextColorSelectorViewDelegate?
private var colorArray = [UIColor]()
private var buttonArray = [IMGLYColorButton]()
private let kButtonYPosition = CGFloat(22)
private let kButtonXPositionOffset = CGFloat(5)
private let kButtonDistance = CGFloat(10)
private let kButtonSideLength = CGFloat(50)
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.autoresizesSubviews = false
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
configureColorArray()
configureColorButtons()
}
private func configureColorArray() {
UIColor(red: 1, green: 2, blue: 2, alpha: 3)
colorArray = [
UIColor.whiteColor(),
UIColor.blackColor(),
UIColor(red: CGFloat(0xec / 255.0), green:CGFloat(0x37 / 255.0), blue:CGFloat(0x13 / 255.0), alpha:1.0),
UIColor(red: CGFloat(0xfc / 255.0), green:CGFloat(0xc0 / 255.0), blue:CGFloat(0x0b / 255.0), alpha:1.0),
UIColor(red: CGFloat(0xa9 / 255.0), green:CGFloat(0xe9 / 255.0), blue:CGFloat(0x0e / 255.0), alpha:1.0),
UIColor(red: CGFloat(0x0b / 255.0), green:CGFloat(0x6a / 255.0), blue:CGFloat(0xf9 / 255.0), alpha:1.0),
UIColor(red: CGFloat(0xff / 255.0), green:CGFloat(0xff / 255.0), blue:CGFloat(0x00 / 255.0), alpha:1.0),
UIColor(red: CGFloat(0xb5 / 255.0), green:CGFloat(0xe5 / 255.0), blue:CGFloat(0xff / 255.0), alpha:1.0),
UIColor(red: CGFloat(0xff / 255.0), green:CGFloat(0xb5 / 255.0), blue:CGFloat(0xe0 / 255.0), alpha:1.0)]
}
private func configureColorButtons() {
for color in colorArray {
let button = IMGLYColorButton()
self.addSubview(button)
button.addTarget(self, action: "colorButtonTouchedUpInside:", forControlEvents: .TouchUpInside)
buttonArray.append(button)
button.backgroundColor = color
button.hasFrame = true
}
}
public override func layoutSubviews() {
super.layoutSubviews()
layoutColorButtons()
}
private func layoutColorButtons() {
var xPosition = kButtonXPositionOffset
for var i = 0; i < colorArray.count; i++ {
let button = buttonArray[i]
button.frame = CGRectMake(xPosition,
kButtonYPosition,
kButtonSideLength,
kButtonSideLength)
xPosition += (kButtonDistance + kButtonSideLength)
}
buttonArray[0].hasFrame = true
contentSize = CGSize(width: xPosition - kButtonDistance + kButtonXPositionOffset, height: 0)
}
@objc private func colorButtonTouchedUpInside(button:UIButton) {
menuDelegate?.textColorSelectorView(self, didSelectColor: button.backgroundColor!)
}
}
| apache-2.0 | bbeb25652e976ce0bca5a009b2072ed2 | 37.516484 | 116 | 0.641369 | 4.197605 | false | false | false | false |
CartoDB/mobile-ios-samples | AdvancedMap.Objective-C/AdvancedMap/SlideInPopupHeader.swift | 1 | 3838 | //
// SlideInPopupHeader.swift
// Feature Demo
//
// Created by Aare Undo on 19/06/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
@objc class SlideInPopupHeader : UIView {
@objc var backButton: PopupBackButton!
@objc var label: UILabel!
@objc var closeButton: PopupCloseButton!
@objc var height: CGFloat = 40
convenience init() {
self.init(frame: CGRect.zero)
label = UILabel()
label.textAlignment = .center
label.font = UIFont(name: "HelveticaNeue", size: 11)
label.textColor = Colors.navy
addSubview(label)
backButton = PopupBackButton()
backButton.text.font = label.font
backButton.text.textColor = label.textColor
backButton.backgroundColor = UIColor.white
addSubview(backButton)
backButton.isHidden = true
closeButton = PopupCloseButton()
addSubview(closeButton)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.closeTapped(_:)))
closeButton.addGestureRecognizer(recognizer)
}
override func layoutSubviews() {
let padding: CGFloat = 15
var x: CGFloat = padding
let y: CGFloat = 0
var w: CGFloat = label.frame.width
let h: CGFloat = frame.height
label.frame = CGRect(x: x, y: y, width: w, height: h)
backButton.frame = CGRect(x: x, y: y, width: w, height: h)
w = h
x = frame.width - w
closeButton.frame = CGRect(x: x, y: y, width: w, height: h)
}
@objc func setText(text: String) {
label.text = text
label.sizeToFit()
layoutSubviews()
}
@objc func closeTapped(_ sender: UITapGestureRecognizer) {
(superview?.superview as? SlideInPopup)?.hide()
}
}
class PopupCloseButton : UIView {
@objc var imageView: UIImageView!
convenience init() {
self.init(frame: CGRect.zero)
imageView = UIImageView()
imageView.image = UIImage(named: "icon_close.png")
addSubview(imageView)
}
override func layoutSubviews() {
let padding: CGFloat = frame.height / 3
imageView.frame = CGRect(x: padding, y: padding, width: frame.width - 2 * padding, height: frame.height - 2 * padding)
}
}
class PopupBackButton : UIView {
@objc var delegate: ClickDelegate?
@objc var button: UIImageView!
@objc var text: UILabel!
convenience init() {
self.init(frame: CGRect.zero)
button = UIImageView()
button.image = UIImage(named: "icon_back_blue.png")
addSubview(button)
text = UILabel()
text.text = "BACK"
addSubview(text)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.backTapped(_:)))
addGestureRecognizer(recognizer)
}
override func layoutSubviews() {
let padding: CGFloat = 3
let imagePadding: CGFloat = frame.height / 4
var x: CGFloat = 0
var y: CGFloat = imagePadding
var h: CGFloat = frame.height - 2 * imagePadding
var w: CGFloat = h / 2
button.frame = CGRect(x: x, y: y, width: w, height: h)
x = button.frame.width + imagePadding
y = 0
w = frame.width - (x + padding)
h = frame.height
text.frame = CGRect(x: x, y: y, width: w, height: h)
}
@objc func backTapped(_ sender: UITapGestureRecognizer) {
delegate?.click(sender: self)
}
}
@objc protocol ClickDelegate {
func click(sender: UIView);
}
| bsd-2-clause | 95b045b9008c143fe797a35e54d495cf | 23.754839 | 126 | 0.572843 | 4.524764 | false | false | false | false |
gmoral/SwiftTraining2016 | Training_Swift/SkillLevel.swift | 1 | 805 | //
// SkillLevels.swift
// Training_Swift
//
// Created by Guillermo Moral on 2/23/16.
// Copyright © 2016 Guillermo Moral. All rights reserved.
//
import SwiftyJSON
class SkillLevel
{
var id: String?
var updated: String?
var skill: String?
var version: Int?
var location: String?
var level: Int?
var created: String?
var want: Bool = false
var user: String?
required init?(data: JSON)
{
id = data["_id"].string!
updated = data["updated"].string!
skill = data["skill"].string!
version = data["_version"].intValue
location = data["location"].string!
level = data["level"].intValue
created = data["created"].string!
want = data["want"].bool!
user = data["user"].string!
}
}
| mit | abd19df036da4f3018aef1789eae41a6 | 21.971429 | 58 | 0.585821 | 3.865385 | false | false | false | false |
qiscus/qiscus-sdk-ios | Qiscus/Qiscus/View/QChatCell/QCellFileRight.swift | 1 | 6273 | //
// QCellFileRight.swift
// QiscusSDK
//
// Created by Ahmad Athaullah on 1/6/17.
// Copyright © 2017 Ahmad Athaullah. All rights reserved.
//
import UIKit
class QCellFileRight: QChatCell {
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var balloonView: UIImageView!
@IBOutlet weak var fileContainer: UIView!
@IBOutlet weak var fileTypeLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var statusImage: UIImageView!
@IBOutlet weak var fileIcon: UIImageView!
@IBOutlet weak var fileNameLabel: UILabel!
@IBOutlet weak var balloonWidth: NSLayoutConstraint!
@IBOutlet weak var cellHeight: NSLayoutConstraint!
@IBOutlet weak var rightMargin: NSLayoutConstraint!
@IBOutlet weak var topMargin: NSLayoutConstraint!
override func awakeFromNib() {
super.awakeFromNib()
fileContainer.layer.cornerRadius = 10
fileIcon.image = Qiscus.image(named: "ic_file")?.withRenderingMode(.alwaysTemplate)
fileIcon.contentMode = .scaleAspectFit
}
public override func commentChanged() {
if let color = self.userNameColor {
self.userNameLabel.textColor = color
}
userNameLabel.text = "YOU".getLocalize()
userNameLabel.isHidden = true
topMargin.constant = 0
cellHeight.constant = 0
balloonView.image = getBallon()
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(QChatCell.showFile))
fileContainer.addGestureRecognizer(tapRecognizer)
if self.showUserName{
userNameLabel.isHidden = false
topMargin.constant = 20
cellHeight.constant = 20
}
if let file = self.comment!.file {
fileNameLabel.text = file.filename
if file.ext == "doc" || file.ext == "docx" || file.ext == "ppt" || file.ext == "pptx" || file.ext == "xls" || file.ext == "xlsx" || file.ext == "txt" {
fileTypeLabel.text = "\(file.ext.uppercased()) File"
}else{
fileTypeLabel.text = "Unknown File"
}
}
dateLabel.text = self.comment!.time.lowercased()
balloonView.tintColor = QiscusColorConfiguration.sharedInstance.rightBaloonColor
dateLabel.textColor = QiscusColorConfiguration.sharedInstance.rightBaloonTextColor
fileIcon.tintColor = QiscusColorConfiguration.sharedInstance.rightBaloonColor
updateStatus(toStatus: self.comment!.status)
if self.comment!.isUploading {
let uploadProgres = Int(self.comment!.progress * 100)
let uploading = QiscusTextConfiguration.sharedInstance.uploadingText
dateLabel.text = "\(uploading) \(QChatCellHelper.getFormattedStringFromInt(uploadProgres)) %"
}
self.updateStatus(toStatus: self.comment!.status)
}
public override func uploadingMedia() {
if self.comment!.isUploading {
let uploadProgres = Int(self.comment!.progress * 100)
let uploading = QiscusTextConfiguration.sharedInstance.uploadingText
dateLabel.text = "\(uploading) \(QChatCellHelper.getFormattedStringFromInt(uploadProgres)) %"
}
}
public override func uploadFinished() {
updateStatus(toStatus: self.comment!.status)
}
public override func updateStatus(toStatus status:QCommentStatus){
super.updateStatus(toStatus: status)
dateLabel.text = self.comment!.time.lowercased()
dateLabel.textColor = QiscusColorConfiguration.sharedInstance.rightBaloonTextColor
statusImage.isHidden = false
statusImage.tintColor = QiscusColorConfiguration.sharedInstance.rightBaloonTextColor
statusImage.isHidden = false
statusImage.tintColor = QiscusColorConfiguration.sharedInstance.rightBaloonTextColor
switch status {
case .deleted:
dateLabel.text = self.comment!.time.lowercased()
statusImage.image = Qiscus.image(named: "ic_deleted")?.withRenderingMode(.alwaysTemplate)
break
case .deleting, .deletePending:
dateLabel.text = QiscusTextConfiguration.sharedInstance.deletingText
if status == .deletePending {
dateLabel.text = self.comment!.time.lowercased()
}
statusImage.image = Qiscus.image(named: "ic_deleting")?.withRenderingMode(.alwaysTemplate)
break;
case .sending, .pending:
dateLabel.text = QiscusTextConfiguration.sharedInstance.sendingText
if status == .pending {
dateLabel.text = self.comment!.time.lowercased()
}
statusImage.image = Qiscus.image(named: "ic_info_time")?.withRenderingMode(.alwaysTemplate)
break
case .sent:
statusImage.image = Qiscus.image(named: "ic_sending")?.withRenderingMode(.alwaysTemplate)
break
case .delivered:
statusImage.image = Qiscus.image(named: "ic_read")?.withRenderingMode(.alwaysTemplate)
break
case .read:
statusImage.tintColor = Qiscus.style.color.readMessageColor
statusImage.image = Qiscus.image(named: "ic_read")?.withRenderingMode(.alwaysTemplate)
break
case .failed:
dateLabel.text = QiscusTextConfiguration.sharedInstance.failedText
dateLabel.textColor = QiscusColorConfiguration.sharedInstance.failToSendColor
statusImage.image = Qiscus.image(named: "ic_warning")?.withRenderingMode(.alwaysTemplate)
statusImage.tintColor = QiscusColorConfiguration.sharedInstance.failToSendColor
break
default: break
}
}
public override func updateUserName() {
if let sender = self.comment?.sender {
self.userNameLabel.text = sender.fullname
}else{
self.userNameLabel.text = self.comment?.senderName
}
}
public override func comment(didChangePosition comment:QComment, position: QCellPosition) {
if comment.uniqueId == self.comment?.uniqueId {
self.balloonView.image = self.getBallon()
}
}
}
| mit | 756f385d5b29617f6581882f02153e35 | 42.255172 | 163 | 0.653061 | 5.204979 | false | true | false | false |
swixbase/multithreading | Sources/Multithreading/PSXJobQueue.swift | 1 | 2126 | /// Copyright 2017 Sergei Egorov
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
import Foundation
internal class PSXJobQueue {
/// Jobs queue.
fileprivate var jobs: [PSXJob] = []
/// Mutex for queue r/w access.
fileprivate let rwmutex = PSXMutex()
/// Flag as binary semaphore.
fileprivate(set) var hasJobs = PSXSemaphore(value: .zero)
/// Returns count of jobs in queue.
internal var jobsCount: Int {
rwmutex.lock()
let jbscount = jobs.count
rwmutex.unlock()
return jbscount
}
}
extension PSXJobQueue {
/// Adds job to queue.
///
/// - Parameters:
/// - newJob: The job to be performed.
/// - priority: If equals .high, the job is inserted at the beginning of the queue.
///
internal func put(newJob: PSXJob, priority: PSXJobPriority) {
rwmutex.lock()
if priority == .high {
jobs.insert(newJob, at: jobs.startIndex)
} else {
jobs.append(newJob)
}
hasJobs.post()
rwmutex.unlock()
}
/// Returns first job from queue, if exist.
///
internal func pull() -> PSXJob? {
rwmutex.lock()
var job: PSXJob?
if jobs.count > 0 {
job = jobs.remove(at: jobs.startIndex)
if jobs.count > 0 { hasJobs.post() }
}
rwmutex.unlock()
return job
}
/// Clears the queue.
///
internal func clear() {
rwmutex.lock()
jobs.removeAll()
hasJobs.reset()
rwmutex.unlock()
}
}
| apache-2.0 | 857e8931a46003da8a1965e6ea118a91 | 25.911392 | 90 | 0.591251 | 4.218254 | false | false | false | false |
LandonRover/SwiftyThreads | Background.swift | 1 | 1097 | //
// STBackround.swift
// SwiftyThreads
//
// Created by Andrew Robinson on 10/22/15.
// Copyright © 2015 Andrew Robinson. All rights reserved.
//
import Foundation
class STBackground {
private var done = false {
didSet {
if done {
taskInterval = nil
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion?()
})
}
}
}
private var taskInterval: (() -> ())?
private var completion: (() -> ())?
init(task: () -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
task()
self.done = true
}
}
func afterInterval(interval: NSTimeInterval, closure: () -> ()) -> STBackground {
taskInterval = closure
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(interval * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) { [weak self] in
self?.taskInterval?()
}
return self
}
func completion(closure: () -> ()) -> STBackground {
completion = closure
return self
}
}
| apache-2.0 | 8dfec635f0773820e75d0276cced76c0 | 21.833333 | 97 | 0.593978 | 3.886525 | false | false | false | false |
ktmswzw/jwtSwiftDemoClient | Temp/ViewController.swift | 1 | 4601 | //
// ViewController.swift
// Temp
//
// Created by vincent on 2/2/16.
// Copyright © 2016 xecoder. All rights reserved.
//
import UIKit
import CryptoSwift
import JWT
import Alamofire
import SwiftyJSON
class ViewController: UIViewController, MyAlertMsg {
let userDefaults = NSUserDefaults.standardUserDefaults()
@IBOutlet var username: UITextField!
@IBOutlet var password: UITextField!
var userId: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: "login-bg")
let blurredImage = image!.imageByApplyingBlurWithRadius(6)
self.view.layer.contents = blurredImage.CGImage
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func login(sender: UIButton) {
if username.text != "" && password.text != ""
{
//123456789001
//123456
let userNameText = username.text
let passwordText = (password.text?.md5())!
Alamofire.request(.POST, "http://192.168.137.1:80/login", parameters: ["username": userNameText!,"password":passwordText,"device":"APP"])
.validate()
.responseJSON { response in
switch response.result {
case .Success:
if let json = response.result.value {
let myJosn = JSON(json)
// print("\(myJosn.dictionary!["status"]!.stringValue)")
let code:Int = Int(myJosn["status"].stringValue)!
if code == 400 {
self.alertMsg(myJosn.dictionary!["message"]!.stringValue,view: self, second: 2)
}
else{
let jwt = JWTTools()
NSLog(myJosn.dictionary!["message"]!.stringValue)
jwt.token = myJosn.dictionary!["message"]!.stringValue
NSLog("\(jwt.getHeader(jwt.token, myDictionary: [:]))")
self.view.makeToast("登陆成功", duration: 1, position: .Top)
self.performSegueWithIdentifier("login", sender: self)
}
}
case .Failure:
self.alertMsg("服务器错误",view: self, second: 2)
}
}
}
else
{
self.alertMsg("帐号或密码为空",view: self, second: 2)
}
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
extension UIViewController {
/**
* Called when 'return' key pressed. return NO to ignore.
*/
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
/**
* Called when the user click on the view (outside the UITextField).
*/
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
//
//
// override func viewDidLoad() {
// self.view.layer.contents = UIImage(named: "Backgroup.png")?.CGImage
// // Do any additional setup after loading the view.
// }
}
@IBDesignable class UIButtonTypeView: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let borderAlpha : CGFloat = 0.7
let cornerRadius : CGFloat = 5.0
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.backgroundColor = UIColor.clearColor()
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor(white: 1.0, alpha: borderAlpha).CGColor
self.layer.cornerRadius = cornerRadius
}
} | apache-2.0 | 44213b3a44f6cd571e8e23a06f68d904 | 29.66443 | 149 | 0.515105 | 5.510253 | false | false | false | false |
SwiftFMI/iOS_2017_2018 | Upr/28.10.17/SecondTaskComplexSolution/SecondTaskComplexSolution/PlayViewController.swift | 1 | 2421 | //
// PlayViewController.swift
// SecondTaskComplexSolution
//
// Created by Petko Haydushki on 2.11.17.
// Copyright © 2017 Petko Haydushki. All rights reserved.
//
import UIKit
import AVFoundation
import AudioToolbox
class PlayViewController: UIViewController {
@IBOutlet weak var artworkImageView: UIImageView!
@IBOutlet weak var songNameLabel: UILabel!
@IBOutlet weak var artistNameLabel: UILabel!
@IBOutlet weak var playPauseButton: UIButton!
@IBOutlet weak var volumeSlider: UISlider!
var currentSong : Song = Song()
var playing : Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Now Playing"
self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Back", style: UIBarButtonItemStyle.done, target: self, action: #selector(back))
self.songNameLabel.text? = currentSong.name
self.artistNameLabel.text? = currentSong.artistName;
self.artworkImageView.image = UIImage(named: currentSong.artworkImageName)
// Do any additional setup after loading the view.
}
@objc func back() -> Void {
self.navigationController?.popViewController(animated: true)
}
@IBAction func playPauseButtonAction(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
playing = !playing
if (playing)
{
let soundFile = Bundle.main.path(forResource: currentSong.artworkImageName, ofType: "mp3")
let url = URL(fileURLWithPath: soundFile!)
appDelegate.mAudioPlayer = try! AVAudioPlayer(contentsOf: url as URL)
appDelegate.mAudioPlayer?.play()
playPauseButton.setImage(UIImage.init(named: "pause"), for: UIControlState.normal)
}
else
{
appDelegate.mAudioPlayer?.pause();
self.playPauseButton.setImage(UIImage.init(named: "play"), for: UIControlState.normal)
}
}
@IBAction func previousTrackButtonAction(_ sender: Any) {
}
@IBAction func nextTrackButtonAction(_ sender: Any) {
}
@IBAction func volumeChanged(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.mAudioPlayer?.setVolume(self.volumeSlider.value, fadeDuration: 0.1)
}
}
| apache-2.0 | 2e408cdd5dc37c87e5b34cf5e73b33a8 | 30.842105 | 156 | 0.655785 | 4.918699 | false | false | false | false |
alloy/realm-cocoa | Realm/Tests/Swift/SwiftObjectInterfaceTests.swift | 1 | 6057 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Realm
class SwiftObjectInterfaceTests: SwiftTestCase {
// Swift models
func testSwiftObject() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let obj = SwiftObject()
realm.addObject(obj)
obj.boolCol = true
obj.intCol = 1234
obj.floatCol = 1.1
obj.doubleCol = 2.2
obj.stringCol = "abcd"
obj.binaryCol = "abcd".dataUsingEncoding(NSUTF8StringEncoding)
obj.dateCol = NSDate(timeIntervalSince1970: 123)
obj.objectCol = SwiftBoolObject()
obj.objectCol.boolCol = true
obj.arrayCol.addObject(obj.objectCol)
realm.commitWriteTransaction()
let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as SwiftObject
XCTAssertEqual(firstObj.boolCol, true, "should be true")
XCTAssertEqual(firstObj.intCol, 1234, "should be 1234")
XCTAssertEqual(firstObj.floatCol, 1.1, "should be 1.1")
XCTAssertEqual(firstObj.doubleCol, 2.2, "should be 2.2")
XCTAssertEqual(firstObj.stringCol, "abcd", "should be abcd")
XCTAssertEqual(firstObj.binaryCol!, "abcd".dataUsingEncoding(NSUTF8StringEncoding)!, "should be abcd data")
XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 123), "should be epoch + 123")
XCTAssertEqual(firstObj.objectCol.boolCol, true, "should be true")
XCTAssertEqual(obj.arrayCol.count, 1, "array count should be 1")
XCTAssertEqual((obj.arrayCol.firstObject() as? SwiftBoolObject)!.boolCol, true, "should be true")
}
func testDefaultValueSwiftObject() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
realm.addObject(SwiftObject())
realm.commitWriteTransaction()
let firstObj = SwiftObject.allObjectsInRealm(realm).firstObject() as SwiftObject
XCTAssertEqual(firstObj.boolCol, false, "should be false")
XCTAssertEqual(firstObj.intCol, 123, "should be 123")
XCTAssertEqual(firstObj.floatCol, 1.23, "should be 1.23")
XCTAssertEqual(firstObj.doubleCol, 12.3, "should be 12.3")
XCTAssertEqual(firstObj.stringCol, "a", "should be a")
XCTAssertEqual(firstObj.binaryCol!, "a".dataUsingEncoding(NSUTF8StringEncoding)!, "should be a data")
XCTAssertEqual(firstObj.dateCol, NSDate(timeIntervalSince1970: 1), "should be epoch + 1")
XCTAssertEqual(firstObj.objectCol.boolCol, false, "should be false")
XCTAssertEqual(firstObj.arrayCol.count, 0, "array count should be zero")
}
func testOptionalSwiftProperties() {
let realm = realmWithTestPath()
realm.transactionWithBlock { realm.addObject(SwiftOptionalObject()) }
let firstObj = SwiftOptionalObject.allObjectsInRealm(realm).firstObject() as SwiftOptionalObject
XCTAssertNil(firstObj.optObjectCol)
realm.transactionWithBlock {
firstObj.optObjectCol = SwiftBoolObject()
firstObj.optObjectCol!.boolCol = true
}
XCTAssertTrue(firstObj.optObjectCol!.boolCol)
}
func testSwiftClassNameIsDemangled() {
XCTAssertEqual(SwiftObject.className()!, "SwiftObject", "Calling className() on Swift class should return demangled name")
}
// Objective-C models
// Note: Swift doesn't support custom accessor names
// so we test to make sure models with custom accessors can still be accessed
func testCustomAccessors() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let ca = CustomAccessorsObject.createInRealm(realm, withObject: ["name", 2])
XCTAssertEqual(ca.name!, "name", "name property should be name.")
ca.age = 99
XCTAssertEqual(ca.age, 99, "age property should be 99")
realm.commitWriteTransaction()
}
func testClassExtension() {
let realm = realmWithTestPath()
realm.beginWriteTransaction()
let bObject = BaseClassStringObject()
bObject.intCol = 1
bObject.stringCol = "stringVal"
realm.addObject(bObject)
realm.commitWriteTransaction()
let objectFromRealm = BaseClassStringObject.allObjectsInRealm(realm)[0] as BaseClassStringObject
XCTAssertEqual(objectFromRealm.intCol, 1, "Should be 1")
XCTAssertEqual(objectFromRealm.stringCol!, "stringVal", "Should be stringVal")
}
func testCreateOrUpdate() {
let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithObject(["string", 1])
let objects = SwiftPrimaryStringObject.allObjects();
XCTAssertEqual(objects.count, 1, "Should have 1 object");
XCTAssertEqual((objects[0] as SwiftPrimaryStringObject).intCol, 1, "Value should be 1");
SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithObject(["stringCol": "string2", "intCol": 2])
XCTAssertEqual(objects.count, 2, "Should have 2 objects")
SwiftPrimaryStringObject.createOrUpdateInDefaultRealmWithObject(["string", 3])
XCTAssertEqual(objects.count, 2, "Should have 2 objects")
XCTAssertEqual((objects[0] as SwiftPrimaryStringObject).intCol, 3, "Value should be 3");
realm.commitWriteTransaction()
}
}
| apache-2.0 | 2ce5e23b4d547482ed66df440c8bd6c7 | 42.264286 | 130 | 0.677563 | 5.107083 | false | true | false | false |
IamAlchemist/DemoDynamicCollectionView | DemoDynamicCollectionView/CalendarDataSource.swift | 1 | 2492 | //
// CalendarDataSource.swift
// DemoDynamicCollectionView
//
// Created by Wizard Li on 1/11/16.
// Copyright © 2016 morgenworks. All rights reserved.
//
import UIKit
class CalendarDataSource : NSObject, UICollectionViewDataSource {
var configureCell : ((cell: CalendarEventCell, event: CalendarEvent) -> Void)?
var configureHeaderView : ((headerView : CalendarHeaderView, kind : String, indexPath : NSIndexPath) -> Void)?
var events = [CalendarEvent]()
override init() {
super.init()
generateSampleData()
}
func generateSampleData()
{
for idx in 0..<20 {
var event = SampleCalendarEvent.randomEvent();
event.title = "E \(idx)"
events.append(event)
}
}
func eventAtIndexPath(indexPath: NSIndexPath) -> CalendarEvent {
return events[indexPath.item]
}
func indexPathsOfEventsBetweenMinDayIndex(minDayIndex: Int, maxDayIndex: Int, minStartHour: Int, maxStartHour: Int) -> [NSIndexPath]
{
var result = [NSIndexPath]()
for (idx, event) in events.enumerate()
{
if event.day >= minDayIndex && event.day <= maxDayIndex && event.startHour >= minStartHour && event.startHour <= maxStartHour
{
result.append(NSIndexPath(forItem: idx, inSection: 0))
}
}
return result
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return events.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CalendarEventCell", forIndexPath: indexPath) as! CalendarEventCell
let event = events[indexPath.item]
configureCell?(cell: cell, event: event)
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView
{
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier:"CalendarHeaderView", forIndexPath: indexPath) as! CalendarHeaderView
configureHeaderView?(headerView: headerView, kind: kind, indexPath: indexPath)
return headerView
}
}
| mit | 636650b2bfbbd71f0f0677fb9782617f | 32.213333 | 174 | 0.657166 | 5.438865 | false | true | false | false |
NUKisZ/MyTools | MyTools/MyTools/Tools/LaunchADView/ADView.swift | 1 | 6400 | //
// ADView.swift
// LaunchAD
//
// Created by zhangk on 17/1/9.
// Copyright © 2017年 zhangk. All rights reserved.
//
import UIKit
private let kAdImageName = "adImageNmae"
private let kAdUrl = "adUrl"
class ADView: UIView {
open var showTime:Int=5
private var adView=UIImageView()
private var countBtn=UIButton()
private var countTimer:Timer?
private var count:Int!
private var imPath:String!
private var imgUrl:String!
private var adUrl:String!
private var clickAdUrl:String!
private var clickImg:((String) -> Void)!
init(frame: CGRect,imagedUrl:String,ad:String,clikImage:@escaping (String)->Void) {
super.init(frame: frame)
clickImg = clikImage
imgUrl = imagedUrl
adUrl = ad
adView = UIImageView.init(frame: frame)
adView.isUserInteractionEnabled = true
adView.contentMode = UIViewContentMode.scaleAspectFill
adView.clipsToBounds = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(pushToAd))
adView.addGestureRecognizer(tap)
let btnW = 60
let btnH = 30
countBtn = UIButton.init(frame: CGRect(x: Int(kScreenWidth) - btnW - 24, y: btnH, width: btnW, height: btnH))
countBtn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
countBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
countBtn.setTitleColor(UIColor.white, for: .normal)
countBtn.backgroundColor = UIColor(red: 38/255.0, green: 38/255.0, blue: 38/255.0, alpha: 0.6)
countBtn.layer.cornerRadius = 4
addSubview(adView)
addSubview(countBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public class func clear()->Bool{
kUserDefaults.removeObject(forKey: kAdUrl)
kUserDefaults.removeObject(forKey: kAdImageName)
kUserDefaults.removeObject(forKey: "ADModel")
kUserDefaults.synchronize()
let flag = CacheTool.clearCache()
if kUserDefaults.value(forKey: kAdUrl)==nil && kUserDefaults.value(forKey: kAdImageName) == nil && flag{
return true
}
return false
}
public func show(){
if imageExist(){
count = showTime
countBtn.setTitle(String(format: "跳过%@", "\(count!)"), for: .normal)
adView.image = UIImage.init(contentsOfFile: imPath)
clickAdUrl = kUserDefaults.value(forKey: kAdUrl) as! String
startTimer()
let window = UIApplication.shared.keyWindow!
window.addSubview(self)
}
setNewADImgUrl(imgUrl: imgUrl)
}
private func imageExist()->Bool{
if kUserDefaults.value(forKey: kAdImageName) == nil || kUserDefaults.value(forKey: kAdUrl) == nil{
return false
}
imPath = getFilePathWithImageName(imageName: kUserDefaults.value(forKey: kAdImageName)as! String)
let fileManager = FileManager.default
let isExist = fileManager.fileExists(atPath: imPath)
return isExist
}
@objc private func countDown(){
count=count-1
let title = String(format: "跳过%@", "\(count!)")
countBtn.setTitle(title, for: .normal)
if count == 0{
dismiss()
}
}
@objc private func pushToAd(){
if (clickAdUrl != nil){
clickImg(clickAdUrl)
dismiss()
}
}
@objc private func dismiss(){
countTimer?.invalidate()
countTimer = nil
UIView.animate(withDuration: 0.3, animations: {
[weak self] in
self?.alpha = 0
}) {
[weak self]
(finished) in
self?.removeFromSuperview()
}
}
private func setNewADImgUrl(imgUrl:String){
let imgName = NSString(string: imgUrl).lastPathComponent
let filePath = getFilePathWithImageName(imageName: imgName)
let fileManager = FileManager.default
let isExist = fileManager.fileExists(atPath: filePath)
if (!isExist){
downloadAdImageWithUrl(imageUrl: imgUrl, imageName: imgName)
}
}
private func downloadAdImageWithUrl(imageUrl:String,imageName:String){
DispatchQueue.global(qos: .default).async {
//下载
let url = URL(string: imageUrl)
let data = try? Data(contentsOf: url!)
if data==nil{
print("广告图片保存失败")
return
}
let image = UIImage(data: data!)
let filePath = self.getFilePathWithImageName(imageName: imageName)
do{
//print(filePath)
try UIImagePNGRepresentation(image!)?.write(to: URL(fileURLWithPath: filePath), options: .atomic)
//print("保存成功")
self.deleteOldImage()
kUserDefaults.setValue(imageName, forKey: kAdImageName)
kUserDefaults.setValue(self.adUrl, forKey: kAdUrl)
kUserDefaults.synchronize()
}catch{
print(error)
print("广告图片保存失败")
}
}
}
private func startTimer(){
count = showTime
if (countTimer == nil){
countTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
}
RunLoop.main.add(countTimer!, forMode: .commonModes)
}
private func getFilePathWithImageName(imageName:String)->String{
let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
let imagePath = cachesPath!+"/"+imageName
return imagePath
}
private func deleteOldImage(){
let imageName = kUserDefaults.value(forKey: kAdImageName)
if ((imageName) != nil){
let imgPath = getFilePathWithImageName(imageName: imageName as! String)
let fileManager = FileManager.default
do {
try fileManager.removeItem(atPath: imgPath)
} catch {
}
}
}
}
| mit | ec35b13e3028b2fa989ad72652c42687 | 33.672131 | 140 | 0.589441 | 4.865798 | false | false | false | false |
NUKisZ/MyTools | MyTools/MyTools/Class/Playground/MyPlayground.playground/Contents.swift | 1 | 643 | //: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
var r = arc4random()%4
var str = "Hello, playground"
var ss = "aaa"
var i = 4
var j = 5
var k = i + j
let btn = UIButton(type: .system)
btn.tag = 99
print(btn.tag)
print(UIFont.Weight.medium)
class SView :UIView{
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let sView = SView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
sView.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = sView
| mit | 77187a5f104b7a80cf90887eed9c9a33 | 22.814815 | 67 | 0.676516 | 3.331606 | false | false | false | false |
kzaher/RxSwift | RxCocoa/macOS/NSTextView+Rx.swift | 7 | 2909 | //
// NSTextView+Rx.swift
// RxCocoa
//
// Created by Cee on 8/5/18.
// Copyright © 2018 Krunoslav Zaher. All rights reserved.
//
#if os(macOS)
import Cocoa
import RxSwift
/// Delegate proxy for `NSTextView`.
///
/// For more information take a look at `DelegateProxyType`.
open class RxTextViewDelegateProxy: DelegateProxy<NSTextView, NSTextViewDelegate>, DelegateProxyType, NSTextViewDelegate {
#if compiler(>=5.2)
/// Typed parent object.
///
/// - note: Since Swift 5.2 and Xcode 11.4, Apple have suddenly
/// disallowed using `weak` for NSTextView. For more details
/// see this GitHub Issue: https://git.io/JvSRn
public private(set) var textView: NSTextView?
#else
/// Typed parent object.
public weak private(set) var textView: NSTextView?
#endif
/// Initializes `RxTextViewDelegateProxy`
///
/// - parameter textView: Parent object for delegate proxy.
init(textView: NSTextView) {
self.textView = textView
super.init(parentObject: textView, delegateProxy: RxTextViewDelegateProxy.self)
}
public static func registerKnownImplementations() {
self.register { RxTextViewDelegateProxy(textView: $0) }
}
fileprivate let textSubject = PublishSubject<String>()
// MARK: Delegate methods
open func textDidChange(_ notification: Notification) {
let textView: NSTextView = castOrFatalError(notification.object)
let nextValue = textView.string
self.textSubject.on(.next(nextValue))
self._forwardToDelegate?.textDidChange?(notification)
}
// MARK: Delegate proxy methods
/// For more information take a look at `DelegateProxyType`.
open class func currentDelegate(for object: ParentObject) -> NSTextViewDelegate? {
object.delegate
}
/// For more information take a look at `DelegateProxyType`.
open class func setCurrentDelegate(_ delegate: NSTextViewDelegate?, to object: ParentObject) {
object.delegate = delegate
}
}
extension Reactive where Base: NSTextView {
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<NSTextView, NSTextViewDelegate> {
RxTextViewDelegateProxy.proxy(for: self.base)
}
/// Reactive wrapper for `string` property.
public var string: ControlProperty<String> {
let delegate = RxTextViewDelegateProxy.proxy(for: self.base)
let source = Observable.deferred { [weak textView = self.base] in
delegate.textSubject.startWith(textView?.string ?? "")
}.take(until: self.deallocated)
let observer = Binder(self.base) { control, value in
control.string = value
}
return ControlProperty(values: source, valueSink: observer.asObserver())
}
}
#endif
| mit | bd24d1452377e8d9fd79c00cfccc45d2 | 29.93617 | 122 | 0.679505 | 4.838602 | false | false | false | false |
tomburns/ios | FiveCalls/FiveCalls/IssuesViewController.swift | 1 | 7701 | //
// IssuesViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/30/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import Crashlytics
import DZNEmptyDataSet
protocol IssuesViewControllerDelegate : class {
func didStartLoadingIssues()
func didFinishLoadingIssues()
}
class IssuesViewController : UITableViewController {
weak var issuesDelegate: IssuesViewControllerDelegate?
var lastLoadResult: IssuesLoadResult?
var isLoading = false
// keep track of when calls are made, so we know if we need to reload any cells
var needToReloadVisibleRowsOnNextAppearance = false
var issuesManager = IssuesManager()
var logs: ContactLogs?
var iPadShareButton: UIButton? { didSet { self.iPadShareButton?.addTarget(self, action: #selector(share), for: .touchUpInside) }}
struct ViewModel {
let issues: [Issue]
}
var viewModel = ViewModel(issues: [])
override func viewDidLoad() {
super.viewDidLoad()
tableView.emptyDataSetDelegate = self
tableView.emptyDataSetSource = self
Answers.logCustomEvent(withName:"Screen: Issues List")
navigationController?.setNavigationBarHidden(true, animated: false)
loadIssues()
tableView.estimatedRowHeight = 75
tableView.rowHeight = UITableViewAutomaticDimension
tableView.tableFooterView = UIView()
NotificationCenter.default.addObserver(forName: .callMade, object: nil, queue: nil) { [weak self] _ in
self?.needToReloadVisibleRowsOnNextAppearance = true
}
NotificationCenter.default.addObserver(self, selector: #selector(madeCall), name: .callMade, object: nil)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
logs = ContactLogs.load()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// only reload rows if we need to. this fixes a rare tableview inconsistency crash we've seen
if needToReloadVisibleRowsOnNextAppearance {
tableView.reloadRows(at: tableView.indexPathsForVisibleRows ?? [], with: .none)
needToReloadVisibleRowsOnNextAppearance = false
}
}
func share(button: UIButton) {
if let nav = self.splitViewController?.viewControllers.last as? UINavigationController, let shareable = nav.viewControllers.last as? IssueShareable {
shareable.shareIssue(from: button)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
func loadIssues() {
isLoading = true
tableView.reloadEmptyDataSet()
issuesDelegate?.didStartLoadingIssues()
issuesManager.userLocation = UserLocation.current
issuesManager.fetchIssues { [weak self] in
self?.issuesLoaded(result: $0)
}
}
private func issuesLoaded(result: IssuesLoadResult) {
isLoading = false
lastLoadResult = result
issuesDelegate?.didFinishLoadingIssues()
if case .success = result {
viewModel = ViewModel(issues: issuesManager.issues)
tableView.reloadData()
} else {
tableView.reloadEmptyDataSet()
}
}
func madeCall() {
logs = ContactLogs.load()
tableView.reloadRows(at: tableView.indexPathsForVisibleRows ?? [], with: .none)
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == R.segue.issuesViewController.issueSegue.identifier, let split = self.splitViewController {
guard let indexPath = tableView.indexPathForSelectedRow else { return true }
let controller = R.storyboard.main.issueDetailViewController()!
controller.issuesManager = issuesManager
controller.issue = issuesManager.issues[indexPath.row]
let nav = UINavigationController(rootViewController: controller)
nav.setNavigationBarHidden(true, animated: false)
split.showDetailViewController(nav, sender: self)
self.iPadShareButton?.isHidden = false
return false
}
return true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let indexPath = tableView.indexPathForSelectedRow else { return }
if let typedInfo = R.segue.issuesViewController.issueSegue(segue: segue) {
typedInfo.destination.issuesManager = issuesManager
typedInfo.destination.issue = viewModel.issues[indexPath.row]
}
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.issues.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let notAButton = BorderedButton(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 26.0))
notAButton.setTitle(R.string.localizable.whatsImportantTitle(), for: .normal)
notAButton.setTitleColor(.fvc_darkBlueText, for: .normal)
notAButton.backgroundColor = .fvc_superLightGray
notAButton.borderWidth = 1
notAButton.borderColor = .fvc_mediumGray
notAButton.topBorder = true
notAButton.bottomBorder = true
return notAButton
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 26.0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.issueCell, for: indexPath)!
let issue = viewModel.issues[indexPath.row]
cell.titleLabel.text = issue.name
if let hasContacted = logs?.hasCompleted(issue: issue.id, allContacts: issue.contacts) {
cell.checkboxView.isChecked = hasContacted
}
return cell
}
}
extension IssuesViewController : DZNEmptyDataSetSource {
private func appropriateErrorMessage(for result: IssuesLoadResult) -> String {
switch result {
case .offline: return R.string.localizable.issueLoadFailedConnection()
case .serverError(_): return R.string.localizable.issueLoadFailedServer()
default:
return ""
}
}
func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
let message = appropriateErrorMessage(for: lastLoadResult ?? .offline)
return NSAttributedString(string: message,
attributes: [
NSFontAttributeName: Appearance.instance.bodyFont
])
}
func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControlState) -> UIImage? {
return #imageLiteral(resourceName: "refresh")
}
}
extension IssuesViewController : DZNEmptyDataSetDelegate {
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
return !isLoading
}
func emptyDataSet(_ scrollView: UIScrollView, didTap button: UIButton) {
loadIssues()
tableView.reloadEmptyDataSet()
}
}
| mit | dd67c05d975acbdbeff774211110e8ea | 34.813953 | 157 | 0.664026 | 5.453258 | false | false | false | false |
DylanModesitt/Picryption_iOS | Pods/Eureka/Source/Validations/RuleURL.swift | 4 | 2042 | // RuleURL.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
public struct RuleURL: RuleType {
public init(allowsEmpty: Bool = true, requiresProtocol: Bool = false) {}
public var id: String?
public var allowsEmpty = true
public var requiresProtocol = false
public var validationError = ValidationError(msg: "Field value must be an URL!")
public func isValid(value: URL?) -> ValidationError? {
if let value = value, value.absoluteString.isEmpty == false {
let predicate = NSPredicate(format:"SELF MATCHES %@", RegExprPattern.URL.rawValue)
guard predicate.evaluate(with: value.absoluteString) else {
return validationError
}
return nil
}
else if !allowsEmpty {
return validationError
}
return nil
}
}
| mit | 942b5d623d86bc844f2bcdb09a77bb5e | 39.84 | 94 | 0.702253 | 4.715935 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/NewCamera/View/CameraViewfinderBorderView.swift | 1 | 1763 | import UIKit
final class CameraViewfinderBorderView: UIView {
private let topBorderLayer = CALayer()
private let bottomBorderLayer = CALayer()
private let leftBorderLayer = CALayer()
private let rightBorderLayer = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
alpha = 0.5
topBorderLayer.backgroundColor = UIColor.white.cgColor
bottomBorderLayer.backgroundColor = UIColor.white.cgColor
leftBorderLayer.backgroundColor = UIColor.white.cgColor
rightBorderLayer.backgroundColor = UIColor.white.cgColor
layer.addSublayer(topBorderLayer)
layer.addSublayer(bottomBorderLayer)
layer.addSublayer(leftBorderLayer)
layer.addSublayer(rightBorderLayer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
topBorderLayer.frame = CGRect(
left: bounds.left + 6,
right: bounds.right - 6,
top: bounds.top + 16,
height: 1
)
bottomBorderLayer.frame = CGRect(
left: bounds.left + 6,
right: bounds.right - 6,
bottom: bounds.bottom - 16,
height: 1
)
leftBorderLayer.frame = CGRect(
x: bounds.left + 16,
y: bounds.top + 6,
width: 1,
height: bounds.height - 6 * 2
)
rightBorderLayer.frame = CGRect(
x: bounds.right - 16 - 1,
y: bounds.top + 6,
width: 1,
height: bounds.height - 6 * 2
)
}
}
| mit | a6daa301ff13fea2aa8f6fbf13c149b0 | 27.901639 | 65 | 0.563244 | 5.008523 | false | false | false | false |
inevs/CoreDataStore | CoreDataStore/UITableViewController+DataFetching.swift | 1 | 1926 | import UIKit
import CoreData
public extension UITableViewController {
var fetchedResultsController: NSFetchedResultsController? {
return nil
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
if controller == self.fetchedResultsController {
self.tableView.beginUpdates()
}
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
if controller == self.fetchedResultsController {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Move, .Update:
break
}
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
if controller != self.fetchedResultsController {
return
}
switch type {
case .Insert:
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
if let cell = self.tableView.cellForRowAtIndexPath(indexPath!) {
self.configureCell(cell, atIndexPath: indexPath!)
}
case .Move:
self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
if controller != self.fetchedResultsController {
return
}
self.tableView.endUpdates()
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
}
}
| mit | 6fae0ea3076bcd50f58fd1807fcaacc7 | 31.644068 | 208 | 0.774143 | 4.863636 | false | false | false | false |
ioscreator/ioscreator | IOS11IndexedTableViewTutorial/IOS11IndexedTableViewTutorial/TableViewController.swift | 1 | 2444 | //
// TableViewController.swift
// IOS11IndexedTableViewTutorial
//
// Created by Arthur Knopper on 11/09/2017.
// Copyright © 2017 Arthur Knopper. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
var carsDictionary = [String: [String]]()
var carSectionTitles = [String]()
var cars = [String]()
override func viewDidLoad() {
super.viewDidLoad()
cars = ["Audi", "Aston Martin","BMW", "Bugatti", "Bentley","Chevrolet", "Cadillac","Dodge","Ferrari", "Ford","Honda","Jaguar","Lamborghini","Mercedes", "Mazda","Nissan","Porsche","Rolls Royce","Toyota","Volkswagen"]
for car in cars {
let carKey = String(car.prefix(1))
if var carValues = carsDictionary[carKey] {
carValues.append(car)
carsDictionary[carKey] = carValues
} else {
carsDictionary[carKey] = [car]
}
}
carSectionTitles = [String](carsDictionary.keys)
carSectionTitles = carSectionTitles.sorted(by: { $0 < $1 })
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return carSectionTitles.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let carKey = carSectionTitles[section]
if let carValues = carsDictionary[carKey] {
return carValues.count
}
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
// Configure the cell...
let carKey = carSectionTitles[indexPath.section]
if let carValues = carsDictionary[carKey] {
cell.textLabel?.text = carValues[indexPath.row]
}
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return carSectionTitles[section]
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return carSectionTitles
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | bcc5e5812ecdb724a2b89e82295c6569 | 29.160494 | 223 | 0.619321 | 4.97556 | false | false | false | false |
BeanstalkData/beanstalk-ios-sdk | Example/Pods/ObjectMapper/ObjectMapper/Core/Mappable.swift | 3 | 3225 | //
// Mappable.swift
// ObjectMapper
//
// Created by Scott Hoyt on 10/25/15.
// Copyright © 2015 hearst. All rights reserved.
//
import Foundation
/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead
public protocol BaseMappable {
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
mutating func mapping(map: Map)
}
public protocol Mappable: BaseMappable {
/// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
init?(_ map: Map)
}
public protocol StaticMappable: BaseMappable {
/// This is function that can be used to:
/// 1) provide an existing cached object to be used for mapping
/// 2) return an object of another class (which conforms to Mappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping
static func objectForMapping(map: Map) -> BaseMappable?
}
public extension BaseMappable {
/// Initializes object from a JSON String
public init?(JSONString: String) {
if let obj: Self = Mapper().map(JSONString) {
self = obj
} else {
return nil
}
}
/// Initializes object from a JSON Dictionary
public init?(JSON: [String: AnyObject]) {
if let obj: Self = Mapper().map(JSON) {
self = obj
} else {
return nil
}
}
/// Returns the JSON Dictionary for the object
public func toJSON() -> [String: AnyObject] {
return Mapper().toJSON(self)
}
/// Returns the JSON String for the object
public func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
public extension Array where Element: BaseMappable {
/// Initialize Array from a JSON String
public init?(JSONString: String) {
if let obj: [Element] = Mapper().mapArray(JSONString) {
self = obj
} else {
return nil
}
}
/// Initialize Array from a JSON Array
public init?(JSONArray: [[String: AnyObject]]) {
if let obj: [Element] = Mapper().mapArray(JSONArray) {
self = obj
} else {
return nil
}
}
/// Returns the JSON Array
public func toJSON() -> [[String: AnyObject]] {
return Mapper().toJSONArray(self)
}
/// Returns the JSON String for the object
public func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
public extension Set where Element: BaseMappable {
/// Initializes a set from a JSON String
public init?(JSONString: String) {
if let obj: Set<Element> = Mapper().mapSet(JSONString) {
self = obj
} else {
return nil
}
}
/// Initializes a set from JSON
public init?(JSONArray: [[String: AnyObject]]) {
if let obj: Set<Element> = Mapper().mapSet(JSONArray) {
self = obj
} else {
return nil
}
}
/// Returns the JSON Set
public func toJSON() -> [[String: AnyObject]] {
return Mapper().toJSONSet(self)
}
/// Returns the JSON String for the object
public func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
| mit | 97a79ecfc9c8412bf6008410019195ff | 25.866667 | 204 | 0.693859 | 3.792941 | false | false | false | false |
ahoppen/swift | test/Sanitizers/asan/asan.swift | 11 | 1245 | // RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address -o %t_asan-binary
// RUN: %target-codesign %t_asan-binary
// RUN: env %env-ASAN_OPTIONS=abort_on_error=0 not %target-run %t_asan-binary 2>&1 | %FileCheck %s
// ODR Indicator variant
// RUN: %target-swiftc_driver %s -target %sanitizers-target-triple -g -sanitize=address \
// RUN: -sanitize-address-use-odr-indicator -o %t_asan-binary-odr-indicator
// RUN: %target-codesign %t_asan-binary-odr-indicator
// RUN: env %env-ASAN_OPTIONS=abort_on_error=0 not %target-run \
// RUN: %t_asan-binary-odr-indicator 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: asan_runtime
// Make sure we can handle swifterror. LLVM's address sanitizer pass needs to
// ignore swifterror addresses.
enum MyError : Error {
case A
}
public func foobar(_ x: Int) throws {
if x == 0 {
throw MyError.A
}
}
public func call_foobar() {
do {
try foobar(1)
} catch(_) {
}
}
// Test AddressSanitizer execution end-to-end.
var a = UnsafeMutablePointer<Int>.allocate(capacity: 1)
a.initialize(to: 5)
a.deinitialize(count: 1)
a.deallocate()
print(a.pointee)
a.deinitialize(count: 1)
a.deallocate()
// CHECK: AddressSanitizer: heap-use-after-free
| apache-2.0 | 94695ea9e620e0b6ba5a670e01f948cd | 26.666667 | 105 | 0.700402 | 3.04401 | false | false | false | false |
huangboju/Moots | Examples/Lumia/Lumia/Component/ClassCopyIvarList/ClassCopyIvarListVC.swift | 1 | 3580 | //
// ClassCopyIvarListVC.swift
// Lumia
//
// Created by xiAo_Ju on 2019/12/31.
// Copyright © 2019 黄伯驹. All rights reserved.
//
import UIKit
class ClassCopyIvarListVC: ListVC {
override func viewDidLoad() {
super.viewDidLoad()
title = "属性查看器"
rows = [
Row<FluidInterfacesCell>(viewData: Interface(name: "UIPickerView", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIDatePicker", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UITextField", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UISlider", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIImageView", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UITabBarItem", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIActivityIndicatorView", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIBarButtonItem", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UILabel", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UINavigationBar", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIProgressView", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIAlertAction", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIViewController", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIRefreshControl", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIAlertController", segue: .segue(ClassCopyIvarDetailVC.self))),
Row<FluidInterfacesCell>(viewData: Interface(name: "UIScrollView", segue: .segue(ClassCopyIvarDetailVC.self))),
]
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let item: Interface = rows[indexPath.row].cellItem()
guard let segue = item.segue else { return }
show(segue) { (vc: ClassCopyIvarDetailVC) in
vc.className = item.name
}
}
}
class ClassCopyIvarDetailVC: ListVC {
var className: String? {
didSet {
title = className
if let v = className {
rows = classCopyIvarList(v)
}
}
}
// MARK: 查看类中的隐藏属性
fileprivate func classCopyIvarList(_ className: String) -> [RowType] {
var classArray: [RowType] = []
let classOjbect: AnyClass! = objc_getClass(className) as? AnyClass
var icount: CUnsignedInt = 0
let ivars = class_copyIvarList(classOjbect, &icount)
print("icount == \(icount)")
for i in 0 ... (icount - 1) {
let memberName = String(utf8String: ivar_getName((ivars?[Int(i)])!)!) ?? ""
print("memberName == \(memberName)")
classArray.append(Row<FluidInterfacesCell>(viewData: Interface(name: memberName)))
}
return classArray
}
}
| mit | 52e36cde9fc78ca5ed2112bec36952cf | 45.038961 | 134 | 0.665162 | 4.862826 | false | false | false | false |
natecook1000/WWDC | WWDC/Theme.swift | 2 | 1149 | //
// Theme.swift
// WWDC
//
// Created by Guilherme Rambo on 18/04/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Cocoa
private let _SharedThemeInstance = Theme()
class Theme: NSObject {
class var WWDCTheme: Theme {
return _SharedThemeInstance
}
let separatorColor = NSColor.grayColor().colorWithAlphaComponent(0.3)
let backgroundColor = NSColor.whiteColor()
let fillColor = NSColor(calibratedRed: 0, green: 0.49, blue: 1, alpha: 1)
private var cachedImages: [String:CGImage] = [:]
private let starImageName = "star"
private let starOutlineImageName = "star-outline"
var starImage: CGImage {
get {
return getImage(starImageName)
}
}
var starOutlineImage: CGImage {
get {
return getImage(starOutlineImageName)
}
}
private func getImage(name: String) -> CGImage {
if let image = cachedImages[name] {
return image
} else {
cachedImages[name] = NSImage(named: name)?.CGImage
return cachedImages[name]!
}
}
} | bsd-2-clause | e6834a6495b16e0c56a7439fe1750123 | 22.958333 | 77 | 0.607485 | 4.436293 | false | false | false | false |
mzaks/Entitas-Swift | Entitas/Matcher.swift | 2 | 5248 | //
// Matcher.swift
// Entitas
//
// Created by Maxim Zaks on 21.12.14.
// Copyright (c) 2014 Maxim Zaks. All rights reserved.
//
public func == (lhs: Matcher, rhs: Matcher) -> Bool {
return lhs.componentIds == rhs.componentIds && lhs.type == rhs.type
}
/// Matcher is used to identify if an entity has the desired components.
public struct Matcher : Hashable {
public let componentIds : Set<ComponentId>
public enum MatcherType{
case All, Any
}
public let type : MatcherType
public static func All(componentIds : ComponentId...) -> Matcher {
return Matcher(componentIds: componentIds, type: .All)
}
public static func Any(componentIds : ComponentId...) -> Matcher {
return Matcher(componentIds: componentIds, type: .Any)
}
init(componentIds : [ComponentId], type : MatcherType) {
self.componentIds = Set(componentIds)
self.type = type
}
public func isMatching(entity : Entity) -> Bool {
switch type {
case .All : return isAllMatching(entity)
case .Any : return isAnyMatching(entity)
}
}
func isAllMatching(entity : Entity) -> Bool {
for cid in componentIds {
if(!entity.hasComponent(cid)){
return false
}
}
return true
}
func isAnyMatching(entity : Entity) -> Bool {
for cid in componentIds {
if(entity.hasComponent(cid)){
return true
}
}
return false
}
public var hashValue: Int {
get {
return componentIds.hashValue
}
}
}
func allOf(componentIds : ComponentId...) -> AllOfMatcher {
return AllOfMatcher(allOf: Set(componentIds))
}
func anyOf(componentIds : ComponentId...) -> AnyOfMatcher {
return AnyOfMatcher(allOf: [], anyOf: Set(componentIds))
}
public protocol _Matcher : Hashable {
func isMatching(entity : Entity) -> Bool
}
public func == (lhs: AllOfMatcher, rhs: AllOfMatcher) -> Bool {
return lhs.allOf == rhs.allOf
}
public struct AllOfMatcher : _Matcher {
private let allOf : Set<ComponentId>
private init(allOf : Set<ComponentId>){
self.allOf = allOf
}
public func anyOf(componentIds : ComponentId...) -> AnyOfMatcher {
return AnyOfMatcher(allOf: self.allOf, anyOf: Set(componentIds))
}
public func noneOf(componentIds : ComponentId...) -> NoneOfMatcher {
return NoneOfMatcher(allOf: self.allOf, anyOf: [], noneOf: Set(componentIds))
}
public func isMatching(entity: Entity) -> Bool {
return isAllMatching(entity, componentIds: allOf)
}
public var hashValue: Int {
return allOf.hashValue
}
}
public func == (lhs: AnyOfMatcher, rhs: AnyOfMatcher) -> Bool {
return lhs.allOf == rhs.allOf && lhs.anyOf == rhs.anyOf
}
public struct AnyOfMatcher : _Matcher {
private let allOf : Set<ComponentId>
private let anyOf : Set<ComponentId>
private init(allOf : Set<ComponentId>, anyOf : Set<ComponentId>){
self.allOf = allOf
self.anyOf = anyOf
}
public func noneOf(componentIds : ComponentId...) -> NoneOfMatcher {
return NoneOfMatcher(allOf: self.allOf, anyOf: self.anyOf, noneOf: Set(componentIds))
}
public func isMatching(entity: Entity) -> Bool {
return isAllMatching(entity, componentIds: allOf) && isAnyMatching(entity, componentIds: anyOf)
}
public var hashValue: Int {
return allOf.hashValue ^ anyOf.hashValue
}
}
public func == (lhs: NoneOfMatcher, rhs: NoneOfMatcher) -> Bool {
return lhs.allOf == rhs.allOf && lhs.anyOf == rhs.anyOf && lhs.noneOf == rhs.noneOf
}
public struct NoneOfMatcher : _Matcher {
private let allOf : Set<ComponentId>
private let anyOf : Set<ComponentId>
private let noneOf : Set<ComponentId>
private init(allOf : Set<ComponentId>, anyOf : Set<ComponentId>, noneOf : Set<ComponentId>){
self.allOf = allOf
self.anyOf = anyOf
self.noneOf = noneOf
}
public func isMatching(entity: Entity) -> Bool {
return isAllMatching(entity, componentIds: allOf) && isAnyMatching(entity, componentIds: anyOf) && isNoneMatching(entity, componentIds: noneOf)
}
public var hashValue: Int {
return allOf.hashValue ^ anyOf.hashValue ^ noneOf.hashValue
}
}
private func isAllMatching(entity : Entity, componentIds : Set<ComponentId>) -> Bool {
if componentIds.isEmpty {
return true
}
for cid in componentIds {
if(!entity.hasComponent(cid)){
return false
}
}
return true
}
private func isAnyMatching(entity : Entity, componentIds : Set<ComponentId>) -> Bool {
if componentIds.isEmpty {
return true
}
for cid in componentIds {
if(entity.hasComponent(cid)){
return true
}
}
return false
}
private func isNoneMatching(entity : Entity, componentIds : Set<ComponentId>) -> Bool {
for cid in componentIds {
if(entity.hasComponent(cid)){
return false
}
}
return true
}
| mit | b940da222135bb11539bd9324dbcd7be | 25.912821 | 151 | 0.618331 | 4.619718 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.