hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
33d1897139f34ec36daf3fa44ec2f57a1b4c773c | 16,697 | //
// XML.swift
// AWSSDKSwift
//
// Created by Adam Fowler on 2019/06/15
//
// Implemented to replace the XML Foundation classes. This was initially required as there is no implementation of the Foundation XMLNode classes in iOS. This is also here because the implementation of XMLNode in Linux Swift 4.2 was causing crashes. Whenever an XMLDocument was deleted all the underlying CoreFoundation objects were deleted. This meant if you still had a reference to a XMLElement from that document, while it was still valid the underlying CoreFoundation object had been deleted.
#if canImport(FoundationXML)
import FoundationXML
#endif
import Foundation
// I have placed everything inside a holding XML class to avoid name clashes with the Foundation version. Otherwise this class reflects the behaviour of the Foundation classes as close as possible with the exceptions of, I haven't implemented queries, DTD, also XMLNodes do not contain an object reference. Also the node creation function in XMLNode return XMLNode instead of Any.
public class XML {
/// base class for all types of XML.Node
public class Node {
/// XML node type
public enum Kind {
case document
case element
case text
case attribute
case namespace
case comment
}
/// defines the type of xml node
public let kind : Kind
public var name : String?
public var stringValue : String?
public fileprivate(set) var children : [XML.Node]?
public weak var parent : XML.Node?
init(kind: Kind) {
self.kind = kind
self.children = nil
self.parent = nil
}
fileprivate init(_ kind: Kind, name: String? = nil, stringValue: String? = nil) {
self.kind = kind
self.name = name
self.stringValue = stringValue
self.children = nil
self.parent = nil
}
/// create XML document node
public static func document() -> XML.Node {
return XML.Document()
}
/// create XML element node
public static func element(withName: String, stringValue: String? = nil) -> XML.Node {
return XML.Element(name: withName, stringValue: stringValue)
}
/// create raw text node
public static func text(stringValue: String) -> XML.Node {
return XML.Node(.text, stringValue: stringValue)
}
/// create XML attribute node
public static func attribute(withName: String, stringValue: String) -> XML.Node {
return XML.Node(.attribute, name: withName, stringValue: stringValue)
}
/// create XML namespace node
public static func namespace(withName: String? = nil, stringValue: String) -> XML.Node {
return XML.Node(.namespace, name: withName, stringValue: stringValue)
}
/// create XML comment node
public static func comment(stringValue: String) -> XML.Node {
return XML.Node(.comment, stringValue: stringValue)
}
/// return child node at index
private func child(at index: Int) -> XML.Node? {
return children?[index]
}
/// return number of children
public var childCount : Int { get {return children?.count ?? 0}}
/// detach XML node from its parent
public func detach() {
parent?.detach(child:self)
parent = nil
}
/// detach child XML Node
fileprivate func detach(child: XML.Node) {
children?.removeAll(where: {$0 === child})
}
/// return children of a specific kind
func children(of kind: Kind) -> [XML.Node]? {
return children?.compactMap { $0.kind == kind ? $0 : nil }
}
private static let xmlEncodedCharacters : [String.Element: String] = [
"&": "&",
"<": "<",
">": ">",
]
/// encode text with XML markup
private static func xmlEncode(string: String) -> String {
var newString = ""
for c in string {
if let replacement = XML.Node.xmlEncodedCharacters[c] {
newString.append(contentsOf:replacement)
} else {
newString.append(c)
}
}
return newString
}
/// output formatted XML
public var xmlString : String {
switch kind {
case .text:
if let stringValue = stringValue {
return XML.Node.xmlEncode(string: stringValue)
}
return ""
case .attribute:
if let name = name {
return "\(name)=\"\(stringValue ?? "")\""
} else {
return ""
}
case .comment:
if let stringValue = stringValue {
return "<!--\(stringValue)-->"
} else {
return ""
}
case .namespace:
var string = "xmlns"
if let name = name, name != "" {
string += ":\(name)"
}
string += "=\"\(stringValue ?? "")\""
return string
default:
return ""
}
}
}
/// XML Document class
public class Document : XML.Node {
public var version : String?
public var characterEncoding : String?
public init() {
super.init(.document)
}
public init(rootElement: XML.Element) {
super.init(.document)
setRootElement(rootElement)
}
/// initialise with a block XML data
public init(data: Data) throws {
super.init(.document)
do {
let element = try XML.Element(xmlData: data)
setRootElement(element)
} catch ParsingError.emptyFile {
}
}
/// set the root element of the document
public func setRootElement(_ rootElement: XML.Element) {
for child in self.children ?? [] {
child.parent = nil
}
children = [rootElement]
}
/// return the root element
public func rootElement() -> XML.Element? {
return children?.first {return ($0 as? XML.Element) != nil} as? XML.Element
}
/// output formatted XML
override public var xmlString: String {
var string = "<?xml version=\"\(version ?? "1.0")\" encoding=\"\(characterEncoding ?? "UTF-8")\"?>"
if let rootElement = rootElement() {
string += rootElement.xmlString
}
return string
}
/// output formatted XML as Data
public var xmlData : Data { return xmlString.data(using: .utf8) ?? Data()}
}
/// XML Element class
public class Element : XML.Node {
/// array of attributes attached to XML ELement
public fileprivate(set) var attributes : [XML.Node]?
/// array of namespaces attached to XML ELement
public fileprivate(set) var namespaces : [XML.Node]?
public init(name: String, stringValue: String? = nil) {
super.init(.element, name: name)
self.stringValue = stringValue
}
/// initialise XML.Element from xml data
public init(xmlData: Data) throws {
super.init(.element)
let parser = XMLParser(data: xmlData)
let parserDelegate = ParserDelegate()
parser.delegate = parserDelegate
if !parser.parse() {
if let error = parserDelegate.error {
throw error
}
} else if let rootElement = parserDelegate.rootElement {
// copy contents of rootElement
self.setChildren(rootElement.children)
self.setAttributes(rootElement.attributes)
self.setNamespaces(rootElement.namespaces)
self.name = rootElement.name
} else {
throw ParsingError.emptyFile
}
}
/// initialise XML.Element from xml string
convenience public init(xmlString: String) throws {
let data = xmlString.data(using: .utf8)!
try self.init(xmlData: data)
}
/// return children XML elements
public func elements(forName: String) -> [XML.Element] {
return children?.compactMap {
if let element = $0 as? XML.Element, element.name == forName {
return element
}
return nil
} ?? []
}
/// return child text nodes all concatenated together
public override var stringValue : String? {
get {
let textNodes = children(of:.text)
let text = textNodes?.reduce("", { return $0 + ($1.stringValue ?? "")}) ?? ""
return text
}
set(value) {
children?.removeAll {$0.kind == .text}
if let value = value {
addChild(XML.Node(.text, stringValue: value))
}
}
}
/// add a child node to the xml element
public func addChild(_ node: XML.Node) {
assert(node.kind != .namespace && node.kind != .attribute && node.kind != .document)
if children == nil {
children = [node]
} else {
children!.append(node)
}
node.parent = self
}
/// insert a child node at position in the list of children nodes
public func insertChild(node: XML.Node, at index: Int) {
assert(node.kind != .namespace && node.kind != .attribute && node.kind != .document)
children?.insert(node, at: index)
node.parent = self
}
/// set this elements children nodes
public func setChildren(_ children: [XML.Node]?) {
for child in self.children ?? [] {
child.parent = nil
}
self.children = children
for child in self.children ?? [] {
assert(child.kind != .namespace && child.kind != .attribute && child.kind != .document)
child.parent = self
}
}
/// return attribute attached to element
public func attribute(forName: String) -> XML.Node? {
return attributes?.first {
if $0.name == forName {
return true
}
return false
}
}
/// add an attribute to an element. If one with this name already exists it is replaced
public func addAttribute(_ node : XML.Node) {
assert(node.kind == .attribute)
if let name = node.name, let attributeNode = attribute(forName: name) {
attributeNode.detach()
}
if attributes == nil {
attributes = [node]
} else {
attributes!.append(node)
}
node.parent = self
}
/// set this elements children nodes
public func setAttributes(_ attributes: [XML.Node]?) {
for attribute in self.attributes ?? [] {
attribute.parent = nil
}
self.attributes = attributes
for attribute in self.attributes ?? [] {
assert(attribute.kind == .attribute)
attribute.parent = self
}
}
/// return namespace attached to element
public func namespace(forName: String?) -> XML.Node? {
return namespaces?.first {
if $0.name == forName {
return true
}
return false
}
}
/// add a namespace to an element. If one with this name already exists it is replaced
public func addNamespace(_ node : XML.Node) {
assert(node.kind == .namespace)
if let attributeNode = namespace(forName: node.name) {
attributeNode.detach()
}
if namespaces == nil {
namespaces = [node]
} else {
namespaces!.append(node)
}
node.parent = self
}
/// set this elements children nodes
public func setNamespaces(_ namespaces: [XML.Node]?) {
for namespace in self.namespaces ?? [] {
namespace.parent = nil
}
self.namespaces = namespaces
for namespace in self.namespaces ?? [] {
assert(namespace.kind == .namespace)
namespace.parent = self
}
}
/// detach child XML Node
fileprivate override func detach(child: XML.Node) {
switch child.kind {
case .attribute:
attributes?.removeAll(where: {$0 === child})
case .namespace:
namespaces?.removeAll(where: {$0 === child})
default:
super.detach(child: child)
}
}
/// return formatted XML
override public var xmlString : String {
var string = ""
string += "<\(name!)"
string += namespaces?.map({" "+$0.xmlString}).joined(separator:"") ?? ""
string += attributes?.map({" "+$0.xmlString}).joined(separator:"") ?? ""
string += ">"
for node in children ?? [] {
string += node.xmlString
}
string += "</\(name!)>"
return string
}
}
/// XML parsing errors
enum ParsingError : Error {
case emptyFile
var localizedDescription: String {
switch self {
case .emptyFile:
return "File contained nothing"
}
}
}
/// parser delegate used in XML parsing
fileprivate class ParserDelegate : NSObject, XMLParserDelegate {
var rootElement : XML.Element?
var currentElement : XML.Element?
var error : Error?
override init() {
self.currentElement = nil
self.rootElement = nil
super.init()
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
let element = XML.Element(name: elementName)
for attribute in attributeDict {
element.addAttribute(XML.Node(.attribute, name: attribute.key, stringValue: attribute.value))
}
if rootElement == nil {
rootElement = element
}
currentElement?.addChild(element)
currentElement = element
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement = currentElement?.parent as? XML.Element
}
func parser(_ parser: XMLParser, foundCharacters: String) {
// if string with white space removed still has characters, add text node
if foundCharacters.components(separatedBy: .whitespacesAndNewlines).joined().count > 0 {
currentElement?.addChild(XML.Node.text(stringValue: foundCharacters))
}
}
func parser(_ parser: XMLParser, foundComment comment: String) {
currentElement?.addChild(XML.Node.comment(stringValue: comment))
}
func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
currentElement?.addChild(XML.Node.text(stringValue: String(data: CDATABlock, encoding: .utf8)!))
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
error = parseError
}
func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) {
error = validationError
}
}
}
extension XML.Node : CustomStringConvertible, CustomDebugStringConvertible {
/// CustomStringConvertible protocol
public var description: String {return xmlString}
/// CustomDebugStringConvertible protocol
public var debugDescription: String {return xmlString}
}
| 35.004193 | 497 | 0.537761 |
0137b69f322b1fe4d25238b05dd027ae6686d42e | 1,241 | import Foundation
func deleteCampaignAction(campaign: Campaign, completion: ((_ ok: Bool, _ message: Bool?, _ error: Error?) -> Void)?) {
var request = URLRequest(url: URL(string: "https://dragontide.herokuapp.com/campaign/" + campaign.id)!);
request.httpMethod = "DELETE";
request.addValue("", forHTTPHeaderField: "Accept-Encoding");
request.addValue("application/json", forHTTPHeaderField: "Content-Type");
let session = URLSession(configuration: URLSessionConfiguration.default);
let task = session.dataTask(with: request) { (Data, Response, Error) in
DispatchQueue.main.async {
if let error = Error {
completion?(false, nil, error);
} else if let jsonData = Data {
let result = try? JSONSerialization.jsonObject(with: jsonData) as! [String: AnyObject];
if let jsonResult = result!["ok"] as? Bool {
completion?(true, jsonResult, nil);
}
} else {
let err = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey : "Data could not be requested"]) as Error;
completion?(false, nil, err);
}
}
};
task.resume();
}
| 45.962963 | 135 | 0.60274 |
212c0dde349eb2c3a1cf4ebf075aec51054a5506 | 1,888 | import Foundation
// TODO: Add firstMatch()
// TODO: Add escape()
public struct RegExp: StringPattern {
private let nsRegExp: NSRegularExpression
public init(_ pattern: String, options: NSRegularExpression.Options = []) {
do {
nsRegExp = try NSRegularExpression(pattern: pattern, options: options)
} catch {
preconditionFailure("Illegal regular expression: \(pattern).")
}
}
public func hasMatch(in string: String) -> Bool {
return nsRegExp.numberOfMatches(in: string, options: [], range: NSRange(string.startIndex..., in: string)) > 0
}
public func matches(in string: String) -> [StringMatch] {
let results = nsRegExp.matches(in: string, options: [], range: NSRange(string.startIndex..., in: string))
return results.map { result in
// TODO: optimize here!
var ranges: [Range<String.Index>] = []
for i in 0..<result.numberOfRanges {
ranges.append(Range(result.range(at: i), in: string)!)
}
let match = StringMatch(value: String(string[ranges[0]]), ranges: ranges)
return match
}
}
public func stringByReplacingMatches(in string: String, with replacementTemplate: String) -> String {
return nsRegExp.stringByReplacingMatches(in: string, options: [], range: NSRange(string.startIndex..., in: string), withTemplate: replacementTemplate)
}
public func stringByReplacingMatches(in string: String, replacementHandler: (StringMatch) -> String?) -> String {
var string = string
matches(in: string).reversed().forEach { match in
if let replacement = replacementHandler(match) {
string = string.replacingCharacters(in: match.range, with: replacement)
}
}
return string
}
}
| 35.622642 | 158 | 0.620233 |
9b2fe86b9064551a0699e1273459b9e2500351f5 | 14,354 | //
// TodayTimes.swift
// Tehilim2.0
//
// Created by israel.berezin on 07/07/2020.
//
// To parse the JSON, add this file to your project and do:
//
// let todayTimes = try TodayTimes(json)
//
// To read values from URLs:
//
// let task = URLSession.shared.todayTimesTask(with: url) { todayTimes, response, error in
// if let todayTimes = todayTimes {
// ...
// }
// }
// task.resume()
import Foundation
// MARK: - TodayTimes
class TodayTimes: Codable, Loopable {
var currentTime, engDateString, hebDateString, dayOfWeek: String?
var zmanim: Zmanim?
var dafYomi: DafYomi?
var specialShabbos: Bool?
var parshaShabbos, candleLightingShabbos: String?
enum CodingKeys: String, CodingKey {
case currentTime, engDateString, hebDateString, dayOfWeek, zmanim, dafYomi, specialShabbos
case parshaShabbos = "parsha_shabbos"
case candleLightingShabbos = "candle_lighting_shabbos"
}
init(currentTime: String?, engDateString: String?, hebDateString: String?, dayOfWeek: String?, zmanim: Zmanim?, dafYomi: DafYomi?, specialShabbos: Bool?, parshaShabbos: String?, candleLightingShabbos: String?) {
self.currentTime = currentTime
self.engDateString = engDateString
self.hebDateString = hebDateString
self.dayOfWeek = dayOfWeek
self.zmanim = zmanim
self.dafYomi = dafYomi
self.specialShabbos = specialShabbos
self.parshaShabbos = parshaShabbos
self.candleLightingShabbos = candleLightingShabbos
}
}
// MARK: TodayTimes convenience initializers and mutators
extension TodayTimes {
convenience init(data: Data) throws {
let me = try newJSONDecoder().decode(TodayTimes.self, from: data)
self.init(currentTime: me.currentTime, engDateString: me.engDateString, hebDateString: me.hebDateString, dayOfWeek: me.dayOfWeek, zmanim: me.zmanim, dafYomi: me.dafYomi, specialShabbos: me.specialShabbos, parshaShabbos: me.parshaShabbos, candleLightingShabbos: me.candleLightingShabbos)
}
convenience init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
convenience init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
currentTime: String?? = nil,
engDateString: String?? = nil,
hebDateString: String?? = nil,
dayOfWeek: String?? = nil,
zmanim: Zmanim?? = nil,
dafYomi: DafYomi?? = nil,
specialShabbos: Bool?? = nil,
parshaShabbos: String?? = nil,
candleLightingShabbos: String?? = nil
) -> TodayTimes {
return TodayTimes(
currentTime: currentTime ?? self.currentTime,
engDateString: engDateString ?? self.engDateString,
hebDateString: hebDateString ?? self.hebDateString,
dayOfWeek: dayOfWeek ?? self.dayOfWeek,
zmanim: zmanim ?? self.zmanim,
dafYomi: dafYomi ?? self.dafYomi,
specialShabbos: specialShabbos ?? self.specialShabbos,
parshaShabbos: parshaShabbos ?? self.parshaShabbos,
candleLightingShabbos: candleLightingShabbos ?? self.candleLightingShabbos
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
//
// To read values from URLs:
//
// let task = URLSession.shared.dafYomiTask(with: url) { dafYomi, response, error in
// if let dafYomi = dafYomi {
// ...
// }
// }
// task.resume()
// MARK: - DafYomi
class DafYomi: Codable, Loopable {
var masechta, daf: String?
init(masechta: String?, daf: String?) {
self.masechta = masechta
self.daf = daf
}
}
// MARK: DafYomi convenience initializers and mutators
extension DafYomi {
convenience init(data: Data) throws {
let me = try newJSONDecoder().decode(DafYomi.self, from: data)
self.init(masechta: me.masechta, daf: me.daf)
}
convenience init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
convenience init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
masechta: String?? = nil,
daf: String?? = nil
) -> DafYomi {
return DafYomi(
masechta: masechta ?? self.masechta,
daf: daf ?? self.daf
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
//
// To read values from URLs:
//
// let task = URLSession.shared.zmanimTask(with: url) { zmanim, response, error in
// if let zmanim = zmanim {
// ...
// }
// }
// task.resume()
// MARK: - Zmanim
class Zmanim: Codable, Loopable {
var sunrise, sofZmanTefilaGra, talisMa, tzeis595_Degrees: String?
var chatzos, minchaKetanaGra, plagMinchaMa, sofZmanShemaGra: String?
var sofZmanTefilaMa, tzeis42_Minutes, tzeis72_Minutes, tzeis850_Degrees: String?
var sunset, sofZmanShemaMa, alosMa, minchaGedolaMa: String?
enum CodingKeys: String, CodingKey {
case sunrise
case sofZmanTefilaGra = "sof_zman_tefila_gra"
case talisMa = "talis_ma"
case tzeis595_Degrees = "tzeis_595_degrees"
case chatzos
case minchaKetanaGra = "mincha_ketana_gra"
case plagMinchaMa = "plag_mincha_ma"
case sofZmanShemaGra = "sof_zman_shema_gra"
case sofZmanTefilaMa = "sof_zman_tefila_ma"
case tzeis42_Minutes = "tzeis_42_minutes"
case tzeis72_Minutes = "tzeis_72_minutes"
case tzeis850_Degrees = "tzeis_850_degrees"
case sunset
case sofZmanShemaMa = "sof_zman_shema_ma"
case alosMa = "alos_ma"
case minchaGedolaMa = "mincha_gedola_ma"
}
init(sunrise: String?, sofZmanTefilaGra: String?, talisMa: String?, tzeis595_Degrees: String?, chatzos: String?, minchaKetanaGra: String?, plagMinchaMa: String?, sofZmanShemaGra: String?, sofZmanTefilaMa: String?, tzeis42_Minutes: String?, tzeis72_Minutes: String?, tzeis850_Degrees: String?, sunset: String?, sofZmanShemaMa: String?, alosMa: String?, minchaGedolaMa: String?) {
self.sunrise = sunrise
self.sofZmanTefilaGra = sofZmanTefilaGra
self.talisMa = talisMa
self.tzeis595_Degrees = tzeis595_Degrees
self.chatzos = chatzos
self.minchaKetanaGra = minchaKetanaGra
self.plagMinchaMa = plagMinchaMa
self.sofZmanShemaGra = sofZmanShemaGra
self.sofZmanTefilaMa = sofZmanTefilaMa
self.tzeis42_Minutes = tzeis42_Minutes
self.tzeis72_Minutes = tzeis72_Minutes
self.tzeis850_Degrees = tzeis850_Degrees
self.sunset = sunset
self.sofZmanShemaMa = sofZmanShemaMa
self.alosMa = alosMa
self.minchaGedolaMa = minchaGedolaMa
}
}
// MARK: Zmanim convenience initializers and mutators
extension Zmanim {
convenience init(data: Data) throws {
let me = try newJSONDecoder().decode(Zmanim.self, from: data)
self.init(sunrise: me.sunrise, sofZmanTefilaGra: me.sofZmanTefilaGra, talisMa: me.talisMa, tzeis595_Degrees: me.tzeis595_Degrees, chatzos: me.chatzos, minchaKetanaGra: me.minchaKetanaGra, plagMinchaMa: me.plagMinchaMa, sofZmanShemaGra: me.sofZmanShemaGra, sofZmanTefilaMa: me.sofZmanTefilaMa, tzeis42_Minutes: me.tzeis42_Minutes, tzeis72_Minutes: me.tzeis72_Minutes, tzeis850_Degrees: me.tzeis850_Degrees, sunset: me.sunset, sofZmanShemaMa: me.sofZmanShemaMa, alosMa: me.alosMa, minchaGedolaMa: me.minchaGedolaMa)
}
convenience init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
convenience init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
sunrise: String?? = nil,
sofZmanTefilaGra: String?? = nil,
talisMa: String?? = nil,
tzeis595_Degrees: String?? = nil,
chatzos: String?? = nil,
minchaKetanaGra: String?? = nil,
plagMinchaMa: String?? = nil,
sofZmanShemaGra: String?? = nil,
sofZmanTefilaMa: String?? = nil,
tzeis42_Minutes: String?? = nil,
tzeis72_Minutes: String?? = nil,
tzeis850_Degrees: String?? = nil,
sunset: String?? = nil,
sofZmanShemaMa: String?? = nil,
alosMa: String?? = nil,
minchaGedolaMa: String?? = nil
) -> Zmanim {
return Zmanim(
sunrise: sunrise ?? self.sunrise,
sofZmanTefilaGra: sofZmanTefilaGra ?? self.sofZmanTefilaGra,
talisMa: talisMa ?? self.talisMa,
tzeis595_Degrees: tzeis595_Degrees ?? self.tzeis595_Degrees,
chatzos: chatzos ?? self.chatzos,
minchaKetanaGra: minchaKetanaGra ?? self.minchaKetanaGra,
plagMinchaMa: plagMinchaMa ?? self.plagMinchaMa,
sofZmanShemaGra: sofZmanShemaGra ?? self.sofZmanShemaGra,
sofZmanTefilaMa: sofZmanTefilaMa ?? self.sofZmanTefilaMa,
tzeis42_Minutes: tzeis42_Minutes ?? self.tzeis42_Minutes,
tzeis72_Minutes: tzeis72_Minutes ?? self.tzeis72_Minutes,
tzeis850_Degrees: tzeis850_Degrees ?? self.tzeis850_Degrees,
sunset: sunset ?? self.sunset,
sofZmanShemaMa: sofZmanShemaMa ?? self.sofZmanShemaMa,
alosMa: alosMa ?? self.alosMa,
minchaGedolaMa: minchaGedolaMa ?? self.minchaGedolaMa
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
//// MARK: - Helper functions for creating encoders and decoders
//
//func newJSONDecoder() -> JSONDecoder {
// let decoder = JSONDecoder()
// if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
// decoder.dateDecodingStrategy = .iso8601
// }
// return decoder
//}
//
//func newJSONEncoder() -> JSONEncoder {
// let encoder = JSONEncoder()
// if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
// encoder.dateEncodingStrategy = .iso8601
// }
// return encoder
//}
// MARK: - URLSession response handlers
extension URLSession {
fileprivate func codableTask<T: Codable>(with url: URL, completionHandler: @escaping (T?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return self.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
completionHandler(nil, response, error)
return
}
completionHandler(try? newJSONDecoder().decode(T.self, from: data), response, nil)
}
}
func todayTimesTask(with url: URL, completionHandler: @escaping (TodayTimes?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
return self.codableTask(with: url, completionHandler: completionHandler)
}
}
// var parshaShabbos, candleLightingShabbos: String?
extension TodayTimes: CustomStringConvertible {
var description: String {
return "hebDateString = \(String(describing: hebDateString)), parshaShabbos = \(String(describing: parshaShabbos)), candleLightingShabbos = \(String(describing: candleLightingShabbos))\nZmanim\n\(String(describing: zmanim))\nDafYomi\n\(String(describing: dafYomi))\n\n)"
}
}
/*
var sunrise, sofZmanTefilaGra, talisMa, tzeis595_Degrees: String?
var chatzos, minchaKetanaGra, plagMinchaMa, sofZmanShemaGra: String?
var sofZmanTefilaMa, tzeis42_Minutes, tzeis72_Minutes, tzeis850_Degrees: String?
var sunset, sofZmanShemaMa, alosMa, minchaGedolaMa: String?
*/
extension Zmanim: CustomStringConvertible {
var description: String {
return "sunrise = \(String(describing: sunrise)) ,sofZmanTefilaGra = \(String(describing: sofZmanTefilaGra)), talisMa = \(String(describing: talisMa)), tzeis595_Degrees = \(String(describing: tzeis595_Degrees)), chatzos = \(String(describing: chatzos)), minchaKetanaGra = \(String(describing: minchaKetanaGra)), plagMinchaMa = \(String(describing: plagMinchaMa)), sofZmanShemaGra = \(String(describing: sofZmanShemaGra)), sofZmanTefilaMa = \(String(describing: sofZmanTefilaMa)), tzeis42_Minutes = \(String(describing: tzeis42_Minutes)), tzeis72_Minutes = \(String(describing: tzeis72_Minutes)), tzeis850_Degrees = \(String(describing: tzeis850_Degrees)), sunset = \(String(describing: sunset)), sofZmanShemaMa = \(String(describing: sofZmanShemaMa)), alosMa = \(String(describing: alosMa)), minchaGedolaMa = \(String(describing: minchaGedolaMa))"
}
}
// var masechta, daf: String?
extension DafYomi: CustomStringConvertible {
var description: String {
return "masechta = \(String(describing: masechta)), daf = \(String(describing: daf))"
}
}
protocol Loopable {
func allProperties() throws -> [[String: Any]]
}
extension Loopable {
func allProperties() throws -> [[String: Any]] {
var result: [[String: Any]] = [[:]]
let mirror = Mirror(reflecting: self)
// Optional check to make sure we're iterating over a struct or class
guard let style = mirror.displayStyle, style == .struct || style == .class else {
throw NSError()
}
for (property, value) in mirror.children {
guard let property = property else {
continue
}
result.append([property:value])
// result[property] = value
}
return result
}
}
| 38.175532 | 855 | 0.661558 |
d7ee7e0bc8d3eab932759a60fd1a18e99141b01a | 2,609 | //
// MIT License
//
// Copyright (c) 2018-2019 Radix DLT ( https://radixdlt.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
public extension CreateTokenAction.InitialSupply {
enum SupplyTypeDefinition: Equatable {
case fixed(to: PositiveSupply)
case mutable(initial: Supply?)
}
}
// MARK: Public
public extension CreateTokenAction.InitialSupply.SupplyTypeDefinition {
var initialSupply: Supply {
switch self {
case .fixed(let positiveInitialSupply):
// return Supply(positiveSupply: positiveInitialSupply)
return Supply(subset: positiveInitialSupply)
case .mutable(let nonNegativeInitialSupply):
return nonNegativeInitialSupply ?? .zero
}
}
var tokenSupplyType: SupplyType {
switch self {
case .fixed: return .fixed
case .mutable: return .mutable
}
}
func isExactMultipleOfGranularity(_ granularity: Granularity) throws {
guard initialSupply.isMultiple(of: granularity) else {
throw CreateTokenAction.Error.initialSupplyNotMultipleOfGranularity
}
}
static var mutableZeroSupply: CreateTokenAction.InitialSupply.SupplyTypeDefinition {
return .mutable(initial: nil)
}
var isMutable: Bool {
switch self {
case .fixed: return false
case .mutable: return true
}
}
var isFixed: Bool {
switch self {
case .fixed: return true
case .mutable: return false
}
}
}
| 33.883117 | 88 | 0.690686 |
9bdc6f10a301fa12caeffe55d2368b767432d934 | 3,657 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
// swiftlint:disable cyclomatic_complexity
extension Amplify {
/// Resets the state of the Amplify framework.
///
/// Internally, this method:
/// - Invokes `reset` on each configured category, which clears that categories registered plugins.
/// - Releases each configured category, and replaces the instances referred to by the static accessor properties
/// (e.g., `Amplify.Hub`) with new instances. These instances must subsequently have providers added, and be
/// configured prior to use.
static func reset() {
// Looping through all categories to ensure we don't accidentally forget a category at some point in the future
let group = DispatchGroup()
for categoryType in CategoryType.allCases {
switch categoryType {
case .analytics:
reset(Analytics, in: group) { group.leave() }
case .api:
reset(API, in: group) { group.leave() }
case .auth:
reset(Auth, in: group) { group.leave() }
case .dataStore:
reset(DataStore, in: group) { group.leave() }
case .storage:
reset(Storage, in: group) { group.leave() }
case .predictions:
reset(Predictions, in: group) { group.leave() }
case .hub, .logging:
// Hub and Logging should be reset after all other categories
break
}
}
group.wait()
for categoryType in CategoryType.allCases {
switch categoryType {
case .hub:
reset(Hub, in: group) { group.leave() }
case .logging:
reset(Logging, in: group) { group.leave() }
default:
break
}
}
if #available(iOS 13.0.0, *) {
devMenu = nil
}
group.wait()
// Initialize Logging and Hub first, to ensure their default plugins are registered and available to other
// categories during their initialization and configuration phases.
Logging = LoggingCategory()
Hub = HubCategory()
// Switch over all category types to ensure we don't forget any
for categoryType in CategoryType.allCases.filter({ $0 != .logging && $0 != .hub }) {
switch categoryType {
case .logging, .hub:
// Initialized above
break
case .analytics:
Analytics = AnalyticsCategory()
case .api:
API = AmplifyAPICategory()
case .auth:
Auth = AuthCategory()
case .dataStore:
DataStore = DataStoreCategory()
case .predictions:
Predictions = PredictionsCategory()
case .storage:
Storage = StorageCategory()
}
}
isConfigured = false
}
/// If `candidate` is `Resettable`, `enter()`s `group`, then invokes `candidate.reset(onComplete)` on a background
/// queue. If `candidate` is not resettable, exits without invoking `onComplete`.
private static func reset(_ candidate: Any, in group: DispatchGroup, onComplete: @escaping BasicClosure) {
guard let resettable = candidate as? Resettable else {
return
}
group.enter()
DispatchQueue.global().async {
resettable.reset(onComplete: onComplete)
}
}
}
| 34.17757 | 119 | 0.565764 |
3a1d9bfbddc9d0661c6205d6ab71d529130a0a20 | 2,276 | //
// MIT License
//
// Copyright (c) 2020 Joseph El Mallah
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import SnapKit
final class SearchResultCell: UITableViewCell {
// MARK: Properties
/// The cell identifier
static let identifier = String(describing: SearchResultCell.self)
// MARK: Subviews
private let searchResultView = SearchResultView()
// MARK: Initializers
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(searchResultView)
searchResultView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Accessors
/// Use the passed model to configure the content of the cell
/// - Parameter searchResult: The search result to use a model
func populate(using searchResult: SearchResultModel) {
searchResultView.autocompletionResult = searchResult.label
searchResultView.distance = searchResult.distance
searchResultView.transportationType = searchResult.icon
}
}
| 37.311475 | 81 | 0.730228 |
e63ddae80f5ee0413d1f0c8bd6136955d4edb1ca | 330 | import Foundation
public class VerifyPhoneNumberRequest: Codable, DictionaryEncodable {
public let phoneNumber: String
public let verificationCode: String
public init(phoneNumber: String, verificationCode: String) {
self.phoneNumber = phoneNumber
self.verificationCode = verificationCode
}
}
| 27.5 | 69 | 0.742424 |
262376227bc58918df0abbdef8d45fbfc60bae09 | 412 | //
// TitleCell.swift
// Yep
//
// Created by nixzhu on 15/10/16.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class TitleCell: UITableViewCell {
@IBOutlet weak var singleTitleLabel: UILabel!
var boldEnabled = false {
didSet {
singleTitleLabel.font = boldEnabled ? UIFont.boldSystemFontOfSize(17) : UIFont.systemFontOfSize(17)
}
}
}
| 18.727273 | 111 | 0.65534 |
1cfcb7ee4c49e0536fe319f80e53c44259d4f6dc | 2,802 | //
// MarkdownImage.swift
// Thesi 🧝♀️
//
// Created by Chris Zielinski on 11/22/18.
// Copyright © 2018 Big Z Labs. All rights reserved.
//
import Foundation
import Regex
struct MarkdownImage {
enum RegexGroupKey: String, CaseIterable {
case indent
case centerAlign
case alternateText
case url
case properties
}
let indent: MarkdownIndent
let isCentered: Bool
let alternateText: String
let url: String
var width: String?
var height: String?
}
extension MarkdownImage: RegexReplaceable {
//swiftlint:disable force_try
static let regex = try! Regex(pattern: "^([ \t]*)!(!)?\\[(.+?)\\] *\\( *\"?(.+?)\"? *(,.+)?\\)",
options: [.anchorsMatchLines],
groupNames: RegexGroupKey.allRawValues)
static let widthRegex = try! Regex(pattern: "width *= *\"?([^,\"]+)\"?",
options: [.caseInsensitive],
groupNames: [])
static let heightRegex = try! Regex(pattern: "height *= *\"?([^,\"]+)\"?",
options: [.caseInsensitive],
groupNames: [])
//swiftlint:enable force_try
var replacementMarkdownString: String {
var imageHTML = "<img src=\"\(url)\" alt=\"\(alternateText)\""
if let width = width {
imageHTML += " width=\"\(width)\""
}
if let height = height {
imageHTML += " height=\"\(height)\""
}
imageHTML += ">"
if isCentered {
return """
\(indent.stringValue)<p align="center">
\(indent.stringValue) \(imageHTML)
\(indent.stringValue)</p>
"""
} else {
return indent.stringValue + imageHTML
}
}
init?(match: Match) {
indent = MarkdownIndent(matchSubstring: match.group(named: RegexGroupKey.indent.rawValue))
// Make sure it isn't inside a code block.
guard !indent.isCodeBlock
else { return nil }
isCentered = match.group(named: RegexGroupKey.centerAlign.rawValue) != nil
alternateText = match.group(named: RegexGroupKey.alternateText.rawValue) ?? ""
url = match.group(named: RegexGroupKey.url.rawValue) ?? ""
if let properties = match.group(named: RegexGroupKey.properties.rawValue) {
width = MarkdownImage.widthRegex.findFirst(in: properties)?.group(at: 1)
height = MarkdownImage.heightRegex.findFirst(in: properties)?.group(at: 1)
}
// Make sure it's not a CommonMark Markdown image.
guard isCentered || width != nil || height != nil
else { return nil }
}
}
| 30.791209 | 100 | 0.541399 |
89b43807c62656f280de6f64a89563bdde70ad95 | 857 | //
// YoLinkViewInterfaceController.swift
// Yo
//
// Created by Peter Reveles on 3/5/15.
//
//
import WatchKit
class YoLinkViewInterfaceController: YoPhotoViewInterfaceController {
// MARK: Life
override init() {
super.init()
// setup
// tell parent app to load image, once parent replies display image
}
override func getPhotoURL() -> NSURL? {
return self.yo?.coverURL
}
// MARK: Override Methods
override func getYoDescriptionForYo(yo: Yo) -> String {
return NSLocalizedString("Link from", comment: "as in Yo Link From {USERNAME}")
}
override func shouldMarkYoAsReadActivation() -> Bool {
return false
}
// MARK - Class Methods
override class func getIdentifier() -> String {
return "YoLinkViewInterfaceControllerID"
}
}
| 23.162162 | 87 | 0.632439 |
21d0bc943e29597c2dedc9e9ac8a2f4b5a3cca2e | 3,004 | //
// Lightning
//
// Created by Otto Suess on 18.09.18.
// Copyright © 2018 Zap. All rights reserved.
//
import Bond
import Foundation
import Logger
import ReactiveKit
import SwiftBTC
import SwiftLnd
public final class HistoryService: NSObject {
public var events = MutableObservableArray<HistoryEventType>()
init(invoiceListUpdater: InvoiceListUpdater, transactionListUpdater: TransactionListUpdater, paymentListUpdater: PaymentListUpdater, channelListUpdater: ChannelListUpdater) {
super.init()
combineLatest(
invoiceListUpdater.items,
transactionListUpdater.items,
paymentListUpdater.items,
channelListUpdater.all,
channelListUpdater.closed)
.observeNext { [weak self] in
let (invoiceChangeset, transactionChangeset, paymentChangeset, channels, closedChannels) = $0
let dateEstimator = DateEstimator(transactions: transactionChangeset.collection)
let newInvoices = invoiceChangeset.collection
.map { (invoice: Invoice) -> DateProvidingEvent in
InvoiceEvent(invoice: invoice)
}
let channelFundingTxids = channels.collection.map { $0.channelPoint.fundingTxid }
let newTransactions = transactionChangeset.collection
.filter { !channelFundingTxids.contains($0.id) }
.compactMap { (transaction: Transaction) -> DateProvidingEvent? in
TransactionEvent(transaction: transaction)
}
let newPayments = paymentChangeset.collection
.map { (payment: Payment) -> DateProvidingEvent in
LightningPaymentEvent(payment: payment)
}
let newOpenChannelEvents = channels.collection
.compactMap { (channel: Channel) -> DateProvidingEvent? in
ChannelEvent(channel: channel, dateEstimator: dateEstimator)
}
let newOpenChannelEvents2 = closedChannels.collection
.compactMap { (channelCloseSummary: ChannelCloseSummary) -> DateProvidingEvent? in
ChannelEvent(opening: channelCloseSummary, dateEstimator: dateEstimator)
}
let newCloseChannelEvents = closedChannels.collection
.compactMap { (channelCloseSummary: ChannelCloseSummary) -> DateProvidingEvent? in
ChannelEvent(closing: channelCloseSummary, dateEstimator: dateEstimator)
}
var result = newInvoices + newTransactions + newPayments + newOpenChannelEvents + newOpenChannelEvents2 + newCloseChannelEvents
result.sort(by: { $0.date < $1.date })
self?.events.replace(with: result.map(HistoryEventType.create))
}
.dispose(in: reactive.bag)
}
}
| 45.515152 | 178 | 0.620173 |
71c7d1e4cfd5890ca36cfdc00380b658e43a8a33 | 2,100 | //
// PhotoStreamViewController.swift
// Collectrest
//
// Created by Jason Sanchez on 2/19/19.
// Copyright © 2019 Jason Sanchez. All rights reserved.
//
import UIKit
import AVFoundation
class PhotoStreamViewController: UICollectionViewController {
var photos = Photo.allPhotos()
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
if let layout = collectionView.collectionViewLayout as? CollectrestLayout {
layout.delegate = self
}
if let patternImage = UIImage(named: "Pattern") {
view.backgroundColor = UIColor(patternImage: patternImage)
}
collectionView?.backgroundColor = .clear
collectionView?.contentInset = UIEdgeInsets(top: 23, left: 16, bottom: 10, right: 16)
}
}
extension PhotoStreamViewController: UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photos.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AnnotatedPhotoCell", for: indexPath as IndexPath) as! AnnotatedPhotoCell
cell.photo = photos[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemSize = (collectionView.frame.width - (collectionView.contentInset.left + collectionView.contentInset.right + 10)) / 2
return CGSize(width: itemSize, height: itemSize)
}
}
extension PhotoStreamViewController: CollectrestLayoutDelegate {
func collectionView(collectionView: UICollectionView, heightForPhotoAtIndexPath indexPath: IndexPath) -> CGFloat {
return photos[indexPath.item].image.size.height
}
}
| 35.59322 | 160 | 0.71619 |
8a2dd2455e26c751fb2d437b2c43f6abaae4b4b8 | 632 | //
// ID3RecordingDayMonthFrameContentParsingOperationFactory.swift
//
// Created by Fabrizio Duroni on 05/08/2018.
// 2018 Fabrizio Duroni.
//
import Foundation
class ID3RecordingDayMonthFrameContentParsingOperationFactory {
static func make() -> ID3FrameStringContentParsingOperation {
return ID3FrameStringContentParsingOperationFactory.make() { (id3Tag: ID3Tag, content: String) in
let dayMonth = ID3CoupleOfNumbersAdapter().adapt(coupleOfNumbers: content)
id3Tag.recordingDateTime?.date?.day = dayMonth.0
id3Tag.recordingDateTime?.date?.month = dayMonth.1
}
}
}
| 33.263158 | 105 | 0.731013 |
6902392e5779fed890b73bc077ba363877706df5 | 278 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
0
}
struct X<T where f: c<T>() -> {
public subscript () -> S
| 23.166667 | 87 | 0.701439 |
d5f2463a21d5f8fb792f5708dab0c30106e4dac8 | 8,304 | //
// PopMenu.swift
// PopMenu
//
// Created by changqi on 7/5/16.
// Copyright © 2016 company. All rights reserved.
//
import Foundation
import UIKit
let MenuItemHeight:Float = 110
let MenuItemVertivalPadding:Float = 10
let MenuItemHorizontalMargin:Float = 10
let MenuItemAnimationTime:Float = 0.1
let MenuItemAnimationInterval:Float = (MenuItemAnimationTime / 5)
let MenuItemBaseTag = 100
typealias Int2Void = (Int)->Void;
class PopMenu: UIView, BlurViewProtocol{
enum PopMenuAnimationType {
case Rise;
case Diffuse;
}
var type:PopMenuAnimationType = .Rise;
var items:Array = [MenuItem]();
var perRowItemCount:Int = 3;
var isShowed:Bool = false;
var startPoint:CGPoint!;
var endPoint:CGPoint!;
var itemClicked:Int2Void?;
lazy var blurView:BlurView = {
let blur = BlurView(frame: self.bounds);
blur.hasTapGustureEnable = true;
blur.showDuration = 0.3;
blur.dismissDuration = 0.3;
blur.delegate = self;
return blur;
}();
override init(frame: CGRect) {
super.init(frame: frame);
}
convenience init(frame:CGRect, item:Array<MenuItem>){
self.init(frame: frame);
self.items = item;
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func showMenuAtView(containerView:UIView){
self.startPoint = CGPoint(x: 0, y: self.bounds.size.height);
self.endPoint = self.startPoint;
if(self.isShowed){
return;
}
self.clipsToBounds = true;
containerView.addSubview(self);
self.blurView.showBlurViewAtView(self);
}
func dismissMenu(){
self.hideItems();
}
func willShowBlurView() {
self.isShowed = true;
self.showItems();
}
func willDismissBlurView() {
self.dismissMenu();
}
func didDismissBlurView() {
self.isShowed = false;
self.removeFromSuperview();
}
/**
show the items with animation
*/
func showItems(){
let itemWidth:Float = (Float(self.bounds.size.width) - (Float(self.perRowItemCount + 1) * MenuItemHorizontalMargin)) / Float(perRowItemCount);
var index = 0;
for menuItem in self.items {
if menuItem.position < 0{
menuItem.position = index;
}
var menuButton:MenuButton? = self.viewWithTag(MenuItemBaseTag+index) as? MenuButton;
let toRect:CGRect = self.getFrameOfItem(AtIndex: index, itemWidth: itemWidth);
var fromRect = toRect;
switch self.type {
case .Rise:
fromRect.origin.y = self.startPoint.y;
case .Diffuse:
fromRect.origin.x = CGRectGetMidX(self.bounds) - CGFloat(itemWidth/2.0);
fromRect.origin.y = self.startPoint.y;
}
if menuButton == nil{
menuButton = MenuButton(frame: fromRect, menuItem: menuItem);
menuButton!.tag = MenuItemBaseTag + index;
menuButton?.itemClicked = { [unowned self] tag in
self.itemClicked?(tag);
}
self.addSubview(menuButton!);
}
else{
menuButton?.frame = fromRect;
}
let delaySeconds:Double = Double(Float(index) * MenuItemAnimationInterval);
self.initAnimation(toRect: toRect, fromRect: fromRect, atView: menuButton!, beginTime: delaySeconds);
index += 1;
}
}
func hideItems(){
for index in 0..<self.items.count{
let menuButton:MenuButton = (self.viewWithTag(MenuItemBaseTag + index) as? MenuButton)!;
let fromRect:CGRect = menuButton.frame;
var toRect:CGRect = fromRect;
switch self.type {
case .Rise:
toRect.origin.y = self.endPoint.y;
case .Diffuse:
toRect.origin.x = CGRectGetMidX(self.bounds) - CGFloat(menuButton.bounds.size.width/2.0);
toRect.origin.y = self.endPoint.y;
}
let delayInSeconds:Double = Double(Float(self.items.count - index) * MenuItemAnimationInterval);
self.initAnimation(toRect: toRect, fromRect: fromRect, atView: menuButton, beginTime: delayInSeconds);
}
}
func initAnimation(toRect toRect:CGRect, fromRect:CGRect, atView:UIView, beginTime:Double){
let startFrame:CGRect = CGRect(x: fromRect.origin.x, y: fromRect.origin.y, width: atView.bounds.size.width, height: atView.bounds.size.height);
atView.frame = startFrame;
UIView.animateWithDuration(0.3, delay: beginTime, options: .CurveEaseInOut, animations: {
let endFrame:CGRect = CGRect(x: toRect.origin.x, y: toRect.origin.y, width: atView.bounds.size.width, height: atView.bounds.size.height);
atView.frame = endFrame;
})
{ (finished) in
};
}
/**
get the frame to show items.
- parameter index: item index
- parameter itemWidth: item width
- returns: frame
*/
func getFrameOfItem(AtIndex index:Int, itemWidth:Float) -> CGRect {
//var perColumItemCount = Int(self.items.count/self.perRowItemCount) + (self.items.count%self.perRowItemCount > 0 ? 1 : 0);
let insetY:Float = Float(UIScreen.mainScreen().bounds.size.height) * 0.1 + 64;
let originX:Float = Float(index % self.perRowItemCount) * (itemWidth + MenuItemHorizontalMargin) + MenuItemHorizontalMargin;
let originY:Float = Float(index / self.perRowItemCount) * (MenuItemHeight + MenuItemVertivalPadding) + MenuItemVertivalPadding;
let itemFrame:CGRect = CGRect(x: CGFloat(originX), y: CGFloat(insetY + originY), width: CGFloat(itemWidth), height: CGFloat(MenuItemHeight));
return itemFrame;
}
}
class MenuButton: UIView{
var iconImageView:UIImageView!;
var titleLabel:UILabel!;
var menuItem:MenuItem!;
var itemClicked:Int2Void?;
override init(frame: CGRect) {
super.init(frame: frame);
}
convenience init(frame: CGRect, menuItem:MenuItem){
self.init(frame: frame);
self.menuItem = menuItem;
self.initContent();
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initContent(){
let imageSize:CGSize = self.menuItem.iconImage.size;
self.iconImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height));
self.iconImageView.userInteractionEnabled = true;
self.iconImageView.image = self.menuItem.iconImage;
self.iconImageView.center = CGPoint(x: CGRectGetMidX(self.bounds), y: CGRectGetMidY(self.iconImageView.bounds));
self.addSubview(self.iconImageView);
self.titleLabel = UILabel(frame: CGRect(x: 0, y: CGRectGetMaxY(self.iconImageView.frame), width: CGRectGetWidth(self.bounds), height: 35));
self.titleLabel.textColor = UIColor.blackColor();
self.titleLabel.backgroundColor = UIColor.clearColor();
self.titleLabel.font = UIFont.systemFontOfSize(14);
self.titleLabel.textAlignment = .Center;
self.titleLabel.text = self.menuItem.title;
var center:CGPoint = self.titleLabel.center;
center.x = CGRectGetMidX(self.bounds);
self.titleLabel.center = center;
self.addSubview(self.titleLabel);
let gesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.itemClickedMethod));
self.addGestureRecognizer(gesture);
}
func itemClickedMethod(){
self.itemClicked?(self.tag - MenuItemBaseTag);
}
} | 32.564706 | 151 | 0.594292 |
6a3b5f298ef600a275d7016e8edab4fb786e20db | 231 |
import Foundation
extension Array: WarningDiagnoser where Element: WarningDiagnoser {
func diagnose(parsed: Struct<Stage.Parsed>) throws -> [Warning] {
return try flatMap { try $0.diagnose(parsed: parsed) }
}
}
| 21 | 69 | 0.701299 |
7971589876e369b14168bdcc0c4b94caf32fff44 | 822 | //
// DBProvider.swift
// SwiftyDating
//
// Created by Maxime De Sogus on 21/02/2017.
// Copyright © 2017 Maxime De Sogus. All rights reserved.
//
import Foundation
import SQLite
class DBProvider {
private init(){
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let fm:FileManager = FileManager.default;
if(!fm.fileExists(atPath: "\(path)/swiftydating.db")){
print("Le fichier n'existe pas ");
}
do {
try connection = Connection("\(path)/swiftydating.db")
print("DB create at : \(path)/swiftydating.db")
} catch {
connection = nil
print(Error.self)
}
}
static var sharedInstance = DBProvider();
var connection:Connection?
}
| 25.6875 | 104 | 0.605839 |
d577419fa088e35cab8162784a9e823857f1bbb2 | 6,108 | //
// ViewController.swift
// Project 10
//
// Created by Alvaro Orellana on 01-06-21.
//
import UIKit
class ViewController: UICollectionViewController {
var people = [Person]() {
didSet{
print("people array was set")
collectionView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addImagePressed))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Show people", style: .done, target: self, action: #selector(printAllPeople))
loadPeople()
}
private func loadPeople() {
let defaults = UserDefaults.standard
if let savedPeople = defaults.object(forKey: "people") as? Data {
let jsonDecoder = JSONDecoder()
do {
people = try jsonDecoder.decode([Person].self, from: savedPeople)
} catch {
print("Failed to load people")
}
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return people.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PersonCell", for: indexPath) as? PersonCell
else {
fatalError("Could not deque cell for collection view")
}
let person = people[indexPath.item]
let imagePath = getDocumentsDirectory().appendingPathComponent(person.imageId)
cell.imageView.image = UIImage(contentsOfFile: imagePath.path)
cell.imageView.layer.borderWidth = 2
cell.imageView.layer.borderColor = UIColor(white: 0, alpha: 0.3).cgColor
cell.imageView.layer.cornerRadius = 3
cell.layer.cornerRadius = 7
cell.label.text = person.name
return cell
}
@objc private func printAllPeople() {
print(people)
}
@objc private func addImagePressed() {
// Create and present ImagePickerController
let picker = UIImagePickerController()
picker.allowsEditing = true
if UIImagePickerController.isSourceTypeAvailable(.camera) {
picker.sourceType = .camera
}
picker.delegate = self
present(picker, animated: true)
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Creates and presents Alert Controller
let alert = UIAlertController(title: "Choose Action", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Change name", style: .default) { _ in
self.updateNameAlert(at: indexPath.item)
})
alert.addAction(UIAlertAction(title: "Delete item", style: .destructive) { _ in
self.deletePerson(at: indexPath.item)
})
alert.addAction(UIAlertAction(title: "Cancel", style: .default))
present(alert, animated: true)
}
private func updateNameAlert(at index: Int) {
let selectedPerson = people[index]
let alert = UIAlertController(title: "Update name", message: nil, preferredStyle: .alert)
alert.addTextField()
alert.addAction(UIAlertAction(title: "Ok", style: .default) { _ in
if let newName = alert.textFields?[0].text {
selectedPerson.name = newName
self.save()
self.collectionView.reloadData()
}
})
alert.addAction(UIAlertAction(title: "Cancel", style: .default))
present(alert, animated: true)
}
private func deletePerson(at index: Int) {
// TODO: Remove from disk
let imagePath = getDocumentsDirectory().appendingPathComponent(people[index].imageId) // Location where photo is be saved
do {
try FileManager.default.removeItem(at: imagePath)
people.remove(at: index)
//collectionView.reloadData()
} catch {
print("Couldn't delete image from disk. Error: \(error)")
}
}
}
// MARK: - UIImagePickerControllerDelegate
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let image = info[.editedImage] as? UIImage else { return }
if let jpegData = image.jpegData(compressionQuality: 0.8) {
saveImageToDisk(image: jpegData)
}
dismiss(animated: true)
}
}
// MARK: - File System interacting functions
extension ViewController {
private func saveImageToDisk(image: Data) {
let imageId = UUID().uuidString
let imagePath = getDocumentsDirectory().appendingPathComponent(imageId) // Location where photo will be saved
do {
try image.write(to: imagePath)
people.append(Person(name: "Unknown", imagePath: imageId))
save()
//collectionView.reloadData()
} catch {
print("Couldn't save image to data. Error: \(error)")
}
}
private func getDocumentsDirectory() -> URL {
let documentsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return documentsPath[0]
}
func save() {
let jsonEncoder = JSONEncoder()
if let savedData = try? jsonEncoder.encode(people) {
let defaults = UserDefaults.standard
defaults.set(savedData, forKey: "people")
} else {
print("Failed to save people.")
}
}
}
| 31.163265 | 144 | 0.611657 |
236c17db69a1862863ae3af7a4764b31864983e7 | 2,927 | //
// SignalClient.swift
// WebRTC
//
// Created by Stasel on 20/05/2018.
// Copyright © 2018 Stasel. All rights reserved.
//
import Foundation
import WebRTC
protocol SignalClientDelegate: AnyObject {
func signalClientDidConnect(_ signalClient: SignalingClient)
func signalClientDidDisconnect(_ signalClient: SignalingClient)
func signalClient(_ signalClient: SignalingClient, didReceiveRemoteSdp sdp: RTCSessionDescription)
func signalClient(_ signalClient: SignalingClient, didReceiveCandidate candidate: RTCIceCandidate)
}
final class SignalingClient {
private let decoder = JSONDecoder()
private let encoder = JSONEncoder()
private let webSocket: WebSocketProvider
weak var delegate: SignalClientDelegate?
init(webSocket: WebSocketProvider) {
self.webSocket = webSocket
}
func connect() {
self.webSocket.delegate = self
self.webSocket.connect()
}
func send(sdp rtcSdp: RTCSessionDescription) {
let message = Message.sdp(SessionDescription(from: rtcSdp))
do {
let dataMessage = try self.encoder.encode(message)
self.webSocket.send(data: dataMessage)
}
catch {
debugPrint("Warning: Could not encode sdp: \(error)")
}
}
func send(candidate rtcIceCandidate: RTCIceCandidate) {
let message = Message.candidate(IceCandidate(from: rtcIceCandidate))
do {
let dataMessage = try self.encoder.encode(message)
self.webSocket.send(data: dataMessage)
}
catch {
debugPrint("Warning: Could not encode candidate: \(error)")
}
}
}
extension SignalingClient: WebSocketProviderDelegate {
func webSocketDidConnect(_ webSocket: WebSocketProvider) {
self.delegate?.signalClientDidConnect(self)
}
func webSocketDidDisconnect(_ webSocket: WebSocketProvider) {
self.delegate?.signalClientDidDisconnect(self)
// try to reconnect every two seconds
DispatchQueue.global().asyncAfter(deadline: .now() + 2) {
debugPrint("Trying to reconnect to signaling server...")
self.webSocket.connect()
}
}
func webSocket(_ webSocket: WebSocketProvider, didReceiveData data: Data) {
let message: Message
do {
message = try self.decoder.decode(Message.self, from: data)
}
catch {
debugPrint("Warning: Could not decode incoming message: \(error)")
return
}
switch message {
case .candidate(let iceCandidate):
self.delegate?.signalClient(self, didReceiveCandidate: iceCandidate.rtcIceCandidate)
case .sdp(let sessionDescription):
self.delegate?.signalClient(self, didReceiveRemoteSdp: sessionDescription.rtcSessionDescription)
}
}
}
| 31.138298 | 108 | 0.652887 |
efc0ccc55e05d1f1e1da13a231f2afbc8b40418c | 25,924 | //——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// THIS FILE IS GENERATED BY EASY BINDINGS, DO NOT MODIFY IT
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
import Cocoa
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ReadOnlyObject_SymbolTypeInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
class ReadOnlyObject_SymbolTypeInDevice : ReadOnlyAbstractObjectProperty <SymbolTypeInDevice> {
//····················································································································
internal override func notifyModelDidChangeFrom (oldValue inOldValue : SymbolTypeInDevice?) {
super.notifyModelDidChangeFrom (oldValue: inOldValue)
//--- Remove observers from removed objects
if let oldValue = inOldValue {
oldValue.mTypeName_property.removeEBObserver (self.mTypeName_property) // Stored property
oldValue.mVersion_property.removeEBObserver (self.mVersion_property) // Stored property
oldValue.mFileData_property.removeEBObserver (self.mFileData_property) // Stored property
oldValue.mStrokeBezierPath_property.removeEBObserver (self.mStrokeBezierPath_property) // Stored property
oldValue.mFilledBezierPath_property.removeEBObserver (self.mFilledBezierPath_property) // Stored property
oldValue.versionString_property.removeEBObserver (self.versionString_property) // Transient property
oldValue.instanceCount_property.removeEBObserver (self.instanceCount_property) // Transient property
oldValue.documentSize_property.removeEBObserver (self.documentSize_property) // Transient property
oldValue.pinNameShape_property.removeEBObserver (self.pinNameShape_property) // Transient property
}
//--- Add observers to added objects
if let newValue = self.mInternalValue {
newValue.mTypeName_property.addEBObserver (self.mTypeName_property) // Stored property
newValue.mVersion_property.addEBObserver (self.mVersion_property) // Stored property
newValue.mFileData_property.addEBObserver (self.mFileData_property) // Stored property
newValue.mStrokeBezierPath_property.addEBObserver (self.mStrokeBezierPath_property) // Stored property
newValue.mFilledBezierPath_property.addEBObserver (self.mFilledBezierPath_property) // Stored property
newValue.versionString_property.addEBObserver (self.versionString_property) // Transient property
newValue.instanceCount_property.addEBObserver (self.instanceCount_property) // Transient property
newValue.documentSize_property.addEBObserver (self.documentSize_property) // Transient property
newValue.pinNameShape_property.addEBObserver (self.pinNameShape_property) // Transient property
}
}
//····················································································································
// Observers of 'mTypeName' stored property
//····················································································································
final let mTypeName_property = EBGenericTransientProperty <String?> ()
//····················································································································
// Observers of 'mVersion' stored property
//····················································································································
final let mVersion_property = EBGenericTransientProperty <Int?> ()
//····················································································································
// Observers of 'mFileData' stored property
//····················································································································
final let mFileData_property = EBGenericTransientProperty <Data?> ()
//····················································································································
// Observers of 'mStrokeBezierPath' stored property
//····················································································································
final let mStrokeBezierPath_property = EBGenericTransientProperty <NSBezierPath?> ()
//····················································································································
// Observers of 'mFilledBezierPath' stored property
//····················································································································
final let mFilledBezierPath_property = EBGenericTransientProperty <NSBezierPath?> ()
//····················································································································
// Observers of 'versionString' transient property
//····················································································································
final let versionString_property = EBGenericTransientProperty <String?> ()
//····················································································································
// Observers of 'instanceCount' transient property
//····················································································································
final let instanceCount_property = EBGenericTransientProperty <Int?> ()
//····················································································································
// Observers of 'documentSize' transient property
//····················································································································
final let documentSize_property = EBGenericTransientProperty <Int?> ()
//····················································································································
// Observers of 'pinNameShape' transient property
//····················································································································
final let pinNameShape_property = EBGenericTransientProperty <EBShape?> ()
//····················································································································
// Observable toMany property: mInstances
//····················································································································
private final var mObserversOf_mInstances = EBWeakEventSet ()
//····················································································································
final func addEBObserverOf_mInstances (_ inObserver : EBEvent) {
self.mObserversOf_mInstances.insert (inObserver)
if let object = self.propval {
object.mInstances_property.addEBObserver (inObserver)
}
}
//····················································································································
final func removeEBObserverOf_mInstances (_ inObserver : EBEvent) {
self.mObserversOf_mInstances.remove (inObserver)
if let object = self.propval {
object.mInstances_property.removeEBObserver (inObserver)
}
}
//····················································································································
// Observable toMany property: mPinTypes
//····················································································································
private final var mObserversOf_mPinTypes = EBWeakEventSet ()
//····················································································································
final func addEBObserverOf_mPinTypes (_ inObserver : EBEvent) {
self.mObserversOf_mPinTypes.insert (inObserver)
if let object = self.propval {
object.mPinTypes_property.addEBObserver (inObserver)
}
}
//····················································································································
final func removeEBObserverOf_mPinTypes (_ inObserver : EBEvent) {
self.mObserversOf_mPinTypes.remove (inObserver)
if let object = self.propval {
object.mPinTypes_property.removeEBObserver (inObserver)
}
}
//····················································································································
// INIT
//····················································································································
override init () {
super.init ()
//--- Configure mTypeName simple stored property
self.mTypeName_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mTypeName_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure mVersion simple stored property
self.mVersion_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mVersion_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure mFileData simple stored property
self.mFileData_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mFileData_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure mStrokeBezierPath simple stored property
self.mStrokeBezierPath_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mStrokeBezierPath_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure mFilledBezierPath simple stored property
self.mFilledBezierPath_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.mFilledBezierPath_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure versionString transient property
self.versionString_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.versionString_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure instanceCount transient property
self.instanceCount_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.instanceCount_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure documentSize transient property
self.documentSize_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.documentSize_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
//--- Configure pinNameShape transient property
self.pinNameShape_property.mReadModelFunction = { [weak self] in
if let model = self?.mInternalValue {
switch model.pinNameShape_property.selection {
case .empty :
return .empty
case .multiple :
return .multiple
case .single (let v) :
return .single (v)
}
}else{
return .single (nil)
}
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// TransientObject SymbolTypeInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class TransientObject_SymbolTypeInDevice : ReadOnlyObject_SymbolTypeInDevice {
//····················································································································
// Data provider
//····················································································································
private var mDataProvider : ReadOnlyObject_SymbolTypeInDevice? = nil
private var mTransientKind : PropertyKind = .empty
//····················································································································
func setDataProvider (_ inProvider : ReadOnlyObject_SymbolTypeInDevice?) {
if self.mDataProvider !== inProvider {
self.mDataProvider?.detachClient (self)
self.mDataProvider = inProvider
self.mDataProvider?.attachClient (self)
}
}
//····················································································································
override func notifyModelDidChange () {
let newObject : SymbolTypeInDevice?
if let dataProvider = self.mDataProvider {
switch dataProvider.selection {
case .empty :
newObject = nil
self.mTransientKind = .empty
case .single (let v) :
newObject = v
self.mTransientKind = .single
case .multiple :
newObject = nil
self.mTransientKind = .empty
}
}else{
newObject = nil
self.mTransientKind = .empty
}
self.mInternalValue = newObject
super.notifyModelDidChange ()
}
//····················································································································
override var selection : EBSelection < SymbolTypeInDevice? > {
switch self.mTransientKind {
case .empty :
return .empty
case .single :
if let internalValue = self.mInternalValue {
return .single (internalValue)
}else{
return .empty
}
case .multiple :
return .multiple
}
}
//····················································································································
override var propval : SymbolTypeInDevice? { return self.mInternalValue }
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// ReadWriteObject_SymbolTypeInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
class ReadWriteObject_SymbolTypeInDevice : ReadOnlyObject_SymbolTypeInDevice {
//····················································································································
func setProp (_ inValue : SymbolTypeInDevice?) { } // Abstract method
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// Proxy: ProxyObject_SymbolTypeInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class ProxyObject_SymbolTypeInDevice : ReadWriteObject_SymbolTypeInDevice {
//····················································································································
private var mModel : ReadWriteObject_SymbolTypeInDevice? = nil
//····················································································································
func setModel (_ inModel : ReadWriteObject_SymbolTypeInDevice?) {
if self.mModel !== inModel {
self.mModel?.detachClient (self)
self.mModel = inModel
self.mModel?.attachClient (self)
}
}
//····················································································································
override func notifyModelDidChange () {
let newModel : SymbolTypeInDevice?
if let model = self.mModel {
switch model.selection {
case .empty :
newModel = nil
case .single (let v) :
newModel = v
case .multiple :
newModel = nil
}
}else{
newModel = nil
}
self.mInternalValue = newModel
super.notifyModelDidChange ()
}
//····················································································································
override func setProp (_ inValue : SymbolTypeInDevice?) {
self.mModel?.setProp (inValue)
}
//····················································································································
override var selection : EBSelection < SymbolTypeInDevice? > {
if let model = self.mModel {
return model.selection
}else{
return .empty
}
}
//····················································································································
override var propval : SymbolTypeInDevice? {
if let model = self.mModel {
switch model.selection {
case .empty, .multiple :
return nil
case .single (let v) :
return v
}
}else{
return nil
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
// StoredObject_SymbolTypeInDevice
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
final class StoredObject_SymbolTypeInDevice : ReadWriteObject_SymbolTypeInDevice, EBSignatureObserverProtocol, EBObservableObjectProtocol {
//····················································································································
init (usedForSignature inUsedForSignature : Bool) {
mUsedForSignature = inUsedForSignature
super.init ()
}
//····················································································································
// Signature ?
//····················································································································
private let mUsedForSignature : Bool
//····················································································································
// Undo manager
//····················································································································
weak final var ebUndoManager : EBUndoManager? = nil // SOULD BE WEAK
//····················································································································
// Opposite relationship management
//····················································································································
private var mSetOppositeRelationship : Optional < (_ inManagedObject : SymbolTypeInDevice) -> Void > = nil
private var mResetOppositeRelationship : Optional < (_ inManagedObject : SymbolTypeInDevice) -> Void > = nil
//····················································································································
func setOppositeRelationShipFunctions (setter inSetter : @escaping (_ inManagedObject : SymbolTypeInDevice) -> Void,
resetter inResetter : @escaping (_ inManagedObject : SymbolTypeInDevice) -> Void) {
self.mSetOppositeRelationship = inSetter
self.mResetOppositeRelationship = inResetter
}
//····················································································································
#if BUILD_OBJECT_EXPLORER
var mValueExplorer : NSButton? {
didSet {
if let unwrappedExplorer = self.mValueExplorer {
switch self.selection {
case .empty, .multiple :
break ;
case .single (let v) :
updateManagedObjectToOneRelationshipDisplay (object: v, button: unwrappedExplorer)
}
}
}
}
#endif
//····················································································································
// Model will change
//····················································································································
override func notifyModelDidChangeFrom (oldValue inOldValue : SymbolTypeInDevice?) {
//--- Register old value in undo manager
self.ebUndoManager?.registerUndo (withTarget: self) { $0.mInternalValue = inOldValue }
//---
if let object = inOldValue {
if self.mUsedForSignature {
object.setSignatureObserver (observer: nil)
}
self.mResetOppositeRelationship? (object)
}
//---
if let object = self.mInternalValue {
if self.mUsedForSignature {
object.setSignatureObserver (observer: self)
}
self.mSetOppositeRelationship? (object)
}
//---
super.notifyModelDidChangeFrom (oldValue: inOldValue)
}
//····················································································································
// Model did change
//····················································································································
override func notifyModelDidChange () {
//--- Update explorer
#if BUILD_OBJECT_EXPLORER
if let valueExplorer = self.mValueExplorer {
updateManagedObjectToOneRelationshipDisplay (object: self.mInternalValue, button: valueExplorer)
}
#endif
//--- Notify observers
self.postEvent ()
self.clearSignatureCache ()
//---
super.notifyModelDidChange ()
}
//····················································································································
override var selection : EBSelection < SymbolTypeInDevice? > {
if let object = self.mInternalValue {
return .single (object)
}else{
return .empty
}
}
//····················································································································
override func setProp (_ inValue : SymbolTypeInDevice?) { self.mInternalValue = inValue }
//····················································································································
override var propval : SymbolTypeInDevice? { return self.mInternalValue }
//····················································································································
// signature
//····················································································································
private weak var mSignatureObserver : EBSignatureObserverProtocol? = nil // SOULD BE WEAK
//····················································································································
private var mSignatureCache : UInt32? = nil
//····················································································································
final func setSignatureObserver (observer inObserver : EBSignatureObserverProtocol?) {
self.mSignatureObserver?.clearSignatureCache ()
self.mSignatureObserver = inObserver
inObserver?.clearSignatureCache ()
self.clearSignatureCache ()
}
//····················································································································
final func signature () -> UInt32 {
let computedSignature : UInt32
if let s = self.mSignatureCache {
computedSignature = s
}else{
computedSignature = self.computeSignature ()
self.mSignatureCache = computedSignature
}
return computedSignature
}
//····················································································································
final private func computeSignature () -> UInt32 {
var crc : UInt32 = 0
if let object = self.mInternalValue {
crc.accumulateUInt32 (object.signature ())
}
return crc
}
//····················································································································
final func clearSignatureCache () {
if self.mSignatureCache != nil {
self.mSignatureCache = nil
self.mSignatureObserver?.clearSignatureCache ()
}
}
//····················································································································
}
//——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
| 41.280255 | 139 | 0.415407 |
7a0ae85f89389636ec6f8fdf44098d140822b746 | 3,334 |
import Foundation
import AppKit
final class ItemModel: ObservableObject {
final class Item: ObservableObject, Identifiable {
@Published var text: String { didSet { dirty = true }}
let id = UUID()
fileprivate var dirty = true
init(initialText: String) {
text = initialText
}
}
final class List: ObservableObject {
@Published var items: [Item] = []
fileprivate var dirty = false
func remove(at index: Int) {
items.remove(at: index)
dirty = true
}
func add(_ x: String) {
items.append(Item(initialText: x))
}
}
enum FooterStatus: String {
case yes = "yes"
case maybe = "maybe"
case no = "no"
}
@Published var planned: List
@Published var today: List
@Published var tomorrow: List
@Published var qbi: List
@Published var footer: [String: FooterStatus]
init() {
planned = List()
today = List()
tomorrow = List()
qbi = List()
footer = [:]
}
func save() {
let lists = [planned, today, tomorrow, qbi]
let dirtyItems = lists.flatMap { $0.items.filter(\.dirty) }
let dirtyLists = lists.filter(\.dirty)
print("checking for save...")
if dirtyItems.count != 0 ||
dirtyLists.count != 0 {
print(" saving")
dirtyItems.forEach { $0.dirty = false }
dirtyLists.forEach { $0.dirty = false }
Task.init(priority: .background) {
await DiskData(itemModel:self).save()
}
}
}
func move(id: UUID, to: List, at: Int ) {
func tryMove(_ list: List) -> Bool {
if let index = list.items.firstIndex(where: {item in item.id == id }) {
let item = list.items.remove(at: index)
let dest = index < at ? at-1 : at
if dest >= to.items.count {
to.items.append(item)
} else {
to.items.insert(item, at: dest)
}
return true
}
return false
}
if !tryMove(planned) &&
!tryMove(today) &&
!tryMove(tomorrow) &&
!tryMove(qbi) {
print("Error: source item not found")
}
}
func clear() {
let settings = UserSettings()
// here, keep and toPlanned have the same meaning
if settings.resetBehaviorPlanned == .discard { planned.items.removeAll() }
// add anything else to planned
if settings.resetBehaviorToday == .toPlanned { planned.items.append(contentsOf: today.items) }
if settings.resetBehaviorTomorrow == .toPlanned { planned.items.append(contentsOf: tomorrow.items) }
if settings.resetBehaviorQbi == .toPlanned { planned.items.append(contentsOf: qbi.items) }
// clear what's needed
if settings.resetBehaviorToday != .keep { today.items.removeAll() }
if settings.resetBehaviorTomorrow != .keep { tomorrow.items.removeAll() }
if settings.resetBehaviorQbi != .keep { qbi.items.removeAll() }
}
}
| 30.587156 | 108 | 0.523695 |
6a7e3e5631ea87b7ff063d6839d4d550dbf9fc39 | 2,245 | //
// CacheManager.swift
// one
//
// Created by sidney on 6/1/21.
//
import Foundation
import SDWebImage
import SceneKit
import WebKit
class CacheManager {
static let shared = CacheManager()
var refreshHeaderImages: [UIImage] = []
var imageInfos: [String: ImageInfo] = [:]
var sceneViews: [SCNView] = []
var webViews: [WKWebView] = []
private init() {
// let webView = WKWebView()
// self.webViews.append(webView)
// for _ in [0...2] {
// let sceneView = SCNView()
// let scene = SCNScene(named: "BrickLandspeeder4501.obj")
// sceneView.scene = scene
// self.sceneViews.append(sceneView)
// }
}
private func getImagesInfo(urls: [String], callback: @escaping () -> Void) {
let notCacheUrls = urls.filter { (url) -> Bool in
return !self.imageInfos.keys.contains(url)
}
if notCacheUrls.count == 0 {
callback()
return
}
}
func preCache(urlstrs: [String], callback: (() -> Void)?) {
var urls: [URL] = []
for urlstr in urlstrs {
if let url = URL(string: urlstr) {
urls.append(url)
}
}
SDWebImagePrefetcher.shared.prefetchURLs(urls) { noOfFinishedUrls, noOfTotalUrls in
} completed: { noOfFinishedUrls, noOfSkippedUrls in
if let callback = callback {
callback()
}
}
}
func getRefreshHeaderImages() {
self.refreshHeaderImages = UIImage.getImagesFromGif(name: "refresh") ?? []
}
func deleteFile(willDeleteCacheKey: String) -> Bool {
// 一定要用path,而不是absoluteString,因为后者包含file://协议头
let path = FileDownloader.getFileUrl(originUrlStr: willDeleteCacheKey).path
if !FileManager.default.fileExists(atPath: path) {
print("文件不存在")
return false
}
do {
try FileManager.default.removeItem(atPath: path)
Storage.mediaCache[willDeleteCacheKey] = ""
return true
} catch let error as NSError {
print(error)
return false
}
}
}
| 27.378049 | 91 | 0.550557 |
ff24b1763c25b6ab425652e2a10a9ebe8f7fbdcc | 6,808 | //
// ViewController.swift
// Metal Utility
//
// Created by 汤迪希 on 2018/8/24.
// Copyright © 2018 DC. All rights reserved.
//
import Cocoa
import MetalKit
import Metal
class ViewController: NSViewController {
lazy var renderer: Renderer = makeRenderer()
lazy var depthStencilState: MTLDepthStencilState = makeDepthStencilState()
lazy var lightFactory: LightFactory = LightFactory()
lazy var lights = [Light]()
lazy var models = [Model]()
var timer: Float = 0.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setup()
}
}
extension ViewController {
func setup() {
guard let device = renderer.device else {
fatalError("Metal is not supported in this device")
}
guard let metalView = view as? MTKView else {
fatalError("Metal need a render view")
}
// Setup models
if models.count == 0 {
let house = Model(name: "lowpoly-house", device: device, pixelFormat: metalView.colorPixelFormat)
house.rotation = [0, radians(fromDegrees: 45), 0]
let plane = Model(name: "plane", device: device, pixelFormat: metalView.colorPixelFormat)
plane.scale = [40,1,40]
plane.tiling = 16
models.append(contentsOf: [house,plane])
}
renderer.depthStencilState = depthStencilState
renderer.draw = { (renderCommandEncoder) in
// Camera
let viewMatrix = float4x4(translation: [0, 1, -4]).inverse
let projectionMatrix = float4x4(projectionFov: radians(fromDegrees: 70),
near: 0.01,
far: 1000,
aspect: Float(self.view.frame.width/self.view.frame.height))
// Dynamic lighting
self.timer += 0.01
var lights = [Light]()
var sunLight = self.lightFactory.sunLight
sunLight.position = [sin(self.timer) * 3, 1, -4]
let ambientLight = self.lightFactory.ambientLight
var pointLight = self.lightFactory.pointLight
pointLight.position = [0, 0.1, -0.7]
var spotLight = self.lightFactory.spotLight
spotLight.position = [-0.2, 0.3, -0.7]
spotLight.coneDirection = [0.2, -0.3, 0.7]
lights.append(contentsOf: [sunLight, ambientLight, spotLight])
// Fragment shader
let cameraPosition = float3(0, 0, 0)
var fragmentUniforms = FragmentUniforms(lightCount: UInt32(lights.count), cameraPosition: cameraPosition, tiling: 1)
renderCommandEncoder.setFragmentBytes(&lights, length: MemoryLayout<Light>.stride * lights.count, index: Int(BufferIndexLights.rawValue))
self.models.forEach({ (model) in
// Setup pipeline state
guard let renderPipelineState = model.renderPipelineState else {
fatalError("Render command encoder need a pipeline state")
}
renderCommandEncoder.setRenderPipelineState(renderPipelineState)
// Texture
if let textures = model.texture?.compactMap({ return $0.basicColor }) {
renderCommandEncoder.setFragmentTexture(textures.first, index: Int(BaseColorTexture.rawValue))
}
// Sampler
if let samplerState = model.samplerState {
renderCommandEncoder.setFragmentSamplerState(samplerState, index: 0)
}
// Setup vertex buffer ( The [[buffer(0)]] attribute in shader)
if let vertexBuffer = model.vertexBuffer {
renderCommandEncoder.setVertexBuffer(vertexBuffer, offset: 0, index: Int(BufferIndexVertex.rawValue))
}
// Setup the uniform data in vertex shader
let normalMatrix = float3x3(normalFrom4x4: model.modelMatrix)
var uniforms = Uniforms(modelMatrix: model.modelMatrix, viewMatrix: viewMatrix, projectionMatrix: projectionMatrix, normalMatrix: normalMatrix)
renderCommandEncoder.setVertexBytes(&uniforms, length: MemoryLayout<Uniforms>.stride, index: Int(BufferIndexUniforms.rawValue))
// Fragment Uniforms
fragmentUniforms.tiling = model.tiling
renderCommandEncoder.setFragmentBytes(&fragmentUniforms, length: MemoryLayout<FragmentUniforms>.stride, index: Int(BufferIndexFragmentUniforms.rawValue))
// Draw all primitives in the model by index
model.mesh?.submeshes.forEach({ (subMesh) in
renderCommandEncoder.drawIndexedPrimitives(type: .triangle, indexCount: subMesh.indexCount, indexType: subMesh.indexType, indexBuffer: subMesh.indexBuffer.buffer, indexBufferOffset: subMesh.indexBuffer.offset)
})
})
// Visiable light
var lightUniforms = Uniforms()
lightUniforms.modelMatrix = float4x4.identity()
lightUniforms.viewMatrix = viewMatrix
lightUniforms.projectionMatrix = projectionMatrix
// Debug lighting
// self.lightFactory.debugDirectionLight(sunLight, renderEncoder: renderCommandEncoder, uniforms: lightUniforms)
// self.lightFactory.debugPointLight(pointLight, renderEncoder: renderCommandEncoder, uniforms: lightUniforms, color: pointLight.color)
}
}
}
extension ViewController {
func makeRenderer() -> Renderer {
guard let metalView = view as? MTKView else {
fatalError("Metal need a render view")
}
metalView.depthStencilPixelFormat = .depth32Float
let renderer = Renderer(metalView: metalView)
return renderer
}
func makeDepthStencilState() -> MTLDepthStencilState {
guard let device = renderer.device else {
fatalError("Metal is not supported in this device")
}
let depthStencilDescriptor = MTLDepthStencilDescriptor()
depthStencilDescriptor.depthCompareFunction = .less
depthStencilDescriptor.isDepthWriteEnabled = true
guard let depthStencilState = device.makeDepthStencilState(descriptor: depthStencilDescriptor) else {
fatalError("Create depth stencil state fail")
}
return depthStencilState
}
}
| 42.285714 | 229 | 0.598414 |
87e2c75f74ef989c6fb33fb56a44dad4e5f99af3 | 3,030 | // RuleLength.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
public struct RuleMinLength: RuleType {
let min: UInt
public var id: String?
public var validationError: ValidationError
public init(minLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have at least \(minLength) characters"
min = minLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value else { return nil }
return value.count < Int(min) ? validationError : nil
}
}
public struct RuleMaxLength: RuleType {
let max: UInt
public var id: String?
public var validationError: ValidationError
public init(maxLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have less than \(maxLength) characters"
max = maxLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value else { return nil }
return value.count > Int(max) ? validationError : nil
}
}
public struct RuleExactLength: RuleType {
let length: UInt
public var id: String?
public var validationError: ValidationError
public init(exactLength: UInt, msg: String? = nil, id: String? = nil) {
let ruleMsg = msg ?? "Field value must have exactly \(exactLength) characters"
length = exactLength
validationError = ValidationError(msg: ruleMsg)
self.id = id
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value else { return nil }
return value.count != Int(length) ? validationError : nil
}
}
| 35.647059 | 86 | 0.686469 |
5d3998ae6ca482b7899c8fc088c9dc03ce15f8ae | 1,071 | //
// CDAKReferenceTest.swift
// CDAKit
//
// Created by Eric Whitley on 12/9/15.
// Copyright © 2015 Eric Whitley. All rights reserved.
//
import XCTest
@testable import CDAKit
class CDAKReferenceTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test_references() {
let r = CDAKRecord()
let c1 = CDAKCondition()
let c2 = CDAKCondition()
r.conditions.append(c1)
r.conditions.append(c2)
c1.add_reference(c2, type: "FLFS")
let refs = c1.references.filter({$0.type == "FLFS"})
XCTAssertEqual(1, refs.count, "expected 1 reference")
// let entries = r.entries
// let x = refs[0].resolve_reference()
// let y = ""
XCTAssertEqual(c2 as CDAKEntry, refs[0].resolve_reference()!)
}
}
| 22.3125 | 109 | 0.639589 |
39349950635583a72f07494c55339506b5fdecb5 | 4,121 | import SceneKit
public typealias BoundingBox = (min: Vector3, max: Vector3)
public typealias BoundingSphere = (center: Vector3, radius: Float)
public class Volume {
public static func boundingSize(_ boundingBox: BoundingBox) -> Vector3 {
return Vector3(abs(boundingBox.max.x - boundingBox.min.x), abs(boundingBox.max.y - boundingBox.min.y), abs(boundingBox.max.z - boundingBox.min.z))
}
public static func boundingCenter(_ boundingBox: BoundingBox) -> Vector3 {
let volumeSize = Volume.boundingSize(boundingBox)
return Vector3(boundingBox.min.x + volumeSize.x / 2,
boundingBox.min.y + volumeSize.y / 2,
boundingBox.min.z + volumeSize.z / 2)
}
public static func moveCenter(_ boundingBox: BoundingBox, center: Vector3Nullable) -> BoundingBox {
let volumeSize = Volume.boundingSize(boundingBox)
var volumeCenter = Volume.boundingCenter(boundingBox)
if let x = center.x { volumeCenter.x = x }
if let y = center.y { volumeCenter.y = y }
if let z = center.z { volumeCenter.z = z }
return (min: Vector3(volumeCenter.x - (volumeSize.x / 2), volumeCenter.y - (volumeSize.y / 2), volumeCenter.z - (volumeSize.z / 2)),
max: Vector3(volumeCenter.x + (volumeSize.x / 2), volumeCenter.y + (volumeSize.y / 2), volumeCenter.z + (volumeSize.z / 2)))
}
}
public func + (left: BoundingBox?, right: BoundingBox?) -> BoundingBox? {
guard let left = left else {
return right
}
guard let right = right else {
return left
}
var add = left
add.min.x = min(left.min.x, right.min.x)
add.min.y = min(left.min.y, right.min.y)
add.min.z = min(left.min.z, right.min.z)
add.max.x = max(left.max.x, right.max.x)
add.max.y = max(left.max.y, right.max.y)
add.max.z = max(left.max.z, right.max.z)
return add
}
public func += (left: inout BoundingBox?, right: BoundingBox?) {
left = left + right
}
public func * (left: BoundingBox, right: Vector3) -> BoundingBox {
return (min: left.min * right, max: left.max * right)
}
public func * (left: BoundingBox, right: Float) -> BoundingBox {
return (min: left.min * right, max: left.max * right)
}
extension GameObject {
public func boundingBoxFromBoundingSphere(relativeTo gameObject: GameObject? = nil) -> BoundingBox? {
return node.boundingBoxFromBoundingSphere(relativeTo: gameObject?.node)
}
public func boundingBox(relativeTo gameObject: GameObject) -> BoundingBox? {
return node.boundingBox(relativeTo: gameObject.node)
}
}
extension SCNNode {
func boundingBoxFromBoundingSphere(relativeTo node: SCNNode? = nil) -> BoundingBox? {
guard let _ = geometry
else { return nil }
let node = node ?? self
let boundingSphere = self.boundingSphere
let relativeCenter = convertPosition(boundingSphere.center, to: node)
return (min: relativeCenter - boundingSphere.radius, max: relativeCenter + boundingSphere.radius)
}
func boundingBox(relativeTo node: SCNNode) -> BoundingBox? {
var boundingBox = childNodes
.reduce(nil) { $0 + $1.boundingBox(relativeTo: node) }
guard let geometry = geometry,
let source = geometry.sources(for: SCNGeometrySource.Semantic.vertex).first
else { return boundingBox }
let vertices = SCNGeometry.vertices(source: source).map { convertPosition($0, to: node) }
guard let first = vertices.first
else { return boundingBox }
boundingBox += vertices.reduce(into: (min: first, max: first), { boundingBox, vertex in
boundingBox.min.x = min(boundingBox.min.x, vertex.x)
boundingBox.min.y = min(boundingBox.min.y, vertex.y)
boundingBox.min.z = min(boundingBox.min.z, vertex.z)
boundingBox.max.x = max(boundingBox.max.x, vertex.x)
boundingBox.max.y = max(boundingBox.max.y, vertex.y)
boundingBox.max.z = max(boundingBox.max.z, vertex.z)
})
return boundingBox
}
}
| 39.247619 | 154 | 0.647173 |
1c11af3cc2e6196fe90374b343798f6b35ab6502 | 262 | //
// Builder.swift
//
//
// Created by Виталий Зарубин on 29.01.2022.
//
import Foundation
protocol IBuilder {
func setName(_ value: String)
func setOs(_ value: DeviceOS)
func setCpu(_ value: DeviceCPU)
func setType(_ value: DeviceType)
}
| 16.375 | 45 | 0.667939 |
7286ae2800fa946e9c3e3091524a91441f7f1b93 | 2,017 | //
// SelectedColorCell.swift
// Tinter
//
// Created by Jairo Eli de Leon on 10/31/16.
// Copyright © 2016 DevMountain. All rights reserved.
//
import UIKit
class SelectedColorCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Properties
let imageView = UIImageView {
$0.image = #imageLiteral(resourceName: "selectedColor")
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
let textView = UILabel {
$0.text = "Pick a base color"
$0.font = FontBook.Medium.of(size: 24)
$0.textColor = Eden.Independence.color
$0.textAlignment = .center
}
let paragraphView = UILabel {
$0.text = "Tap on a color you want to analyze the color harmonies."
$0.font = FontBook.Medium.of(size: 18)
$0.textColor = Eden.Gray.color
$0.textAlignment = .center
$0.numberOfLines = 2
}
let lineSeperatorView = UIView {
$0.backgroundColor = .clear //UIColor(white: 0.9, alpha: 1)
}
// MARK: Setup
func setupViews() {
addSubview(imageView)
addSubview(textView)
addSubview(paragraphView)
addSubview(lineSeperatorView)
imageView.anchorToTop(top: topAnchor, left: leftAnchor, bottom: lineSeperatorView.topAnchor, right: rightAnchor)
textView.anchorWithConstantsToTop(top: lineSeperatorView.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 8, leftConstant: 16, bottomConstant: 0, rightConstant: 16)
paragraphView.anchorWithConstantsToTop(top: textView.bottomAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 16, leftConstant: 28, bottomConstant: 0, rightConstant: 28)
_ = lineSeperatorView.anchor(top: topAnchor, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: frame.height - 160, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 1)
}
}
| 30.560606 | 223 | 0.70947 |
e9468cd67ff6ad978a6ab500d658514b8d858fee | 591 | //
// User.swift
// InstaClone
//
// Created by Manas Aggarwal on 05/12/19.
// Copyright © 2019 Personal. All rights reserved.
//
import Foundation
import UIKit
class User: NSObject {
var username: String
var name: String
var profileImgUrl: String
var uid: String
var email: String
init(username: String = "", name: String = "", profileImgUrl: String = "", uid: String = "", email: String = "") {
self.username = username
self.name = name
self.profileImgUrl = profileImgUrl
self.uid = uid
self.email = email
}
}
| 21.888889 | 118 | 0.612521 |
679754d539019c99f4485f0f8eafbdfce4eee669 | 4,925 | // MIT License
// Copyright (c) 2017 Haik Aslanyan
import Foundation
import UIKit
import Firebase
class User: NSObject {
//MARK: Properties
let name: String
let email: String
let id: String
var profilePic: UIImage
//MARK: Methods
class func registerUser(withName: String, email: String, password: String, profilePic: UIImage, completion: @escaping (Bool) -> Swift.Void) {
Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in
if error == nil {
user?.sendEmailVerification(completion: nil)
let storageRef = Storage.storage().reference().child("usersProfilePics").child(user!.uid)
let imageData = UIImageJPEGRepresentation(profilePic, 0.1)
storageRef.putData(imageData!, metadata: nil, completion: { (metadata, err) in
if err == nil {
let path = metadata?.downloadURL()?.absoluteString
let values = ["name": withName, "email": email, "profilePicLink": path!]
Database.database().reference().child("users").child((user?.uid)!).child("credentials").updateChildValues(values, withCompletionBlock: { (errr, _) in
if errr == nil {
let userInfo = ["email" : email, "password" : password]
UserDefaults.standard.set(userInfo, forKey: "userInformation")
completion(true)
}
})
}
})
}
else {
completion(false)
}
})
}
class func loginUser(withEmail: String, password: String, completion: @escaping (Bool) -> Swift.Void) {
Auth.auth().signIn(withEmail: withEmail, password: password, completion: { (user, error) in
if error == nil {
let userInfo = ["email": withEmail, "password": password]
UserDefaults.standard.set(userInfo, forKey: "userInformation")
completion(true)
} else {
completion(false)
}
})
}
class func logOutUser(completion: @escaping (Bool) -> Swift.Void) {
do {
try Auth.auth().signOut()
UserDefaults.standard.removeObject(forKey: "userInformation")
completion(true)
} catch _ {
completion(false)
}
}
class func info(forUserID: String, completion: @escaping (User) -> Swift.Void) {
Database.database().reference().child("users").child(forUserID).child("credentials").observeSingleEvent(of: .value, with: { (snapshot) in
if let data = snapshot.value as? [String: String] {
let name = data["name"]!
let email = data["email"]!
let link = URL.init(string: data["profilePicLink"]!)
URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in
if error == nil {
let profilePic = UIImage.init(data: data!)
let user = User.init(name: name, email: email, id: forUserID, profilePic: profilePic!)
completion(user)
}
}).resume()
}
})
}
class func downloadAllUsers(exceptID: String, completion: @escaping (User) -> Swift.Void) {
Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
let id = snapshot.key
let data = snapshot.value as! [String: Any]
let credentials = data["credentials"] as! [String: String]
if id != exceptID {
let name = credentials["name"]!
let email = credentials["email"]!
let link = URL.init(string: credentials["profilePicLink"]!)
URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in
if error == nil {
let profilePic = UIImage.init(data: data!)
let user = User.init(name: name, email: email, id: id, profilePic: profilePic!)
completion(user)
}
}).resume()
}
})
}
class func checkUserVerification(completion: @escaping (Bool) -> Swift.Void) {
Auth.auth().currentUser?.reload(completion: { (_) in
let status = (Auth.auth().currentUser?.isEmailVerified)!
completion(status)
})
}
//MARK: Inits
init(name: String, email: String, id: String, profilePic: UIImage) {
self.name = name
self.email = email
self.id = id
self.profilePic = profilePic
}
}
| 41.041667 | 173 | 0.530964 |
8fd1ae602bfd754f146f17bfe0c1cc96da1adcc9 | 11,866 | //
// PostgresTimeWithTimeZone.swift
// PostgresClientKit
//
// Copyright 2019 David Pitfield and the PostgresClientKit contributors
//
// 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
/// Represents a Postgres `TIME WITH TIME ZONE` value, which consists of the following components:
///
/// - hour
/// - minute
/// - seconds (and fractional seconds)
/// - time zone (expressed as an offset from UTC/GMT)
///
/// For example, `20:10:05.128-07:00`.
///
/// Unlike `TIMESTAMP WITH TIME ZONE`, a `TIME WITH TIME ZONE` value is not normalized to UTC/GMT;
/// the time zone in which it is specified is preserved.
///
/// Like Foundation `DateComponents`, PostgresClientKit records fractional seconds in nanoseconds.
/// However, [due to a bug](https://stackoverflow.com/questions/23684727) in the Foundation
/// `DateFormatter` class, only 3 fractional digits are preserved (millisecond resolution) in
/// values sent to and received from the Postgres server.
public struct PostgresTimeWithTimeZone:
PostgresValueConvertible, Equatable, CustomStringConvertible {
/// Creates a `PostgresTimeWithTimeZone` from components.
///
/// For example, to represent `20:10:05.128-07:00`:
///
/// let time = PostgresTimeWithTimeZone(hour: 20,
/// minute: 10,
/// second: 05,
/// nanosecond: 128000000,
/// timeZone: TimeZone(secondsFromGMT: -7 * 60 * 60)!)
///
/// The specified time zone must have a fixed offset from UTC/GMT; its offset must not change
/// due to daylight savings time. (This requirement is a consequence of `TIME WITH TIME ZONE`
/// values not having the year, month, and day components required to determine whether daylight
/// savings time is in effect.)
///
/// - Parameters:
/// - hour: the hour value
/// - minute: the minute value
/// - second: the second value
/// - nanosecond: the nanosecond value
/// - timeZone: the time zone in which to interpret these components
public init?(hour: Int,
minute: Int,
second: Int,
nanosecond: Int = 0,
timeZone: TimeZone) {
#if os(Linux) // temporary workaround for https://bugs.swift.org/browse/SR-10516
guard timeZone.nextDaylightSavingTimeTransition == nil ||
timeZone.nextDaylightSavingTimeTransition?.timeIntervalSinceReferenceDate == 0.0 else {
Postgres.logger.info(
"timeZone must not observe daylight savings time; use TimeZone(secondsFromGMT:)")
return nil
}
#else
guard timeZone.nextDaylightSavingTimeTransition == nil else {
Postgres.logger.info(
"timeZone must not observe daylight savings time; use TimeZone(secondsFromGMT:)")
return nil
}
#endif
var dc = DateComponents()
dc.hour = hour
dc.minute = minute
dc.second = second
dc.nanosecond = nanosecond
dc.timeZone = timeZone
guard dc.isValidDate(in: Postgres.enUsPosixUtcCalendar) else {
return nil
}
inner = Inner(dateComponents: dc)
}
/// Creates a `PostgresTimeWithTimeZone` by interpreting a `Date` in a specified time zone to
/// obtain the hour, minute, second, and fractional second components, discarding the year,
/// month, and day components.
///
/// (Foundation `Date` instances represent moments in time, not *(year, month, day)* tuples.)
///
/// The specified time zone must have a fixed offset from UTC/GMT; its offset must not change
/// due to daylight savings time. (This requirement is a consequence of `TIME WITH TIME ZONE`
/// values not having the year, month, and day components required to determine whether daylight
/// savings time is in effect.)
///
/// - Parameters:
/// - date: the moment in time
/// - timeZone: the time zone in which to interpret that moment
public init?(date: Date, in timeZone: TimeZone) {
let dc = Postgres.enUsPosixUtcCalendar.dateComponents(in: timeZone, from: date)
guard let hour = dc.hour,
let minute = dc.minute,
let second = dc.second,
let nanosecond = dc.nanosecond else {
// Can't happen.
preconditionFailure("Invalid date components from \(date): \(dc)")
}
self.init(hour: hour,
minute: minute,
second: second,
nanosecond: nanosecond,
timeZone: timeZone)
}
/// Creates a `PostgresTimeWithTimeZone` from a string.
///
/// The string must conform to the [date format pattern](
/// http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns)
/// `HH:mm:ss.SSSxxxxx`. For example, `20:10:05.128-07:00`.
///
/// - Parameter string: the string
public init?(_ string: String) {
var string = string.trimmingCharacters(in: [ " " ])
var timeZone: TimeZone
if string.hasSuffix("Z") {
timeZone = TimeZone(secondsFromGMT: 0)!
string.removeLast()
} else {
guard let offsetSignIndex = string.lastIndex(where: { $0 == "+" || $0 == "-" }) else {
return nil
}
var offset = (string[offsetSignIndex] == "+") ? 1 : -1
var timeZoneString = string[string.index(after: offsetSignIndex)...].filter { $0 != ":" }
string.removeSubrange(offsetSignIndex...)
if timeZoneString.count == 1 || timeZoneString.count == 3 {
timeZoneString = "0" + timeZoneString
}
switch timeZoneString.count {
case 4:
let i2 = timeZoneString.index(timeZoneString.startIndex, offsetBy: 2)
guard let offsetHH = Int(timeZoneString[..<i2]) else { return nil }
guard let offsetMM = Int(timeZoneString[i2...]) else { return nil }
offset *= 3600 * offsetHH + 60 * offsetMM
case 2:
guard let offsetHH = Int(timeZoneString) else { return nil }
offset *= 3600 * offsetHH
default:
return nil
}
guard let tz = TimeZone(secondsFromGMT: offset) else {
return nil
}
timeZone = tz
}
guard var date = PostgresTimeWithTimeZone.formatter.date(from: string) else {
return nil
}
date = date - TimeInterval(exactly: timeZone.secondsFromGMT())!
self.init(date: date, in: timeZone)
}
/// A `DateComponents` for this `PostgresTimeWithTimeZone`.
///
/// The returned value has the following components set:
///
/// - `hour`
/// - `minute`
/// - `second`
/// - `nanosecond`
/// - `timeZone`
public var dateComponents: DateComponents {
return inner.dateComponents
}
/// A `Date` for this `PostgresTimeWithTimeZone`, created by setting the year component to 2000
/// and the month and day components to 1.
///
/// (Foundation `Date` instances represent moments in time, not *(year, month, day)* tuples.)
///
/// - Parameter timeZone: the time zone
/// - Returns: the moment in time
public var date: Date {
return inner.date
}
/// The time zone in which this `PostgresTimeWithTimeZone` was specified.
public var timeZone: TimeZone {
return inner.dateComponents.timeZone!
}
//
// MARK: PostgresValueConvertible
//
/// A `PostgresValue` for this `PostgresTimeWithTimeZone`.
public var postgresValue: PostgresValue {
return inner.postgresValue
}
//
// MARK: Equatable
//
/// True if `lhs.postgresValue == rhs.postgresValue`.
public static func == (lhs: PostgresTimeWithTimeZone, rhs: PostgresTimeWithTimeZone) -> Bool {
return lhs.postgresValue == rhs.postgresValue
}
//
// MARK: CustomStringConvertible
//
/// A string representation of this `PostgresTimeWithTimeZone`.
///
/// Equivalent to `String(describing: postgresValue)`.
public var description: String {
return String(describing: postgresValue)
}
//
// MARK: Implementation
//
/// Formats Postgres `TIME WITH TIME ZONE` values (excluding the terminal time zone part).
private static let formatter: DateFormatter = {
let df = DateFormatter()
df.calendar = Postgres.enUsPosixUtcCalendar
df.dateFormat = "HH:mm:ss.SSS"
df.locale = Postgres.enUsPosixLocale
df.timeZone = Postgres.utcTimeZone
return df
}()
// Inner class to allow the struct to be immutable yet have lazily instantiated properties.
private let inner: Inner
private class Inner {
fileprivate init(dateComponents: DateComponents) {
self.dateComponents = dateComponents
}
fileprivate let dateComponents: DateComponents
fileprivate lazy var date: Date = {
var dc = dateComponents
dc.calendar = Postgres.enUsPosixUtcCalendar
dc.year = 2000
dc.month = 1
dc.day = 1
return Postgres.enUsPosixUtcCalendar.date(from: dc)! // validated components on the way in
}()
fileprivate lazy var postgresValue: PostgresValue = {
var dc = dateComponents
dc.calendar = Postgres.enUsPosixUtcCalendar
dc.timeZone = Postgres.utcTimeZone // since formatter assumes UTC; timeZone handled below
dc.year = 2000
dc.month = 1
dc.day = 1
let d = Postgres.enUsPosixUtcCalendar.date(from: dc)!
let s = PostgresTimeWithTimeZone.formatter.string(from: d)
var offset = dateComponents.timeZone!.secondsFromGMT()
var timeZoneString = (offset < 0) ? "-" : "+"
offset = abs(offset)
let offsetHH = offset / 3600
let offsetMM = (offset % 3600) / 60
timeZoneString += String(format: "%02d:%02d", offsetHH, offsetMM)
return PostgresValue(s + timeZoneString)
}()
}
}
public extension Date {
/// Creates a `PostgresTimeWithTimeZone` by interpreting this `Date` in a specified time zone.
///
/// Equivalent to `PostgresTimeWithTimeZone(date: self, in: timeZone)`.
///
/// - Parameter timeZone: the time zone
/// - Returns: the `PostgresTimeWithTimeZone`
func postgresTimeWithTimeZone(in timeZone: TimeZone) -> PostgresTimeWithTimeZone? {
return PostgresTimeWithTimeZone(date: self, in: timeZone)
}
}
// EOF
| 36.510769 | 103 | 0.586887 |
f4d8185ef6337bb688e1b804da17146680f23439 | 4,339 | //
// Rendition.swift
// CartoolKit
//
// Created by Xudong Xu on 1/11/21.
//
import Cocoa
import CoreUI
import UniformTypeIdentifiers
public class LazyRendition: Rendition {
private var unsafeCreatedNSImageStore: NSImage? = nil
public var unsafeCreatedNSImage: NSImage? {
get {
if unsafeCreatedNSImageStore == nil {
unsafeCreatedNSImageStore = unsafeCreateImage()
.map { ($0, .zero) }
.map(NSImage.init(cgImage:size:))
}
return unsafeCreatedNSImageStore
} set {
unsafeCreatedNSImageStore = newValue
}
}
}
public class Rendition {
public var fileName: String {
internalRendition.name()
}
public var internalName: String {
internalRendition.internalName
}
public var renditionClass: String {
internalRendition.className.replacingOccurrences(of: "_", with: "")
}
public let renditionName: String
public let appearance: String
public var scale: Int {
Int(internalRendition.scale())
}
public var isVector: Bool {
internalRendition.isVectorBased() && !internalRendition.isInternalLink()
}
public var isPDF: Bool {
internalRendition.isPDFRendition
}
public var isLinkingToPDF: Bool {
internalRendition.isInternalLink() && internalRendition.linkingTo().isPDFRendition
}
public var isSVG: Bool {
internalRendition.isSVGRendition
}
public var isLinkingToSVG: Bool {
internalRendition.isInternalLink() && internalRendition.linkingTo().isSVGRendition
}
internal var internalRendition: CUIThemeRendition
required init(_ rendition: CUIThemeRendition, _ renditionName: String, _ appearance: String) {
self.internalRendition = rendition
self.renditionName = renditionName
self.appearance = appearance
}
public func unsafeCreateImage() -> CGImage? {
let snapshot = internalRendition.createImage()
return snapshot
}
public func unsafeCreateImageRep() -> NSBitmapImageRep? {
guard let created: CGImage = unsafeCreateImage() else {
return nil
}
let rep = NSBitmapImageRep(cgImage: created)
rep.size = CGSize(width: created.width, height: created.height)
return rep
}
@discardableResult
public func writeTo(_ providedURL: URL, options: Data.WritingOptions = [.atomicWrite]) throws -> URL {
var fileURL = providedURL
//UIAppearanceAny UIAppearanceLight UIAppearanceDark
fileURL.appendPathComponent(appearance)
NSLog("%@", appearance);
if !renditionName.isEmpty {
fileURL.appendPathComponent(renditionName)
}
if !FileManager.default.fileExists(atPath: fileURL.path) {
try FileManager.default.createDirectory(at: fileURL, withIntermediateDirectories: true, attributes: nil)
}
if scale > 1 {
let file = URL(string: "file:///\(fileName)".addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)!)!
let pathExtension = file.pathExtension
//change
//fileURL.appendPathComponent("\(fileName.dropLast(pathExtension.count + 1))@\(scale)x.\(pathExtension)")
fileURL.appendPathComponent("\(renditionName)@\(scale)x.\(pathExtension)")
//change
} else {
fileURL.appendPathComponent(fileName)
}
if isSVG {
CGSVGDocumentWriteToURL(internalRendition.svgDocument(), fileURL as CFURL, nil)
} else if isPDF {
try internalRendition.srcData.map {
try $0.write(to: fileURL, options: options)
}
} else {
if fileURL.pathExtension != UTType.png.preferredFilenameExtension {
fileURL.appendPathExtension(for: .png)
}
try unsafeCreateImageRep()?.data().map {
try $0.write(to: fileURL, options: options)
}
}
return fileURL
}
}
| 28.926667 | 121 | 0.595759 |
2289f7aca583c5dcb0b4fa88199a7b68dd96a4c3 | 15,080 | //
// 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 MaterialComponents
protocol SessionFeedbackRatingDelegate: NSObjectProtocol {
func cell(_ cell: SessionFeedbackCollectionViewCell,
didChangeRating rating: Int?,
`for` feedbackQuestion: FeedbackQuestion)
}
class SessionFeedbackCollectionViewCell: UICollectionViewCell {
private enum Constants {
static let padding: CGFloat = 16
static let bodyFont = UIFont.preferredFont(forTextStyle: .body)
static let contentTextColor = UIColor(red: 66 / 255, green: 66 / 255, blue: 66 / 255, alpha: 1)
}
let titleLabel = UILabel()
let ratingView = RatingView()
private var feedbackQuestion: FeedbackQuestion?
weak var delegate: SessionFeedbackRatingDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(titleLabel)
contentView.addSubview(ratingView)
setupTitleLabel()
setupRatingView()
setupConstraints()
contentView.layer.cornerRadius = 8
contentView.layer.borderColor = UIColor(hex: 0xdadce0).cgColor
contentView.layer.borderWidth = 1
}
func setupTitleLabel() {
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.font = Constants.bodyFont
titleLabel.enableAdjustFontForContentSizeCategory()
titleLabel.textColor = Constants.contentTextColor
}
func setupRatingView() {
ratingView.translatesAutoresizingMaskIntoConstraints = false
ratingView.addTarget(self, action: #selector(ratingDidChange(_:)), for: .valueChanged)
}
func setupConstraints() {
var constraints: [NSLayoutConstraint] = []
// title label top
constraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .top,
relatedBy: .equal,
toItem: contentView,
attribute: .top,
multiplier: 1,
constant: Constants.padding))
// title label left
constraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .left,
relatedBy: .equal,
toItem: contentView,
attribute: .left,
multiplier: 1,
constant: Constants.padding))
// title label right
constraints.append(NSLayoutConstraint(item: titleLabel,
attribute: .right,
relatedBy: .equal,
toItem: contentView,
attribute: .right,
multiplier: 1,
constant: -Constants.padding))
// rating view top
constraints.append(NSLayoutConstraint(item: ratingView,
attribute: .top,
relatedBy: .equal,
toItem: titleLabel,
attribute: .bottom,
multiplier: 1,
constant: Constants.padding))
// rating view center
constraints.append(NSLayoutConstraint(item: ratingView,
attribute: .centerX,
relatedBy: .equal,
toItem: contentView,
attribute: .centerX,
multiplier: 1,
constant: 0))
contentView.addConstraints(constraints)
}
func populate(question: FeedbackQuestion,
rating: Int?,
delegate: SessionFeedbackRatingDelegate?,
didSubmitFeedback: Bool = false) {
feedbackQuestion = question
titleLabel.text = question.body
ratingView.accessibilityLabel = question.body
ratingView.rating = rating
self.delegate = delegate
if didSubmitFeedback {
isUserInteractionEnabled = false
} else {
isUserInteractionEnabled = true
}
}
@objc private func ratingDidChange(_ sender: Any) {
guard let view = sender as? RatingView else { return }
guard view === ratingView else { return }
delegate?.cell(self, didChangeRating: ratingView.rating, for: feedbackQuestion!)
}
override func prepareForReuse() {
delegate = nil
feedbackQuestion = nil
}
static func heightForCell(withTitle title: String, maxWidth: CGFloat) -> CGFloat {
let titleHeight = title.boundingRect(with: CGSize(width: maxWidth - 2 * Constants.padding,
height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin],
attributes: [NSAttributedString.Key.font: Constants.bodyFont],
context: nil).height
return titleHeight + Constants.padding * 3 + RatingView.viewHeight
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported for cell of type: \(SessionFeedbackCollectionViewCell.self)")
}
}
class FeedbackHeader: UICollectionReusableView {
private enum Constants {
static let font = UIFont.preferredFont(forTextStyle: .title2)
static let textColor = UIColor(red: 66 / 255, green: 66 / 255, blue: 66 / 255, alpha: 1)
static let padding: CGFloat = 16
static let submittedFont = UIFont.preferredFont(forTextStyle: .callout)
static let submittedBackgroundColor = UIColor(red: 28 / 255, green: 232 / 255, blue: 181 / 255, alpha: 1)
static let submittedText = NSLocalizedString("You've already submitted feedback for this session.",
comment: "Describing a session the user has already reviewed")
}
static let identifier = "FeedbackHeader"
private let label = UILabel()
private var didSubmitFeedback: Bool {
didSet {
removeSubmittedLabel()
if didSubmitFeedback {
addSubmittedLabel()
setNeedsLayout()
}
}
}
private let submittedLabel = UILabel()
private let submittedLabelContainer = UIView()
override init(frame: CGRect) {
didSubmitFeedback = false
super.init(frame: frame)
backgroundColor = .white
addSubview(label)
addSubview(submittedLabelContainer)
setupLabel()
setupSubmittedLabelContainer()
setupSubmittedLabel()
setupConstraints()
}
private func setupLabel() {
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.textColor = Constants.textColor
label.enableAdjustFontForContentSizeCategory()
label.font = Constants.font
}
private func setupConstraints() {
var constraints: [NSLayoutConstraint] = []
// label top
constraints.append(NSLayoutConstraint(item: label,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: Constants.padding))
// label left
constraints.append(NSLayoutConstraint(item: label,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1,
constant: 0))
// label right
constraints.append(NSLayoutConstraint(item: label,
attribute: .right,
relatedBy: .equal,
toItem: self,
attribute: .right,
multiplier: 1,
constant: 0))
// submitted container view top
constraints.append(NSLayoutConstraint(item: submittedLabelContainer,
attribute: .top,
relatedBy: .equal,
toItem: label,
attribute: .bottom,
multiplier: 1,
constant: Constants.padding))
// submitted container view left
constraints.append(NSLayoutConstraint(item: submittedLabelContainer,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1,
constant: 0))
// submitted container view right
constraints.append(NSLayoutConstraint(item: submittedLabelContainer,
attribute: .right,
relatedBy: .equal,
toItem: self,
attribute: .right,
multiplier: 1,
constant: 0))
// submitted container view bottom
constraints.append(NSLayoutConstraint(item: submittedLabelContainer,
attribute: .bottom,
relatedBy: .equal,
toItem: self,
attribute: .bottom,
multiplier: 1,
constant: 0))
addConstraints(constraints)
}
private func addSubmittedLabel(withText text: String = Constants.submittedText) {
submittedLabel.text = text
submittedLabelContainer.addSubview(submittedLabel)
var constraints: [NSLayoutConstraint] = []
// submitted label top
constraints.append(NSLayoutConstraint(item: submittedLabel,
attribute: .top,
relatedBy: .equal,
toItem: submittedLabelContainer,
attribute: .top,
multiplier: 1,
constant: Constants.padding))
// submitted label left
constraints.append(NSLayoutConstraint(item: submittedLabel,
attribute: .left,
relatedBy: .equal,
toItem: submittedLabelContainer,
attribute: .left,
multiplier: 1,
constant: Constants.padding))
// submitted label right
constraints.append(NSLayoutConstraint(item: submittedLabel,
attribute: .right,
relatedBy: .equal,
toItem: submittedLabelContainer,
attribute: .right,
multiplier: 1,
constant: -Constants.padding))
submittedLabelContainer.addConstraints(constraints)
}
private func removeSubmittedLabel() {
submittedLabelContainer.removeConstraints(submittedLabelContainer.constraints)
submittedLabelContainer.subviews.forEach {
$0.removeFromSuperview()
}
}
private static func submittedLabelHeight(withText text: String = Constants.submittedText,
maxWidth: CGFloat) -> CGFloat {
let textHeight = text.boundingRect(with: CGSize(width: maxWidth - Constants.padding * 2,
height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin],
attributes: [NSAttributedString.Key.font: Constants.submittedFont],
context: nil).size.height
return textHeight + 2 * Constants.padding
}
private func setupSubmittedLabelContainer() {
submittedLabelContainer.translatesAutoresizingMaskIntoConstraints = false
}
private func setupSubmittedLabel() {
submittedLabel.translatesAutoresizingMaskIntoConstraints = false
submittedLabel.enableAdjustFontForContentSizeCategory()
submittedLabel.font = Constants.submittedFont
submittedLabel.textColor = Constants.textColor
submittedLabel.numberOfLines = 0
}
func populate(title: String, feedbackSubmitted: Bool) {
label.text = title
didSubmitFeedback = feedbackSubmitted
}
static func height(withTitle title: String,
maxWidth: CGFloat,
submittedFeedback: Bool) -> CGFloat {
let submittedHeight = submittedFeedback ? submittedLabelHeight(maxWidth: maxWidth) : 0
let textHeight = title.boundingRect(with: CGSize(width: maxWidth - Constants.padding * 2,
height: .greatestFiniteMagnitude),
options: [.usesLineFragmentOrigin, .usesDeviceMetrics, .usesFontLeading],
attributes: [NSAttributedString.Key.font: Constants.font],
context: nil).size.height
return textHeight + 2 * Constants.padding + submittedHeight
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 40.978261 | 113 | 0.524536 |
91e46f3157076ebf6c08426942a1fb0cd8f4f181 | 986 | import Foundation
extension Int64: XDRCodable {
public func toXDR() -> Data {
var n = UInt64(bitPattern: self)
var array = [UInt8]()
let divisor = UInt64(UInt8.max) + 1
for _ in 0..<(self.bitWidth / UInt8.bitWidth) {
array.append(UInt8(n % divisor))
n /= divisor
}
return Data(bytes: array.reversed())
}
public init(xdrData: inout Data) throws {
var n: UInt64 = 0
let count = UInt64.bitWidth / UInt8.bitWidth
if xdrData.count < count {
throw XDRErrors.decodingError
}
xdrData.withUnsafeBytes { (bp: UnsafePointer<UInt8>) -> Void in
for index in 0..<count {
n *= 256
n += UInt64(bp.advanced(by: index).pointee)
}
}
(0..<count).forEach { _ in xdrData.remove(at: 0) }
self = Int64(bitPattern: n)
}
}
| 25.947368 | 71 | 0.494929 |
23ca06723f1703420c59579dcda9207f6dfbd549 | 2,092 | //
// AppDelegate.swift
// PWSideViewControlSwift
//
// Created by PeterWang on 7/16/15.
// Copyright (c) 2015 PeterWang. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 44.510638 | 281 | 0.777725 |
0ad13ac7cb21738e4d824583a708e16dd09229cf | 3,969 | import Benchmark
import Foundation
import Parsing
/// This benchmarks implements an [RFC-3339-compliant](https://www.ietf.org/rfc/rfc3339.txt) date
/// parser in a relatively naive way and pits it against `DateFormatter` and `ISO8601DateFormatter`.
///
/// Not only is the parser faster than both formatters, it is more flexible and accurate: it will parse
/// parse fractional seconds and time zone offsets automatically, and it will parse to the nanosecond,
/// while the formatters do not parse beyond the millisecond.
let dateSuite = BenchmarkSuite(name: "Date") { suite in
let digits = { (n: Int) in
Prefix<Substring.UTF8View>(n) {
(.init(ascii: "0") ... .init(ascii: "9")).contains($0)
}
.pipe {
Int.parser()
End()
}
}
let dateFullyear = digits(4)
let dateMonth = digits(2)
let dateMday = digits(2)
let timeDelim = OneOf {
"T".utf8
"t".utf8
" ".utf8
}
let timeHour = digits(2)
let timeMinute = digits(2)
let timeSecond = digits(2)
let nanoSecfrac = Prefix(while: (.init(ascii: "0") ... .init(ascii: "9")).contains)
.map { $0.prefix(9) }
let timeSecfrac = Parse {
".".utf8
nanoSecfrac
}
.compactMap { n in
Int(String(decoding: n, as: UTF8.self))
.map { $0 * Int(pow(10, 9 - Double(n.count))) }
}
let timeNumoffset = Parse {
OneOf {
"+".utf8.map { 1 }
"-".utf8.map { -1 }
}
timeHour
":".utf8
timeMinute
}
let timeOffset = OneOf {
"Z".utf8.map { ( /*sign: */1, /*minute: */ 0, /*second: */ 0) }
timeNumoffset
}
.compactMap { TimeZone(secondsFromGMT: $0 * ($1 * 60 + $2)) }
let partialTime = Parse {
timeHour
":".utf8
timeMinute
":".utf8
timeSecond
Optionally {
timeSecfrac
}
}
let fullDate = Parse {
dateFullyear
"-".utf8
dateMonth
"-".utf8
dateMday
}
let offsetDateTime = Parse {
fullDate
timeDelim
partialTime
timeOffset
}
.map { date, time, timeZone -> DateComponents in
let (year, month, day) = date
let (hour, minute, second, nanosecond) = time
return DateComponents(
timeZone: timeZone,
year: year, month: month, day: day,
hour: hour, minute: minute, second: second, nanosecond: nanosecond
)
}
let localDateTime = Parse {
fullDate
timeDelim
partialTime
}
.map { date, time -> DateComponents in
let (year, month, day) = date
let (hour, minute, second, nanosecond) = time
return DateComponents(
year: year, month: month, day: day,
hour: hour, minute: minute, second: second, nanosecond: nanosecond
)
}
let localDate =
fullDate
.map { DateComponents(year: $0, month: $1, day: $2) }
let localTime =
partialTime
.map { DateComponents(hour: $0, minute: $1, second: $2, nanosecond: $3) }
let dateTime = OneOf {
offsetDateTime
localDateTime
localDate
localTime
}
let input = "1979-05-27T00:32:00Z"
let expected = Date(timeIntervalSince1970: 296_613_120)
var output: Date!
let dateTimeParser = dateTime.compactMap(Calendar.current.date(from:))
suite.benchmark("Parser") {
var input = input[...].utf8
output = try dateTimeParser.parse(&input)
} tearDown: {
precondition(output == expected)
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)!
suite.benchmark("DateFormatter") {
output = dateFormatter.date(from: input)
} tearDown: {
precondition(output == expected)
}
if #available(macOS 10.12, *) {
let iso8601DateFormatter = ISO8601DateFormatter()
iso8601DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
suite.benchmark("ISO8601DateFormatter") {
output = iso8601DateFormatter.date(from: input)
} tearDown: {
precondition(output == expected)
}
}
}
| 24.80625 | 103 | 0.633913 |
9bde7ec5ec668f95787b923e8c3ef7f0fea91e55 | 1,421 | //
// hwaheaUITests.swift
// hwaheaUITests
//
// Created by seungjin on 2020/01/07.
// Copyright © 2020 Jinnify. All rights reserved.
//
import XCTest
class hwaheaUITests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 32.295455 | 182 | 0.651654 |
231a9ec05766652e35f562392511d6d17b05d724 | 648 | import Cocoa
import FlutterMacOS
public class FlireatorPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "flireator", binaryMessenger: registrar.messenger)
let instance = FlireatorPlugin()
registrar.addMethodCallDelegate(instance, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "getPlatformVersion":
result("macOS " + ProcessInfo.processInfo.operatingSystemVersionString)
default:
result(FlutterMethodNotImplemented)
}
}
}
| 32.4 | 95 | 0.760802 |
fee0037223c3fd9a82062c9298cf4b1c2c47aeaf | 246 | let Prototype = ThieveryCorporationPersonDisplay(font:"Ubuntu")
let Philippe = Prototype.clone()
Philippe.name = "Philippe"
let Christoph = Prototype.clone()
Christoph.name = "Christoph"
let Eduardo = Prototype.clone()
Eduardo.name = "Eduardo" | 24.6 | 63 | 0.768293 |
28526c8da6798182a5bb855bee628ed41d17b671 | 18,982 | //
// ArrayExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 SwifterSwift
//
// MARK: - Methods (Integer)
public extension Array where Element: Numeric {
/// SwifterSwift: Sum of all elements in array.
///
/// [1, 2, 3, 4, 5].sum() -> 15
///
/// - Returns: sum of the array's elements.
public func sum() -> Element {
var total: Element = 0
for i in 0..<count {
total += self[i]
}
return total
}
}
// MARK: - Methods (FloatingPoint)
public extension Array where Element: FloatingPoint {
/// SwifterSwift: Average of all elements in array.
///
/// [1.2, 2.3, 4.5, 3.4, 4.5].average() = 3.18
///
/// - Returns: average of the array's elements.
public func average() -> Element {
guard !isEmpty else { return 0 }
var total: Element = 0
for i in 0..<count {
total += self[i]
}
return total / Element(count)
}
}
// MARK: - Methods
public extension Array {
/// SwifterSwift: Element at the given index if it exists.
///
/// [1, 2, 3, 4, 5].item(at: 2) -> 3
/// [1.2, 2.3, 4.5, 3.4, 4.5].item(at: 3) -> 3.4
/// ["h", "e", "l", "l", "o"].item(at: 10) -> nil
///
/// - Parameter index: index of element.
/// - Returns: optional element (if exists).
public func item(at index: Int) -> Element? {
guard startIndex..<endIndex ~= index else { return nil }
return self[index]
}
/// SwifterSwift: Remove last element from array and return it.
///
/// [1, 2, 3, 4, 5].pop() // returns 5 and remove it from the array.
/// [].pop() // returns nil since the array is empty.
///
/// - Returns: last element in array (if applicable).
@discardableResult public mutating func pop() -> Element? {
return popLast()
}
/// SwifterSwift: Insert an element at the beginning of array.
///
/// [2, 3, 4, 5].prepend(1) -> [1, 2, 3, 4, 5]
/// ["e", "l", "l", "o"].prepend("h") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
public mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// SwifterSwift: Insert an element to the end of array.
///
/// [1, 2, 3, 4].push(5) -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l"].push("o") -> ["h", "e", "l", "l", "o"]
///
/// - Parameter newElement: element to insert.
public mutating func push(_ newElement: Element) {
append(newElement)
}
/// SwifterSwift: Safely Swap values at index positions.
///
/// [1, 2, 3, 4, 5].safeSwap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].safeSwap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func safeSwap(from index: Int, to otherIndex: Int) {
guard index != otherIndex,
startIndex..<endIndex ~= index,
startIndex..<endIndex ~= otherIndex else { return }
swapAt(index, otherIndex)
}
/// SwifterSwift: Swap values at index positions.
///
/// [1, 2, 3, 4, 5].swap(from: 3, to: 0) -> [4, 2, 3, 1, 5]
/// ["h", "e", "l", "l", "o"].swap(from: 1, to: 0) -> ["e", "h", "l", "l", "o"]
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func swap(from index: Int, to otherIndex: Int) {
swapAt(index, otherIndex)
}
/// SwifterSwift: Get first index where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 6].firstIndex { $0 % 2 == 0 } -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: first index where the specified condition evaluates to true. (optional)
public func firstIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: Get last index where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 8].lastIndex { $0 % 2 == 0 } -> 6
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: last index where the specified condition evaluates to true. (optional)
public func lastIndex(where condition: (Element) throws -> Bool) rethrows -> Int? {
for (index, value) in lazy.enumerated().reversed() {
if try condition(value) { return index }
}
return nil
}
/// SwifterSwift: Get all indices where condition is met.
///
/// [1, 7, 1, 2, 4, 1, 8].indices(where: { $0 == 1 }) -> [0, 2, 5]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: all indices where the specified condition evaluates to true. (optional)
public func indices(where condition: (Element) throws -> Bool) rethrows -> [Int]? {
var indicies: [Int] = []
for (index, value) in lazy.enumerated() {
if try condition(value) { indicies.append(index) }
}
return indicies.isEmpty ? nil : indicies
}
/// SwifterSwift: Check if all elements in array match a conditon.
///
/// [2, 2, 4].all(matching: {$0 % 2 == 0}) -> true
/// [1,2, 2, 4].all(matching: {$0 % 2 == 0}) -> false
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when all elements in the array match the specified condition.
public func all(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try !condition($0) }
}
/// SwifterSwift: Check if no elements in array match a conditon.
///
/// [2, 2, 4].none(matching: {$0 % 2 == 0}) -> false
/// [1, 3, 5, 7].none(matching: {$0 % 2 == 0}) -> true
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: true when no elements in the array match the specified condition.
public func none(matching condition: (Element) throws -> Bool) rethrows -> Bool {
return try !contains { try condition($0) }
}
/// SwifterSwift: Get last element that satisfies a conditon.
///
/// [2, 2, 4, 7].last(where: {$0 % 2 == 0}) -> 4
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: the last element in the array matching the specified condition. (optional)
public func last(where condition: (Element) throws -> Bool) rethrows -> Element? {
for element in reversed() {
if try condition(element) { return element }
}
return nil
}
/// SwifterSwift: Filter elements based on a rejection condition.
///
/// [2, 2, 4, 7].reject(where: {$0 % 2 == 0}) -> [7]
///
/// - Parameter condition: to evaluate the exclusion of an element from the array.
/// - Returns: the array with rejected values filtered from it.
public func reject(where condition: (Element) throws -> Bool) rethrows -> [Element] {
return try filter { return try !condition($0) }
}
/// SwifterSwift: Get element count based on condition.
///
/// [2, 2, 4, 7].count(where: {$0 % 2 == 0}) -> 3
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: number of times the condition evaluated to true.
public func count(where condition: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try condition(element) { count += 1 }
}
return count
}
/// SwifterSwift: Iterate over a collection in reverse order. (right to left)
///
/// [0, 2, 4, 7].forEachReversed({ print($0)}) -> //Order of print: 7,4,2,0
///
/// - Parameter body: a closure that takes an element of the array as a parameter.
public func forEachReversed(_ body: (Element) throws -> Void) rethrows {
try reversed().forEach { try body($0) }
}
/// SwifterSwift: Calls given closure with each element where condition is true.
///
/// [0, 2, 4, 7].forEach(where: {$0 % 2 == 0}, body: { print($0)}) -> //print: 0, 2, 4
///
/// - Parameters:
/// - condition: condition to evaluate each element against.
/// - body: a closure that takes an element of the array as a parameter.
public func forEach(where condition: (Element) throws -> Bool, body: (Element) throws -> Void) rethrows {
for element in self where try condition(element) {
try body(element)
}
}
/// SwifterSwift: Reduces an array while returning each interim combination.
///
/// [1, 2, 3].accumulate(initial: 0, next: +) -> [1, 3, 6]
///
/// - Parameters:
/// - initial: initial value.
/// - next: closure that combines the accumulating value and next element of the array.
/// - Returns: an array of the final accumulated value and each interim combination.
public func accumulate<U>(initial: U, next: (U, Element) throws -> U) rethrows -> [U] {
var runningTotal = initial
return try map { element in
runningTotal = try next(runningTotal, element)
return runningTotal
}
}
/// SwifterSwift: Filtered and map in a single operation.
///
/// [1,2,3,4,5].filtered({ $0 % 2 == 0 }, map: { $0.string }) -> ["2", "4"]
///
/// - Parameters:
/// - isIncluded: condition of inclusion to evaluate each element against.
/// - transform: transform element function to evaluate every element.
/// - Returns: Return an filtered and mapped array.
public func filtered<T>(_ isIncluded: (Element) throws -> Bool, map transform: (Element) throws -> T) rethrows -> [T] {
return try flatMap({
if try isIncluded($0) {
return try transform($0)
}
return nil
})
}
/// SwifterSwift: Keep elements of Array while condition is true.
///
/// [0, 2, 4, 7].keep( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
public mutating func keep(while condition: (Element) throws -> Bool) rethrows {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
self = Array(self[startIndex..<index])
break
}
}
}
/// SwifterSwift: Take element of Array while condition is true.
///
/// [0, 2, 4, 7, 6, 8].take( where: {$0 % 2 == 0}) -> [0, 2, 4]
///
/// - Parameter condition: condition to evaluate each element against.
/// - Returns: All elements up until condition evaluates to false.
public func take(while condition: (Element) throws -> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[startIndex..<index])
}
}
return self
}
/// SwifterSwift: Skip elements of Array while condition is true.
///
/// [0, 2, 4, 7, 6, 8].skip( where: {$0 % 2 == 0}) -> [6, 8]
///
/// - Parameter condition: condition to eveluate each element against.
/// - Returns: All elements after the condition evaluates to false.
public func skip(while condition: (Element) throws-> Bool) rethrows -> [Element] {
for (index, element) in lazy.enumerated() {
if try !condition(element) {
return Array(self[index..<endIndex])
}
}
return [Element]()
}
/// SwifterSwift: Calls given closure with an array of size of the parameter slice where condition is true.
///
/// [0, 2, 4, 7].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7]
/// [0, 2, 4, 7, 6].forEach(slice: 2) { print($0) } -> //print: [0, 2], [4, 7], [6]
///
/// - Parameters:
/// - slice: size of array in each interation.
/// - body: a closure that takes an array of slice size as a parameter.
public func forEach(slice: Int, body: ([Element]) throws -> Void) rethrows {
guard slice > 0, !isEmpty else { return }
var value: Int = 0
while value < count {
try body(Array(self[Swift.max(value, startIndex)..<Swift.min(value + slice, endIndex)]))
value += slice
}
}
/// SwifterSwift: Returns an array of slices of length "size" from the array. If array can't be split evenly, the final slice will be the remaining elements.
///
/// [0, 2, 4, 7].group(by: 2) -> [[0, 2], [4, 7]]
/// [0, 2, 4, 7, 6].group(by: 2) -> [[0, 2], [4, 7], [6]]
///
/// - Parameters:
/// - size: The size of the slices to be returned.
public func group(by size: Int) -> [[Element]]? {
//Inspired by: https://lodash.com/docs/4.17.4#chunk
guard size > 0, !isEmpty else { return nil }
var value: Int = 0
var slices: [[Element]] = []
while value < count {
slices.append(Array(self[Swift.max(value, startIndex)..<Swift.min(value + size, endIndex)]))
value += size
}
return slices
}
/// SwifterSwift: Group the elements of the array in a dictionary.
///
/// [0, 2, 5, 4, 7].groupByKey { $0%2 ? "evens" : "odds" } -> [ "evens" : [0, 2, 4], "odds" : [5, 7] ]
///
/// - Parameter getKey: Clousure to define the key for each element.
/// - Returns: A dictionary with values grouped with keys.
public func groupByKey<K: Hashable>(keyForValue: (_ element: Element) throws -> K) rethrows -> [K: [Element]] {
var group = [K: [Element]]()
for value in self {
let key = try keyForValue(value)
group[key] = (group[key] ?? []) + [value]
}
return group
}
/// SwifterSwift: Returns a new rotated array by the given places.
///
/// [1, 2, 3, 4].rotated(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotated(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
/// - Returns: The new rotated array
public func rotated(by places: Int) -> [Element] {
//Inspired by: https://ruby-doc.org/core-2.2.0/Array.html#method-i-rotate
guard places != 0 && places < count else {
return self
}
var array: [Element] = self
if places > 0 {
let range = (array.count - places)..<array.endIndex
let slice = array[range]
array.removeSubrange(range)
array.insert(contentsOf: slice, at: 0)
} else {
let range = array.startIndex..<(places * -1)
let slice = array[range]
array.removeSubrange(range)
array.append(contentsOf: slice)
}
return array
}
/// SwifterSwift: Rotate the array by the given places.
///
/// [1, 2, 3, 4].rotate(by: 1) -> [4,1,2,3]
/// [1, 2, 3, 4].rotate(by: 3) -> [2,3,4,1]
/// [1, 2, 3, 4].rotated(by: -1) -> [2,3,4,1]
///
/// - Parameter places: Number of places that the array should be rotated. If the value is positive the end becomes the start, if it negative it's that start becom the end.
public mutating func rotate(by places: Int) {
self = rotated(by: places)
}
}
// MARK: - Methods (Equatable)
public extension Array where Element: Equatable {
/// SwifterSwift: Shuffle array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffle() // shuffles array
///
public mutating func shuffle() {
//http://stackoverflow.com/questions/37843647/shuffle-array-swift-3
guard count > 1 else { return }
for index in startIndex..<endIndex - 1 {
let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
if index != randomIndex { swapAt(index, randomIndex) }
}
}
/// SwifterSwift: Shuffled version of array. (Using Fisher-Yates Algorithm)
///
/// [1, 2, 3, 4, 5].shuffled // return a shuffled version from given array e.g. [2, 4, 1, 3, 5].
///
/// - Returns: the array with its elements shuffled.
public func shuffled() -> [Element] {
var array = self
array.shuffle()
return array
}
/// SwifterSwift: Check if array contains an array of elements.
///
/// [1, 2, 3, 4, 5].contains([1, 2]) -> true
/// [1.2, 2.3, 4.5, 3.4, 4.5].contains([2, 6]) -> false
/// ["h", "e", "l", "l", "o"].contains(["l", "o"]) -> true
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { return true }
var found = true
for element in elements {
if !contains(element) {
found = false
}
}
return found
}
/// SwifterSwift: All indexes of specified item.
///
/// [1, 2, 2, 3, 4, 2, 5].indexes(of 2) -> [1, 2, 5]
/// [1.2, 2.3, 4.5, 3.4, 4.5].indexes(of 2.3) -> [1]
/// ["h", "e", "l", "l", "o"].indexes(of "l") -> [2, 3]
///
/// - Parameter item: item to check.
/// - Returns: an array with all indexes of the given item.
public func indexes(of item: Element) -> [Int] {
var indexes: [Int] = []
for index in startIndex..<endIndex where self[index] == item {
indexes.append(index)
}
return indexes
}
/// SwifterSwift: Remove all instances of an item from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll(2) -> [1, 3, 4, 5]
/// ["h", "e", "l", "l", "o"].removeAll("l") -> ["h", "e", "o"]
///
/// - Parameter item: item to remove.
public mutating func removeAll(_ item: Element) {
self = filter { $0 != item }
}
/// SwifterSwift: Remove all instances contained in items parameter from array.
///
/// [1, 2, 2, 3, 4, 5].removeAll([2,5]) -> [1, 3, 4]
/// ["h", "e", "l", "l", "o"].removeAll(["l", "h"]) -> ["e", "o"]
///
/// - Parameter items: items to remove.
public mutating func removeAll(_ items: [Element]) {
guard !items.isEmpty else { return }
self = filter { !items.contains($0) }
}
/// SwifterSwift: Remove all duplicate elements from Array.
///
/// [1, 2, 2, 3, 4, 5].removeDuplicates() -> [1, 2, 3, 4, 5]
/// ["h", "e", "l", "l", "o"]. removeDuplicates() -> ["h", "e", "l", "o"]
///
public mutating func removeDuplicates() {
// Thanks to https://github.com/sairamkotha for improving the method
self = reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: Return array with all duplicate elements removed.
///
/// [1, 1, 2, 2, 3, 3, 3, 4, 5].duplicatesRemoved() -> [1, 2, 3, 4, 5])
/// ["h", "e", "l", "l", "o"].duplicatesRemoved() -> ["h", "e", "l", "o"])
///
/// - Returns: an array of unique elements.
///
public func duplicatesRemoved() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the property
return reduce(into: [Element]()) {
if !$0.contains($1) {
$0.append($1)
}
}
}
/// SwifterSwift: First index of a given item in an array.
///
/// [1, 2, 2, 3, 4, 2, 5].firstIndex(of: 2) -> 1
/// [1.2, 2.3, 4.5, 3.4, 4.5].firstIndex(of: 6.5) -> nil
/// ["h", "e", "l", "l", "o"].firstIndex(of: "l") -> 2
///
/// - Parameter item: item to check.
/// - Returns: first index of item in array (if exists).
public func firstIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated() where value == item {
return index
}
return nil
}
/// SwifterSwift: Last index of element in array.
///
/// [1, 2, 2, 3, 4, 2, 5].lastIndex(of: 2) -> 5
/// [1.2, 2.3, 4.5, 3.4, 4.5].lastIndex(of: 6.5) -> nil
/// ["h", "e", "l", "l", "o"].lastIndex(of: "l") -> 3
///
/// - Parameter item: item to check.
/// - Returns: last index of item in array (if exists).
public func lastIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated().reversed() where value == item {
return index
}
return nil
}
}
| 34.325497 | 173 | 0.600727 |
e45885017f95bb956720607ba0ed1964b220792f | 7,371 | //
// ViewController.swift
// RadioTunes
//
// Created by Chris on 1/19/16.
// Copyright © 2016 Chris Mendez. All rights reserved.
//
import UIKit
import MediaPlayer
class ViewController: UIViewController {
let stream = NSURL(string: "http://playerservices.streamtheworld.com/pls/KUSCAAC64.pls")
var radio:YLHTTPRadio?
var interruptedDuringPlayback = false
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var composerLabel: UILabel!
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var programName: UILabel!
@IBOutlet weak var playPauseButton: UIButton!
@IBAction func onPlayPause(sender: AnyObject) {
if radio?.isPlaying() == false {
radio?.play()
}
else if radio?.isPlaying() == true {
radio?.pause()
}
}
@IBOutlet weak var volumeSlider: UISlider!
@IBAction func onVolumeSlider(sender: AnyObject) {
let slider = sender as? UISlider
//print("onVolumeSlider:", slider?.value)
radio?.setVolume((slider?.value)!)
}
func updatePlayPause(title:String, enabled:Bool){
playPauseButton.titleLabel?.text = ""
playPauseButton.titleLabel?.text = title
playPauseButton.enabled = enabled
}
func updateTitle(title:String){
titleLabel.text = title
//TODO - Split the text using a string parser then updateComposer
}
func updateComposer(composer:String){
composerLabel.text = composer
}
func updateName(name:String){
programName.text = name
}
func updateGenre(genre:String){
genreLabel.text = genre
}
func onLoad(){
print("onLoad \(stream!)")
radio = YLHTTPRadio.init(URL: stream!)
radio?.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
onLoad()
//Tracks the headphone stuff
YLAudioSession.sharedInstance().addDelegate(self)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//Not sure what this does
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func canBecomeFirstResponder() -> Bool {
return true
}
}
extension ViewController:YLAudioSessionDelegate {
func beginInterruption() {
if radio == nil {
print("Begin Interruption")
return
}
if radio?.isPlaying() == true {
print("Interrupted During Playback")
interruptedDuringPlayback = true
radio?.pause()
}
}
func endInterruptionWithFlags(flags: UInt) {
if radio == nil {
return
}
if radio?.isPaused() == true {
if interruptedDuringPlayback == true {
radio?.play()
}
}
interruptedDuringPlayback = false
}
func headphoneUnplugged() {
if radio == nil {
return
}
if radio?.isPlaying() == true {
radio?.pause()
}
}
}
extension ViewController:YLRadioDelegate{
override func remoteControlReceivedWithEvent(event: UIEvent?) {
if event?.type == UIEventType.RemoteControl {
print("remoteControlReceivedWithEvent", event?.type)
if event?.subtype == UIEventSubtype.RemoteControlTogglePlayPause {
}
else if event?.subtype == UIEventSubtype.RemoteControlPause {
}
else if event?.subtype == UIEventSubtype.RemoteControlPlay {
}
else {
print( event?.subtype )
}
}
}
func radioStateChanged(radio: YLRadio!) {
let state = radio.radioState
//print("radioStateChanged:", state)
if state == kRadioStateConnecting {
print("Status: Connecting")
updatePlayPause("Pause", enabled: false)
}
else if state == kRadioStateBuffering {
print("Radio is Buffering")
updatePlayPause("Pause", enabled: true)
}
else if state == kRadioStatePlaying {
print("Radio is Playing")
updatePlayPause("Pause", enabled: true)
}
else if state == kRadioStateStopped {
print("Radio is Stopped")
updatePlayPause("Play", enabled: true)
}
else if state == kRadioStateError {
let error = radio.radioError
updatePlayPause("Play", enabled: true)
print( "Radio Error \(error)")
switch(error){
case kRadioErrorAudioQueueBufferCreate:
print("Audio buffers could not be created.")
break
case kRadioErrorAudioQueueBufferCreate:
print("Audio queue could not be created.")
break
case kRadioErrorAudioQueueEnqueue:
print("Audio queue enqueue failed.")
break
case kRadioErrorAudioQueueStart:
print("Audio queue could not be started.")
break
case kRadioErrorFileStreamGetProperty:
print("File stream get property failed.")
break
case kRadioErrorFileStreamOpen:
print("File stream could not be opened.")
break
case kRadioErrorPlaylistParsing:
print("Playlist could not be parsed.")
break
case kRadioErrorDecoding:
print("Audio decoding error.")
break
case kRadioErrorHostNotReachable:
print("Radio host not reachable.")
break
case kRadioErrorNetworkError:
print("Network connection error.")
break
case kRadioErrorUnsupportedStreamFormat:
print("Unsupported stream format.")
break
default:
print("Unknown Error \(error)")
break
}
}
}
func radioMetadataReady(radio: YLRadio!) {
print("radioMetadataReady:", radio)
let title = radio.radioTitle
let name = radio.radioName
let genre = radio.radioGenre
let url = radio.radioUrl
if title != nil {
print("Radio Metadata Title:", title)
updateTitle(title)
}
if name != nil {
print("Radio Metadata Name :", name)
updateName(name)
}
if genre != nil {
print("Radio Metadata Genre :", genre)
updateGenre(genre)
}
if url != nil {
//print("Radio Metadata URL :", url)
}
}
} | 29.721774 | 92 | 0.560847 |
4b8bfd71c5055b70b4507e717125cc9a913dbfad | 5,589 | //
// QRScanView.swift
// CommonUI
//
// Created by 朱德坤 on 2017/11/29.
// Copyright © 2017年 sinoroad. All rights reserved.
//
import UIKit
// TODO: 横竖屏切换、顶部多余线条
/// 二维码扫描
public class QRScanView: UIView {
private let transparentAreaSize = CGSize(width: 200, height: 200)
private var scanLineView: UIImageView!
private var scanLineViewY: CGFloat!
private var timer: Timer!
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clear
}
public override func layoutSubviews() {
super.layoutSubviews()
addScanLine()
addTipLabel()
timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(animateScanLine), userInfo: nil, repeats: true)
timer.fire()
}
/// 释放相关资源
public func destroy() {
timer.invalidate()
}
func addScanLine() {
scanLineView = UIImageView(frame: CGRect(x: (width - transparentAreaSize.width) / 2, y: (height - transparentAreaSize.height) / 2, width: transparentAreaSize.width, height: 2))
scanLineView.backgroundColor = Theme.themeColor
scanLineView.contentMode = .scaleAspectFill
addSubview(scanLineView)
scanLineViewY = scanLineView.frame.origin.y
}
func addTipLabel() {
let label = UILabel(frame: CGRect(x: 0, y: (height + transparentAreaSize.height) / 2 + 10, width: width, height: 30))
label.text = "将二维码放入框内,即可自动扫描"
label.textColor = UIColor.white
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 12)
addSubview(label)
}
@objc func animateScanLine() {
UIView.animate(withDuration: 0.02,
animations: {
var rect = self.scanLineView.frame
rect.origin.y = self.scanLineViewY
self.scanLineView.frame = rect
},
completion: { _ in
let maxBorder = self.frame.size.height / 2 + self.transparentAreaSize.height / 2 - 4
if self.scanLineViewY > maxBorder {
self.scanLineViewY = (self.frame.height - self.transparentAreaSize.height) / 2
}
self.scanLineViewY = self.scanLineViewY + 1 // swiftlint:disable:this shorthand_operator
})
}
public override func draw(_ rect: CGRect) {
let screenSize = UIScreen.main.bounds.size
let screenDrawRect = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
let originX = (screenDrawRect.width - transparentAreaSize.width) / 2
let originY = (screenDrawRect.height - transparentAreaSize.height) / 2
let clearDrawRect = CGRect(x: originX, y: originY, width: transparentAreaSize.width, height: transparentAreaSize.height)
addScreenFillRect(screenDrawRect)
addCenterClearRect(clearDrawRect)
addWhiteRect(clearDrawRect)
addCornerLine(clearDrawRect)
}
private func addScreenFillRect(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()!
ctx.setFillColor(red: 40 / 255.0, green: 40 / 255.0, blue: 40 / 255.0, alpha: 0.5)
ctx.fill(rect)
}
private func addCenterClearRect(_ rect: CGRect) {
UIGraphicsGetCurrentContext()!.clear(rect)
}
private func addWhiteRect(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()!
ctx.setStrokeColor(red: 1, green: 1, blue: 1, alpha: 1)
ctx.stroke(rect, width: 0.8)
}
private func addCornerLine(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()!
ctx.setLineWidth(5)
ctx.setStrokeColor(red: 83 / 255, green: 239 / 255, blue: 111 / 255, alpha: 1)
// 左上角
let leftTopPoints = [
CGPoint(x: rect.origin.x, y: rect.origin.y),
CGPoint(x: rect.origin.x, y: rect.origin.y + 15),
CGPoint(x: rect.origin.x, y: rect.origin.y),
CGPoint(x: rect.origin.x + 15, y: rect.origin.y)
]
ctx.strokeLineSegments(between: leftTopPoints)
// 左下角
let leftBottomPoints = [
CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height - 15),
CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height),
CGPoint(x: rect.origin.x, y: rect.origin.y + rect.size.height),
CGPoint(x: rect.origin.x + 15, y: rect.origin.y + rect.size.height)
]
ctx.strokeLineSegments(between: leftBottomPoints)
// 右上角
let rightTopPoints = [
CGPoint(x: rect.origin.x + rect.size.width - 15, y: rect.origin.y),
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y),
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y),
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + 15)
]
ctx.strokeLineSegments(between: rightTopPoints)
// 右下角
let rightBottomPoints = [
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height + -15),
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height),
CGPoint(x: rect.origin.x + rect.size.width - 15, y: rect.origin.y + rect.size.height),
CGPoint(x: rect.origin.x + rect.size.width, y: rect.origin.y + rect.size.height)
]
ctx.strokeLineSegments(between: rightBottomPoints)
}
}
| 39.638298 | 184 | 0.606549 |
dea742a6a0bc8dd5f65c5b72ae71afe4db6a6da0 | 2,148 | //
// PlaceholderTextView.swift
// ShopApp
//
// Created by bruceyao on 2021/4/25.
//
import Foundation
import SnapKit
import RxSwift
open class PlaceholderTextView : UITextView {
public let placeholderLabel: UILabel = UILabel()
@IBInspectable public var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
@IBInspectable public var placeholderColor: UIColor = UIColor(hex: "c7c7cd") {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
override open var font: UIFont! {
didSet {
placeholderLabel.font = font
}
}
override open var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
commonInit()
}
func commonInit() {
NotificationCenter.default.addObserver(self,
selector: #selector(PlaceholderTextView.textDidChange),
name: UITextView.textDidChangeNotification,
object: nil)
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholder
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = UIColor.clear
addSubview(placeholderLabel)
placeholderLabel.snp.makeConstraints{ make in
make.top.equalTo(5)
make.left.equalTo(2)
}
}
override open var text: String! {
didSet {
textDidChange()
}
}
@objc func textDidChange() {
placeholderLabel.isHidden = !text.isEmpty
}
}
| 26.518519 | 102 | 0.577281 |
90f1c181259412740c1a6b230cb58888bd73515e | 544 | //
// TokenRequestFile.swift
// StravaAPI
//
// Created by Ben Shutt on 30/09/2020.
//
import Foundation
/// File for reading and writing `TokenRequest` model
struct TokenRequestFile: ModelFile {
typealias Entity = TokenRequest
/// Name of the `TokenRequest` file
private static let fileName = "StravaTokenRequest.json"
// MARK: - ModelFile
/// `URL` of the `TokenRequest` file
static func url() throws -> URL {
return try TokenFile.setupDirectory()
.appendingPathComponent(fileName)
}
}
| 21.76 | 59 | 0.669118 |
5db58a50170b6276c75f46146e2f895f08d48d7c | 3,232 | //
// ProfileTableViewController.swift
// weibosina
//
// Created by 李明禄 on 15/10/8.
// Copyright © 2015年 李明禄. All rights reserved.
//
import UIKit
class ProfileTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 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 {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
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
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// 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.
}
*/
}
| 33.666667 | 157 | 0.687191 |
5bb250e63674cfd9fc67d07a66029abf19376d91 | 510 | //
// ViewController.swift
// TwitterDemo
//
// Created by CS Student on 2/22/17.
// Copyright © 2017 LionelEisenberg. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
}
| 19.615385 | 80 | 0.672549 |
c1520dde547e445c4fa60da48c25998de5c73cc0 | 1,507 | //
// iOSEngineerCodeCheckUITests.swift
// iOSEngineerCodeCheckUITests
//
// Created by 史 翔新 on 2020/04/20.
// Copyright © 2020 YUMEMI Inc. All rights reserved.
//
import XCTest
class iOSEngineerCodeCheckUITests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// UI tests must launch the application that they test.
let app = XCUIApplication()
app.launch()
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testLaunchPerformance() throws {
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
// This measures how long it takes to launch your application.
measure(metrics: [XCTOSSignpostMetric.applicationLaunch]) {
XCUIApplication().launch()
}
}
}
}
| 35.046512 | 182 | 0.668215 |
9ba5a229d69b6d6cb3e193e026aefa5d43f960f2 | 1,179 | // Copyright 2018 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 Cocoa
import FlutterMacOS
class FlutterWindow: NSWindow {
override func awakeFromNib() {
let project = FlutterDartProject.init()
var arguments: [String] = [];
#if !DEBUG
arguments.append("--disable-dart-asserts");
#endif
project.engineSwitches = arguments
let flutterViewController = FlutterViewController.init(project: project)
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
}
| 31.026316 | 76 | 0.744699 |
b9f90a4efec30298f4a58f36f17ac3b2cd8f8875 | 1,959 | //
// ViewController.swift
// tvos
//
// Created by Manuel García-Estañ on 19/10/16.
// Copyright © 2016 manuege. All rights reserved.
//
import UIKit
import Alamofire
import AlamofireActivityLogger
class TVViewController: UIViewController {
@IBOutlet var levelSegmentedControl: UISegmentedControl!
@IBOutlet var prettySegmentedControl: UISegmentedControl!
@IBOutlet var separatorSegmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
levelSegmentedControl.removeAllSegments()
Constants.levelsAndNames.enumerated().forEach { (index, element) in
levelSegmentedControl.insertSegment(withTitle: element.1,
at: index,
animated: false)
}
levelSegmentedControl.selectedSegmentIndex = 1
prettySegmentedControl.selectedSegmentIndex = 0
separatorSegmentedControl.selectedSegmentIndex = 0
}
// MARK: Actions
@IBAction func didPressSuccess(_ sender: AnyObject) {
performRequest(success: true)
}
@IBAction func didPressError(_ sender: AnyObject) {
performRequest(success: false)
}
private func performRequest(success: Bool) {
// Build options
var options: [LogOption] = []
if prettySegmentedControl.selectedSegmentIndex == 0 {
options.append(.jsonPrettyPrint)
}
if separatorSegmentedControl.selectedSegmentIndex == 0 {
options.append(.includeSeparator)
}
// Level
let level = Constants.levelsAndNames[levelSegmentedControl.selectedSegmentIndex].0
Helper.performRequest(success: success,
level: level,
options: options) {
}
}
}
| 28.808824 | 90 | 0.598775 |
16e35e2c5c401a89b965ef6cffbb2162d6619911 | 1,504 | //
// ChainExampleViewController.swift
// SimpleLayout
//
// Created by pisces on 02/01/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import SimpleLayout_Swift
class ChainExampleViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = .bottom
let subview1 = label(backgroundColor: .red, text: "subview1")
let subview2 = label(backgroundColor: .purple, text: "subview2")
let subview3 = label(backgroundColor: .blue, text: "subview3")
view.addSubview(subview1)
view.addSubview(subview2)
view.addSubview(subview3)
subview1.layout
.leading()
.top()
.trailing()
.height(fixed: 150)
subview2.layout
.leading(by: subview1)
.top(by: subview1, attribute: .bottom)
.width(fixed: view.width/2)
.bottom(by: view._safeAreaLayoutGuide)
subview3.layout
.leading(by: subview2, attribute: .trailing)
.top(by: subview2)
.trailing(by: subview1)
.bottom(by: subview2)
}
private func label(backgroundColor: UIColor, text: String) -> UILabel {
let label = UILabel()
label.backgroundColor = backgroundColor
label.text = text
label.textAlignment = .center
label.textColor = .white
return label
}
}
| 27.851852 | 75 | 0.590426 |
11a27c670ab4189222321acf9bf959b194539942 | 2,698 | //
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
import Foundation
import Amplify
import AWSPluginsCore
import AWSS3
public class AWSS3StorageRemoveOperation: AmplifyOperation<StorageRemoveRequest, Void, String, StorageError>,
StorageRemoveOperation {
let storageService: AWSS3StorageServiceBehaviour
let authService: AWSAuthServiceBehavior
init(_ request: StorageRemoveRequest,
storageService: AWSS3StorageServiceBehaviour,
authService: AWSAuthServiceBehavior,
listener: EventListener?) {
self.storageService = storageService
self.authService = authService
super.init(categoryType: .storage,
eventName: HubPayload.EventName.Storage.remove,
request: request,
listener: listener)
}
override public func cancel() {
super.cancel()
}
override public func main() {
if isCancelled {
finish()
return
}
if let error = request.validate() {
dispatch(error)
finish()
return
}
let identityIdResult = authService.getIdentityId()
guard case let .success(identityId) = identityIdResult else {
if case let .failure(error) = identityIdResult {
dispatch(StorageError.authError(error.errorDescription, error.recoverySuggestion))
}
finish()
return
}
let serviceKey = StorageRequestUtils.getServiceKey(accessLevel: request.options.accessLevel,
identityId: identityId,
key: request.key)
if isCancelled {
finish()
return
}
storageService.delete(serviceKey: serviceKey) { [weak self] event in
self?.onServiceEvent(event: event)
}
}
private func onServiceEvent(event: StorageEvent<Void, Void, Void, StorageError>) {
switch event {
case .completed:
dispatch(request.key)
finish()
case .failed(let error):
dispatch(error)
finish()
default:
break
}
}
private func dispatch(_ result: String) {
let asyncEvent = AsyncEvent<Void, String, StorageError>.completed(result)
dispatch(event: asyncEvent)
}
private func dispatch(_ error: StorageError) {
let asyncEvent = AsyncEvent<Void, String, StorageError>.failed(error)
dispatch(event: asyncEvent)
}
}
| 28.4 | 109 | 0.591549 |
7208ee91af4d6ad9691df0757ea93851b00cdf17 | 3,686 | //
// CustomListsViewController.swift
// UpcomingMovies
//
// Created by Alonso on 4/19/19.
// Copyright © 2019 Alonso. All rights reserved.
//
import UIKit
import UpcomingMoviesDomain
class CustomListsViewController: UIViewController, Storyboarded, PlaceholderDisplayable, LoadingDisplayable {
@IBOutlet private weak var tableView: UITableView!
static var storyboardName = "CustomLists"
private var dataSource: SimpleTableViewDataSource<CustomListCellViewModelProtocol>!
var viewModel: CustomListsViewModelProtocol?
weak var coordinator: CustomListsCoordinatorProtocol?
// MARK: - LoadingDisplayable
var loaderView: LoadingView = RadarView()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupBindables()
viewModel?.getCustomLists()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let textAttributes: [NSAttributedString.Key: UIColor]
textAttributes = [NSAttributedString.Key.foregroundColor: ColorPalette.Label.defaultColor]
navigationController?.navigationBar.titleTextAttributes = textAttributes
}
// MARK: - Private
private func setupUI() {
title = LocalizedStrings.customListGroupOption()
setupNavigationBar()
setupTableView()
}
private func setupNavigationBar() {
let backBarButtonItem = UIBarButtonItem(title: "",
style: .done,
target: nil, action: nil)
navigationItem.backBarButtonItem = backBarButtonItem
}
private func setupTableView() {
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 100.0
tableView.delegate = self
tableView.registerNib(cellType: CustomListTableViewCell.self)
}
private func reloadTableView() {
guard let viewModel = viewModel else { return }
dataSource = SimpleTableViewDataSource.make(for: viewModel.listCells)
tableView.dataSource = dataSource
tableView.reloadData()
}
/**
* Configures the tableview given its current state.
*/
private func configureView(withState state: SimpleViewState<List>) {
switch state {
case .populated, .paging, .initial:
hideDisplayedPlaceholderView()
tableView.tableFooterView = UIView()
case .empty:
presentEmptyView(with: "No created lists to show")
case .error(let error):
presentRetryView(with: error.localizedDescription,
retryHandler: { [weak self] in
self?.viewModel?.refreshCustomLists()
})
}
}
// MARK: - Reactive Behavior
private func setupBindables() {
viewModel?.viewState.bindAndFire({ [weak self] state in
guard let self = self else { return }
DispatchQueue.main.async {
self.configureView(withState: state)
self.reloadTableView()
}
})
viewModel?.startLoading.bind({ [weak self] start in
start ? self?.showLoader() : self?.hideLoader()
})
}
}
// MARK: - UITableViewDelegate
extension CustomListsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let viewModel = viewModel else { return }
coordinator?.showListDetail(for: viewModel.list(at: indexPath.row))
}
}
| 30.213115 | 109 | 0.644059 |
f98b697f37c690d21fbd90f899377020a5a7c94b | 242 | //
// UIView+extensions.swift
// Aula12_02
//
// Created by SP11793 on 23/03/22.
//
import Foundation
import UIKit
extension UIView {
public func addSubViews(_ subviews: UIView...) {
subviews.forEach(addSubview)
}
}
| 14.235294 | 52 | 0.64876 |
abb84bb0d63b1a8acb903cd85ce3d5f601b11ba6 | 3,845 | //: [Previous](@previous)
import Foundation
// Optional binding
let cities = ["Paris": 2241, "Madrid": 3165, "Amsterdam": 827, "Berlin": 3562]
if let madridPopulation = cities["Madrid"] {
print("The population of Madrid is \(madridPopulation * 1000)")
}
// Optional unwrapping
infix operator ???
func ???<T>(optional: T?, defaultValue: T) -> T {
if let value = optional {
return value
}
return defaultValue
}
let population1 = cities["Qwerty"] ??? 3232 // Default value is always evaluated if it's result of method etc.
infix operator ????
func ????<T>(optional: T?, defaultValue: () -> T) -> T {
if let value = optional {
return value
}
return defaultValue()
}
let population2 = cities["Qwerty"] ???? { 23232 } // Should be closured with {}
infix operator ?????
func ?????<T>(optional: T?, defaultValue: @autoclosure () -> T) -> T {
if let value = optional {
return value
}
return defaultValue()
}
let population3 = cities["Qwerty"] ????? 232323 // Close to perfect
// Optional chaining
struct Order {
let id: Int
let person: Person?
}
struct Person {
let name: String
let address: Address?
}
struct Address {
let streetName: String
let city: String
let state: String?
}
let order = Order(id: 3, person: nil)
if let state = order.person?.address?.state {
print("State - \(state)")
} else {
print("Unknown person, address or state")
}
// Optional switch case
let berlinPopulation = cities["Berlin"]
switch berlinPopulation {
case 0?: print("Nobody here")
case (1...1000)?: print("Less than million")
case .none: print("We don't know about Berlin")
case .some(let x): print("\(x) people in Berlin")
}
func populationDescriptionForCity(_ city: String) -> String? {
guard let population = cities[city] else { return nil }
return "Population of \(city) is \(population * 1000) people"
}
populationDescriptionForCity("Madrid")
populationDescriptionForCity("Qwerty")
// Optional mapping
func incrementOptional(_ optional: Int?) -> Int? {
guard let x = optional else { return nil }
return x + 1
}
extension Optional {
func customMap<U>(_ transform:(Wrapped) -> U) -> U? {
guard let x = self else { return nil }
return transform(x)
}
}
func incrementOptional2(_ optional: Int?) -> Int? {
return optional.customMap { $0 + 1 }
}
// Optional binding revisited
func addOptionals1(_ x: Int?, _ y: Int?) -> Int? {
if let ux = x {
if let uy = y {
return ux + uy
}
}
return nil
}
func addOptionals2(_ x: Int?, _ y: Int?) -> Int? {
if let ux = x, let uy = y {
return ux + uy
}
return nil
}
func addOptionals3(_ x: Int?, _ y: Int?) -> Int? {
guard let ux = x, let uy = y else { return nil }
return ux + uy
}
let capitals = [
"France": "Paris",
"Spain": "Madrid",
"The Netherlands": "Amsterdam",
"Belgium": "Brussels"
]
func populationOfCapital(country: String) -> Int? {
guard let capital = capitals[country], let population = cities[capital] else { return nil }
return population * 1000
}
populationOfCapital(country: "France")
populationOfCapital(country: "Unknown country")
// Optional flat map
func addOptionals4(_ x: Int?, _ y: Int?) -> Int? {
return x.flatMap { ux in
y.flatMap { uy in
return ux + uy
}
}
}
func populationOfCapital2(country: String) -> Int? {
return capitals[country].flatMap { capital in
cities[capital].flatMap { population in
return population * 1000
}
}
}
func populationOfCapital3(country: String) -> Int? {
return capitals[country].flatMap { capital in
return cities[capital]
}.flatMap { population in
return population * 1000
}
}
//: [Next](@next)
| 22.886905 | 110 | 0.621586 |
d92a86dba4ee835d8a6f14654b78fa283f59fa3f | 4,566 | //
// Copyright (c) 2018 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 Firebase
class BasicRestaurantsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView: UITableView!
// You can ignore these properties. They're used later on in the workshop.
@IBOutlet var activeFiltersStackView: UIStackView!
@IBOutlet var stackViewHeightConstraint: NSLayoutConstraint!
@IBOutlet var cityFilterLabel: UILabel!
@IBOutlet var categoryFilterLabel: UILabel!
@IBOutlet var priceFilterLabel: UILabel!
let backgroundView = UIImageView()
var restaurantData: [Restaurant] = []
var restaurantListener: ListenerRegistration?
private func startListeningForRestaurants() {
// TODO: Create a listener for the "restaurants" collection and use that data
// to popualte our `restaurantData` model
}
func tryASampleQuery() {
let basicQuery = Firestore.firestore().collection("restaurants").limit(to: 3)
basicQuery.getDocuments { (snapshot, error) in
if let error = error {
print("Oh no! Got an error! \(error.localizedDescription)")
return
}
guard let snapshot = snapshot else { return }
self.restaurantData = []
for restaurantDocument in snapshot.documents {
if let newRestaurant = Restaurant(document: restaurantDocument) {
self.restaurantData.append(newRestaurant)
}
}
self.tableView.reloadData()
}
}
private func stopListeningForRestaurants() {
restaurantListener?.remove()
restaurantListener = nil
}
override func viewDidLoad() {
super.viewDidLoad()
backgroundView.image = UIImage(named: "pizza-monster")!
backgroundView.contentMode = .scaleAspectFit
backgroundView.alpha = 0.5
tableView.backgroundView = backgroundView
tableView.tableFooterView = UIView()
stackViewHeightConstraint.constant = 0
activeFiltersStackView.isHidden = true
tableView.delegate = self
tableView.dataSource = self
tryASampleQuery()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setNeedsStatusBarAppearanceUpdate()
startListeningForRestaurants()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
stopListeningForRestaurants()
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return restaurantData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RestaurantTableViewCell",
for: indexPath) as! RestaurantTableViewCell
let restaurant = restaurantData[indexPath.row]
cell.populate(restaurant: restaurant)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let restaurant = restaurantData[indexPath.row]
let controller = RestaurantDetailViewController.fromStoryboard(restaurant: restaurant)
self.navigationController?.pushViewController(controller, animated: true)
}
@IBAction func didTapPopulateButton(_ sender: Any) {
let confirmationBox = UIAlertController(title: "Populate the database",
message: "This will add populate the database with several new restaurants and reviews. Would you like to proceed?",
preferredStyle: .alert)
confirmationBox.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
confirmationBox.addAction(UIAlertAction(title: "Yes", style: .default, handler: { _ in
Firestore.firestore().prepopulate()
}))
present(confirmationBox, animated: true)
}
}
| 35.952756 | 160 | 0.711126 |
1424ab326c2855f2715a2500c26edecc4ee8bf61 | 7,812 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
@available(macOS 10.11, iOS 9.0, *)
public struct PersonNameComponents : ReferenceConvertible, Hashable, Equatable, _MutableBoxing {
public typealias ReferenceType = NSPersonNameComponents
internal var _handle: _MutableHandle<NSPersonNameComponents>
public init() {
_handle = _MutableHandle(adoptingReference: NSPersonNameComponents())
}
fileprivate init(reference: __shared NSPersonNameComponents) {
_handle = _MutableHandle(reference: reference)
}
/* The below examples all assume the full name Dr. Johnathan Maple Appleseed Esq., nickname "Johnny" */
/* Pre-nominal letters denoting title, salutation, or honorific, e.g. Dr., Mr. */
public var namePrefix: String? {
get { return _handle.map { $0.namePrefix } }
set { _applyMutation { $0.namePrefix = newValue } }
}
/* Name bestowed upon an individual by one's parents, e.g. Johnathan */
public var givenName: String? {
get { return _handle.map { $0.givenName } }
set { _applyMutation { $0.givenName = newValue } }
}
/* Secondary given name chosen to differentiate those with the same first name, e.g. Maple */
public var middleName: String? {
get { return _handle.map { $0.middleName } }
set { _applyMutation { $0.middleName = newValue } }
}
/* Name passed from one generation to another to indicate lineage, e.g. Appleseed */
public var familyName: String? {
get { return _handle.map { $0.familyName } }
set { _applyMutation { $0.familyName = newValue } }
}
/* Post-nominal letters denoting degree, accreditation, or other honor, e.g. Esq., Jr., Ph.D. */
public var nameSuffix: String? {
get { return _handle.map { $0.nameSuffix } }
set { _applyMutation { $0.nameSuffix = newValue } }
}
/* Name substituted for the purposes of familiarity, e.g. "Johnny"*/
public var nickname: String? {
get { return _handle.map { $0.nickname } }
set { _applyMutation { $0.nickname = newValue } }
}
/* Each element of the phoneticRepresentation should correspond to an element of the original PersonNameComponents instance.
The phoneticRepresentation of the phoneticRepresentation object itself will be ignored. nil by default, must be instantiated.
*/
public var phoneticRepresentation: PersonNameComponents? {
get { return _handle.map { $0.phoneticRepresentation } }
set { _applyMutation { $0.phoneticRepresentation = newValue } }
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_handle._uncopiedReference())
}
@available(macOS 10.11, iOS 9.0, *)
public static func ==(lhs : PersonNameComponents, rhs: PersonNameComponents) -> Bool {
// Don't copy references here; no one should be storing anything
return lhs._handle._uncopiedReference().isEqual(rhs._handle._uncopiedReference())
}
}
@available(macOS 10.11, iOS 9.0, *)
extension PersonNameComponents : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return self.customMirror.children.reduce("") {
$0.appending("\($1.label ?? ""): \($1.value) ")
}
}
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
if let r = namePrefix { c.append((label: "namePrefix", value: r)) }
if let r = givenName { c.append((label: "givenName", value: r)) }
if let r = middleName { c.append((label: "middleName", value: r)) }
if let r = familyName { c.append((label: "familyName", value: r)) }
if let r = nameSuffix { c.append((label: "nameSuffix", value: r)) }
if let r = nickname { c.append((label: "nickname", value: r)) }
if let r = phoneticRepresentation { c.append((label: "phoneticRepresentation", value: r)) }
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
@available(macOS 10.11, iOS 9.0, *)
extension PersonNameComponents : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSPersonNameComponents.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSPersonNameComponents {
return _handle._copiedReference()
}
public static func _forceBridgeFromObjectiveC(_ personNameComponents: NSPersonNameComponents, result: inout PersonNameComponents?) {
if !_conditionallyBridgeFromObjectiveC(personNameComponents, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ personNameComponents: NSPersonNameComponents, result: inout PersonNameComponents?) -> Bool {
result = PersonNameComponents(reference: personNameComponents)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSPersonNameComponents?) -> PersonNameComponents {
var result: PersonNameComponents?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
@available(macOS 10.11, iOS 9.0, *)
extension NSPersonNameComponents : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as PersonNameComponents)
}
}
@available(macOS 10.11, iOS 9.0, *)
extension PersonNameComponents : Codable {
private enum CodingKeys : Int, CodingKey {
case namePrefix
case givenName
case middleName
case familyName
case nameSuffix
case nickname
}
public init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.namePrefix = try container.decodeIfPresent(String.self, forKey: .namePrefix)
self.givenName = try container.decodeIfPresent(String.self, forKey: .givenName)
self.middleName = try container.decodeIfPresent(String.self, forKey: .middleName)
self.familyName = try container.decodeIfPresent(String.self, forKey: .familyName)
self.nameSuffix = try container.decodeIfPresent(String.self, forKey: .nameSuffix)
self.nickname = try container.decodeIfPresent(String.self, forKey: .nickname)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
if let np = self.namePrefix { try container.encode(np, forKey: .namePrefix) }
if let gn = self.givenName { try container.encode(gn, forKey: .givenName) }
if let mn = self.middleName { try container.encode(mn, forKey: .middleName) }
if let fn = self.familyName { try container.encode(fn, forKey: .familyName) }
if let ns = self.nameSuffix { try container.encode(ns, forKey: .nameSuffix) }
if let nn = self.nickname { try container.encode(nn, forKey: .nickname) }
}
}
| 42.923077 | 152 | 0.662954 |
1dc3ea085f1ceeeb64d46e6b95bdae9804121d06 | 267 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g{enum b{struct S{enum B<d{func c{enum S<T:T.B
| 33.375 | 87 | 0.741573 |
21c868217bc6c6487578c2da7548205718077267 | 11,115 | //
// NetworkManager.swift
// Dylan.Lee
//
// Created by Dylan on 2017/8/15.
// Copyright © 2017年 Dylan.Lee. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import RealmSwift
class NetworkManager {
/// 网络工具实例
static let sharedInstance = NetworkManager()
/// SessionManager 实例
private var sessionManager: SessionManager = {
/// set up URLSessiong configure
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = Alamofire.SessionManager.defaultHTTPHeaders
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.timeoutIntervalForRequest = 30
let sm = Alamofire.SessionManager(configuration: configuration)
// Ignore SSL Challenge
sm.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = sm.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
return sm
}()
/// 网络请求
///
/// - Parameters:
/// - targetType: 请求数据模型
/// - response: 请求相应
func request<T: Request>(_ targetType: T, responseHandler: @escaping ResponseBlock<T.EntityType>) where T.EntityType: DBModel {
var url: URL!
if targetType.path.contains("https") || targetType.path.contains("http") {
url = URL(string: targetType.path)!
} else {
url = URL(string: targetType.baseURL.appending(targetType.path))!
}
sessionManager.request(url,
method: targetType.method,
parameters: targetType.parameters,
encoding: URLEncoding.default,
headers: nil)
.validate(contentType: NetworkConfig.kContentType)
.validate(statusCode: 200..<400)
.responseJSON(completionHandler: {[weak self] response in
self?.handleResult(response, handler: responseHandler)
})
}
/// 下载文件
///
/// - Parameters:
/// - targetType: 下载对象模型
/// - destinationPath: 存储路径 默认在沙盒Document下
/// - response: 请求相应
/// - Returns: 下载请求
func download<T: Request>(_ targetType: T, destinationPath: String = "",response: ResponseBlock<T.EntityType>) -> Alamofire.DownloadRequest where T.EntityType: DBModel {
var url: URL!
if targetType.path.contains("https") || targetType.path.contains("http") {
url = URL(string: targetType.path)!
} else {
url = URL(string: targetType.baseURL.appending(targetType.path))!
}
var destPath: URL
if destinationPath.count == 0 {
let directoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
destPath = directoryURLs[0].appendingPathComponent("/Music/")
} else {
destPath = URL(string: destinationPath)!
}
let destination: Alamofire.DownloadRequest.DownloadFileDestination = { temporaryURL, response in
return (destPath.appendingPathComponent("\(url.lastPathComponent.urlDecoded())"), [.createIntermediateDirectories])
}
return sessionManager.download(URLRequest(url: url), to: destination).response(completionHandler: { response in
})
}
func upload<T: Request>(_ targetType: T, responseHandler: @escaping ResponseBlock<T.EntityType>) where T.EntityType: DBModel {
assert(targetType.files != nil, "上传文件不能为空")
var url: URL!
if targetType.path.contains("https") || targetType.path.contains("http") {
url = URL(string: targetType.path)!
} else {
url = URL(string: targetType.baseURL.appending(targetType.path))!
}
sessionManager.upload(multipartFormData: { multiData in
guard let files = targetType.files else {
return;
}
if let parameters = targetType.parameters {
for (key, value) in parameters {
let data = JSON(value)
let dataStr = data.string
multiData.append((dataStr?.data(using: .utf8))!, withName: key)
}
}
for file in files {
if file.uploadType == .data {
multiData.append(file.data, withName: "file", fileName: file.name, mimeType: file.mimeType)
} else {
multiData.append(URL(string: file.filePath)!, withName: file.name, fileName: file.name + file.mimeType, mimeType: file.mimeType)
}
}
}, to: url) { [weak self] encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
self?.handleResult(response, handler: responseHandler)
}
case .failure(let encodingError):
print(encodingError)
}
}
}
/// 处理返回数据
///
/// - Parameters:
/// - response: resonse实例
/// - responseHandler: 处理后回调
func handleResult<T: DBModel>(_ response: DataResponse<Any>, handler responseHandler: @escaping ResponseBlock<T>) {
switch response.result.isSuccess {
case true:
if let value = response.result.value {
let responseObj = JSON(value)
/// 与服务端约定数据格式
if let respDic = responseObj.dictionary {
let code = NetWorkRetCode(respDic)
let msg = NetworkRetMsg(respDic)
let data = NetworkRetData(respDic)
if let resultDatas = data.arrayObject {
var models = [T]()
for modelDic in resultDatas {
models.append(T(value: modelDic))
}
let result = Result(value: nil, code: code, values: models, message: Message.responseMsg(msg).retMsg())
let customResult = Response<T>.Success(result)
responseHandler(customResult)
} else if let resultData = data.dictionaryObject {
let model = T(value: resultData)
let result = Result(value: model, code: code, values: nil, message: Message.responseMsg(msg).retMsg())
let customResult = Response<T>.Success(result)
responseHandler(customResult)
} else {
DebugPrint("❌❌❌❌==数据结构异常==❌❌❌❌")
let error = NetError(code: code, message: msg)
let customResult = Response<T>.Failure(error)
responseHandler(customResult)
}
} else if let respArr = responseObj.arrayObject { /// 直接返回数组
var resultObjs = [T]()
for item in respArr {
resultObjs.append(T(value: item))
}
let result = Result<T>(value: nil, code: 0 , values: resultObjs, message: Message.success.retMsg())
let customResult = Response<T>.Success(result)
responseHandler(customResult)
} else { /// 直接返回字符串
let responseStr = String(data: response.data!, encoding: .utf8)
let result = Result<T>(value: T(value: responseStr ?? ""), code: 0, values: [T(value: responseStr ?? "")], message: Message.success.retMsg())
let customResult = Response.Success(result)
responseHandler(customResult)
}
}
case false:
DebugPrint("❌❌❌❌==请求错误==❌❌❌❌")
handleError(error: response.error, completeHandler: responseHandler)
}
}
/// 处理错误
///
/// - Parameters:
/// - error: 错误
/// - completeHandler: 处理回调
func handleError<T>(error: Error?, completeHandler: ResponseBlock<T>) {
var errMsg: String!
var errorCode = -999
if let error = error as? AFError {
switch error {
case .invalidURL(let url):
errMsg = "无效的请求"
DebugPrint("无效 URL: \(url) - \(error.localizedDescription)")
case .parameterEncodingFailed(let reason):
errMsg = "参数编码失败"
DebugPrint("失败理由: \(reason)")
case .multipartEncodingFailed(let reason):
errMsg = "参数编码失败"
DebugPrint("失败理由: \(reason)")
case .responseValidationFailed(let reason):
DebugPrint("Response 校验失败: \(error.localizedDescription)")
DebugPrint("失败理由: \(reason)")
switch reason {
case .dataFileNil, .dataFileReadFailed:
errMsg = "文件不存在"
DebugPrint("无法读取下载文件")
case .missingContentType(let acceptableContentTypes):
errMsg = "文件类型不明"
DebugPrint("文件类型不明: \(acceptableContentTypes)")
case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
errMsg = "文件无法读取"
DebugPrint("文件类型: \(responseContentType) 无法读取: \(acceptableContentTypes)")
case .unacceptableStatusCode(let code):
errMsg = "请求被拒绝"
errorCode = code
DebugPrint("请求失败: \(code)")
}
case .responseSerializationFailed(let reason):
errMsg = "请求返回内容解析失败"
DebugPrint("失败理由: \(reason)")
}
DebugPrint("错误: \(String(describing: error.underlyingError))")
} else if let error = error as? URLError {
errMsg = "网络异常,请检查网络"
errorCode = error.code.rawValue
DebugPrint("网络异常,请检查网络: \(error)")
} else {
let nsError = (error! as NSError)
errorCode = nsError.code
errMsg = nsError.description
}
let error = NetError(code: errorCode, message: errMsg)
let customResult = Response<T>.Failure(error)
completeHandler(customResult)
}
}
| 26.214623 | 170 | 0.556185 |
8aa4e0078d2b1b8b25f8c1807b446dc3bec147c0 | 1,088 | //
// PayType.swift
// Component_Pay
//
// Created by 武飞跃 on 2018/7/30.
//
import Foundation
/*
public class PostFormControl {
/// 支付视图控制器
public var viewController: UIViewController!
public var willOpenURL: ((URL) -> Bool)?
func payOrder(profile: PostFormProfile, result: @escaping ResponseCompletion) {
let postFormWebViewController = PostFormWebViewController(formProfile: profile)
postFormWebViewController.backAction = result
postFormWebViewController.title = profile.title
postFormWebViewController.willOpenURL = {
let isDidOpenURL = self.willOpenURL?($0)
if isDidOpenURL == true {
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
postFormWebViewController.navigationController?.popViewController(animated: true)
})
}
}
viewController.navigationController?.pushViewController(postFormWebViewController, animated: true)
}
}
*/
| 27.2 | 106 | 0.620404 |
3869f60a8260c5613ec1183143a799be3ddf4548 | 2,479 | // Copyright 2016-2018 Cisco Systems Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class MetricsBuffer: NSObject {
private var metrics = [Metric]()
var count: Int {
var count: Int = 0
synchronized(lock: self) {
count = metrics.count
}
return count
}
func add(metric: Metric) {
synchronized(lock: self) {
metrics.append(metric)
}
}
func add(metrics: [Metric]) {
synchronized(lock: self) {
self.metrics.append(contentsOf: metrics)
}
}
func popAllIfGreaterThan(_ amount: Int) -> [Metric]? {
var metricsCopy: [Metric]?
synchronized(lock: self) {
if metrics.count > amount {
metricsCopy = metrics
metrics.removeAll()
}
}
return metricsCopy
}
func popAmount(_ amount: Int) -> [Metric]? {
var metricsCopy: [Metric]?
synchronized(lock: self) {
if metrics.count >= amount {
metricsCopy = Array(metrics.prefix(amount))
metrics.removeFirst(amount)
}
}
return metricsCopy
}
func popAll() -> [Metric]? {
var metricsCopy: [Metric]?
synchronized(lock: self) {
metricsCopy = metrics
metrics.removeAll()
}
return metricsCopy
}
}
| 32.194805 | 80 | 0.624445 |
c124b27e513df8ce36c08b6cfe9b9733559b8757 | 4,630 | //
// MealViewController.swift
// FoodTracker
//
// Created by Jane Appleseed on 5/23/15.
// Copyright © 2015 Apple Inc. All rights reserved.
// See LICENSE.txt for this sample’s licensing information.
//
import UIKit
class MealViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
/*
This value is either passed by `MealTableViewController` in `prepareForSegue(_:sender:)`
or constructed as part of adding a new meal.
*/
var meal: Meal?
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field’s user input via delegate callbacks.
nameTextField.delegate = self
// Set up views if editing an existing Meal.
if let meal = meal {
navigationItem.title = meal.name
nameTextField.text = meal.name
photoImageView.image = meal.photo
ratingControl.rating = meal.rating
}
// Enable the Save button only if the text field has a valid Meal name.
checkValidMealName()
}
// MARK: UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField) {
// Disable the Save button while editing.
saveButton.enabled = false
}
func checkValidMealName() {
// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
saveButton.enabled = !text.isEmpty
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
checkValidMealName()
navigationItem.title = textField.text
}
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Navigation
@IBAction func cancel(sender: UIBarButtonItem) {
// Depending on style of presentation (modal or push presentation), this view controller needs to be dismissed in two different ways.
let isPresentingInAddMealMode = presentingViewController is UINavigationController
if isPresentingInAddMealMode {
dismissViewControllerAnimated(true, completion: nil)
}
else {
navigationController!.popViewControllerAnimated(true)
}
}
// This method lets you configure a view controller before it's presented.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
let photo = photoImageView.image
let rating = ratingControl.rating
// Set the meal to be passed to MealTableViewController after the unwind segue.
meal = Meal(name: name, photo: photo, rating: rating)
}
}
// MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
}
| 35.891473 | 141 | 0.665011 |
ff27739c96cf0d3a9e8ba7e6783ee4d3bc90d933 | 1,079 | //
// NotificationHandler.swift
// PWCLogin
//
// Created by rboopathi001 on 13/04/16.
// Copyright © 2016 PWC SDC Bangalore. All rights reserved.
//
import Foundation
let kUpdateNotificationHandler = "UpdateNotificationHandler"
let kLoginSuccessfulNotification = "LoginSuccessfulNotification"
let kReasonForNotification = "ReasonForNotification"
class NotificationHandler: NSObject {
let defaultCenter = NSNotificationCenter.defaultCenter()
static let sharedInstance = NotificationHandler()
override init() {
super.init()
defaultCenter.addObserver(self, selector: "postNotification:", name: kUpdateNotificationHandler, object: nil)
}
func postNotification(notification: NSNotification) {
print("MyNotification was handled")
let notificationName = notification.userInfo![kReasonForNotification] as! String
defaultCenter.postNotificationName(notificationName, object: nil, userInfo: notification.userInfo!)
}
deinit {
defaultCenter.removeObserver(self)
}
} | 29.162162 | 117 | 0.724745 |
c195302dd2a82f8356a9db36b3a5488ecaf4479e | 1,178 | //
// Constants.swift
// SeyoungARBasic
//
// Created by YOUNG on 10/08/2017.
// Copyright © 2017 YOUNG. All rights reserved.
//
import Foundation
import SceneKit
enum Settings {
static let isDebugging = false
static let cancelNoise = true
}
enum Constants {
static let pi = Float(Double.pi)
static let measureLineRadius: CGFloat = 0.005
static let measureLineColor = UIColor.cyan
static let measureLabelFontSizeSmall: CGFloat = 25
static let measureLabelFontSizeLarge: CGFloat = 60
static let measureLabelFontSizeXLarge: CGFloat = 80
static let measurePlaneColor = UIColor(red: 0.7, green: 0.0, blue: 0.2, alpha: 0.5)
static let screenWidth = UIScreen.main.bounds.width
static let screenHeight = UIScreen.main.bounds.height
static let markerRadius:CGFloat = 0.01
/// This is an empirical value
static let epsilon:Float = 1e-5 //0.00001
}
enum Helper {
static func getSignAsString<T>(n: T) -> String where T: Comparable, T: SignedNumeric {
if n > 0 {
return "+"
} else if n == 0 {
return "0"
} else {
return "-"
}
}
}
| 25.06383 | 90 | 0.641766 |
2676d535e49c85622f5e7803e7095ca6ef22c43d | 677 | //
// main.swift
// 01-SelectionSort
//
// Created by 买明 on 10/03/2017.
// Copyright © 2017 买明. All rights reserved.
//
import Foundation
func selectionSort<T>(_ arr: inout Array<T>,
_ isNotOrdered: (T, T) -> Bool) {
// 依次查找极值
for i in 0..<arr.count {
// 记录极值的下标
var index = i
// 查找后续极值下标
for j in i + 1..<arr.count {
// 更新极值下标
if isNotOrdered(arr[j], arr[index]) {
index = j
}
}
// 交换位置
arr.swapAt(i, index)
}
}
TestHelper.checkSortAlgorithm(selectionSort)
TestHelper.checkSortAlgorithm(selectionSort, 10000)
| 20.515152 | 55 | 0.516987 |
9be9010cd8dabe42a50a058e54e432ee8c431676 | 2,047 | //
// MainView.swift
// Longinus-SwiftUI-Example
//
// Created by Qitao Yang on 2020/8/30.
//
// Copyright (c) 2020 KittenYang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import SwiftUI
import class Longinus.LonginusManager
struct MainView: View {
var body: some View {
NavigationView {
List {
Button(
action: {
LonginusManager.shared.imageCacher?.removeAll()
},
label: {
Text("Clear Cache").foregroundColor(.blue)
}
)
NavigationLink(destination: SwiftUIView()) { Text("Basic Image") }
NavigationLink(destination: SwiftUIList()) { Text("List") }
}.navigationBarTitle(Text("Longinus-SwiftUI"))
}
}
}
#if DEBUG
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
#endif
| 35.293103 | 82 | 0.651685 |
6a749b400a898db7cea8530e7352ce0b7c0018fc | 1,952 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import VCCrypto
public struct ECPublicJwk: Codable, Equatable {
public let keyType: String
public let keyId: String?
public let use: String?
public let keyOperations: [String]?
public let algorithm: String?
public let curve: String
public let x: String
public let y: String
enum CodingKeys: String, CodingKey {
case keyType = "kty"
case keyId = "kid"
case keyOperations = "key_ops"
case algorithm = "alg"
case curve = "crv"
case use, x, y
}
public init(x: String, y: String, keyId: String) {
self.keyType = "EC"
self.keyId = keyId
self.use = "sig"
self.keyOperations = ["verify"]
self.algorithm = "ES256K"
self.curve = "secp256k1"
self.x = x
self.y = y
}
public init(withPublicKey key: Secp256k1PublicKey, withKeyId kid: String) {
let x = key.x.base64URLEncodedString()
let y = key.y.base64URLEncodedString()
self.init(x: x, y: y, keyId: kid)
}
func getMinimumAlphabeticJwk() -> String {
return "{\"crv\":\"\(self.curve)\",\"kty\":\"\(self.keyType)\",\"x\":\"\(self.x)\",\"y\":\"\(self.y)\"}"
}
public func getThumbprint() throws -> String {
let hashAlgorithm = Sha256()
guard let encodedJwk = self.getMinimumAlphabeticJwk().data(using: .utf8) else {
throw VCTokenError.unableToParseString
}
let hash = hashAlgorithm.hash(data: encodedJwk)
return hash.base64URLEncodedString()
}
}
| 32.533333 | 112 | 0.534836 |
18fa52449818f6de1d868d0db9e9137a90372731 | 1,286 | //
// AppDelegate.swift
// Extensions
//
// Created by Paul Richardson on 07/06/2021.
//
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
// MARK: UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}
| 34.756757 | 176 | 0.786936 |
1a74dd46d4cd4349c8efeaa84894de280edc3e21 | 773 | //
// AccountViewModel.swift
// Steve
//
// Created by Mateusz Stompór on 26/04/2020.
// Copyright © 2020 Th3re. All rights reserved.
//
import Combine
import Foundation
class AccountViewModel: ObservableObject {
// MARK: - Properties
@Published var loggedUser: UserInfo?
let accountManager: AccountManageable
private var subscription: AnyCancellable?
// MARK: - Initialization
init(accountManager: AccountManageable) {
self.accountManager = accountManager
setupSubscription()
}
// MARK: - Private
func setupSubscription() {
subscription = accountManager.publishers.currentlyLogged.assign(to: \.loggedUser, on: self)
}
// MARK: - Deinitialization
deinit {
subscription?.cancel()
}
}
| 24.935484 | 99 | 0.681759 |
eb64195a78534183f4781ba04863bff961e338c4 | 482 | // Copyright 2015-present 650 Industries. All rights reserved.
import Foundation
@objc
open class DevMenuItem: NSObject {
@objc(DevMenuItemType)
public enum ItemType: Int {
case Action = 1
case Group = 2
case Screen = 3
case Link = 4
case SelectionList = 5
}
@objc
public let type: ItemType
init(type: ItemType) {
self.type = type
}
@objc
open func serialize() -> [String : Any] {
return [
"type": type.rawValue,
]
}
}
| 16.066667 | 62 | 0.626556 |
89e4cdfd2061d98fe12fc5449194e6dc8d5351cd | 1,650 | //
// PasteDetailViewModel.swift
// Pwned
//
// Created by Kevin on 11/10/18.
// Copyright © 2018 Kevin. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import RxFlow
class PasteDetailViewModel: ViewModel {
private static var countFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = Locale.current
formatter.numberStyle = .decimal
return formatter
}
private let paste: Paste
private let disposeBag = DisposeBag()
// MARK: - Rx Inputs
/// Trigger the visitURL step
var visitURLTrigger = PublishSubject<Void>()
var title: String {
return paste.titleOrDefault
}
var formattedDate: String? {
return paste.formattedDate
}
var emailCount: String {
return PasteDetailViewModel.countFormatter
.string(from: NSNumber(value: paste.emailCount)) ?? ""
}
var source: String {
return paste.source
}
var url: String? {
let pasteService = PasteService(rawValue: paste.source)
guard let service = pasteService else { return nil }
let url = service.getURL(for: paste.identifier)
return url
}
init(paste: Paste) {
self.paste = paste
visitURLTrigger
.subscribe(onNext: { [weak self] in
self?.visitURL()
})
.disposed(by: disposeBag)
}
}
extension PasteDetailViewModel: Stepper {
public func visitURL() {
if let urlString = self.url, let url = URL(string: urlString) {
self.step.accept(AppStep.visitURL(url))
}
}
}
| 23.571429 | 71 | 0.621818 |
f540e5a453f3ac392d23c5fc89a110de49e7108e | 7,860 | //
// MeasureRepeatTests.swift
// MusicNotationCore
//
// Created by Kyle Sherman on 3/9/16.
// Copyright © 2016 Kyle Sherman. All rights reserved.
//
import XCTest
@testable import MusicNotationCoreMac
class MeasureRepeatTests: XCTestCase {
static let timeSignature = TimeSignature(topNumber: 4, bottomNumber: 4, tempo: 120)
static let key = Key(noteLetter: .c)
static let note1 = Note(noteDuration: .eighth, pitch: SpelledPitch(noteLetter: .c, octave: .octave1))
static let note2 = Note(noteDuration: .quarter, pitch: SpelledPitch(noteLetter: .d, octave: .octave1))
let measure1 = Measure(timeSignature: timeSignature, key: key, notes: [[note1, note1]])
let measure2 = Measure(timeSignature: timeSignature, key: key, notes: [[note2, note2]])
// MARK: - init(measures:repeateCount:)
// MARK: Failures
func testInitInvalidRepeatCount() {
assertThrowsError(MeasureRepeatError.invalidRepeatCount) {
_ = try MeasureRepeat(measures: [measure1], repeatCount: -2)
}
}
func testInitNoMeasures() {
assertThrowsError(MeasureRepeatError.noMeasures) {
_ = try MeasureRepeat(measures: [])
}
}
// MARK: Successes
func testInitNotSpecifiedRepeatCount() {
assertNoErrorThrown {
let measureRepeat = try MeasureRepeat(measures: [measure1])
XCTAssertEqual(measureRepeat.repeatCount, 1)
}
}
func testInitSingleMeasure() {
assertNoErrorThrown {
_ = try MeasureRepeat(measures: [measure2], repeatCount: 3)
}
}
func testInitMultipleMeasures() {
assertNoErrorThrown {
_ = try MeasureRepeat(measures: [measure1, measure2], repeatCount: 4)
}
}
// MARK: - expand()
func testExpandSingleMeasureRepeatedOnce() {
assertNoErrorThrown {
let measureRepeat = try MeasureRepeat(measures: [measure1], repeatCount: 1)
let expected = [measure1, RepeatedMeasure(immutableMeasure: measure1)] as [ImmutableMeasure]
let actual = measureRepeat.expand()
guard actual.count == expected.count else {
XCTFail()
return
}
XCTAssertTrue(compareImmutableMeasureArrays(actual: actual, expected: expected))
XCTAssertEqual(String(describing: measureRepeat), "[ |4/4: [1/8c1, 1/8c1]| ] × 2")
}
}
func testExpandSingleMeasureRepeatedMany() {
assertNoErrorThrown {
let measureRepeat = try MeasureRepeat(measures: [measure1], repeatCount: 3)
let repeatedMeasure = RepeatedMeasure(immutableMeasure: measure1)
let expected = [measure1, repeatedMeasure, repeatedMeasure, repeatedMeasure] as [ImmutableMeasure]
let actual = measureRepeat.expand()
guard actual.count == expected.count else {
XCTFail()
return
}
XCTAssertTrue(compareImmutableMeasureArrays(actual: actual, expected: expected))
XCTAssertEqual(String(describing: measureRepeat), "[ |4/4: [1/8c1, 1/8c1]| ] × 4")
}
}
func testExpandManyMeasuresRepeatedOnce() {
assertNoErrorThrown {
let measureRepeat = try MeasureRepeat(measures: [measure1, measure2], repeatCount: 1)
let repeatedMeasure1 = RepeatedMeasure(immutableMeasure: measure1)
let repeatedMeasure2 = RepeatedMeasure(immutableMeasure: measure2)
let expected = [measure1, measure2, repeatedMeasure1, repeatedMeasure2] as [ImmutableMeasure]
let actual = measureRepeat.expand()
guard actual.count == expected.count else {
XCTFail()
return
}
XCTAssertTrue(compareImmutableMeasureArrays(actual: actual, expected: expected))
XCTAssertEqual(String(describing: measureRepeat), "[ |4/4: [1/8c1, 1/8c1]|, |4/4: [1/4d1, 1/4d1]| ] × 2")
}
}
func testExpandManyMeasuresRepeatedMany() {
assertNoErrorThrown {
let measureRepeat = try MeasureRepeat(measures: [measure1, measure2], repeatCount: 3)
let repeatedMeasure1 = RepeatedMeasure(immutableMeasure: measure1)
let repeatedMeasure2 = RepeatedMeasure(immutableMeasure: measure2)
let expected = [
measure1, measure2,
repeatedMeasure1, repeatedMeasure2,
repeatedMeasure1, repeatedMeasure2,
repeatedMeasure1, repeatedMeasure2
] as [ImmutableMeasure]
let actual = measureRepeat.expand()
guard actual.count == expected.count else {
XCTFail()
return
}
XCTAssertTrue(compareImmutableMeasureArrays(actual: actual, expected: expected))
XCTAssertEqual(String(describing: measureRepeat), "[ |4/4: [1/8c1, 1/8c1]|, |4/4: [1/4d1, 1/4d1]| ] × 4")
}
}
// MARK: - ==
// MARK: Failures
func testEqualitySameMeasureCountDifferentMeasures() {
assertNoErrorThrown {
let measureRepeat1 = try MeasureRepeat(measures: [measure1, measure2, measure1])
let measureRepeat2 = try MeasureRepeat(measures: [measure2, measure1, measure2])
XCTAssertFalse(measureRepeat1 == measureRepeat2)
}
}
func testEqualityDifferentMeasureCountSameMeasures() {
assertNoErrorThrown {
let measureRepeat1 = try MeasureRepeat(measures: [measure1, measure2])
let measureRepeat2 = try MeasureRepeat(measures: [measure1, measure2, measure1])
XCTAssertFalse(measureRepeat1 == measureRepeat2)
}
}
func testEqualityDifferentMeasureCountDifferentMeasures() {
assertNoErrorThrown {
let measureRepeat1 = try MeasureRepeat(measures: [measure1, measure2])
let measureRepeat2 = try MeasureRepeat(measures: [measure2, measure1, measure2])
XCTAssertFalse(measureRepeat1 == measureRepeat2)
}
}
func testEqualityDifferentRepeatCount() {
assertNoErrorThrown {
let measureRepeat1 = try MeasureRepeat(measures: [measure1, measure2], repeatCount: 2)
let measureRepeat2 = try MeasureRepeat(measures: [measure1, measure2], repeatCount: 3)
XCTAssertFalse(measureRepeat1 == measureRepeat2)
}
}
// MARK: Successes
func testEqualitySucceeds() {
assertNoErrorThrown {
let measureRepeat1 = try MeasureRepeat(measures: [measure1], repeatCount: 2)
let measureRepeat2 = try MeasureRepeat(measures: [measure1], repeatCount: 2)
XCTAssertTrue(measureRepeat1 == measureRepeat2)
}
}
// MARK: - Helpers
private func compareImmutableMeasureArrays(actual: [ImmutableMeasure], expected: [ImmutableMeasure]) -> Bool {
for (index, item) in actual.enumerated() {
if let item = item as? RepeatedMeasure {
if let expectedItem = expected[index] as? RepeatedMeasure {
if item == expectedItem {
continue
} else {
return false
}
} else {
return false
}
} else if let item = item as? Measure {
if let expectedItem = expected[index] as? Measure {
if item == expectedItem {
continue
} else {
return false
}
} else {
return false
}
} else {
XCTFail("Item was not a Measure nor RepeatedMeasure")
return false
}
}
return true
}
}
| 38.910891 | 117 | 0.606997 |
39ea46b63284b77315dce4ee482cc6ef9dee3fce | 1,169 | //
// RowSource.swift
// SwiftTable
//
// Created by Bradley Hilton on 2/13/16.
// Copyright © 2016 Brad Hilton. All rights reserved.
//
public protocol RowSource : _Row {
// Delegate
func willDisplayCell(_ cell: UITableViewCell)
func didEndDisplayingCell(_ cell: UITableViewCell)
var height: CGFloat { get }
var estimatedHeight: CGFloat { get }
func accessoryButtonTapped()
var shouldHighlight: Bool { get }
func didHighlight()
func didUnhighlight()
var willSelect: Bool { get }
var willDeselect: Bool { get }
func didSelect()
func didDeselect()
var editingStyle: UITableViewCell.EditingStyle { get }
var titleForDeleteConfirmationButton: String? { get }
var editActions: [UITableViewRowAction]? { get }
var shouldIndentWhileEditing: Bool { get }
func willBeginEditing()
func didEndEditing()
var indentationLevel: Int { get }
var shouldShowMenu: Bool { get }
// Data Source
var cell: UITableViewCell { get }
var canEdit: Bool { get }
var canMove: Bool { get }
func commitEditingStyle(_ editingStyle: UITableViewCell.EditingStyle)
}
| 26.568182 | 73 | 0.674936 |
0a16e6725ab161dbbdb29c62dfc496a0fafac1b0 | 1,785 | //
// FxAnyHrpSelectAddressViewModel.swift
// XWallet
//
// Created by HeiHua BaiHua on 2020/5/23.
// Copyright © 2020 Andy.Chan 6K. All rights reserved.
//
import WKKit
import FunctionX
//MARK: AddressListViewModel
extension FxAnyHrpSelectAddressViewController {
class AddressListViewModel: ListViewModel {
let hrp: String
let derivationTemplate: String?
init(_ wallet: Wallet, hrp: String, derivationTemplate: String? = nil) {
self.hrp = hrp
self.derivationTemplate = derivationTemplate
super.init(wallet)
}
override func cellVM(derivationAddress: Int) -> CellViewModel {
return AddressCellViewModel(wallet, derivationAddress: derivationAddress, hrp: hrp, derivationTemplate: derivationTemplate)
}
}
}
//MARK: AddressCellViewModel
extension FxAnyHrpSelectAddressViewController {
class AddressCellViewModel: CellViewModel {
let hrp: String
let path: String
init(_ wallet: Wallet, derivationAddress: Int, hrp: String, derivationTemplate: String? = nil) {
self.hrp = hrp
let template = derivationTemplate ?? "m/44'/118'/0'/0/0"
var components = template.components(separatedBy: "/")
components.removeLast()
components.append(String(derivationAddress))
self.path = components.joined(separator: "/")
super.init(wallet, derivationAddress: derivationAddress)
}
override var derivationPath: String { path }
override func generateAddress() -> String {
return FunctionXAddress(hrpString: hrp, publicKey: publicKey.data)?.description ?? ""
}
}
}
| 31.315789 | 135 | 0.633053 |
fe32297e17ba179d8c859ff5f674ef42689cec01 | 4,539 | //
// SystemLayoutAnchor.swift
// AnchorPal
//
// Created by Steven Mok on 2021/2/7.
//
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public protocol SystemLayoutAnchor: NSObject {
func constraint(_ relation: ConstraintRelation, to anchor: Self, constant: CGFloat, position: AnchorPosition) -> NSLayoutConstraint
@available(iOS 11, tvOS 11, macOS 11, *)
func constraint(_ relation: ConstraintRelation, toSystemSpacingAfter anchor: Self, multiplier: CGFloat) -> NSLayoutConstraint
static var customDimensionPosition: AnchorPosition { get }
@available(iOS 10, tvOS 10, macOS 10.12, *)
func anchorWithOffset(to otherAnchor: Self) -> NSLayoutDimension
}
extension NSLayoutXAxisAnchor: SystemLayoutAnchor {
public static let customDimensionPosition: AnchorPosition = .centerX
}
extension NSLayoutYAxisAnchor: SystemLayoutAnchor {
public static let customDimensionPosition: AnchorPosition = .centerY
}
public extension NSLayoutXAxisAnchor {
func constraint(_ relation: ConstraintRelation, to anchor: NSLayoutXAxisAnchor, constant: CGFloat, position: AnchorPosition) -> NSLayoutConstraint {
switch relation {
case .lessEqual:
return constraint(lessThanOrEqualTo: anchor, constant: constant).position(position)
case .equal:
return constraint(equalTo: anchor, constant: constant).position(position)
case .greaterEqual:
return constraint(greaterThanOrEqualTo: anchor, constant: constant).position(position)
}
}
@available(iOS 11, tvOS 11, macOS 11, *)
func constraint(_ relation: ConstraintRelation, toSystemSpacingAfter anchor: NSLayoutXAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint {
switch relation {
case .lessEqual:
return constraint(lessThanOrEqualToSystemSpacingAfter: anchor, multiplier: multiplier)
case .equal:
return constraint(equalToSystemSpacingAfter: anchor, multiplier: multiplier)
case .greaterEqual:
return constraint(greaterThanOrEqualToSystemSpacingAfter: anchor, multiplier: multiplier)
}
}
}
public extension NSLayoutYAxisAnchor {
func constraint(_ relation: ConstraintRelation, to anchor: NSLayoutYAxisAnchor, constant: CGFloat, position: AnchorPosition) -> NSLayoutConstraint {
switch relation {
case .lessEqual:
return constraint(lessThanOrEqualTo: anchor, constant: constant).position(position)
case .equal:
return constraint(equalTo: anchor, constant: constant).position(position)
case .greaterEqual:
return constraint(greaterThanOrEqualTo: anchor, constant: constant).position(position)
}
}
@available(iOS 11, tvOS 11, macOS 11, *)
func constraint(_ relation: ConstraintRelation, toSystemSpacingAfter anchor: NSLayoutYAxisAnchor, multiplier: CGFloat) -> NSLayoutConstraint {
switch relation {
case .lessEqual:
return constraint(lessThanOrEqualToSystemSpacingBelow: anchor, multiplier: multiplier)
case .equal:
return constraint(equalToSystemSpacingBelow: anchor, multiplier: multiplier)
case .greaterEqual:
return constraint(greaterThanOrEqualToSystemSpacingBelow: anchor, multiplier: multiplier)
}
}
}
public extension NSLayoutDimension {
func constraint(_ relation: ConstraintRelation, to dimension: NSLayoutDimension, multiplier: CGFloat, constant: CGFloat, position: AnchorPosition) -> NSLayoutConstraint {
switch relation {
case .lessEqual:
return constraint(lessThanOrEqualTo: dimension, multiplier: multiplier, constant: constant).position(position)
case .equal:
return constraint(equalTo: dimension, multiplier: multiplier, constant: constant).position(position)
case .greaterEqual:
return constraint(greaterThanOrEqualTo: dimension, multiplier: multiplier, constant: constant).position(position)
}
}
func constraint(_ relation: ConstraintRelation, toConstant constant: CGFloat, position: AnchorPosition) -> NSLayoutConstraint {
switch relation {
case .lessEqual:
return constraint(lessThanOrEqualToConstant: constant).position(position)
case .equal:
return constraint(equalToConstant: constant).position(position)
case .greaterEqual:
return constraint(greaterThanOrEqualToConstant: constant).position(position)
}
}
}
| 42.420561 | 174 | 0.716017 |
61a0822df54673aab4baef011d04296e918ad0c7 | 877 | //
// Level43.swift
// Blocky
//
// Created by Lodewijck Vogelzang on 07-12-18
// Copyright (c) 2018 Lodewijck Vogelzang. All rights reserved.
//
import UIKit
final class Level43: Level {
let levelNumber = 43
var tiles = [[0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 0]]
let cameraFollowsBlock = false
let blocky: Blocky
let enemies: [Enemy]
let foods: [Food]
init() {
blocky = Blocky(startLocation: (0, 1), endLocation: (4, 1))
let pattern0 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy0 = Enemy(enemyNumber: 0, startLocation: (1, 3), animationPattern: pattern0)
let pattern1 = [("S", 0.5), ("S", 0.5), ("S", 0.5), ("N", 0.5), ("N", 0.5), ("N", 0.5)]
let enemy1 = Enemy(enemyNumber: 1, startLocation: (3, 3), animationPattern: pattern1)
enemies = [enemy0, enemy1]
foods = []
}
}
| 25.057143 | 89 | 0.573546 |
28a191dbaa3eb76a36f5f63d9728484c7e715021 | 2,631 | //
// MultiCache.swift
// Cache
//
// Created by Sam Soffes on 5/6/16.
// Copyright © 2016 Sam Soffes. All rights reserved.
//
import Darwin
/// Reads from the first cache available. Writes to all caches in order. If there is a cache miss and the value is later
/// found in a subsequent cache, it is written to all previous caches.
public struct MultiCache<Element>: Cache {
// MARK: - Properties
public let caches: [AnyCache<Element>]
// MARK: - Initializers
public init(caches: [AnyCache<Element>]) {
self.caches = caches
}
// MARK: - Cache
public func set(key: String, value: Element, completion: (() -> Void)? = nil) {
coordinate(block: { cache, finish in
cache.set(key: key, value: value, completion: finish)
}, completion: completion)
}
public func get(key: String, completion: @escaping ((Element?) -> Void)) {
var misses = [AnyCache<Element>]()
func finish(_ value: Element?) {
// Found
if let value = value {
// Call completion with the value
completion(value)
// Fill previous caches that missed
for miss in misses {
miss.set(key: key, value: value)
}
return
}
// Not in any of the caches
if misses.count + 1 == self.caches.count {
completion(nil)
return
}
// Not found in this cache
misses.append(self.caches[misses.count])
// Try the next cache
get(key: key, cacheIndex: misses.count, completion: finish)
}
// Try the first cache
get(key: key, cacheIndex: 0, completion: finish)
}
public func remove(key: String, completion: (() -> Void)?) {
coordinate(block: { cache, finish in
cache.remove(key: key, completion: finish)
}, completion: completion)
}
public func removeAll(completion: (() -> Void)?) {
coordinate(block: { cache, finish in
cache.removeAll(completion: finish)
}, completion: completion)
}
// MARK: - Private
// Calls the completion block after all messages to all caches are complete.
private func coordinate(block: ((AnyCache<Element>, (() -> Void)?) -> Void), completion: (() -> Void)?) {
// Count starts with the count of caches
var count = Int32(caches.count)
let finish: () -> () = {
// Safely decrement the count
OSAtomicCompareAndSwap32(count, count - 1, &count)
// If the count is 0, we're received all of the callbacks.
if count == 0 {
// Call the completion
completion?()
}
}
// Kick off the work for each cache
caches.forEach { block($0, finish) }
}
private func get(key: String, cacheIndex index: Int, completion: @escaping ((Element?) -> Void)) {
caches[index].get(key: key, completion: completion)
}
}
| 24.588785 | 120 | 0.654884 |
1e516f13e839d9783a603e04fe5c5f0fcc862b87 | 1,835 | //#-hidden-code
import PlaygroundSupport
import SwiftUI
import UIKit
import SpriteKit
//#-end-hidden-code
/*:
# Learning Physics with SpriteKit
## Format
This playground is built on **4** experiments. Use code to configure and evaluate results in LiveView. Users learn basic physics concepts and their application in `SpriteKit`.
## Programming
There several abstractions including:
- `canvas.addLedge(width: Int, angle: Int, position: (Int, Int))` creates a ledge
- `canvas.add(_: SKNode)` adds a custom node (more on last page)
## Interacting
Here's what you can do on the right side:
- Drag Ledges
- Click and hold to create marbles
- Track duration of marble runs
- Use a consistent start point (white circle)
*/
//#-hidden-code
let conf = Configuration (
BackgroundColor: #colorLiteral(red: 0.06274510175, green: 0, blue: 0.1921568662, alpha: 1),
BallColor: #colorLiteral(red: 0.9686274529, green: 0.78039217, blue: 0.3450980484, alpha: 1),
LedgeColor: #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1)
)
let uiconf = InterfaceConfiguration (
MainText: "Press and Hold",
SubText: "Then release to create a marble"
)
let canvas = InterfaceView(gameconfig: conf, uiconfig: uiconf)
//#-end-hidden-code
//: Let's start making some ledges. **Press "Run My Code"** for the defaults or add more.
//#-editable-code
// each line adds a ledge
canvas.addLedge(width: 200, angle: 10, position: (150, 200))
canvas.addLedge(width: 200, angle: -10, position: (-100, 50))
canvas.addLedge(width: 200, angle: 10, position: (100, -100))
//#-end-editable-code
//: Copy the code to clipboard. After running, use the arrows above to continue
//#-hidden-code
let wrapper = UIHostingController(rootView: canvas)
PlaygroundPage.current.liveView = wrapper
//#-end-hidden-code
| 33.363636 | 176 | 0.725886 |
1cb9bfdf4d9e7a54fa89479992050282bcbd676b | 1,597 | //
// Core+UICollectionView.swift
// AnyImageKit
//
// Created by 蒋惠 on 2019/9/17.
// Copyright © 2019-2022 AnyImageKit.org. All rights reserved.
//
import UIKit
extension UICollectionView {
func registerCell<T: UICollectionViewCell>(_ type: T.Type) {
let identifier = String(describing: type.self)
register(type, forCellWithReuseIdentifier: identifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(_ type: T.Type, for indexPath: IndexPath) -> T {
let identifier = String(describing: type.self)
guard let cell = dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? T else {
fatalError("\(type.self) was not registered")
}
return cell
}
}
extension UICollectionView {
func scrollToFirst(at scrollPosition: UICollectionView.ScrollPosition, animated: Bool) {
guard numberOfSections > 0 else { return }
guard numberOfItems(inSection: 0) > 0 else { return }
let indexPath = IndexPath(item: 0, section: 0)
scrollToItem(at: indexPath, at: scrollPosition, animated: animated)
}
func scrollToLast(at scrollPosition: UICollectionView.ScrollPosition, animated: Bool) {
guard numberOfSections > 0 else { return }
let lastSection = numberOfSections - 1
guard numberOfItems(inSection: lastSection) > 0 else { return }
let lastIndexPath = IndexPath(item: numberOfItems(inSection: lastSection)-1, section: lastSection)
scrollToItem(at: lastIndexPath, at: scrollPosition, animated: animated)
}
}
| 36.295455 | 106 | 0.685034 |
fe10ca57bfa11e1565e729757cf51c8c1a89140f | 1,038 | // Generated using Sourcery 1.0.0 — https://github.com/krzysztofzablocki/Sourcery
// DO NOT EDIT
import UIKit
public extension UIStepper {
@discardableResult
func isContinuous(_ newValue: Bool) -> Self {
isContinuous = newValue
return self
}
@discardableResult
func autorepeat(_ newValue: Bool) -> Self {
autorepeat = newValue
return self
}
@discardableResult
func wraps(_ newValue: Bool) -> Self {
wraps = newValue
return self
}
@discardableResult
func value(_ newValue: Double) -> Self {
value = newValue
return self
}
@discardableResult
func minimumValue(_ newValue: Double) -> Self {
minimumValue = newValue
return self
}
@discardableResult
func maximumValue(_ newValue: Double) -> Self {
maximumValue = newValue
return self
}
@discardableResult
func stepValue(_ newValue: Double) -> Self {
stepValue = newValue
return self
}
}
| 20.352941 | 81 | 0.614644 |
d79b59c3d867ff3b22e55a990bd0e0784c8f8212 | 548 | //
// ViewController.swift
// Example
//
// Created by Lshiva on 07/08/2019.
// Copyright © 2019 what3words. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var suggestionField : W3wTextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
suggestionField!.setAPIKey(APIKey: "<Secret API Key>")
suggestionField?.didSelect(completion: { (words) in
print(words)
})
}
}
| 21.076923 | 62 | 0.638686 |
3869736a10f1ef45fef4122800d09ed10169f342 | 280 | //
// LooseSerializable.swift
// commonLib
//
// Created by opiopan on 2017/10/14.
// Copyright © 2017年 opiopan. All rights reserved.
//
import Foundation
public protocol LooseSerializable {
init(dict : [String : Any]) throws
var dictionary : [String : Any] {get}
}
| 18.666667 | 51 | 0.678571 |
90355e4b77ad72a51365162f0329ae454efc3410 | 5,359 | //
// PXOneTapInstallmentsSelectorView.swift
// MercadoPagoSDK
//
// Created by AUGUSTO COLLERONE ALFONSO on 16/10/18.
//
import UIKit
final class PXOneTapInstallmentsSelectorView: PXComponentView {
private var model: PXOneTapInstallmentsSelectorViewModel
let tableView = UITableView()
let tableViewTopSeparator = UIView()
let shadowView = UIImageView(image: ResourceManager.shared.getImage("one-tap-installments-shadow"))
weak var delegate: PXOneTapInstallmentsSelectorProtocol?
var tableViewHeightConstraint: NSLayoutConstraint?
init(viewModel: PXOneTapInstallmentsSelectorViewModel) {
model = viewModel
super.init()
render()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(viewModel: PXOneTapInstallmentsSelectorViewModel) {
model = viewModel
render()
}
}
extension PXOneTapInstallmentsSelectorView {
func render() {
removeAllSubviews()
pinContentViewToTop()
addSubviewToBottom(tableView)
backgroundColor = .clear
tableViewHeightConstraint = PXLayout.setHeight(owner: tableView, height: 0)
tableViewHeightConstraint?.isActive = true
PXLayout.pinLeft(view: tableView).isActive = true
PXLayout.pinRight(view: tableView).isActive = true
tableView.separatorInset = .init(top: 0, left: 0, bottom: 0, right: 0)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
tableViewTopSeparator.translatesAutoresizingMaskIntoConstraints = false
tableViewTopSeparator.backgroundColor = tableView.separatorColor
tableView.tableHeaderView = tableViewTopSeparator
PXLayout.matchWidth(ofView: tableViewTopSeparator, toView: tableView).isActive = true
PXLayout.centerHorizontally(view: tableViewTopSeparator, to: tableView).isActive = true
PXLayout.pinTop(view: tableViewTopSeparator, to: tableView).isActive = true
PXLayout.setHeight(owner: tableViewTopSeparator, height: 0.5).isActive = true
tableView.tableHeaderView?.layoutIfNeeded()
tableView.reloadData()
}
func expand(animator: PXAnimator, completion: @escaping () -> ()) {
self.layoutIfNeeded()
self.tableViewTopSeparator.alpha = 1
self.tableView.alpha = 0
animateTableViewHeight(tableViewHeight: self.frame.height, tableViewAlpha: 1, completion: completion)
animator.animate()
}
func collapse(animator: PXAnimator, completion: @escaping () -> ()) {
self.layoutIfNeeded()
animateTableViewHeight(tableViewHeight: 0, tableViewAlpha: 0, hideTopSeparator: true, completion: completion)
animator.animate()
}
func animateTableViewHeight(tableViewHeight: CGFloat, tableViewAlpha: CGFloat, hideTopSeparator: Bool = false, completion: @escaping () -> ()) {
self.superview?.layoutIfNeeded()
tableView.isUserInteractionEnabled = false
var pxAnimator = PXAnimator(duration: 0.5, dampingRatio: 1)
pxAnimator.addAnimation(animation: { [weak self] in
guard let strongSelf = self else {
return
}
if hideTopSeparator {
strongSelf.tableViewTopSeparator.alpha = 0
}
strongSelf.tableViewHeightConstraint?.constant = tableViewHeight
strongSelf.tableView.alpha = tableViewAlpha
strongSelf.layoutIfNeeded()
})
pxAnimator.addCompletion(completion: completion)
pxAnimator.addCompletion { [weak self] in
self?.tableView.isUserInteractionEnabled = true
}
pxAnimator.animate()
}
}
// MARK: UITableViewDelegate & DataSource
extension PXOneTapInstallmentsSelectorView: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model.numberOfRowsInSection(section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return model.cellForRowAt(indexPath)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return model.heightForRowAt(indexPath)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let selectedPayerCost = model.getPayerCostForRowAt(indexPath) {
delegate?.payerCostSelected(selectedPayerCost)
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
shadowView.contentMode = .scaleToFill
shadowView.translatesAutoresizingMaskIntoConstraints = false
if tableView.contentOffset.y > CGFloat(0.0) {
self.addSubview(shadowView)
PXLayout.pinRight(view: shadowView).isActive = true
PXLayout.pinLeft(view: shadowView).isActive = true
PXLayout.pinTop(view: shadowView).isActive = true
PXLayout.setHeight(owner: shadowView, height: 22).isActive = true
} else {
shadowView.removeFromSuperview()
shadowView.removeConstraints(shadowView.constraints)
}
}
}
| 38.833333 | 148 | 0.69248 |
e6e61d41547a0158d5a462c6610192ecda7d0c30 | 11,930 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Deduction of generic arguments
//===----------------------------------------------------------------------===//
func identity<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> T { return value }
func identity2<T>(_ value: T) -> Int { return 0 }
struct X { }
struct Y { }
func useIdentity(_ x: Int, y: Float, i32: Int32) {
var x2 = identity(x)
var y2 = identity(y)
// Deduction that involves the result type
x2 = identity(17)
var i32_2 : Int32 = identity(17)
// Deduction where the result type and input type can get different results
var xx : X, yy : Y
xx = identity(yy) // expected-error{{cannot assign value of type 'Y' to type 'X'}}
// FIXME: rdar://41416647
xx = identity2(yy) // expected-error{{type of expression is ambiguous without more context}}
}
// FIXME: Crummy diagnostic!
func twoIdentical<T>(_ x: T, _ y: T) -> T {}
func useTwoIdentical(_ xi: Int, yi: Float) {
var x = xi, y = yi
x = twoIdentical(x, x)
y = twoIdentical(y, y)
x = twoIdentical(x, 1)
x = twoIdentical(1, x)
y = twoIdentical(1.0, y)
y = twoIdentical(y, 1.0)
twoIdentical(x, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func mySwap<T>(_ x: inout T,
_ y: inout T) {
let tmp = x
x = y
y = tmp
}
func useSwap(_ xi: Int, yi: Float) {
var x = xi, y = yi
mySwap(&x, &x)
mySwap(&y, &y)
mySwap(x, x) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{10-10=&}}
// expected-error @-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{13-13=&}}
mySwap(&x, &y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func takeTuples<T, U>(_: (T, U), _: (U, T)) {
}
func useTuples(_ x: Int, y: Float, z: (Float, Int)) {
takeTuples((x, y), (y, x))
takeTuples((x, y), (x, y)) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
// FIXME: Use 'z', which requires us to fix our tuple-conversion
// representation.
}
func acceptFunction<T, U>(_ f: (T) -> U, _ t: T, _ u: U) {}
func passFunction(_ f: (Int) -> Float, x: Int, y: Float) {
acceptFunction(f, x, y)
acceptFunction(f, y, y) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
}
func returnTuple<T, U>(_: T) -> (T, U) { } // expected-note 2{{in call to function 'returnTuple'}}
func testReturnTuple(_ x: Int, y: Float) {
returnTuple(x) // expected-error{{generic parameter 'U' could not be inferred}}
var _ : (Int, Float) = returnTuple(x)
var _ : (Float, Float) = returnTuple(y)
// <rdar://problem/22333090> QoI: Propagate contextual information in a call to operands
var _ : (Int, Float) = returnTuple(y) // expected-error{{generic parameter 'U' could not be inferred}}
}
func confusingArgAndParam<T, U>(_ f: (T) -> U, _ g: (U) -> T) {
confusingArgAndParam(g, f)
confusingArgAndParam(f, g)
}
func acceptUnaryFn<T, U>(_ f: (T) -> U) { }
func acceptUnaryFnSame<T>(_ f: (T) -> T) { }
func acceptUnaryFnRef<T, U>(_ f: inout (T) -> U) { }
func acceptUnaryFnSameRef<T>(_ f: inout (T) -> T) { }
func unaryFnIntInt(_: Int) -> Int {}
func unaryFnOvl(_: Int) -> Int {} // expected-note{{found this candidate}}
func unaryFnOvl(_: Float) -> Int {} // expected-note{{found this candidate}}
// Variable forms of the above functions
var unaryFnIntIntVar : (Int) -> Int = unaryFnIntInt
func passOverloadSet() {
// Passing a non-generic function to a generic function
acceptUnaryFn(unaryFnIntInt)
acceptUnaryFnSame(unaryFnIntInt)
// Passing an overloaded function set to a generic function
// FIXME: Yet more terrible diagnostics.
acceptUnaryFn(unaryFnOvl) // expected-error{{ambiguous use of 'unaryFnOvl'}}
acceptUnaryFnSame(unaryFnOvl)
// Passing a variable of function type to a generic function
acceptUnaryFn(unaryFnIntIntVar)
acceptUnaryFnSame(unaryFnIntIntVar)
// Passing a variable of function type to a generic function to an inout parameter
acceptUnaryFnRef(&unaryFnIntIntVar)
acceptUnaryFnSameRef(&unaryFnIntIntVar)
acceptUnaryFnRef(unaryFnIntIntVar) // expected-error{{passing value of type '(Int) -> Int' to an inout parameter requires explicit '&'}} {{20-20=&}}
}
func acceptFnFloatFloat(_ f: (Float) -> Float) {}
func acceptFnDoubleDouble(_ f: (Double) -> Double) {}
func passGeneric() {
acceptFnFloatFloat(identity)
acceptFnFloatFloat(identity2)
}
//===----------------------------------------------------------------------===//
// Simple deduction for generic member functions
//===----------------------------------------------------------------------===//
struct SomeType {
func identity<T>(_ x: T) -> T { return x }
func identity2<T>(_ x: T) -> T { return x } // expected-note 2{{found this candidate}}
func identity2<T>(_ x: T) -> Float { } // expected-note 2{{found this candidate}}
func returnAs<T>() -> T {}
}
func testMemberDeduction(_ sti: SomeType, ii: Int, fi: Float) {
var st = sti, i = ii, f = fi
i = st.identity(i)
f = st.identity(f)
i = st.identity2(i)
f = st.identity2(f) // expected-error{{ambiguous use of 'identity2'}}
i = st.returnAs()
f = st.returnAs()
acceptFnFloatFloat(st.identity)
acceptFnFloatFloat(st.identity2) // expected-error{{ambiguous use of 'identity2'}}
acceptFnDoubleDouble(st.identity2)
}
struct StaticFuncs {
static func chameleon<T>() -> T {}
func chameleon2<T>() -> T {}
}
struct StaticFuncsGeneric<U> {
// FIXME: Nested generics are very broken
// static func chameleon<T>() -> T {}
}
func chameleon<T>() -> T {}
func testStatic(_ sf: StaticFuncs, sfi: StaticFuncsGeneric<Int>) {
var x: Int16
x = StaticFuncs.chameleon()
x = sf.chameleon2()
// FIXME: Nested generics are very broken
// x = sfi.chameleon()
// typealias SFI = StaticFuncsGeneric<Int>
// x = SFI.chameleon()
_ = x
}
//===----------------------------------------------------------------------===//
// Deduction checking for constraints
//===----------------------------------------------------------------------===//
protocol IsBefore {
func isBefore(_ other: Self) -> Bool
}
func min2<T : IsBefore>(_ x: T, _ y: T) -> T {
if y.isBefore(x) { return y }
return x
}
extension Int : IsBefore {
func isBefore(_ other: Int) -> Bool { return self < other }
}
func callMin(_ x: Int, y: Int, a: Float, b: Float) {
_ = min2(x, y)
min2(a, b) // expected-error{{argument type 'Float' does not conform to expected type 'IsBefore'}}
}
func rangeOfIsBefore<R : IteratorProtocol>(_ range: R) where R.Element : IsBefore {}
func callRangeOfIsBefore(_ ia: [Int], da: [Double]) {
rangeOfIsBefore(ia.makeIterator())
rangeOfIsBefore(da.makeIterator()) // expected-error{{'(IndexingIterator<[Double]>) -> ()' requires that 'Double' conform to 'IsBefore'}}
}
func testEqualIterElementTypes<A: IteratorProtocol, B: IteratorProtocol>(_ a: A, _ b: B) where A.Element == B.Element {}
// expected-note@-1 {{candidate requires that the types 'Int' and 'Double' be equivalent (requirement specified as 'A.Element' == 'B.Element' [with A = IndexingIterator<[Int]>, B = IndexingIterator<[Double]>])}}
func compareIterators() {
var a: [Int] = []
var b: [Double] = []
testEqualIterElementTypes(a.makeIterator(), b.makeIterator())
// expected-error@-1 {{cannot invoke 'testEqualIterElementTypes(_:_:)' with an argument list of type '(IndexingIterator<[Int]>, IndexingIterator<[Double]>)'}}
}
protocol P_GI {
associatedtype Y
}
class C_GI : P_GI {
typealias Y = Double
}
class GI_Diff {}
func genericInheritsA<T>(_ x: T) where T : P_GI, T.Y : GI_Diff {}
// expected-note@-1 {{candidate requires that 'GI_Diff' inherit from 'T.Y' (requirement specified as 'T.Y' : 'GI_Diff' [with T = C_GI])}}
genericInheritsA(C_GI())
// expected-error@-1 {{cannot invoke 'genericInheritsA(_:)' with an argument list of type '(C_GI)'}}
//===----------------------------------------------------------------------===//
// Deduction for member operators
//===----------------------------------------------------------------------===//
protocol Addable {
static func +(x: Self, y: Self) -> Self
}
func addAddables<T : Addable, U>(_ x: T, y: T, u: U) -> T {
u + u // expected-error{{binary operator '+' cannot be applied to two 'U' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
return x+y
}
//===----------------------------------------------------------------------===//
// Deduction for bound generic types
//===----------------------------------------------------------------------===//
struct MyVector<T> { func size() -> Int {} }
func getVectorSize<T>(_ v: MyVector<T>) -> Int {
return v.size()
}
func ovlVector<T>(_ v: MyVector<T>) -> X {}
func ovlVector<T>(_ v: MyVector<MyVector<T>>) -> Y {}
func testGetVectorSize(_ vi: MyVector<Int>, vf: MyVector<Float>) {
var i : Int
i = getVectorSize(vi)
i = getVectorSize(vf)
getVectorSize(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'MyVector<_>'}}
var x : X, y : Y
x = ovlVector(vi)
x = ovlVector(vf)
var vvi : MyVector<MyVector<Int>>
y = ovlVector(vvi)
var yy = ovlVector(vvi)
yy = y
y = yy
}
// <rdar://problem/15104554>
postfix operator <*>
protocol MetaFunction {
associatedtype Result
static postfix func <*> (_: Self) -> Result?
}
protocol Bool_ {}
struct False : Bool_ {}
struct True : Bool_ {}
postfix func <*> <B>(_: Test<B>) -> Int? { return .none }
postfix func <*> (_: Test<True>) -> String? { return .none }
class Test<C: Bool_> : MetaFunction {
typealias Result = Int
} // picks first <*>
typealias Inty = Test<True>.Result
var iy : Inty = 5 // okay, because we picked the first <*>
var iy2 : Inty = "hello" // expected-error{{cannot convert value of type 'String' to specified type 'Inty' (aka 'Int')}}
// rdar://problem/20577950
class DeducePropertyParams {
let badSet: Set = ["Hello"]
}
// SR-69
struct A {}
func foo() {
for i in min(1,2) { // expected-error{{type 'Int' does not conform to protocol 'Sequence'}}
}
let j = min(Int(3), Float(2.5)) // expected-error{{cannot convert value of type 'Float' to expected argument type 'Int'}}
let k = min(A(), A()) // expected-error{{argument type 'A' does not conform to expected type 'Comparable'}}
let oi : Int? = 5
let l = min(3, oi) // expected-error{{value of optional type 'Int?' must be unwrapped}}
// expected-note@-1{{coalesce}}
// expected-note@-2{{force-unwrap}}
}
infix operator +&
func +&<R, S>(lhs: inout R, rhs: S) where R : RangeReplaceableCollection, S : Sequence, R.Element == S.Element {}
// expected-note@-1 {{candidate requires that the types 'String' and 'Character' be equivalent (requirement specified as 'R.Element' == 'S.Element' [with R = [String], S = String])}}
func rdar33477726_1() {
var arr: [String] = []
arr +& "hello"
// expected-error@-1 {{binary operator '+&(_:_:)' cannot be applied to operands of type '[String]' and 'String'}}
}
func rdar33477726_2<R, S>(_: R, _: S) where R: Sequence, S == R.Element {}
// expected-note@-1 {{candidate requires that the types 'Int' and 'Character' be equivalent (requirement specified as 'S' == 'R.Element' [with R = String, S = Int])}}
rdar33477726_2("answer", 42)
// expected-error@-1 {{cannot invoke 'rdar33477726_2(_:_:)' with an argument list of type '(String, Int)'}}
prefix operator +-
prefix func +-<T>(_: T) where T: Sequence, T.Element == Int {}
// expected-note@-1 {{candidate requires that the types 'Character' and 'Int' be equivalent (requirement specified as 'T.Element' == 'Int' [with T = String])}}
+-"hello"
// expected-error@-1 {{unary operator '+-(_:)' cannot be applied to an operand of type 'String'}}
| 34.380403 | 211 | 0.618692 |
0ed792d4d95ca3331b8eb04227b25a2653cb502f | 3,977 | //
// StartViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-10-22.
// Copyright © 2016 breadwallet LLC. All rights reserved.
//
import UIKit
class StartViewController : UIViewController {
//MARK: - Public
init(store: Store, didTapCreate: @escaping () -> Void, didTapRecover: @escaping () -> Void) {
self.store = store
self.didTapRecover = didTapRecover
self.didTapCreate = didTapCreate
self.faq = UIButton.buildFaqButton(store: store, articleId: ArticleIds.startView)
super.init(nibName: nil, bundle: nil)
}
//MARK: - Private
private let message = UILabel(font: .customMedium(size: 18.0), color: .whiteTint)
private let create = ShadowButton(title: S.StartViewController.createButton, type: .primary)
private let recover = ShadowButton(title: S.StartViewController.recoverButton, type: .secondary)
private let store: Store
private let didTapRecover: () -> Void
private let didTapCreate: () -> Void
private let background = LoginBackgroundView()
private var logo: UIImageView = {
let image = UIImageView(image: #imageLiteral(resourceName: "Logo"))
image.contentMode = .scaleAspectFit
return image
}()
private var faq: UIButton
override func viewDidLoad() {
view.backgroundColor = .white
setData()
addSubviews()
addConstraints()
addButtonActions()
}
private func setData() {
message.text = S.StartViewController.message
message.lineBreakMode = .byWordWrapping
message.numberOfLines = 0
message.textAlignment = .center
faq.tintColor = .whiteTint
}
private func addSubviews() {
view.addSubview(background)
view.addSubview(logo)
view.addSubview(message)
view.addSubview(create)
view.addSubview(recover)
view.addSubview(faq)
}
private func addConstraints() {
background.constrain(toSuperviewEdges: nil)
let yConstraint = NSLayoutConstraint(item: logo, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 0.5, constant: 0.0)
logo.constrain([
logo.constraint(.centerX, toView: view, constant: nil),
yConstraint])
message.constrain([
message.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]),
message.topAnchor.constraint(equalTo: logo.bottomAnchor, constant: C.padding[3]),
message.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]) ])
recover.constrain([
recover.constraint(.leading, toView: view, constant: C.padding[2]),
recover.constraint(.bottom, toView: view, constant: -C.padding[3]),
recover.constraint(.trailing, toView: view, constant: -C.padding[2]),
recover.constraint(.height, constant: C.Sizes.buttonHeight) ])
create.constrain([
create.constraint(toTop: recover, constant: -C.padding[2]),
create.constraint(.centerX, toView: recover, constant: nil),
create.constraint(.width, toView: recover, constant: nil),
create.constraint(.height, constant: C.Sizes.buttonHeight) ])
faq.constrain([
faq.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: C.padding[2]),
faq.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]),
faq.widthAnchor.constraint(equalToConstant: 44.0),
faq.heightAnchor.constraint(equalToConstant: 44.0) ])
}
private func addButtonActions() {
recover.tap = didTapRecover
create.tap = didTapCreate
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 38.990196 | 163 | 0.658788 |
0140d0cc6d598d94099cd272d0e4de7270f79c02 | 2,481 | //
// SlideInPresentationManager.swift
// MedalCount
//
// Created by Warif Akhand Rishi on 10/18/16.
// Copyright © 2016 Ron Kliffer. All rights reserved.
//
import UIKit
enum PresentationDirection {
case left
case top
case right
case bottom
}
class SlideInPresentationManager: NSObject {
var direction = PresentationDirection.left
var disableCompactHeight = false
}
// MARK: - UIViewControllerTransitioningDelegate
extension SlideInPresentationManager: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController,
presenting: UIViewController?,
source: UIViewController) -> UIPresentationController? {
let presentationController = SlideInPresentationController(presentedViewController: presented,
presenting: presenting,
direction: direction)
presentationController.delegate = self
return presentationController
}
func animationController(forPresented presented: UIViewController,
presenting: UIViewController,
source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SlideInPresentationAnimator(direction: direction, isPresentation: true)
}
func animationController(forDismissed dismissed: UIViewController)
-> UIViewControllerAnimatedTransitioning? {
return SlideInPresentationAnimator(direction: direction, isPresentation: false)
}
}
// MARK: - UIAdaptivePresentationControllerDelegate
extension SlideInPresentationManager: UIAdaptivePresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController,
traitCollection: UITraitCollection) -> UIModalPresentationStyle {
if traitCollection.verticalSizeClass == .compact && disableCompactHeight {
return .overFullScreen
} else {
return .none
}
}
func presentationController(_ controller: UIPresentationController,
viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle)
-> UIViewController? {
guard style == .overFullScreen else { return nil }
return UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "RotateViewController")
}
}
| 35.442857 | 105 | 0.692463 |
20be1375f34cebd5a41af9e34ae18ac72b4b5438 | 3,459 | //
// PageControl.swift
// StackUI
//
// Created by jiaxin on 2021/9/12.
//
import UIKit
public protocol StackUIPageControl: UIPageControl, StackUIControl {
func numberOfPages(_ numberOfPages: Int) -> Self
func currentPage(_ currentPage: Int) -> Self
func currentPage(_ publisher: Publisher<Int>) -> Self
func hidesForSinglePage(_ hidesForSinglePage: Bool) -> Self
func pageIndicatorTintColor(_ pageIndicatorTintColor: UIColor?) -> Self
func currentPageIndicatorTintColor(_ currentPageIndicatorTintColor: UIColor?) -> Self
@available(iOS 14.0, *)
func backgroundStyle(_ backgroundStyle: PageControl.BackgroundStyle) -> Self
@available(iOS 14.0, *)
func allowsContinuousInteraction(_ allowsContinuousInteraction: Bool) -> Self
@available(iOS 14.0, *)
func preferredIndicatorImage(_ preferredIndicatorImage: UIImage?) -> Self
@available(iOS 14.0, *)
func indicatorImage(_ image: UIImage?, forPage page: Int) -> Self
@available(iOS, introduced: 2.0, deprecated: 14.0, message: "updateCurrentPageDisplay no longer does anything reasonable with the new interaction mode.")
func defersCurrentPageDisplay(_ defersCurrentPageDisplay: Bool) -> Self
}
public extension StackUIPageControl {
func numberOfPages(_ numberOfPages: Int) -> Self {
self.numberOfPages = numberOfPages
return self
}
func currentPage(_ currentPage: Int) -> Self {
self.currentPage = currentPage
return self
}
func currentPage(_ publisher: Publisher<Int>) -> Self {
publisher.addSubscriber {[weak self] currentPage in
self?.currentPage = currentPage
}
return self
}
func hidesForSinglePage(_ hidesForSinglePage: Bool) -> Self {
self.hidesForSinglePage = hidesForSinglePage
return self
}
func pageIndicatorTintColor(_ pageIndicatorTintColor: UIColor?) -> Self {
self.pageIndicatorTintColor = pageIndicatorTintColor
return self
}
func currentPageIndicatorTintColor(_ currentPageIndicatorTintColor: UIColor?) -> Self {
self.currentPageIndicatorTintColor = currentPageIndicatorTintColor
return self
}
@available(iOS 14.0, *)
func backgroundStyle(_ backgroundStyle: PageControl.BackgroundStyle) -> Self {
self.backgroundStyle = backgroundStyle
return self
}
@available(iOS 14.0, *)
func allowsContinuousInteraction(_ allowsContinuousInteraction: Bool) -> Self {
self.allowsContinuousInteraction = allowsContinuousInteraction
return self
}
@available(iOS 14.0, *)
func preferredIndicatorImage(_ preferredIndicatorImage: UIImage?) -> Self {
self.preferredIndicatorImage = preferredIndicatorImage
return self
}
@available(iOS 14.0, *)
func indicatorImage(_ image: UIImage?, forPage page: Int) -> Self {
self.setIndicatorImage(image, forPage: page)
return self
}
@available(iOS, introduced: 2.0, deprecated: 14.0, message: "updateCurrentPageDisplay no longer does anything reasonable with the new interaction mode.")
func defersCurrentPageDisplay(_ defersCurrentPageDisplay: Bool) -> Self {
self.defersCurrentPageDisplay = defersCurrentPageDisplay
return self
}
}
open class PageControl: UIPageControl, StackUIPageControl {
public func apply(_ closure: (Self) -> ()) -> Self {
closure(self)
return self
}
}
| 38.865169 | 157 | 0.703961 |
d5b2a308bc9bced893b9e9dcaf40aa8f6355487d | 2,207 | //
// AppDelegate.swift
// On The Map
//
// Created by Marcus Ronélius on 2015-10-06.
// Copyright © 2015 Ronelium Applications. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 46.957447 | 285 | 0.75623 |
ff651c98be3877fabfbd46010e4a0c2bb6dff99a | 153 | // Copyright © 2021 SpotHero, Inc. All rights reserved.
public enum SourceType {
case `default`
case repository
case url
case invalid
}
| 17 | 55 | 0.679739 |
f90c5b428ad6e160c163b8206b1ca849d3d19c2b | 9,034 | //
// Token.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 18/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
open class Token {
var type: TokenType = TokenType.Doctype
private init() {
}
func tokenType() -> String {
return String(describing: Swift.type(of: self))
}
/**
* Reset the data represent by this token, for reuse. Prevents the need to create transfer objects for every
* piece of data, which immediately get GCed.
*/
@discardableResult
public func reset() -> Token {
preconditionFailure("This method must be overridden")
}
static func reset(_ sb: StringBuilder) {
sb.clear()
}
open func toString()throws->String {
return String(describing: Swift.type(of: self))
}
final class Doctype: Token {
let name: StringBuilder = StringBuilder()
var pubSysKey: String?
let publicIdentifier: StringBuilder = StringBuilder()
let systemIdentifier: StringBuilder = StringBuilder()
var forceQuirks: Bool = false
override init() {
super.init()
type = TokenType.Doctype
}
@discardableResult
override func reset() -> Token {
Token.reset(name)
pubSysKey = nil
Token.reset(publicIdentifier)
Token.reset(systemIdentifier)
forceQuirks = false
return self
}
func getName() -> String {
return name.toString()
}
func getPubSysKey()->String? {
return pubSysKey;
}
func getPublicIdentifier() -> String {
return publicIdentifier.toString()
}
open func getSystemIdentifier() -> String {
return systemIdentifier.toString()
}
open func isForceQuirks() -> Bool {
return forceQuirks
}
}
class Tag: Token {
public var _tagName: String?
public var _normalName: String? // lc version of tag name, for case insensitive tree build
private var _pendingAttributeName: String? // attribute names are generally caught in one hop, not accumulated
private let _pendingAttributeValue: StringBuilder = StringBuilder() // but values are accumulated, from e.g. & in hrefs
private var _pendingAttributeValueS: String? // try to get attr vals in one shot, vs Builder
private var _hasEmptyAttributeValue: Bool = false // distinguish boolean attribute from empty string value
private var _hasPendingAttributeValue: Bool = false
public var _selfClosing: Bool = false
// start tags get attributes on construction. End tags get attributes on first new attribute (but only for parser convenience, not used).
public var _attributes: Attributes = Attributes()
override init() {
super.init()
}
@discardableResult
override func reset() -> Tag {
_tagName = nil
_normalName = nil
_pendingAttributeName = nil
Token.reset(_pendingAttributeValue)
_pendingAttributeValueS = nil
_hasEmptyAttributeValue = false
_hasPendingAttributeValue = false
_selfClosing = false
_attributes = Attributes()
return self
}
func newAttribute()throws {
// if (_attributes == nil){
// _attributes = Attributes()
// }
if (_pendingAttributeName != nil) {
var attribute: Attribute
if (_hasPendingAttributeValue) {
attribute = try Attribute(key: _pendingAttributeName!, value: _pendingAttributeValue.length > 0 ? _pendingAttributeValue.toString() : _pendingAttributeValueS!)
} else if (_hasEmptyAttributeValue) {
attribute = try Attribute(key: _pendingAttributeName!, value: "")
} else {
attribute = try BooleanAttribute(key: _pendingAttributeName!)
}
_attributes.put(attribute: attribute)
}
_pendingAttributeName = nil
_hasEmptyAttributeValue = false
_hasPendingAttributeValue = false
Token.reset(_pendingAttributeValue)
_pendingAttributeValueS = nil
}
func finaliseTag()throws {
// finalises for emit
if (_pendingAttributeName != nil) {
// todo: check if attribute name exists; if so, drop and error
try newAttribute()
}
}
func name()throws->String { // preserves case, for input into Tag.valueOf (which may drop case)
try Validate.isFalse(val: _tagName == nil || _tagName!.unicodeScalars.count == 0)
return _tagName!
}
func normalName() -> String? { // loses case, used in tree building for working out where in tree it should go
return _normalName
}
@discardableResult
func name(_ name: String) -> Tag {
_tagName = name
_normalName = name.lowercased()
return self
}
func isSelfClosing() -> Bool {
return _selfClosing
}
func getAttributes() -> Attributes {
return _attributes
}
// these appenders are rarely hit in not null state-- caused by null chars.
func appendTagName(_ append: String) {
_tagName = _tagName == nil ? append : _tagName!.appending(append)
_normalName = _tagName?.lowercased()
}
func appendTagName(_ append: UnicodeScalar) {
appendTagName("\(append)")
}
func appendAttributeName(_ append: String) {
_pendingAttributeName = _pendingAttributeName == nil ? append : _pendingAttributeName?.appending(append)
}
func appendAttributeName(_ append: UnicodeScalar) {
appendAttributeName("\(append)")
}
func appendAttributeValue(_ append: String) {
ensureAttributeValue()
if (_pendingAttributeValue.length == 0) {
_pendingAttributeValueS = append
} else {
_pendingAttributeValue.append(append)
}
}
func appendAttributeValue(_ append: UnicodeScalar) {
ensureAttributeValue()
_pendingAttributeValue.appendCodePoint(append)
}
func appendAttributeValue(_ append: [UnicodeScalar]) {
ensureAttributeValue()
_pendingAttributeValue.appendCodePoints(append)
}
func appendAttributeValue(_ appendCodepoints: [Int]) {
ensureAttributeValue()
for codepoint in appendCodepoints {
_pendingAttributeValue.appendCodePoint(UnicodeScalar(codepoint)!)
}
}
func setEmptyAttributeValue() {
_hasEmptyAttributeValue = true
}
private func ensureAttributeValue() {
_hasPendingAttributeValue = true
// if on second hit, we'll need to move to the builder
if (_pendingAttributeValueS != nil) {
_pendingAttributeValue.append(_pendingAttributeValueS!)
_pendingAttributeValueS = nil
}
}
}
final class StartTag: Tag {
override init() {
super.init()
_attributes = Attributes()
type = TokenType.StartTag
}
@discardableResult
override func reset() -> Tag {
super.reset()
_attributes = Attributes()
// todo - would prefer these to be null, but need to check Element assertions
return self
}
@discardableResult
func nameAttr(_ name: String, _ attributes: Attributes) -> StartTag {
self._tagName = name
self._attributes = attributes
_normalName = _tagName?.lowercased()
return self
}
open override func toString()throws->String {
if (_attributes.size() > 0) {
return try "<" + (name()) + " " + (_attributes.toString()) + ">"
} else {
return try "<" + name() + ">"
}
}
}
final class EndTag: Tag {
override init() {
super.init()
type = TokenType.EndTag
}
open override func toString()throws->String {
return "</" + (try name()) + ">"
}
}
final class Comment: Token {
let data: StringBuilder = StringBuilder()
var bogus: Bool = false
@discardableResult
override func reset() -> Token {
Token.reset(data)
bogus = false
return self
}
override init() {
super.init()
type = TokenType.Comment
}
func getData() -> String {
return data.toString()
}
open override func toString()throws->String {
return "<!--" + getData() + "-->"
}
}
final class Char: Token {
public var data: String?
override init() {
super.init()
type = TokenType.Char
}
@discardableResult
override func reset() -> Token {
data = nil
return self
}
@discardableResult
func data(_ data: String) -> Char {
self.data = data
return self
}
func getData() -> String? {
return data
}
open override func toString()throws->String {
try Validate.notNull(obj: data)
return getData()!
}
}
final class EOF: Token {
override init() {
super.init()
type = Token.TokenType.EOF
}
@discardableResult
override func reset() -> Token {
return self
}
}
func isDoctype() -> Bool {
return type == TokenType.Doctype
}
func asDoctype() -> Doctype {
return self as! Doctype
}
func isStartTag() -> Bool {
return type == TokenType.StartTag
}
func asStartTag() -> StartTag {
return self as! StartTag
}
func isEndTag() -> Bool {
return type == TokenType.EndTag
}
func asEndTag() -> EndTag {
return self as! EndTag
}
func isComment() -> Bool {
return type == TokenType.Comment
}
func asComment() -> Comment {
return self as! Comment
}
func isCharacter() -> Bool {
return type == TokenType.Char
}
func asCharacter() -> Char {
return self as! Char
}
func isEOF() -> Bool {
return type == TokenType.EOF
}
public enum TokenType {
case Doctype
case StartTag
case EndTag
case Comment
case Char
case EOF
}
}
| 23.22365 | 164 | 0.68054 |
67320550cc3b27018dc171001aa91a79a0a06495 | 827 | import Foundation
public class ConsoleAppender: LogboardAppender {
public init() {
}
public func append(_ logboard: Logboard, level: Logboard.Level, message: [Any], file: StaticString, function: StaticString, line: Int) {
print(Logboard.dateFormatter.string(from: Date()), "[\(level)]", "[\(logboard.identifier)]", "[\(filename(file.description)):\(line)]", function, ">", message.map({ String(describing: $0) }).joined(separator: ""))
}
public func append(_ logboard: Logboard, level: Logboard.Level, format: String, arguments: CVarArg, file: StaticString, function: StaticString, line: Int) {
print(Logboard.dateFormatter.string(from: Date()), "[\(level)]", "[\(logboard.identifier)]", "[\(filename(file.description)):\(line)]", function, ">", String(format: format, arguments))
}
}
| 59.071429 | 221 | 0.675937 |
bbe0104deefb0a37bc2af7031ce6b4d4606d5d65 | 529 | //
// FP_Bundle+Extension.swift
// FlashPrinter
//
// Created by yulong mei on 2021/3/15.
//
import Foundation
extension UIImage {
/// Pod中加载Image
/// - Parameter name: ImageName
/// - Returns: UIImage
public static func fp_make(name: String) -> UIImage? {
guard let bundlePath = Bundle(for: FPBaseViewController.self).resourcePath else { return nil }
let bundle = Bundle(path: bundlePath + "/FlashPrinter.bundle")
return UIImage(named: name, in: bundle, compatibleWith: nil)
}
}
| 26.45 | 102 | 0.663516 |
75d0929a1896856a1572e23f8521625a4b29db42 | 736 | //
// CLLocationCoordinate2D+ExtensionsTests.swift
// FindMyRoute-DemoTests
//
// Created by Saul Moreno Abril on 9/9/20.
// Copyright © 2020 Saul Moreno Abril. All rights reserved.
//
import XCTest
import Quick
import Nimble
import Codextended
import MapKit
@testable import FindMyRoute_Demo
class CLLocationCoordinate2DExtensionsTests: QuickSpec {
override func spec() {
describe("A coordinate") {
it("can be compared") {
let firstC = CLLocationCoordinate2D(latitude: -10, longitude: 40)
let secondC = CLLocationCoordinate2D(latitude: -9, longitude: 41)
expect(firstC) == firstC
expect(firstC) != secondC
}
}
}
}
| 23.741935 | 81 | 0.642663 |
18a622ba9f2581d1db3143365bae99f255993f3f | 884 | //
// KarrotTests.swift
// KarrotTests
//
// Created by User on 2021/07/16.
//
import XCTest
@testable import Karrot
class KarrotTests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26 | 111 | 0.659502 |
624abe22b98f610c375c8c73e17fee785a50039c | 213 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b(){struct c<d where a:c{func b()->Self | 42.6 | 87 | 0.751174 |
72ba234273e8e5618df536618fe732bde42f045f | 4,802 | //
// Connectable.swift
// SourceArchitecture
//
// Copyright (c) 2022 Daniel Hall
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public enum Connectable<Value> {
case connected(Connected)
case disconnected(Disconnected)
@dynamicMemberLookup
public struct Connected {
public let disconnect: Action<Void>
public let value: Value
public init(value: Value, disconnect: Action<Void>) {
self.value = value
self.disconnect = disconnect
}
public subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> T {
value[keyPath: keyPath]
}
public subscript<T, V>(dynamicMember keyPath: KeyPath<V, T>) -> T? where Value == Optional<V> {
value?[keyPath: keyPath]
}
}
public struct Disconnected {
public let connect: Action<Void>
public init(connect: Action<Void>) {
self.connect = connect
}
}
public var connected: Connected? {
if case .connected(let connected) = self {
return connected
}
return nil
}
public var disconnected: Disconnected? {
if case .disconnected(let disconnected) = self {
return disconnected
}
return nil
}
public var isConnected: Bool {
connected != nil
}
public func connect(ifUnavailable: (Swift.Error) -> Void = _defaultActionUnavailableHandler) {
disconnected?.connect(ifUnavailable: ifUnavailable)
}
public func disconnect(ifUnavailable: (Swift.Error) -> Void = _defaultActionUnavailableHandler) {
connected?.disconnect(ifUnavailable: ifUnavailable)
}
}
public extension Connectable {
func addingPlaceholder<Placeholder>(_ placeholder: Placeholder) -> ConnectableWithPlaceholder<Value, Placeholder> {
switch self {
case .disconnected(let disconnected): return .disconnected(.init(placeholder: placeholder, connect: disconnected.connect))
case .connected(let connected): return .connected(.init(placeholder: placeholder, value: connected.value, disconnect: connected.disconnect))
}
}
}
public extension Connectable {
func map<NewValue>(_ transform: (Value) -> NewValue) -> Connectable<NewValue> {
switch self {
case .connected(let connected):
return .connected(.init(value: transform(connected.value), disconnect: connected.disconnect))
case .disconnected(let disconnected):
return .disconnected(.init(connect: disconnected.connect))
}
}
}
public protocol ConnectableRepresentable {
associatedtype Value
func asConnectable() -> Connectable<Value>
}
extension Connectable: ConnectableRepresentable {
public func asConnectable() -> Connectable<Value> {
self
}
}
extension Connectable: Equatable where Value: Equatable {
public static func ==(lhs: Connectable<Value>, rhs: Connectable<Value>) -> Bool {
switch (lhs, rhs) {
case (.connected(let left), .connected(let right)):
return left.value == right.value
case (.disconnected, .disconnected):
return true
default: return false
}
}
}
public extension Source where Model: ConnectableRepresentable {
// Disfavored overload because if the Model is also ConnectableWithPlaceholderRepresentable, we want to prefer that version of mapConnectedValue to preserve the more complete type
@_disfavoredOverload func mapConnectedValue<NewValue>(_ transform: @escaping (Model.Value) -> NewValue) -> Source<Connectable<NewValue>> {
map { $0.asConnectable().map(transform) }
}
}
| 35.051095 | 183 | 0.672845 |
bb841601fe5557c5cf5a6939e434f3d491a2161c | 255 | //
// ___FILENAME___
// ___PROJECTNAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright © ___YEAR___ AppCraft. All rights reserved.
//
import Foundation
import DPUIKit
class ___VARIABLE_viperModuleName___ViewModel: DPViewModel { }
| 19.615385 | 62 | 0.776471 |
2865e85b2465ffb733c03eb73427912c008a52da | 497 | //
// UIRoundProfileImageView.swift
// ProfileImage
//
// Created by Victor Obretin on 2017-01-15.
// Copyright © 2017 Victor Obretin. All rights reserved.
//
import UIKit
@IBDesignable
class UIRoundProfileImageView: UIProfileImageView {
override internal func getPath(bounds: CGRect, scale: CGFloat)->UIBezierPath {
let resultPath: UIBezierPath = UIBezierPath(ovalIn: bounds)
UIBezierPath.scalePath(path: resultPath, scale: scale)
return resultPath
}
}
| 24.85 | 82 | 0.71831 |
e6e5ba5bf56d44099f12b48c601de401819f0260 | 1,594 | //
// Store+PromiseKit.swift
// SwiftRedux
//
// Created by Charles Julian Knight on 7/25/16.
// Copyright © 2016 Charles Julian Knight. All rights reserved.
//
import Foundation
import PromiseKit
public class PKStore<State,Action>: BaseStore<State,Action> {
private var subscribers: [(Promise<State>, (State->Void),(ErrorType->Void))] = []
private let lock = NSLock()
public override init(withState initialState: State, middleware: [Middleware], reducer: Reducer) {
super.init(withState: initialState, middleware: middleware, reducer: reducer)
}
override public var state: State {
didSet {
lock.lock()
while !subscribers.isEmpty {
if let (_, f, _) = subscribers.popLast() {
f(state)
}
}
lock.unlock()
}
}
public func dispatchAsync(promise: Promise<Action>) {
promise.then { action in
self.dispatch(action)
}.error { error in
if let action = self.errorAction(error) {
self.dispatch(action)
}else{
print("warning: action promise errored but was not handled: \(error)")
}
}
}
public func errorAction(error: ErrorType) -> Action? {
return nil
}
public func promiseNextChange() -> Promise<State> {
lock.lock()
let pp = Promise<State>.pendingPromise()
subscribers.append(pp)
lock.unlock()
return pp.promise
}
} | 27.964912 | 101 | 0.557089 |
1d04eb91d092a0e8739e85148b15d871d6b9b85d | 3,497 | //
// XCTestCase.swift
// ClickerApp
//
// Created by Leo Picado on 6/25/16.
// Copyright © 2016 greenpixels. All rights reserved.
//
import Foundation
import XCTest
extension XCTestCase {
/**
Takes user to the Settings screen, in case it wasn't there.
- parameter app: current app
*/
func visitSettingsScreen(app app: XCUIApplication) {
guard !app.navigationBars["Settings"].exists else { return }
app.navigationBars.buttons["settingIcon"].tap()
}
/**
Takes user to the Main screen, in case it wasn't there.
- parameter app: current app
*/
func visitMainScreen(app app: XCUIApplication) {
guard app.navigationBars["Settings"].exists else { return }
app.navigationBars.buttons["Count It"].tap()
}
/**
Increases the current count of the clicker.
- parameter times: how many times the clicker should be incremented
- parameter app: current app
- parameter byTapping: interaction to be used
*/
func increaseCount(times times: Int = 1, app: XCUIApplication, byTapping: Bool = true) {
if byTapping {
let incrementCountButton = app.buttons["incrementCount"]
incrementCountButton.tapWithNumberOfTaps(UInt(times), numberOfTouches: 1)
} else {
for _ in 1...times {
app.windows.elementBoundByIndex(0).swipeUp()
}
}
}
/**
Decreases the current count of the clicker.
- parameter times: how many times the clicker should be decrementd
- parameter app: current app
- parameter byTapping: interaction to be used
*/
func decreaseCount(times times: Int = 1, app: XCUIApplication, byTapping: Bool = true) {
if byTapping {
let bottomToolbar = app.toolbars.elementBoundByIndex(0)
let decreaseButton = bottomToolbar.buttons.elementBoundByIndex(1)
decreaseButton.tapWithNumberOfTaps(UInt(times), numberOfTouches: 1)
} else {
for _ in 1...times {
app.windows.elementBoundByIndex(0).swipeDown()
}
}
}
/**
Asserts the current clicker count value.
- parameter equals: expectation
- parameter app: current app
*/
func assertCurrentCount(equals equals: Int, app: XCUIApplication) {
XCTAssertEqual(getCurrentCount(app: app), equals)
}
/**
Restores the current clicker count back to zero, in case it wasn't at zero yet.
- parameter app: current app
*/
func resetCount(app app: XCUIApplication) {
visitMainScreen(app: app)
guard getCurrentCount(app: app) != 0 else { return }
let bottomToolbar = app.toolbars.elementBoundByIndex(0)
let resetButton = bottomToolbar.buttons.elementBoundByIndex(0)
resetButton.tap()
let resetAlert = app.alerts["Count It"]
let okayButton = resetAlert.buttons["Ok"]
okayButton.tap()
}
/**
Resets the multiplier to steps of 1, in case it wasn't there yet.
- parameter app: current app
*/
func resetMultiplier(app app: XCUIApplication) {
visitSettingsScreen(app: app)
guard !app.staticTexts["Increment by 1"].exists else {
visitMainScreen(app: app)
return
}
while !app.staticTexts["Increment by 1"].exists {
app.tables.buttons["Decrement"].tap()
}
visitMainScreen(app: app)
}
/**
Retrieves the current clicker count.
- parameter app: current app
- returns: Casted Int of current count
*/
private func getCurrentCount(app app: XCUIApplication) -> Int {
return Int(app.staticTexts["currentCount"].label)!
}
}
| 26.293233 | 90 | 0.674864 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.