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
4bb012d444422e222bb4574fe6a925031d9495bc
299
// // EntityOperationsService.swift // Patter // // Created by Maksim Ivanov on 14/06/2019. // Copyright © 2019 Maksim Ivanov. All rights reserved. // import Foundation protocol EnitiyOperationsService: class { func createPatterWithName(_ name: String) func deletePatter(id: String) }
19.933333
56
0.729097
8f625d15bfd74690c3d6409667c7ac71bdef5ea5
1,918
/*: ## Exercise - Use Playgrounds The code below prints a few short statements about what you have learned in this lesson. Open the console area and view the code's output. */ print("I have learned the following:") print("What features make Swift a modern and safe language") print("How to use the Swift REPL in Terminal") print("How to use playgrounds to make writing Swift fun and simple") /*: Now print your own phrases to the console. Pick one of your favorite songs. Use your knowledge of the `print` function to display the song title and artist. */ print("Rolling in the Deep, by Adele") /*: Use multiple `print` functions to write out some of the lyrics to the song. */ print("There's a fire starting in my heart") print("Reaching a fever pitch and it's bringing me out the dark") print("Finally I can see you crystal clear") /*: _Copyright © 2018 Apple 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._ */
58.121212
463
0.77268
5096fc6c49631e2cad28b6c2a10c038f694b6d8e
8,770
// // Date+Extension.swift // MemoryChain // // Created by Marc Zhao on 2018/8/6. // Copyright © 2018年 Memory Chain technology(China) co,LTD. All rights reserved. // import Foundation //MARK: - method public extension Date { func next() ->Date? { let calendar = Calendar.current let daysComponents = calendar.dateComponents([.month,.day], from: self) return calendar.nextDate(after: Date(), matching: daysComponents, matchingPolicy: .nextTime) } func at(_ hours:Int,minutes:Int = 0) ->Date { return Calendar.current.date(bySettingHour: hours, minute: minutes, second: 0, of: self)! } static func data_form(string:String?) ->Date? { return self.data_form(string: string, formatter: "yyyy-MM-dd HH:mm:ss") } static func data_form(string:String?, formatter:String?)->Date? { let dateFormatter = DateFormatter() dateFormatter.locale = Locale.current dateFormatter.timeZone = TimeZone.current if let date_formatter = formatter { dateFormatter.dateFormat = date_formatter if let time_string = string { let date = dateFormatter.date(from: time_string) return date } } return nil } func string_from(formatter:String?) -> String { if formatter != nil { let dateFormatter = DateFormatter() dateFormatter.locale = Locale.current dateFormatter.timeZone = TimeZone.current dateFormatter.dateFormat = formatter let date_String = dateFormatter.string(from: self) return date_String } return "" } // 获得当天星期几 func getDayAndWeek() ->String { var date = "" let weekDay = self.getAbbreviationWeekDay(weekDay: self.weekDay()) date = String(self.day()) + weekDay return date } func getAbbreviationWeekDay(weekDay: Int) -> String { switch weekDay { case 1: return "Mon" case 2: return "Tue" case 3: return "Wed" case 4: return "Thu" case 5: return "Fri" case 6: return "Sat" case 7: return "Sun" default: return "" } } func getAbbreviationMonth(unixDate: Int64) ->String { if unixDate == 0 { return "Jan" } let date = Date(timeIntervalSince1970: TimeInterval(unixDate)) let formatter = DateFormatter() formatter.dateFormat = "MM" let month = Int(formatter.string(from: date)) switch month { case 1: return "Jan" case 2: return "Feb" case 3: return "Mar" case 4: return "Apr" case 5: return "May" case 6: return "Jun" case 7: return "Jul" case 8: return "Aug" case 9: return "Sep" case 10: return "Oct" case 11: return "Nov" case 12: return "Dec" default: return "Jan" } } } //MARK: - method for date public extension NSDate { class func date_form(string:String?) ->NSDate? { return self.date_from(string: string, formatter: "yyyy-MM-DD HH:mm:ss") } class func date_from(string: String?, formatter: String?) -> NSDate? { let dateFormatter = DateFormatter() dateFormatter.locale = Locale.current dateFormatter.timeZone = TimeZone.current if let da_formatter = formatter { dateFormatter.dateFormat = da_formatter if let time_str = string { let date = dateFormatter.date(from: time_str) return date as NSDate? } } return nil } } extension Date { /// 年 func year() ->Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day], from: self) return com.year! } /// 月 func month() ->Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day], from: self) return com.month! } /// 日 func day() ->Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day], from: self) return com.day! } /// 星期几 func weekDay()->Int{ let interval = Int(self.timeIntervalSince1970) let days = Int(interval/86400) // 24*60*60 let weekday = ((days + 4)%7+7)%7 return weekday == 0 ? 7 : weekday } /// 当月天数 func countOfDaysInMonth() ->Int { let calendar = Calendar(identifier:Calendar.Identifier.gregorian) let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: self) return (range?.length)! } /// 当月第一天是星期几 func firstWeekDay() ->Int { //1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat. let calendar = Calendar(identifier:Calendar.Identifier.gregorian) let firstWeekDay = (calendar as NSCalendar?)?.ordinality(of: NSCalendar.Unit.weekday, in: NSCalendar.Unit.weekOfMonth, for: self) return firstWeekDay! - 1 } /// 是否是今天 func isToday()->Bool { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day], from: self) let comNow = calendar.dateComponents([.year,.month,.day], from: Date()) return com.year == comNow.year && com.month == comNow.month && com.day == comNow.day } /// 是否是这个月 func isThisMonth()->Bool { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day], from: self) let comNow = calendar.dateComponents([.year,.month,.day], from: Date()) return com.year == comNow.year && com.month == comNow.month } /// 获取当前 秒级 时间戳 - var timeStamp : Int64 { let timeInterval: TimeInterval = self.timeIntervalSince1970 let timeStamp = Int64(timeInterval) return timeStamp } /// 获取当前 毫秒级 时间戳 - 13位 var milliStamp : String { let timeInterval: TimeInterval = self.timeIntervalSince1970 let millisecond = CLongLong(round(timeInterval*1000)) return "\(millisecond)" } /// 转日记时间格式 var noteDate: String { let date = Date() let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy年MM月dd日 HH:mm" return dateFormat.string(from: date) } func noteDate(unixTime: Int64) -> String { let date = Date.init(timeIntervalSince1970: TimeInterval(unixTime)) let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy年MM月dd日 HH:mm" return dateFormat.string(from: date) } func getNoteDate(unixTime: Int64) -> String { let date = Date.init(timeIntervalSince1970: TimeInterval(unixTime)) let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy/MM/dd" return dateFormat.string(from: date) } } public enum DateConstants: String { case locationBr = "pt_BR" case dateTimeBr = "dd/MM/yyyy HH:mm:ss" case dateTimeBrHyphen = "dd-MM-yyyy HH:mm:ss" case dateBr = "dd/MM/yyyy" case dateBrHyphen = "dd-MM-yyyy" case dateYMD = "yyyy-MM-dd" case dateYMDHMS = "yyyy-MM-dd HH:mm:ss" } public extension Date { static func constants(_ constants: DateConstants) -> String { return constants.rawValue } static func getTime(timeStamp: String, format: DateConstants) -> String { let interval: TimeInterval = TimeInterval(timeStamp)! let date = Date(timeIntervalSince1970: interval) let formatter = DateFormatter() formatter.locale = Locale(identifier: Date.constants(.locationBr)) formatter.dateFormat = format.rawValue return formatter.string(from: date) } func toString(withFormat format: DateConstants) -> String { let formatter = DateFormatter() formatter.locale = Locale(identifier: Date.constants(.locationBr)) formatter.dateFormat = format.rawValue return formatter.string(from: self) } static func getTimeInterval(formatTime: String) -> TimeInterval { // 00:00.89 -> 多少秒 let minAndSec = formatTime .components(separatedBy: ":") if minAndSec.count == 2 { // 分钟 let min = TimeInterval(minAndSec[0])! // 秒数 let sec = TimeInterval(minAndSec[1])! return min * 60 + sec } return 0 } }
31.321429
137
0.58358
87138110ad21c51f5d574b68bb7bacd03894574b
26,441
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 extension ExpressionConvertible { static func operate(prefix: String, operand: ExpressionConvertible) -> Expression { return Expression(withRaw: "(\(prefix)\(operand.asExpression().description))") } static func operate(title: String, infix: String?, operands: [ExpressionConvertible]) -> Expression { return Expression(withRaw: "\(title)(\(infix != nil ? infix!+" " : "")\(operands.joined()))") } static func operate(operand: ExpressionConvertible, postfix: String) -> Expression { return Expression(withRaw: "(\(operand.asExpression().description) \(postfix))") } static func operate(left: ExpressionConvertible, `operator`: String, right: ExpressionConvertible) -> Expression { let leftDescription = left.asExpression().description let rightDescription = right.asExpression().description return Expression(withRaw: "(\(leftDescription) \(`operator`) \(rightDescription))") } static func operate(one: ExpressionConvertible, operator1: String, two: ExpressionConvertible, operator2: String, three: ExpressionConvertible) -> Expression { let oneDescription = one.asExpression().description let twoDescription = two.asExpression().description let threeDescription = three.asExpression().description let raws = [oneDescription, operator1, twoDescription, operator2, threeDescription] return Expression(withRaw: "(\(raws.joined(separateBy: " ")))") } } public protocol ExpressionCanBeOperated: ExpressionConvertible { static func || <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func && <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func * <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func / <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func % <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func + <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func - <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func << <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func >> <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func & <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func | <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func < <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func <= <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func > <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func >= <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func == <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression static func != <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression } extension ExpressionCanBeOperated { public static func || <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return Expression.operate(left: left, operator: "OR", right: right) } public static func && <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "AND", right: right) } public static func * <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "*", right: right) } public static func / <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "/", right: right) } public static func % <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "%", right: right) } public static func + <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "+", right: right) } public static func - <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "-", right: right) } public static func << <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "<<", right: right) } public static func >> <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: ">>", right: right) } public static func & <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "&", right: right) } public static func | <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "|", right: right) } public static func < <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "<", right: right) } public static func <= <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "<=", right: right) } public static func > <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: ">", right: right) } public static func >= <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: ">=", right: right) } public static func == <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "=", right: right) } public static func != <ExpressionOperableType: ExpressionOperable>( left: Self, right: ExpressionOperableType) -> Expression { return operate(left: left, operator: "!=", right: right) } } public protocol ExpressionOperable: ExpressionCanBeOperated { //Unary prefix static func ! (operand: Self) -> Expression prefix static func + (operand: Self) -> Expression prefix static func - (operand: Self) -> Expression prefix static func ~ (operand: Self) -> Expression //Binary static func || <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func && <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func * <ExpressionConvertibleType: ExpressionConvertible> (left: Self, right: ExpressionConvertibleType) -> Expression static func / <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func % <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func + <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func - <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func << <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func >> <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func & <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func | <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func < <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func <= <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func > <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func >= <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func == <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression static func != <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression func concat(_ operand: ExpressionConvertible) -> Expression func substr(start: ExpressionConvertible, length: ExpressionConvertible) -> Expression func like(_ operand: ExpressionConvertible) -> Expression func glob(_ operand: ExpressionConvertible) -> Expression func match(_ operand: ExpressionConvertible) -> Expression func regexp(_ operand: ExpressionConvertible) -> Expression func notLike(_ operand: ExpressionConvertible) -> Expression func notGlob(_ operand: ExpressionConvertible) -> Expression func notMatch(_ operand: ExpressionConvertible) -> Expression func notRegexp(_ operand: ExpressionConvertible) -> Expression func like(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func glob(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func match(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func regexp(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func notLike(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func notGlob(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func notMatch(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func notRegexp(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression func isNull() -> Expression func isNotNull() -> Expression func `is`(_ operand: ExpressionConvertible) -> Expression func isNot(_ operand: ExpressionConvertible) -> Expression func between(_ begin: ExpressionConvertible, _ end: ExpressionConvertible) -> Expression func notBetween(_ begin: ExpressionConvertible, _ end: ExpressionConvertible) -> Expression func `in`(_ statementSelect: StatementSelect) -> Expression func notIn(_ statementSelect: StatementSelect) -> Expression func `in`(_ expressionConvertibleList: ExpressionConvertible...) -> Expression func notIn(_ expressionConvertibleList: ExpressionConvertible...) -> Expression func `in`(_ expressionConvertibleList: [ExpressionConvertible]) -> Expression func notIn(_ expressionConvertibleList: [ExpressionConvertible]) -> Expression //aggregate functions func avg(isDistinct: Bool) -> Expression func count(isDistinct: Bool) -> Expression func groupConcat(isDistinct: Bool) -> Expression func groupConcat(isDistinct: Bool, separateBy seperator: String) -> Expression func max(isDistinct: Bool) -> Expression func min(isDistinct: Bool) -> Expression func sum(isDistinct: Bool) -> Expression func total(isDistinct: Bool) -> Expression //core functions func abs(isDistinct: Bool) -> Expression func hex(isDistinct: Bool) -> Expression func length(isDistinct: Bool) -> Expression func lower(isDistinct: Bool) -> Expression func upper(isDistinct: Bool) -> Expression func round(isDistinct: Bool) -> Expression //FTS3 func matchinfo() -> Expression func offsets() -> Expression func snippet() -> Expression } extension ExpressionOperable { //Unary public prefix static func ! (operand: Self) -> Expression { return operate(prefix: "NOT ", operand: operand) } public prefix static func + (operand: Self) -> Expression { return operate(prefix: "", operand: operand) } public prefix static func - (operand: Self) -> Expression { return operate(prefix: "-", operand: operand) } public prefix static func ~ (operand: Self) -> Expression { return operate(prefix: "~", operand: operand) } //Binary public static func || <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "OR", right: right) } public static func && <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "AND", right: right) } public static func * <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "*", right: right) } public static func / <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "/", right: right) } public static func % <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "%", right: right) } public static func + <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "+", right: right) } public static func - <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "-", right: right) } public static func << <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "<<", right: right) } public static func >> <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: ">>", right: right) } public static func & <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "&", right: right) } public static func | <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "|", right: right) } public static func < <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "<", right: right) } public static func <= <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "<=", right: right) } public static func > <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: ">", right: right) } public static func >= <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: ">=", right: right) } public static func == <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "=", right: right) } public static func != <ExpressionConvertibleType: ExpressionConvertible>( left: Self, right: ExpressionConvertibleType) -> Expression { return operate(left: left, operator: "!=", right: right) } public func concat(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "||", right: operand) } public func substr(start: ExpressionConvertible, length: ExpressionConvertible) -> Expression { let description = asExpression().description let startDescription = start.asExpression().description let lengthDescription = length.asExpression().description return Expression(withRaw: "SUBSTR(\(description), \(startDescription), \(lengthDescription))") } public func like(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "LIKE", right: operand) } public func glob(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "GLOB", right: operand) } public func match(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "MATCH", right: operand) } public func regexp(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "REGEXP", right: operand) } public func notLike(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "NOT LIKE", right: operand) } public func notGlob(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "NOT GLOB", right: operand) } public func notMatch(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "NOT MATCH", right: operand) } public func notRegexp(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "NOT REGEXP", right: operand) } public func like(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "LIKE", two: operand, operator2: "ESCAPE", three: escape) } public func glob(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "GLOB", two: operand, operator2: "ESCAPE", three: escape) } public func match(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "MATCH", two: operand, operator2: "ESCAPE", three: escape) } public func regexp(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "REGEXP", two: operand, operator2: "ESCAPE", three: escape) } public func notLike(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "NOT LIKE", two: operand, operator2: "ESCAPE", three: escape) } public func notGlob(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "NOT GLOB", two: operand, operator2: "ESCAPE", three: escape) } public func notMatch(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "NOT MATCH", two: operand, operator2: "ESCAPE", three: escape) } public func notRegexp(_ operand: ExpressionConvertible, escape: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "NOT REGEXP", two: operand, operator2: "ESCAPE", three: escape) } public func isNull() -> Expression { return Self.operate(operand: self, postfix: "ISNULL") } public func isNotNull() -> Expression { return Self.operate(operand: self, postfix: "NOTNULL") } public func `is`(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "IS", right: operand) } public func isNot(_ operand: ExpressionConvertible) -> Expression { return Self.operate(left: self, operator: "IS NOT", right: operand) } public func between(_ begin: ExpressionConvertible, _ end: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "BETWEEN", two: begin, operator2: "AND", three: end) } public func notBetween(_ begin: ExpressionConvertible, _ end: ExpressionConvertible) -> Expression { return Self.operate(one: self, operator1: "NOT BETWEEN", two: begin, operator2: "AND", three: end) } public func `in`(_ statementSelect: StatementSelect) -> Expression { return Self.operate(prefix: "IN ", operand: statementSelect) } public func notIn(_ statementSelect: StatementSelect) -> Expression { return Self.operate(prefix: "NOT IN ", operand: statementSelect) } public func `in`(_ expressionConvertibleList: ExpressionConvertible...) -> Expression { return self.`in`(expressionConvertibleList) } public func notIn(_ expressionConvertibleList: ExpressionConvertible...) -> Expression { return self.notIn(expressionConvertibleList) } public func `in`(_ expressionConvertibleList: [ExpressionConvertible]) -> Expression { return Self.operate(operand: self, postfix: "IN(\(expressionConvertibleList.joined()))") } public func notIn(_ expressionConvertibleList: [ExpressionConvertible]) -> Expression { return Self.operate(operand: self, postfix: "NOT IN(\(expressionConvertibleList.joined()))") } //aggregate functions public func avg(isDistinct: Bool = false) -> Expression { return Expression.function(named: "AVG", self, isDistinct: isDistinct) } public func count(isDistinct: Bool = false) -> Expression { return Expression.function(named: "COUNT", self, isDistinct: isDistinct) } public func groupConcat(isDistinct: Bool = false) -> Expression { return Expression.function(named: "GROUP_CONCAT", self, isDistinct: isDistinct) } public func groupConcat(isDistinct: Bool = false, separateBy seperator: String) -> Expression { return Expression.function(named: "GROUP_CONCAT", self, seperator, isDistinct: isDistinct) } public func max(isDistinct: Bool = false) -> Expression { return Expression.function(named: "MAX", self, isDistinct: isDistinct) } public func min(isDistinct: Bool = false) -> Expression { return Expression.function(named: "MIN", self, isDistinct: isDistinct) } public func sum(isDistinct: Bool = false) -> Expression { return Expression.function(named: "SUM", self, isDistinct: isDistinct) } public func total(isDistinct: Bool = false) -> Expression { return Expression.function(named: "TOTAL", self, isDistinct: isDistinct) } //core functions public func abs(isDistinct: Bool = false) -> Expression { return Expression.function(named: "ABS", self, isDistinct: isDistinct) } public func hex(isDistinct: Bool = false) -> Expression { return Expression.function(named: "HEX", self, isDistinct: isDistinct) } public func length(isDistinct: Bool = false) -> Expression { return Expression.function(named: "LENGTH", self, isDistinct: isDistinct) } public func lower(isDistinct: Bool = false) -> Expression { return Expression.function(named: "LOWER", self, isDistinct: isDistinct) } public func upper(isDistinct: Bool = false) -> Expression { return Expression.function(named: "UPPER", self, isDistinct: isDistinct) } public func round(isDistinct: Bool = false) -> Expression { return Expression.function(named: "ROUND", self, isDistinct: isDistinct) } //FTS3 public func matchinfo() -> Expression { return Expression.function(named: "MATCHINFO", self) } public func offsets() -> Expression { return Expression.function(named: "OFFSETS", self) } public func snippet() -> Expression { return Expression.function(named: "SNIPPET", self) } }
46.144852
113
0.698234
dd5272211be33ad6eb37754703c85a59c250a9e1
1,378
// // Created by Alex Jackson on 2018-12-23. // import Foundation /// A `String` wrapper that implements case insensitive comparison, sorting and hashing methods. public struct CaseInsensitiveString: CustomStringConvertible { // MARK: - Public Properties public var description: String { return _string } // MARK: - Private Properties private let _string: String // MARK: - Initializers public init(_ string: String) { self._string = string } } // MARK: - String Literal Conformance extension CaseInsensitiveString: ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value) } } // MARK: - Equatable Conformance extension CaseInsensitiveString: Equatable { public static func == (lhs: CaseInsensitiveString, rhs: CaseInsensitiveString) -> Bool { return lhs._string.lowercased() == rhs._string.lowercased() } } // MARK: - Hashable Conformance extension CaseInsensitiveString: Hashable { public func hash(into hasher: inout Hasher) { _string.lowercased().hash(into: &hasher) } } // MARK: - Comparable Conformance extension CaseInsensitiveString: Comparable { public static func < (lhs: CaseInsensitiveString, rhs: CaseInsensitiveString) -> Bool { return lhs._string.lowercased() < rhs._string.lowercased() } }
23.355932
96
0.698839
dbe258ee824b8eedb79c4fa1343b341804eae1a8
4,999
// // ALKFriendDocumentCell.swift // ApplozicSwift // // Created by sunil on 05/03/19. // import Applozic import Foundation import Kingfisher import UIKit class ALKFriendDocumentCell: ALKDocumentCell { struct Padding { struct NameLabel { static let top: CGFloat = 6 static let leading: CGFloat = 57 static let height: CGFloat = 16 static let trailing: CGFloat = 56 } struct AvatarImageView { static let top: CGFloat = 18 static let leading: CGFloat = 9 static let height: CGFloat = 37 } struct TimeLabel { static let left: CGFloat = 2 static let bottom: CGFloat = 2 } struct BubbleView { static let top: CGFloat = 1 static let leading: CGFloat = 5 static let bottom: CGFloat = 8 static let trailing: CGFloat = 48 } } private var avatarImageView: UIImageView = { let imv = UIImageView() imv.contentMode = .scaleAspectFill imv.clipsToBounds = true let layer = imv.layer layer.cornerRadius = 18.5 layer.backgroundColor = UIColor.lightGray.cgColor layer.masksToBounds = true imv.isUserInteractionEnabled = true return imv }() private var nameLabel: UILabel = { let label = UILabel() label.numberOfLines = 1 label.font = UIFont.boldSystemFont(ofSize: 12) label.textColor = UIColor.lightGray return label }() override func setupViews() { super.setupViews() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(avatarTappedAction)) avatarImageView.addGestureRecognizer(tapGesture) contentView.addViewsForAutolayout(views: [avatarImageView, nameLabel, timeLabel]) nameLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: Padding.NameLabel.top).isActive = true nameLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Padding.NameLabel.leading).isActive = true nameLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Padding.NameLabel.trailing).isActive = true nameLabel.heightAnchor.constraint(equalToConstant: Padding.NameLabel.height).isActive = true avatarImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: Padding.AvatarImageView.top).isActive = true avatarImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: Padding.AvatarImageView.leading).isActive = true avatarImageView.heightAnchor.constraint(equalToConstant: Padding.AvatarImageView.height).isActive = true avatarImageView.widthAnchor.constraint(equalTo: avatarImageView.heightAnchor).isActive = true timeLabel.leftAnchor.constraint(equalTo: bubbleView.rightAnchor, constant: Padding.TimeLabel.left).isActive = true timeLabel.bottomAnchor.constraint(equalTo: bubbleView.bottomAnchor, constant: -Padding.TimeLabel.bottom).isActive = true bubbleView.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: Padding.BubbleView.top).isActive = true bubbleView.leadingAnchor.constraint(equalTo: avatarImageView.trailingAnchor, constant: Padding.BubbleView.leading).isActive = true bubbleView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -Padding.BubbleView.trailing).isActive = true bubbleView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -Padding.BubbleView.bottom).isActive = true } override func update(viewModel: ALKMessageViewModel) { super.update(viewModel: viewModel) let placeHolder = UIImage(named: "placeholder", in: Bundle.applozic, compatibleWith: nil) if let url = viewModel.avatarURL { let resource = ImageResource(downloadURL: url, cacheKey: url.absoluteString) avatarImageView.kf.setImage(with: resource, placeholder: placeHolder) } else { avatarImageView.image = placeHolder } nameLabel.text = viewModel.displayName } override func setupStyle() { super.setupStyle() timeLabel.setStyle(ALKMessageStyle.time) nameLabel.setStyle(ALKMessageStyle.displayName) bubbleView.backgroundColor = ALKMessageStyle.receivedBubble.color } override class func rowHeigh(viewModel _: ALKMessageViewModel, width _: CGFloat) -> CGFloat { let minimumHeight: CGFloat = 60 // 55 is avatar image... + padding let messageHeight: CGFloat = heightPadding() return max(messageHeight, minimumHeight) } class func heightPadding() -> CGFloat { return commonHeightPadding() + Padding.NameLabel.height + Padding.NameLabel.top + Padding.BubbleView.bottom + Padding.BubbleView.top } @objc private func avatarTappedAction() { avatarTapped?() } }
40.314516
143
0.694739
693c6164746c90494faa03a0cac1175b34fc0387
2,299
// // AppDelegate.swift // NetworkTest // // Created by Hellen Soloviy on 11/16/18. // Copyright © 2018 Hellen Soloviy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // print("----------- SERVER -----------") // print("----------- CLIENT -----------") 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 invalidate graphics rendering callbacks. 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 active 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:. } }
45.98
285
0.726838
224a180fb61ccb358ba656313f2bcbcb1ba34903
945
// // DeclineButton.swift // Intercom App // // Created by Sergey Osipyan on 4/12/19. // Copyright © 2019 Lambda School. All rights reserved. // import UIKit let kDeclineButtonBackgroundColor = UIColor(displayP3Red: 178/255, green: 178/255, blue: 178/255, alpha: 1) let kDeclineButtonTintColor = UIColor.white let kDeclineButtonCornerRadius: CGFloat = 6.0 class DeclineButton: UIButton { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.configureUI() } private func configureUI() { //self.backgroundColor = kDeclineButtonBackgroundColor self.layer.cornerRadius = kDeclineButtonCornerRadius self.tintColor = UIColor.red self.setTitleColor(.red, for: .normal) self.layer.borderWidth = 1 self.layer.borderColor = UIColor.red.cgColor self.titleLabel?.font = UIFont(name: "AppleSDGothicNeo-Regular", size: 14) } }
28.636364
107
0.687831
013aedd0352459558f24e059048c8b7863a6232b
885
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit import XCTest class BrownianNoiseTests: XCTestCase { func testDefault() { let engine = AudioEngine() let brown = BrownianNoise() engine.output = brown brown.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testAmplitude() { let engine = AudioEngine() let brown = BrownianNoise() brown.amplitude = 0.5 engine.output = brown brown.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testGeneric() { testMD5(generatorNodeRandomizedTest(factory: { BrownianNoise() })) } }
26.818182
100
0.630508
462e2256de941c7dbd699e0978f1806cc4535105
8,223
// // RGBToneCurveFilter.swift // // Copyright © 2018 sunlubo. All rights reserved. // import Foundation import CoreImage // https://github.com/YuAo/Vivid/blob/master/Sources/YUCIRGBToneCurve.m // https://github.com/BradLarson/GPUImage/blob/master/framework/Source/GPUImageToneCurveFilter.m public final class RGBToneCurveFilter: CIFilter { static let kernel = CIKernel(filename: "RGBToneCurve") static let defaultControlPoints = [CIVector(x: 0.0, y: 0.0), CIVector(x: 0.5, y: 0.5), CIVector(x: 1.0, y: 1.0)] @objc public var inputImage: CIImage? @objc public var inputRedControlPoints: [CIVector] = RGBToneCurveFilter.defaultControlPoints @objc public var inputGreenControlPoints: [CIVector] = RGBToneCurveFilter.defaultControlPoints @objc public var inputBlueControlPoints: [CIVector] = RGBToneCurveFilter.defaultControlPoints @objc public var inputRGBCompositeControlPoints: [CIVector] = RGBToneCurveFilter.defaultControlPoints @objc public var inputIntensity: Float = 1.0 var redCurve = [CGFloat]() var greenCurve = [CGFloat]() var blueCurve = [CGFloat]() var rgbCompositeCurve = [CGFloat]() public override func setDefaults() { inputRedControlPoints = RGBToneCurveFilter.defaultControlPoints inputGreenControlPoints = RGBToneCurveFilter.defaultControlPoints inputBlueControlPoints = RGBToneCurveFilter.defaultControlPoints inputRGBCompositeControlPoints = RGBToneCurveFilter.defaultControlPoints inputIntensity = 1.0 } public override var outputImage: CIImage! { guard let inputImage = inputImage else { return nil } let toneCurveTexture = getToneCurveTexture() let arguments = [inputImage, toneCurveTexture, inputIntensity] as [Any] return RGBToneCurveFilter.kernel.apply(extent: inputImage.extent, roiCallback: { index, rect in return index == 0 ? rect : toneCurveTexture.extent }, arguments: arguments) } func getToneCurveTexture() -> CIImage { redCurve = getPreparedSplineCurve(points: inputRedControlPoints) greenCurve = getPreparedSplineCurve(points: inputGreenControlPoints) blueCurve = getPreparedSplineCurve(points: inputBlueControlPoints) rgbCompositeCurve = getPreparedSplineCurve(points: inputRGBCompositeControlPoints) let bitmap = UnsafeMutablePointer<UInt8>.allocate(capacity: 4 * 256) bitmap.initialize(to: 0) // BGRA for upload to texture for i in 0..<256 { let b = UInt8(min(max(CGFloat(i) + blueCurve[i], 0), 255)) let g = UInt8(min(max(CGFloat(i) + greenCurve[i], 0), 255)) let r = UInt8(min(max(CGFloat(i) + redCurve[i], 0), 255)) bitmap[i * 4 + 0] = UInt8(min(max(CGFloat(b) + rgbCompositeCurve[Int(b)], 0), 255)) bitmap[i * 4 + 1] = UInt8(min(max(CGFloat(g) + rgbCompositeCurve[Int(g)], 0), 255)) bitmap[i * 4 + 2] = UInt8(min(max(CGFloat(r) + rgbCompositeCurve[Int(r)], 0), 255)) bitmap[i * 4 + 3] = 255 } let bitmapData = Data(bytesNoCopy: bitmap, count: 4 * 256, deallocator: .custom({ ptr, _ in ptr.deallocate() })) return CIImage(bitmapData: bitmapData, bytesPerRow: 256 * 4, size: CGSize(width: 256, height: 1), format: .BGRA8, colorSpace: nil) } func getPreparedSplineCurve(points: [CIVector]) -> [CGFloat] { assert(points.count > 0) let convertedPoints = points .sorted { $0.x < $1.x } // Sort the array. .map({ CIVector(x: $0.x * 255, y: $0.y * 255) }) // Convert from (0, 1) to (0, 255). var splinePoints = splineCurve(points: convertedPoints) // If we have a first point like (0.3, 0) we'll be missing some points at the beginning that should be 0. if splinePoints.first!.x > 0 { var i = splinePoints.first!.x while i >= 0 { splinePoints.insert(CIVector(x: i, y: 0), at: 0) i -= 1 } } // Insert points similarly at the end, if necessary. if splinePoints.last!.x < 255 { var i = splinePoints.last!.x + 1 while i <= 255 { splinePoints.append(CIVector(x: i, y: 255)) i += 1 } } // Prepare the spline points. var preparedSplinePoints = [CGFloat]() for i in 0..<splinePoints.count { let newPoint = splinePoints[i] let oriPoint = CIVector(x: newPoint.x, y: newPoint.x) var distance = sqrt(pow(oriPoint.x - newPoint.x, 2.0) + pow(oriPoint.y - newPoint.y, 2.0)) if oriPoint.y > newPoint.y { distance = -distance } preparedSplinePoints.append(distance) } return preparedSplinePoints } func splineCurve(points: [CIVector]) -> [CIVector] { let sd = secondDerivative(points: points) let n = sd.count assert(n > 0) var output = [CIVector]() for i in 0..<(n - 1) { let cur = points[i] let next = points[i + 1] var x = Int(cur.x) while x < Int(next.x) { let t = (CGFloat(x) - cur.x) / (next.x - cur.x) let a = 1 - t let b = t let h = next.x - cur.x var y = a * cur.y + b * next.y + (h * h / 6) * ((a * a * a - a) * CGFloat(sd[i]) + (b * b * b - b) * CGFloat(sd[i + 1])) if y > 255 { y = 255 } else if y < 0 { y = 0 } output.append(CIVector(x: CGFloat(x), y: y)) x += 1 } } // The above always misses the last point because the last point is the last next, so we approach but don't equal it. output.append(points.last!) return output } func secondDerivative(points: [CIVector]) -> [Double] { let n = points.count assert(n > 1) var matrix = Array<Array<Double>>(repeating: Array<Double>(repeating: 0, count: 3), count: n) // n x 3 var result = Array<Double>(repeating: 0, count: n) // n matrix[0][1] = 1 // What about matrix[0][0] and matrix[0][2]? Assuming 0 for now (Brad L.) matrix[0][0] = 0 matrix[0][2] = 0 for i in 1..<(n - 1) { let p1 = points[i - 1] let p2 = points[i] let p3 = points[i + 1] matrix[i][0] = Double((p2.x - p1.x) / 6) matrix[i][1] = Double((p3.x - p1.x) / 3) matrix[i][2] = Double((p3.x - p2.x) / 6) result[i] = Double((p3.y - p2.y) / (p3.x - p2.x) - (p2.y - p1.y) / (p2.x - p1.x)) } // What about result[0] and result[n-1]? Assuming 0 for now (Brad L.) result[0] = 0 result[n - 1] = 0 matrix[n - 1][1] = 1 // What about matrix[n-1][0] and matrix[n-1][2]? For now, assuming they are 0 (Brad L.) matrix[n - 1][0] = 0 matrix[n - 1][2] = 0 // solving pass1 (up->down) for i in 1..<n { let k = matrix[i][0] / matrix[i - 1][1] matrix[i][1] -= k * matrix[i - 1][2] matrix[i][0] = 0 result[i] -= k * result[i - 1] } // solving pass2 (down->up) for i in (0...(n - 2)).reversed() { let k = matrix[i][2] / matrix[i + 1][1] matrix[i][1] -= k * matrix[i + 1][0] matrix[i][2] = 0 result[i] -= k * result[i + 1] } var output = [Double]() for i in 0..<n { output.append(result[i] / matrix[i][1]) } return output } }
40.308824
136
0.526329
ef03944014e939ed6b0399c675a50a7ac49336ea
2,527
import XCTest class SynchronizableTests: XCTestCase { var obj: KeychainSwift! override func setUp() { super.setUp() obj = KeychainSwift() obj.clear() obj.lastQueryParameters = nil obj.synchronizable = false } // MARK: - addSynchronizableIfRequired func testAddSynchronizableGroup_addItemsFalse() { let items: [String: NSObject] = [ "one": "two" ] obj.synchronizable = true let result = obj.addSynchronizableIfRequired(items, addingItems: false) XCTAssertEqual(2, result.count) XCTAssertEqual("two", result["one"]) XCTAssertEqual(kSecAttrSynchronizableAny, result["sync"]) } func testAddSynchronizableGroup_addItemsTrue() { let items: [String: NSObject] = [ "one": "two" ] obj.synchronizable = true let result = obj.addSynchronizableIfRequired(items, addingItems: true) XCTAssertEqual(2, result.count) XCTAssertEqual("two", result["one"]) XCTAssertEqual(true, result["sync"]) } func testAddSynchronizableGroup_nil() { let items: [String: NSObject] = [ "one": "two" ] let result = obj.addSynchronizableIfRequired(items, addingItems: false) XCTAssertEqual(1, result.count) XCTAssertEqual("two", result["one"]) } // MARK: - Set func testSet() { obj.synchronizable = true obj.set("hello :)", forKey: "key 1") XCTAssertEqual(true, obj.lastQueryParameters?["sync"]) } func testSet_doNotSetSynchronizable() { obj.set("hello :)", forKey: "key 1") XCTAssertNil(obj.lastQueryParameters?["sync"]) } // MARK: - Get func testGet() { obj.synchronizable = true _ = obj.get("key 1") XCTAssertEqual(kSecAttrSynchronizableAny, obj.lastQueryParameters?["sync"]) } func testGet_doNotSetSynchronizable() { _ = obj.get("key 1") XCTAssertNil(obj.lastQueryParameters?["sync"]) } // MARK: - Delete func testDelete() { obj.synchronizable = true obj.delete("key 1") XCTAssertEqual(kSecAttrSynchronizableAny, obj.lastQueryParameters?["sync"]) } func testDelete_doNotSetSynchronizable() { obj.delete("key 1") XCTAssertNil(obj.lastQueryParameters?["sync"]) } // MARK: - Clear func testClear() { obj.synchronizable = true obj.clear() XCTAssertEqual(kSecAttrSynchronizableAny, obj.lastQueryParameters?["sync"]) } func testClear_doNotSetSynchronizable() { obj.clear() XCTAssertNil(obj.lastQueryParameters?["sync"]) } }
23.616822
79
0.655718
4b326053028d1056d12b5f31063a42ec37100b3c
836
// // This file is part of Gaikan // // Created by JC on 25/10/15. // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code // import Foundation /** Code for AssociationObject using Swift types From https://wezzard.com/2015/10/09/associated-object-and-swift-struct **/ internal final class AssociatedObject<T> : NSObject, NSCopying { typealias AssociatedType = T let value: AssociatedType required init(_ value: AssociatedType) { self.value = value } func copy(with zone: NSZone?) -> Any { return AssociatedObject(self.value) } } extension AssociatedObject where T:NSCopying { func copyWithZone(_ zone: NSZone?) -> AnyObject { return AssociatedObject(value.copy(with: zone) as! AssociatedType) } }
25.333333
74
0.698565
20f81b0b2fc720fd8415b07e480d67530566d27c
3,329
// // AuthorizeSettingVC.swift // NewSG // // Created by z on 2018/11/8. // Copyright © 2018年 simpleWQZ. All rights reserved. // import UIKit class AuthorizeSettingVC: UIViewController { @IBOutlet weak var popView: UIView! @IBOutlet weak var icon: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subTitleLabel: UILabel! var checkType: CheckType? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "权限设置" setupUI() } @IBAction func tapGesture(_ sender: UITapGestureRecognizer) { dismissAnimation() } func setupUI() { switch checkType { case .contact?: icon.image = UIImage(named:"bg") titleLabel.text = "通讯录权限" subTitleLabel.text = "您已禁止访问通讯录权限,请您同意打开通讯录权限,以方便添加好友" case .photo?: icon.image = UIImage(named:"bg") titleLabel.text = "相册权限" subTitleLabel.text = "打开相册权限才能选择美图哦, 快去打开. 请去-> [设置 - 隐私 - 相册/照片] 打开访问开关" case .location?: icon.image = UIImage(named:"bg") titleLabel.text = "定位权限" subTitleLabel.text = "打开定位权限才能查看发现周边朋友哦, 快去打开" case .video?: icon.image = UIImage(named:"bg") titleLabel.text = "相机权限" subTitleLabel.text = "打开相机权限才能扫描,拍照等操作哦" case .audio?: icon.image = UIImage(named:"bg") titleLabel.text = "麦克风权限" subTitleLabel.text = "打开麦克风权限才能录制视屏,发送语音等功能哦" default: break } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scaleAnimation(self.popView) } @IBAction func settingAction(_ sender: UIButton) { openSettingsURL() } @IBAction fileprivate func dismiss(_ sender: Any) { dismissAnimation() } fileprivate func dismissAnimation() { identityAnimation(self.popView) } } extension AuthorizeSettingVC { // MARK: - 延迟执行 fileprivate func dispatch_later(block: @escaping ()->()) { let t = DispatchTime.now() + 0.2 DispatchQueue.main.asyncAfter(deadline: t, execute: block) } func scaleAnimation( _ animateView: UIView) { animateView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.00000001) UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseIn, animations: { animateView.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) }) { (comp) in } // UIView.animate(withDuration: 0.5, animations: { // self.popView.alpha = 1 // }, completion: nil) } func identityAnimation( _ animateView: UIView) { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: .curveEaseOut, animations: { animateView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001) // animateView.transform = CGAffineTransform.identity }) { (comp) in self.dispatch_later { self.dismiss(animated: false, completion: nil) } } } }
29.201754
142
0.590568
2867fd5310ab9b6d2d2980404e2b505963bcc694
1,105
import Foundation import Moya import ReactiveSwift import ReactiveMoya class RMProvider { enum Failure: LocalizedError { case fetchFailure var localizedDescription: String { switch self { case .fetchFailure: return "Sorry, something really strange happened. 🤯" } } } static let shared = RMProvider() private lazy var rmService: MoyaProvider<RMService> = appEnvironment.resolve() private init () { } func fetchCharacters( page: Int, name: String, status: String, gender: String, species: String) -> SignalProducer<([Character], Int), Failure> { rmService.reactive.request(.characters( page: page, name: name, status: status, gender: gender, species: species)) .map(Response<Character>.self) .map { ($0.results, $0.info.pages) } .mapError { _ in return Failure.fetchFailure } } }
25.697674
82
0.534842
acfed4ac773b9b51136a8f0fc1aec9fbc458f3e0
1,321
// Copyright SIX DAY LLC. All rights reserved. import Foundation import TrustCore enum RefreshType { case balance case ethBalance } class WalletSession { let account: Wallet let balanceCoordinator: BalanceCoordinator let config: Config let chainState: ChainState var balance: Balance? { return balanceCoordinator.balance } var sessionID: String { return "\(account.address.description.lowercased())-\(config.chainID)" } var balanceViewModel: Subscribable<BalanceBaseViewModel> = Subscribable(nil) var nonceProvider: NonceProvider init( account: Wallet, config: Config, balanceCoordinator: BalanceCoordinator, nonceProvider: NonceProvider ) { self.account = account self.config = config self.chainState = ChainState(config: config) self.nonceProvider = nonceProvider self.balanceCoordinator = balanceCoordinator self.balanceCoordinator.delegate = self self.chainState.start() } func refresh() { balanceCoordinator.refresh() } func stop() { chainState.stop() } } extension WalletSession: BalanceCoordinatorDelegate { func didUpdate(viewModel: BalanceViewModel) { balanceViewModel.value = viewModel } }
23.589286
80
0.673732
90bdf8b089718800a9fd65263c030580f19c7258
5,900
/* SBMessageView.swift Copyright (c) 2014, Alice Atlas Copyright (c) 2010, Atsushi Jike All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import BLKGUI class SBMessageView: SBView { private lazy var textLabel: NSTextField = { let textLabel = NSTextField(frame: self.textLabelRect) textLabel.editable = false textLabel.bordered = false textLabel.drawsBackground = false textLabel.textColor = .whiteColor() textLabel.font = self.textFont textLabel.cell!.wraps = true textLabel.stringValue = "JavaScript" return textLabel }() private lazy var messageLabel: NSTextField = { let messageLabel = NSTextField(frame: self.messageLabelRect) messageLabel.autoresizingMask = [.ViewMinXMargin, .ViewMinYMargin] messageLabel.editable = false messageLabel.bordered = false messageLabel.drawsBackground = false messageLabel.textColor = .whiteColor() messageLabel.font = .boldSystemFontOfSize(16) messageLabel.alignment = .Center messageLabel.cell!.wraps = true return messageLabel }() private lazy var cancelButton: BLKGUI.Button = { let cancelButton = BLKGUI.Button(frame: self.cancelButtonRect) cancelButton.title = NSLocalizedString("Cancel", comment: "") cancelButton.target = self cancelButton.action = #selector(cancel) cancelButton.keyEquivalent = "\u{1B}" return cancelButton }() private lazy var doneButton: BLKGUI.Button = { let doneButton = BLKGUI.Button(frame: self.doneButtonRect) doneButton.title = NSLocalizedString("OK", comment: "") doneButton.target = self doneButton.action = #selector(done) doneButton.enabled = true doneButton.keyEquivalent = "\r" // busy if button is added into a view return doneButton }() var message: String { get { return messageLabel.stringValue } set(message) { messageLabel.stringValue = message } } var text: String { get { return textLabel.stringValue } set(text) { textLabel.stringValue = text let size = text.sizeWithAttributes([NSFontAttributeName: textFont]) textLabel.alignment = size.width > (textLabelRect.size.width - 20.0) ? .Left : .Center } } override var cancelSelector: Selector { didSet { if cancelSelector != nil { addSubview(cancelButton) } else if cancelButton.superview != nil { cancelButton.removeFromSuperview() } } } override var doneSelector: Selector { didSet { if doneSelector != nil { addSubview(doneButton) } else if doneButton.superview != nil { doneButton.removeFromSuperview() } } } init(frame: NSRect, text: String) { super.init(frame: frame) self.text = text addSubviews(textLabel, messageLabel) let viewsDictionary: [NSObject: AnyObject] = ["textLabel": textLabel, "messageLabel": messageLabel, "cancelButton": cancelButton, "doneButton": doneButton] autoresizingMask = [.ViewMinXMargin, .ViewMaxXMargin, .ViewMinYMargin, .ViewMaxYMargin] } required init(coder: NSCoder) { fatalError("NSCoding not supported") } // MARK: Rects let margin = NSMakePoint(36.0, 32.0) let labelWidth: CGFloat = 85.0 let buttonSize = NSMakeSize(105.0, 24.0) let buttonMargin: CGFloat = 15.0 let textFont = NSFont.systemFontOfSize(16) var messageLabelRect: NSRect { var r = NSZeroRect r.size.width = bounds.size.width - margin.x * 2 r.size.height = 36.0 r.origin.x = margin.x r.origin.y = bounds.size.height - r.size.height - margin.y return r } var textLabelRect: NSRect { var r = NSZeroRect r.size.width = bounds.size.width - margin.x * 2 r.size.height = bounds.size.height - margin.y * 2 r.origin.x = margin.x r.origin.y = messageLabelRect.origin.y - r.size.height return r } var doneButtonRect: NSRect { var r = NSZeroRect r.size = buttonSize r.origin.y = margin.y r.origin.x = cancelButtonRect.origin.x + r.size.width + buttonMargin return r } var cancelButtonRect: NSRect { var r = NSZeroRect r.size = buttonSize r.origin.y = margin.y; r.origin.x = (bounds.size.width - (r.size.width * 2 + buttonMargin)) / 2 return r } }
36.875
163
0.655763
7530bc017c563e9765fd9d7d9299ed5e69ba0b3d
768
import XCTest import SlidingHeaderPageViewController class Tests: 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 testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
26.482759
111
0.611979
e5e7e67b495a301c5d833ed662b58616a254caa0
766
// // Filtered.swift // Common // // Created by Barış Uyar on 29.03.2020. // Copyright © 2020 Barış Uyar. All rights reserved. // import Foundation public protocol Filterable { var filterString : String { get } } @propertyWrapper public struct Filtered<T> where T: Filterable { public var filterString: String public var wrappedValue:[T] public var filtered:[T] { if filterString.count > 0 { return wrappedValue.filter({ $0.filterString.lowercased().range(of: filterString, options: .caseInsensitive) != nil }) } return wrappedValue } public init(filterString : String) { self.wrappedValue = [] as! [T] self.filterString = filterString } }
21.885714
102
0.617493
f792d15dd572b5932e7d1fefbbb2589b2feef9f1
5,567
// Copyright (C) 2021 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation import GroundSdk /// Controller for privacy related settings, like private mode. class PrivacyController: DeviceComponentController { /// User Account Utility private var userAccountUtility: UserAccountUtilityCore? /// Monitor of the userAccount changes private var userAccountMonitor: MonitorCore? /// Decoder for privacy events. private var arsdkDecoder: ArsdkPrivacyEventDecoder! /// Whether `State` message has been received since `GetState` command was sent. private var stateReceived = false /// Whether connected drone supports private mode. private var privateModeSupported = false /// Private mode value. private var privateMode = false /// Constructor /// /// - Parameter deviceController: device controller owning this component controller (weak) override init(deviceController: DeviceController) { userAccountUtility = deviceController.engine.utilities.getUtility(Utilities.userAccount) super.init(deviceController: deviceController) arsdkDecoder = ArsdkPrivacyEventDecoder(listener: self) } /// Drone is about to be connected. override func willConnect() { super.willConnect() stateReceived = false _ = sendGetStateCommand() } /// Drone is connected. override func didConnect() { userAccountMonitor = userAccountUtility?.startMonitoring(accountDidChange: { _ in self.applyPresets() }) } /// Drone is disconnected. override func didDisconnect() { userAccountMonitor?.stop() userAccountMonitor = nil } /// Applies presets. private func applyPresets() { let userPrivateMode = userAccountUtility?.userAccountInfo?.privateMode ?? false if privateModeSupported && privateMode != userPrivateMode { _ = sendLogModeCommand(userPrivateMode) privateMode = userPrivateMode } } /// A command has been received. /// /// - Parameter command: received command override func didReceiveCommand(_ command: OpaquePointer) { arsdkDecoder.decode(command) } } /// Extension for methods to send Privacy commands. private extension PrivacyController { /// Sends to the drone a Privacy command. /// /// - Parameter command: command to send /// - Returns: `true` if the command has been sent func sendPrivacyCommand(_ command: Arsdk_Privacy_Command.OneOf_ID) -> Bool { var sent = false if let encoder = ArsdkPrivacyCommandEncoder.encoder(command) { sendCommand(encoder) sent = true } return sent } /// Sends get state command. /// /// - Returns: `true` if the command has been sent func sendGetStateCommand() -> Bool { var getState = Arsdk_Privacy_Command.GetState() getState.includeDefaultCapabilities = true return sendPrivacyCommand(.getState(getState)) } /// Sends log mode command. /// /// - Parameter privateMode: requested private mode /// - Returns: `true` if the command has been sent func sendLogModeCommand(_ privateMode: Bool) -> Bool { var setLogMode = Arsdk_Privacy_Command.SetLogMode() setLogMode.logStorage = privateMode ? .none : .persistent setLogMode.logConfigPersistence = .persistent return sendPrivacyCommand(.setLogMode(setLogMode)) } } /// Extension for events processing. extension PrivacyController: ArsdkPrivacyEventDecoderListener { func onState(_ state: Arsdk_Privacy_Event.State) { if state.hasDefaultCapabilities { privateModeSupported = state.defaultCapabilities.supportedLogStorage.contains(.none) } privateMode = state.logStorage == .none && state.logConfigPersistence == .persistent if !stateReceived { stateReceived = true applyPresets() } } }
35.916129
96
0.690677
225726f05e47b396c96603514044525b4aac77b4
317
// // Array+Shuffle.swift // EmojiCollectionApp // // Created by burt on 2018. 8. 26.. // Copyright © 2018년 Burt.K. All rights reserved. // import Foundation extension Array { mutating func shuffle() { for _ in 0..<count { sort { (_,_) in arc4random() < arc4random() } } } }
17.611111
57
0.574132
87862fd87ef3ce24f7502a149a16554e52031855
1,805
//// // 🦠 Corona-Warn-App // import Foundation import HealthCertificateToolkit extension Name { var fullName: String { return [resolvedGivenName, resolvedFamilyName].formatted() } var reversedFullName: String { var resolvedFamilyName = self.resolvedFamilyName ?? "" resolvedFamilyName += "," return [resolvedFamilyName, resolvedGivenName].formatted() } var reversedFullNameWithoutFallback: String { return [familyName, givenName].formatted(separator: ", ") } var standardizedName: String { return [standardizedGivenName, standardizedFamilyName].formatted() } var groupingStandardizedName: String { return standardizedName .replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) .replacingOccurrences(of: "<+", with: "<", options: .regularExpression) .trimmingCharacters(in: .whitespaces) } var reversedStandardizedName: String { var standardizedFamilyName = self.standardizedFamilyName standardizedFamilyName += "<<" return [standardizedFamilyName, standardizedGivenName].formatted(separator: "") } private var resolvedGivenName: String? { var givenName = self.givenName if givenName == nil || givenName?.trimmingCharacters(in: .whitespacesAndNewlines) == "" { givenName = standardizedGivenName } return givenName } private var resolvedFamilyName: String? { var familyName = self.familyName if familyName == nil || familyName?.trimmingCharacters(in: .whitespacesAndNewlines) == "" { familyName = standardizedFamilyName } return familyName } } fileprivate extension Sequence where Element == String? { func formatted(separator: String = " ") -> String { return self .compactMap { $0 } .filter { $0.trimmingCharacters(in: .whitespacesAndNewlines) != "" } .joined(separator: separator) } }
26.544118
93
0.730748
bf49029ca6174862459feb09546636600bc4e633
2,686
import Foundation import azureSwiftRuntime public protocol ConnectionMonitorsStart { var headerParameters: [String: String] { get set } var resourceGroupName : String { get set } var networkWatcherName : String { get set } var connectionMonitorName : String { get set } var subscriptionId : String { get set } var apiVersion : String { get set } func execute(client: RuntimeClient, completionHandler: @escaping (Error?) -> Void) -> Void; } extension Commands.ConnectionMonitors { // Start starts the specified connection monitor. This method may poll for completion. Polling can be canceled by // passing the cancel channel argument. The channel will be used to cancel polling and any outstanding HTTP requests. internal class StartCommand : BaseCommand, ConnectionMonitorsStart { public var resourceGroupName : String public var networkWatcherName : String public var connectionMonitorName : String public var subscriptionId : String public var apiVersion = "2018-01-01" public init(resourceGroupName: String, networkWatcherName: String, connectionMonitorName: String, subscriptionId: String) { self.resourceGroupName = resourceGroupName self.networkWatcherName = networkWatcherName self.connectionMonitorName = connectionMonitorName self.subscriptionId = subscriptionId super.init() self.method = "Post" self.isLongRunningOperation = true self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/start" self.headerParameters = ["Content-Type":"application/json; charset=utf-8"] } public override func preCall() { self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName) self.pathParameters["{networkWatcherName}"] = String(describing: self.networkWatcherName) self.pathParameters["{connectionMonitorName}"] = String(describing: self.connectionMonitorName) self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId) self.queryParameters["api-version"] = String(describing: self.apiVersion) } public func execute(client: RuntimeClient, completionHandler: @escaping (Error?) -> Void) -> Void { client.executeAsyncLRO(command: self) { (error) in completionHandler(error) } } } }
49.740741
207
0.678704
abd15b7ec68c4a852da973f1fda3f90c84c494f5
6,338
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// extension ByteBuffer { @inlinable func _toEndianness<T: FixedWidthInteger> (value: T, endianness: Endianness) -> T { switch endianness { case .little: return value.littleEndian case .big: return value.bigEndian } } /// Read an integer off this `ByteBuffer`, move the reader index forward by the integer's byte size and return the result. /// /// - parameters: /// - endianness: The endianness of the integer in this `ByteBuffer` (defaults to big endian). /// - as: the desired `FixedWidthInteger` type (optional parameter) /// - returns: An integer value deserialized from this `ByteBuffer` or `nil` if there aren't enough bytes readable. @inlinable public mutating func readInteger<T: FixedWidthInteger>(endianness: Endianness = .big, as: T.Type = T.self) -> T? { return self.getInteger(at: self.readerIndex, endianness: endianness, as: T.self).map { self._moveReaderIndex(forwardBy: MemoryLayout<T>.size) return $0 } } /// Get the integer at `index` from this `ByteBuffer`. Does not move the reader index. /// The selected bytes must be readable or else `nil` will be returned. /// /// - parameters: /// - index: The starting index of the bytes for the integer into the `ByteBuffer`. /// - endianness: The endianness of the integer in this `ByteBuffer` (defaults to big endian). /// - as: the desired `FixedWidthInteger` type (optional parameter) /// - returns: An integer value deserialized from this `ByteBuffer` or `nil` if the bytes of interest are not /// readable. @inlinable public func getInteger<T: FixedWidthInteger>(at index: Int, endianness: Endianness = Endianness.big, as: T.Type = T.self) -> T? { guard let range = self.rangeWithinReadableBytes(index: index, length: MemoryLayout<T>.size) else { return nil } if T.self == UInt8.self { assert(range.count == 1) return self.withUnsafeReadableBytes { ptr in ptr[range.startIndex] as! T } } return self.withUnsafeReadableBytes { ptr in var value: T = 0 withUnsafeMutableBytes(of: &value) { valuePtr in valuePtr.copyMemory(from: UnsafeRawBufferPointer(rebasing: ptr[range])) } return _toEndianness(value: value, endianness: endianness) } } /// Write `integer` into this `ByteBuffer`, moving the writer index forward appropriately. /// /// - parameters: /// - integer: The integer to serialize. /// - endianness: The endianness to use, defaults to big endian. /// - returns: The number of bytes written. @discardableResult @inlinable public mutating func writeInteger<T: FixedWidthInteger>(_ integer: T, endianness: Endianness = .big, as: T.Type = T.self) -> Int { let bytesWritten = self.setInteger(integer, at: self.writerIndex, endianness: endianness) self._moveWriterIndex(forwardBy: bytesWritten) return Int(bytesWritten) } /// Write `integer` into this `ByteBuffer` starting at `index`. This does not alter the writer index. /// /// - parameters: /// - integer: The integer to serialize. /// - index: The index of the first byte to write. /// - endianness: The endianness to use, defaults to big endian. /// - returns: The number of bytes written. @discardableResult @inlinable public mutating func setInteger<T: FixedWidthInteger>(_ integer: T, at index: Int, endianness: Endianness = .big, as: T.Type = T.self) -> Int { var value = _toEndianness(value: integer, endianness: endianness) return Swift.withUnsafeBytes(of: &value) { ptr in self.setBytes(ptr, at: index) } } } extension FixedWidthInteger { /// Returns the next power of two. @inlinable func nextPowerOf2() -> Self { guard self != 0 else { return 1 } return 1 << (Self.bitWidth - (self - 1).leadingZeroBitCount) } } extension UInt32 { /// Returns the next power of two unless that would overflow, in which case UInt32.max (on 64-bit systems) or /// Int32.max (on 32-bit systems) is returned. The returned value is always safe to be cast to Int and passed /// to malloc on all platforms. func nextPowerOf2ClampedToMax() -> UInt32 { guard self > 0 else { return 1 } var n = self #if arch(arm) || arch(i386) // on 32-bit platforms we can't make use of a whole UInt32.max (as it doesn't fit in an Int) let max = UInt32(Int.max) #else // on 64-bit platforms we're good let max = UInt32.max #endif n -= 1 n |= n >> 1 n |= n >> 2 n |= n >> 4 n |= n >> 8 n |= n >> 16 if n != max { n += 1 } return n } } /// Endianness refers to the sequential order in which bytes are arranged into larger numerical values when stored in /// memory or when transmitted over digital links. public enum Endianness { /// The endianness of the machine running this program. public static let host: Endianness = hostEndianness0() private static func hostEndianness0() -> Endianness { let number: UInt32 = 0x12345678 return number == number.bigEndian ? .big : .little } /// big endian, the most significant byte (MSB) is at the lowest address case big /// little endian, the least significant byte (LSB) is at the lowest address case little }
37.952096
147
0.596876
674b0358099587d9904d83293f05387f00b1d55d
18,954
import Foundation import Contacts import Postbox import TelegramCore import SyncCore public final class DeviceContactPhoneNumberData: Equatable { public let label: String public let value: String public init(label: String, value: String) { self.label = label self.value = value } public static func == (lhs: DeviceContactPhoneNumberData, rhs: DeviceContactPhoneNumberData) -> Bool { if lhs.label != rhs.label { return false } if lhs.value != rhs.value { return false } return true } } public final class DeviceContactEmailAddressData: Equatable { public let label: String public let value: String public init(label: String, value: String) { self.label = label self.value = value } public static func == (lhs: DeviceContactEmailAddressData, rhs: DeviceContactEmailAddressData) -> Bool { if lhs.label != rhs.label { return false } if lhs.value != rhs.value { return false } return true } } public final class DeviceContactUrlData: Equatable { public let label: String public let value: String public init(label: String, value: String) { self.label = label self.value = value } public static func == (lhs: DeviceContactUrlData, rhs: DeviceContactUrlData) -> Bool { if lhs.label != rhs.label { return false } if lhs.value != rhs.value { return false } return true } } public final class DeviceContactAddressData: Equatable, Hashable { public let label: String public let street1: String public let street2: String public let state: String public let city: String public let country: String public let postcode: String public init(label: String, street1: String, street2: String, state: String, city: String, country: String, postcode: String) { self.label = label self.street1 = street1 self.street2 = street2 self.state = state self.city = city self.country = country self.postcode = postcode } public static func == (lhs: DeviceContactAddressData, rhs: DeviceContactAddressData) -> Bool { if lhs.label != rhs.label { return false } if lhs.street1 != rhs.street1 { return false } if lhs.street2 != rhs.street2 { return false } if lhs.state != rhs.state { return false } if lhs.city != rhs.city { return false } if lhs.country != rhs.country { return false } if lhs.postcode != rhs.postcode { return false } return true } public func hash(into hasher: inout Hasher) { hasher.combine(self.label) hasher.combine(self.street1) hasher.combine(self.street2) hasher.combine(self.state) hasher.combine(self.city) hasher.combine(self.country) hasher.combine(self.postcode) } } public final class DeviceContactSocialProfileData: Equatable, Hashable { public let label: String public let service: String public let username: String public let url: String public init(label: String, service: String, username: String, url: String) { self.label = label self.service = service self.username = username self.url = url } public static func == (lhs: DeviceContactSocialProfileData, rhs: DeviceContactSocialProfileData) -> Bool { if lhs.label != rhs.label { return false } if lhs.service != rhs.service { return false } if lhs.username != rhs.username { return false } if lhs.url != rhs.url { return false } return true } public func hash(into hasher: inout Hasher) { hasher.combine(self.label) hasher.combine(self.service) hasher.combine(self.username) hasher.combine(self.url) } } public final class DeviceContactInstantMessagingProfileData: Equatable, Hashable { public let label: String public let service: String public let username: String public init(label: String, service: String, username: String) { self.label = label self.service = service self.username = username } public static func == (lhs: DeviceContactInstantMessagingProfileData, rhs: DeviceContactInstantMessagingProfileData) -> Bool { if lhs.label != rhs.label { return false } if lhs.service != rhs.service { return false } if lhs.username != rhs.username { return false } return true } public func hash(into hasher: inout Hasher) { hasher.combine(self.label) hasher.combine(self.service) hasher.combine(self.username) } } public let phonebookUsernamePathPrefix = "@id" private let phonebookUsernamePrefix = "https://t.me/" + phonebookUsernamePathPrefix public extension DeviceContactUrlData { convenience init(appProfile: PeerId) { self.init(label: "Telegram", value: "\(phonebookUsernamePrefix)\(appProfile.id)") } } public func parseAppSpecificContactReference(_ value: String) -> PeerId? { if !value.hasPrefix(phonebookUsernamePrefix) { return nil } let idString = String(value[value.index(value.startIndex, offsetBy: phonebookUsernamePrefix.count)...]) if let id = Int32(idString) { return PeerId(namespace: Namespaces.Peer.CloudUser, id: id) } return nil } public final class DeviceContactBasicData: Equatable { public let firstName: String public let lastName: String public let phoneNumbers: [DeviceContactPhoneNumberData] public init(firstName: String, lastName: String, phoneNumbers: [DeviceContactPhoneNumberData]) { self.firstName = firstName self.lastName = lastName self.phoneNumbers = phoneNumbers } public static func ==(lhs: DeviceContactBasicData, rhs: DeviceContactBasicData) -> Bool { if lhs.firstName != rhs.firstName { return false } if lhs.lastName != rhs.lastName { return false } if lhs.phoneNumbers != rhs.phoneNumbers { return false } return true } } public final class DeviceContactBasicDataWithReference: Equatable { public let stableId: DeviceContactStableId public let basicData: DeviceContactBasicData public init(stableId: DeviceContactStableId, basicData: DeviceContactBasicData) { self.stableId = stableId self.basicData = basicData } public static func ==(lhs: DeviceContactBasicDataWithReference, rhs: DeviceContactBasicDataWithReference) -> Bool { return lhs.stableId == rhs.stableId && lhs.basicData == rhs.basicData } } public final class DeviceContactExtendedData: Equatable { public let basicData: DeviceContactBasicData public let middleName: String public let prefix: String public let suffix: String public let organization: String public let jobTitle: String public let department: String public let emailAddresses: [DeviceContactEmailAddressData] public let urls: [DeviceContactUrlData] public let addresses: [DeviceContactAddressData] public let birthdayDate: Date? public let socialProfiles: [DeviceContactSocialProfileData] public let instantMessagingProfiles: [DeviceContactInstantMessagingProfileData] public let note: String public init(basicData: DeviceContactBasicData, middleName: String, prefix: String, suffix: String, organization: String, jobTitle: String, department: String, emailAddresses: [DeviceContactEmailAddressData], urls: [DeviceContactUrlData], addresses: [DeviceContactAddressData], birthdayDate: Date?, socialProfiles: [DeviceContactSocialProfileData], instantMessagingProfiles: [DeviceContactInstantMessagingProfileData], note: String) { self.basicData = basicData self.middleName = middleName self.prefix = prefix self.suffix = suffix self.organization = organization self.jobTitle = jobTitle self.department = department self.emailAddresses = emailAddresses self.urls = urls self.addresses = addresses self.birthdayDate = birthdayDate self.socialProfiles = socialProfiles self.instantMessagingProfiles = instantMessagingProfiles self.note = note } public static func ==(lhs: DeviceContactExtendedData, rhs: DeviceContactExtendedData) -> Bool { if lhs.basicData != rhs.basicData { return false } if lhs.middleName != rhs.middleName { return false } if lhs.prefix != rhs.prefix { return false } if lhs.suffix != rhs.suffix { return false } if lhs.organization != rhs.organization { return false } if lhs.jobTitle != rhs.jobTitle { return false } if lhs.department != rhs.department { return false } if lhs.emailAddresses != rhs.emailAddresses { return false } if lhs.urls != rhs.urls { return false } if lhs.addresses != rhs.addresses { return false } if lhs.birthdayDate != rhs.birthdayDate { return false } if lhs.socialProfiles != rhs.socialProfiles { return false } if lhs.instantMessagingProfiles != rhs.instantMessagingProfiles { return false } if lhs.note != rhs.note { return false } return true } } public extension DeviceContactExtendedData { convenience init?(vcard: Data) { if #available(iOSApplicationExtension 9.0, iOS 9.0, *) { guard let contact = (try? CNContactVCardSerialization.contacts(with: vcard))?.first else { return nil } self.init(contact: contact) } else { return nil } } @available(iOSApplicationExtension 9.0, iOS 9.0, *) func asMutableCNContact() -> CNMutableContact { let contact = CNMutableContact() contact.givenName = self.basicData.firstName contact.familyName = self.basicData.lastName contact.namePrefix = self.prefix contact.nameSuffix = self.suffix contact.middleName = self.middleName contact.phoneNumbers = self.basicData.phoneNumbers.map { phoneNumber -> CNLabeledValue<CNPhoneNumber> in return CNLabeledValue<CNPhoneNumber>(label: phoneNumber.label, value: CNPhoneNumber(stringValue: phoneNumber.value)) } contact.emailAddresses = self.emailAddresses.map { email -> CNLabeledValue<NSString> in CNLabeledValue<NSString>(label: email.label, value: email.value as NSString) } contact.urlAddresses = self.urls.map { url -> CNLabeledValue<NSString> in CNLabeledValue<NSString>(label: url.label, value: url.value as NSString) } contact.socialProfiles = self.socialProfiles.map({ profile -> CNLabeledValue<CNSocialProfile> in return CNLabeledValue<CNSocialProfile>(label: profile.label, value: CNSocialProfile(urlString: nil, username: profile.username, userIdentifier: nil, service: profile.service)) }) contact.instantMessageAddresses = self.instantMessagingProfiles.map({ profile -> CNLabeledValue<CNInstantMessageAddress> in return CNLabeledValue<CNInstantMessageAddress>(label: profile.label, value: CNInstantMessageAddress(username: profile.username, service: profile.service)) }) contact.postalAddresses = self.addresses.map({ address -> CNLabeledValue<CNPostalAddress> in let value = CNMutablePostalAddress() value.street = address.street1 + "\n" + address.street2 value.state = address.state value.city = address.city value.country = address.country value.postalCode = address.postcode return CNLabeledValue<CNPostalAddress>(label: address.label, value: value) }) if let birthdayDate = self.birthdayDate { contact.birthday = Calendar(identifier: .gregorian).dateComponents([.day, .month, .year], from: birthdayDate) } return contact } func serializedVCard() -> String? { if #available(iOSApplicationExtension 9.0, iOS 9.0, *) { guard let data = try? CNContactVCardSerialization.data(with: [self.asMutableCNContact()]) else { return nil } return String(data: data, encoding: .utf8) } return nil } @available(iOSApplicationExtension 9.0, iOS 9.0, *) convenience init(contact: CNContact) { var phoneNumbers: [DeviceContactPhoneNumberData] = [] for number in contact.phoneNumbers { phoneNumbers.append(DeviceContactPhoneNumberData(label: number.label ?? "", value: number.value.stringValue)) } var emailAddresses: [DeviceContactEmailAddressData] = [] for email in contact.emailAddresses { emailAddresses.append(DeviceContactEmailAddressData(label: email.label ?? "", value: email.value as String)) } var urls: [DeviceContactUrlData] = [] for url in contact.urlAddresses { urls.append(DeviceContactUrlData(label: url.label ?? "", value: url.value as String)) } var addresses: [DeviceContactAddressData] = [] for address in contact.postalAddresses { addresses.append(DeviceContactAddressData(label: address.label ?? "", street1: address.value.street, street2: "", state: address.value.state, city: address.value.city, country: address.value.country, postcode: address.value.postalCode)) } var birthdayDate: Date? if let birthday = contact.birthday { if let date = birthday.date { birthdayDate = date } } var socialProfiles: [DeviceContactSocialProfileData] = [] for profile in contact.socialProfiles { socialProfiles.append(DeviceContactSocialProfileData(label: profile.label ?? "", service: profile.value.service, username: profile.value.username, url: profile.value.urlString)) } var instantMessagingProfiles: [DeviceContactInstantMessagingProfileData] = [] for profile in contact.instantMessageAddresses { instantMessagingProfiles.append(DeviceContactInstantMessagingProfileData(label: profile.label ?? "", service: profile.value.service, username: profile.value.username)) } let basicData = DeviceContactBasicData(firstName: contact.givenName, lastName: contact.familyName, phoneNumbers: phoneNumbers) self.init(basicData: basicData, middleName: contact.middleName, prefix: contact.namePrefix, suffix: contact.nameSuffix, organization: contact.organizationName, jobTitle: contact.jobTitle, department: contact.departmentName, emailAddresses: emailAddresses, urls: urls, addresses: addresses, birthdayDate: birthdayDate, socialProfiles: socialProfiles, instantMessagingProfiles: instantMessagingProfiles, note: "") } var isPrimitive: Bool { if self.basicData.phoneNumbers.count > 1 { return false } if !self.organization.isEmpty { return false } if !self.jobTitle.isEmpty { return false } if !self.department.isEmpty { return false } if !self.emailAddresses.isEmpty { return false } if !self.urls.isEmpty { return false } if !self.addresses.isEmpty { return false } if self.birthdayDate != nil { return false } if !self.socialProfiles.isEmpty { return false } if !self.instantMessagingProfiles.isEmpty { return false } if !self.note.isEmpty { return false } return true } } public extension DeviceContactExtendedData { convenience init?(peer: Peer) { guard let user = peer as? TelegramUser else { return nil } var phoneNumbers: [DeviceContactPhoneNumberData] = [] if let phone = user.phone, !phone.isEmpty { phoneNumbers.append(DeviceContactPhoneNumberData(label: "_$!<Mobile>!$_", value: phone)) } self.init(basicData: DeviceContactBasicData(firstName: user.firstName ?? "", lastName: user.lastName ?? "", phoneNumbers: phoneNumbers), middleName: "", prefix: "", suffix: "", organization: "", jobTitle: "", department: "", emailAddresses: [], urls: [], addresses: [], birthdayDate: nil, socialProfiles: [], instantMessagingProfiles: [], note: "") } } extension DeviceContactAddressData { public var dictionary: [String: String] { var dictionary: [String: String] = [:] if !self.street1.isEmpty { dictionary["Street"] = self.street1 } if !self.city.isEmpty { dictionary["City"] = self.city } if !self.state.isEmpty { dictionary["State"] = self.state } if !self.country.isEmpty { dictionary["Country"] = self.country } if !self.postcode.isEmpty { dictionary["ZIP"] = self.postcode } return dictionary } public var string: String { var array: [String] = [] if !self.street1.isEmpty { array.append(self.street1) } if !self.city.isEmpty { array.append(self.city) } if !self.state.isEmpty { array.append(self.state) } if !self.country.isEmpty { array.append(self.country) } if !self.postcode.isEmpty { array.append(self.postcode) } return array.joined(separator: " ") } public var displayString: String { var array: [String] = [] if !self.street1.isEmpty { array.append(self.street1) } if !self.city.isEmpty { array.append(self.city) } if !self.state.isEmpty { array.append(self.state) } if !self.country.isEmpty { array.append(self.country) } return array.joined(separator: ", ") } }
35.1
437
0.623351
03ed015bae9ef530ba69b909eec237d9f153bedd
549
import Vapor import Submissions struct CreatePostRequest: Content, CreateRequest { let title: String func create(on request: Request) -> EventLoopFuture<Post> { request.eventLoop.future(Post(title: title)) } static func validations(on request: Request) -> EventLoopFuture<Validations> { var validations = Validations() if request.url.query == "fail" { validations.add("validation", result: ValidatorResults.TestFailure()) } return request.eventLoop.future(validations) } }
28.894737
82
0.675774
75d9f7d31fc04d419855783b3465b28e056c025e
4,934
// Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // A copy of the License is located at // // http://www.apache.org/licenses/LICENSE-2.0 // // or in the "license" file accompanying this file. This file 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. // // swiftlint:disable superfluous_disable_command // swiftlint:disable file_length line_length identifier_name type_name vertical_parameter_alignment // swiftlint:disable type_body_length function_body_length generic_type_name cyclomatic_complexity // -- Generated Code; do not edit -- // // StepFunctionsOperationsClientInput.swift // StepFunctionsClient // import Foundation import SmokeHTTPClient import StepFunctionsModel /** Type to handle the input to the CreateActivity operation in a HTTP client. */ public typealias CreateActivityOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the CreateStateMachine operation in a HTTP client. */ public typealias CreateStateMachineOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the DeleteActivity operation in a HTTP client. */ public typealias DeleteActivityOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the DeleteStateMachine operation in a HTTP client. */ public typealias DeleteStateMachineOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the DescribeActivity operation in a HTTP client. */ public typealias DescribeActivityOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the DescribeExecution operation in a HTTP client. */ public typealias DescribeExecutionOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the DescribeStateMachine operation in a HTTP client. */ public typealias DescribeStateMachineOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the DescribeStateMachineForExecution operation in a HTTP client. */ public typealias DescribeStateMachineForExecutionOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the GetActivityTask operation in a HTTP client. */ public typealias GetActivityTaskOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the GetExecutionHistory operation in a HTTP client. */ public typealias GetExecutionHistoryOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the ListActivities operation in a HTTP client. */ public typealias ListActivitiesOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the ListExecutions operation in a HTTP client. */ public typealias ListExecutionsOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the ListStateMachines operation in a HTTP client. */ public typealias ListStateMachinesOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the ListTagsForResource operation in a HTTP client. */ public typealias ListTagsForResourceOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the SendTaskFailure operation in a HTTP client. */ public typealias SendTaskFailureOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the SendTaskHeartbeat operation in a HTTP client. */ public typealias SendTaskHeartbeatOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the SendTaskSuccess operation in a HTTP client. */ public typealias SendTaskSuccessOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the StartExecution operation in a HTTP client. */ public typealias StartExecutionOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the StartSyncExecution operation in a HTTP client. */ public typealias StartSyncExecutionOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the StopExecution operation in a HTTP client. */ public typealias StopExecutionOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the TagResource operation in a HTTP client. */ public typealias TagResourceOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the UntagResource operation in a HTTP client. */ public typealias UntagResourceOperationHTTPRequestInput = BodyHTTPRequestInput /** Type to handle the input to the UpdateStateMachine operation in a HTTP client. */ public typealias UpdateStateMachineOperationHTTPRequestInput = BodyHTTPRequestInput
34.992908
99
0.815768
2fe3df65d526ceb1380b0076fb5458b23f6fcae4
9,652
// // FileIndex.swift // // // Created by Dmytro Anokhin on 11/09/2020. // import Foundation import CoreData #if canImport(PlainDatabase) import PlainDatabase #endif #if canImport(Log) import Log #endif #if canImport(Common) import Common #endif @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public class FileIndex { public struct Configuration { /// URL of the directory to keep file index, typically `~/Library/Caches/<main bundle identifier>` public var directoryURL: URL /// Name of the database file inside `directoryURL` public var name: String /// Name of the directory inside `directoryURL` to copy files to public var filesDirectoryName: String public init(name: String, filesDirectoryName: String, baseDirectoryName: String) { let directoryURL = FileManager.default.cachesDirectoryURL.appendingPathComponent(baseDirectoryName) self.init(name: name, filesDirectoryName: filesDirectoryName, directoryURL: directoryURL) } public init(name: String, filesDirectoryName: String, directoryURL: URL) { self.name = name self.filesDirectoryName = filesDirectoryName self.directoryURL = directoryURL } public var filesDirectoryURL: URL { directoryURL.appendingPathComponent(filesDirectoryName) } let modelDescription = CoreDataModelDescription( entity: .init(name: "File", managedObjectClass: NSManagedObject.self, attributes: [ .attribute(name: "identifier", type: .stringAttributeType), .attribute(name: "dateCreated", type: .dateAttributeType), .attribute(name: "expiryInterval", type: .doubleAttributeType, isOptional: true), .attribute(name: "originalURL", type: .URIAttributeType), .attribute(name: "fileName", type: .stringAttributeType), .attribute(name: "fileExtension", type: .stringAttributeType, isOptional: true), .attribute(name: "expiryDate", type: .dateAttributeType, isOptional: true) ], indexes: [ .index(name: "byIdentifier", elements: [ .property(name: "identifier") ]), .index(name: "byOriginalURL", elements: [ .property(name: "originalURL") ]), .index(name: "byExpiryDate", elements: [ .property(name: "expiryDate") ]) ]) ) var databaseConfiguration: Database.Configuration { Database.Configuration(name: name, directoryURL: directoryURL) } } public let configuration: Configuration public init(configuration: Configuration) { defer { log_debug(self, #function, "FileIndex path: \(configuration.directoryURL.path)") } self.configuration = configuration // Create directories if necessary. Directory must be created before initializing index or adding files. try? FileManager.default.createDirectory(at: configuration.filesDirectoryURL, withIntermediateDirectories: true, attributes: nil) database = PlainDatabase(configuration: configuration.databaseConfiguration, modelDescription: configuration.modelDescription) } public func location(of file: File) -> URL { var location = configuration.filesDirectoryURL.appendingPathComponent(file.fileName) if let fileExtension = file.fileExtension { location.appendPathExtension(fileExtension) } return location } // MARK: - Actions /// Move downloaded file to index directory and record it in the database @discardableResult public func move(_ sourceLocation: URL, originalURL: URL, identifier: String? = nil, fileName: String? = nil, fileExtension: String? = nil, expireAfter expiryInterval: TimeInterval? = nil ) throws -> File { let id: String = .string(suggested: identifier, generator: UUID().uuidString) let fileName: String = .string(suggested: fileName, generator: UUID().uuidString) let fileExtension: String? = .string(suggested: fileExtension, generator: originalURL.pathExtension) let file = File(id: id, dateCreated: Date(), expiryInterval: expiryInterval, originalURL: originalURL, fileName: fileName, fileExtension: fileExtension) try FileManager.default.moveItem(at: sourceLocation, to: location(of: file)) database.create(file) return file } /// Write data to a file in index directory and record it in the database @discardableResult public func write(_ data: Data, originalURL: URL, identifier: String? = nil, fileName: String? = nil, fileExtension: String? = nil, expireAfter expiryInterval: TimeInterval? = nil ) throws -> File { let id: String = .string(suggested: identifier, generator: UUID().uuidString) let fileName: String = .string(suggested: fileName, generator: UUID().uuidString) let fileExtension: String? = .string(suggested: fileExtension, generator: originalURL.pathExtension) let file = File(id: id, dateCreated: Date(), expiryInterval: expiryInterval, originalURL: originalURL, fileName: fileName, fileExtension: fileExtension) try data.write(to: location(of: file)) database.create(file) return file } public func get(_ originalURL: URL) -> [File] { let predicate = database.predicate(key: "originalURL", operator: .equalTo, value: originalURL.absoluteString, stringOptions: .caseInsensitive) return get(predicate) } public func get(_ identifier: String) -> [File] { let predicate = database.predicate(key: "identifier", operator: .equalTo, value: identifier, stringOptions: []) return get(predicate) } public func delete(_ file: File) { database.delete(where: "identifier", is: .equalTo, value: file.id) do { try FileManager.default.removeItem(at: location(of: file)) } catch { print(error) } } public func deleteAll(_ completion: (() -> Void)? = nil) { let request = database.request() delete(request: request, completion) } public func deleteExpired(_ completion: (() -> Void)? = nil) { let predicate = database.predicate(key: "expiryDate", operator: .lessThan, value: Date(), stringOptions: .caseInsensitive) let request = database.request(with: predicate) delete(request: request, completion) } private func delete(request: NSFetchRequest<NSManagedObject>, _ completion: (() -> Void)? = nil) { database.async { context in let objects = try context.fetch(request) for object in objects { guard let file = File(managedObject: object) else { continue } context.delete(object) do { try FileManager.default.removeItem(at: self.location(of: file)) } catch { print(error) } } if context.hasChanges { try context.save() } completion?() } } // MARK: - Private private let database: PlainDatabase<File> private func get(_ predicate: NSPredicate) -> [File] { let request = database.request(with: predicate) return database.sync { context in let objects = try context.fetch(request) var result: [NSManagedObject] = [] for object in objects { guard let file = File(managedObject: object) else { continue } let location = self.location(of: file) guard FileManager.default.fileExists(atPath: location.path) else { // File was deleted from disk, need to also delete it from the database context.delete(object) continue } result.append(object) } if context.hasChanges { try context.save() } return result } } } private extension String { /// Returns suggested string if not nil or empty, otherwise returns generator result. static func string(suggested: String?, generator: @autoclosure () -> String) -> String { if let suggested = suggested, !suggested.isEmpty { return suggested } return generator() } } private extension Optional where Wrapped == String { /// Returns suggested string if not nil or empty, otherwise returns generator result. static func string(suggested: String?, generator: @autoclosure () -> String?) -> String? { if let suggested = suggested, !suggested.isEmpty { return suggested } return generator() } }
35.098182
150
0.585164
79bded9ddcb415e1a143addc572f40b109f4bf80
6,756
import XCTest @testable import SwiftKueryORM import Foundation import KituraContracts class TestId: XCTestCase { static var allTests: [(String, (TestId) -> () throws -> Void)] { return [ ("testFind", testFind), ("testUpdate", testUpdate), ("testDelete", testDelete), ("testNilIDInsert", testNilIDInsert), ("testNonAutoNilIDInsert", testNonAutoNilIDInsert), ] } struct Person: Model { static var tableName = "People" static var idColumnName = "name" var name: String var age: Int } /** The following tests check that the ID field for the model is the name field in the model. */ /** Testing that the correct SQL Query is created to retrieve a specific model. Testing that the model can be retrieved */ func testFind() { let connection: TestConnection = createConnection(.returnOneRow) Database.default = Database(single: connection) performTest(asyncTasks: { expectation in Person.find(id: "Joe") { p, error in XCTAssertNil(error, "Find Failed: \(String(describing: error))") XCTAssertNotNil(connection.query, "Find Failed: Query is nil") if let query = connection.query { let expectedQuery = "SELECT * FROM \"People\" WHERE \"People\".\"name\" = ?1" let resultQuery = connection.descriptionOf(query: query) XCTAssertEqual(resultQuery, expectedQuery, "Find Failed: Invalid query") } XCTAssertNotNil(p, "Find Failed: No model returned") if let p = p { XCTAssertEqual(p.name, "Joe", "Find Failed: \(String(describing: p.name)) is not equal to Joe") XCTAssertEqual(p.age, 38, "Find Failed: \(String(describing: p.age)) is not equal to 38") } expectation.fulfill() } }) } /** Testing that the correct SQL Query is created to update a specific model. */ func testUpdate() { let connection: TestConnection = createConnection() Database.default = Database(single: connection) performTest(asyncTasks: { expectation in let person = Person(name: "Joe", age: 38) person.update(id: "Joe") { p, error in XCTAssertNil(error, "Update Failed: \(String(describing: error))") XCTAssertNotNil(connection.query, "Update Failed: Query is nil") if let query = connection.query { let expectedPrefix = "UPDATE \"People\" SET" let expectedSuffix = "WHERE \"People\".\"name\" = ?3" let expectedUpdates = [["\"name\" = ?1", "\"name\" = ?2"], ["\"age\" = ?1", "\"age\" = ?2"]] let resultQuery = connection.descriptionOf(query: query) XCTAssertTrue(resultQuery.hasPrefix(expectedPrefix)) XCTAssertTrue(resultQuery.hasSuffix(expectedSuffix)) for updates in expectedUpdates { var success = false for update in updates where resultQuery.contains(update) { success = true } XCTAssertTrue(success) } } XCTAssertNotNil(p, "Update Failed: No model returned") if let p = p { XCTAssertEqual(p.name, person.name, "Update Failed: \(String(describing: p.name)) is not equal to \(String(describing: person.name))") XCTAssertEqual(p.age, person.age, "Update Failed: \(String(describing: p.age)) is not equal to \(String(describing: person.age))") } expectation.fulfill() } }) } /** Testing that the correct SQL Query is created to delete a specific model */ func testDelete() { let connection: TestConnection = createConnection() Database.default = Database(single: connection) performTest(asyncTasks: { expectation in Person.delete(id: "Joe") { error in XCTAssertNil(error, "Delete Failed: \(String(describing: error))") XCTAssertNotNil(connection.query, "Delete Failed: Query is nil") if let query = connection.query { let expectedQuery = "DELETE FROM \"People\" WHERE \"People\".\"name\" = ?1" let resultQuery = connection.descriptionOf(query: query) XCTAssertEqual(resultQuery, expectedQuery, "Expected query \(String(describing: expectedQuery)) did not match result query: \(String(describing: resultQuery))") } expectation.fulfill() } }) } struct IdentifiedPerson: Model { static var tableName = "People" static var idKeyPath: IDKeyPath = \IdentifiedPerson.id var id: Int? var name: String var age: Int } func testNilIDInsert() { let connection: TestConnection = createConnection(.returnOneRow) //[1, "Joe", Int32(38)] Database.default = Database(single: connection) performTest(asyncTasks: { expectation in let myIPerson = IdentifiedPerson(id: nil, name: "Joe", age: 38) myIPerson.save() { identifiedPerson, error in XCTAssertNil(error, "Error on IdentifiedPerson.save") if let newPerson = identifiedPerson { XCTAssertEqual(newPerson.id, 1, "Id not stored on IdentifiedPerson") } expectation.fulfill() } }) } struct NonAutoIDPerson: Model { static var tableName = "People" var id: Int? var name: String var age: Int } func testNonAutoNilIDInsert() { let connection: TestConnection = createConnection(.returnOneRow) //[1, "Joe", Int32(38)] Database.default = Database(single: connection) performTest(asyncTasks: { expectation in NonAutoIDPerson.createTable { result, error in XCTAssertNil(error, "Table Creation Failed: \(String(describing: error))") XCTAssertNotNil(connection.raw, "Table Creation Failed: Query is nil") if let raw = connection.raw { let expectedQuery = "CREATE TABLE \"People\" (\"id\" type PRIMARY KEY, \"name\" type NOT NULL, \"age\" type NOT NULL)" XCTAssertEqual(raw, expectedQuery, "Table Creation Failed: Invalid query") } expectation.fulfill() } }) } }
42.490566
178
0.5672
bf52adcb8a2bbbf8371fe9338ac8a7cf54274b3b
6,221
// // ZanAnimation.swift // 点赞动画 // // Created by xiudou on 16/11/2. // Copyright © 2016年 dfpo. All rights reserved. // import UIKit class ZanAnimation: NSObject { // MARK:- 单粒 static let shareInstance = ZanAnimation() // MARK:- 常量 var zanCount : Int32 = 0 // MARK:- 懒加载 // 加载的数组 此处主要是循环利用对象 fileprivate lazy var keepArray : [UIImageView] = { let keepArray = [UIImageView]() return keepArray }() // 删除的数组 fileprivate lazy var deletArray : [UIImageView] = { let deletArray = [UIImageView]() return deletArray }() /** 粒子动画 - parameter view: 显示在拿一个view上 - parameter center_X: 动画的起始中心点X - parameter center_Y: 动画的起始中心点Y */ func startAnimation(_ view : UIView,center_X : CGFloat,center_Y : CGFloat){ if zanCount == INT_MAX{ zanCount = 0 } var tempImageView : UIImageView? let imageName = randomImageName() if deletArray.count > 0{ tempImageView = deletArray.first tempImageView?.image = UIImage(named: imageName) deletArray.removeFirst() }else{ guard let image = UIImage.init(named: imageName) else { return } tempImageView = UIImageView.init(image: image) // 初始位置(随便设置一个屏幕外的位置) tempImageView!.center = CGPoint(x: -5000, y: -5000) } view.addSubview(tempImageView!) keepArray.append(tempImageView!) let group = groupAnimation(center_X, center_Y: center_Y) tempImageView!.layer.add(group, forKey: "ZanAnimation\(zanCount)") } fileprivate func groupAnimation(_ center_X : CGFloat,center_Y : CGFloat) -> CAAnimationGroup{ let group = CAAnimationGroup() group.duration = 2.0; group.repeatCount = 1; let animation = scaleAnimation() let keyAnima = positionAnimatin(center_X, center_Y: center_Y) let alphaAnimation = alphaAnimatin() group.animations = [animation, keyAnima, alphaAnimation] group.delegate = self; return group } fileprivate func scaleAnimation() -> CABasicAnimation { // 设定为缩放 let animation = CABasicAnimation.init(keyPath: "transform.scale") // 动画选项设定 animation.duration = 0.5// 动画持续时间 animation.isRemovedOnCompletion = false // 缩放倍数 animation.fromValue = 0.1 // 开始时的倍率 animation.toValue = 1.0 // 结束时的倍率 return animation } fileprivate func positionAnimatin(_ center_X : CGFloat,center_Y : CGFloat) -> CAKeyframeAnimation { let keyAnima=CAKeyframeAnimation() keyAnima.keyPath="position" //1.1告诉系统要执行什么动画 //创建一条路径 let path = CGMutablePath() let transform = CGAffineTransform.identity path.move(to: CGPoint(x: center_X, y: center_Y), transform: transform) // 控制点X波动值 let controlX = Int((arc4random() % UInt32(60))) - 30 // 控制点Y波动值 let controlY = Int((arc4random() % UInt32(50))) // 端点X波动值 let entX = Int((arc4random() % UInt32(100))) - Int(50) // CGPathAddQuadCurveToPoint(path, &transform, CGFloat(Int(center_X) - controlX), CGFloat(Int(center_Y) - controlY), CGFloat(Int(center_X) + entX), CGFloat(arc4random() % UInt32(50) + 150)) path.addQuadCurve(to: CGPoint(x: CGFloat(Int(center_X) + entX), y: CGFloat(arc4random() % UInt32(50) + 150)), control: CGPoint(x: CGFloat(Int(center_X) - controlX), y: CGFloat(Int(center_Y) - controlY)), transform: transform) keyAnima.path=path; //1.2设置动画执行完毕后,不删除动画 keyAnima.isRemovedOnCompletion = false //1.3设置保存动画的最新状态 keyAnima.fillMode=kCAFillModeForwards //1.4设置动画执行的时间 keyAnima.duration=2.0 //1.5设置动画的节奏 keyAnima.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) return keyAnima } fileprivate func alphaAnimatin() -> CABasicAnimation { let alphaAnimation = CABasicAnimation.init(keyPath: "opacity") // 动画选项设定 alphaAnimation.duration = 1.5 // 动画持续时间 alphaAnimation.isRemovedOnCompletion = false alphaAnimation.fromValue = 1.0 alphaAnimation.toValue = 0.1 alphaAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn) alphaAnimation.beginTime = 0.5 return alphaAnimation } fileprivate func randomImageName() -> String { let number = Int(arc4random() % (8 + 1)); var randomImageName: String switch (number) { case 1: randomImageName = "good1_30x30" break; case 2: randomImageName = "good2_30x30" break; case 3: randomImageName = "good3_30x30" break; case 4: randomImageName = "good4_30x30" break; case 5: randomImageName = "good5_30x30" break; case 6: randomImageName = "good6_30x30" break; case 7: randomImageName = "good7_30x30" break; case 8: randomImageName = "good8_30x30" break; default: randomImageName = "good9_30x30" break; } return randomImageName } } // MARK:- CAAnimationGroup代理方法 extension ZanAnimation : CAAnimationDelegate{ // override func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { // guard let tempImageView = keepArray.first else { return } // tempImageView.layer.removeAllAnimations() // deletArray.append(tempImageView) // keepArray.removeFirst() // } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard let tempImageView = keepArray.first else { return } tempImageView.layer.removeAllAnimations() deletArray.append(tempImageView) keepArray.removeFirst() } }
31.902564
233
0.593474
ff72c3927f6ea3c016db7deb05869a37f208ca09
363
// // ContentView.swift // Settings // // Created by Liu Chuan on 2019/6/10. // Copyright © 2020 Liu Chuan. All rights reserved. // import SwiftUI struct ContentView: View { var body: some View { HomeView() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
14.52
52
0.61157
de64973b22defe2ee9cfd488868216f7525d8742
7,308
// // HitsInteractorSearcherConnectionTests.swift // InstantSearchCore // // Created by Vladislav Fitc on 02/12/2019. // Copyright © 2019 Algolia. All rights reserved. // import Foundation import AlgoliaSearchClient @testable import InstantSearchCore import XCTest class HitsInteractorSearcherConnectionTests: XCTestCase { weak var disposableInteractor: HitsInteractor<JSON>? weak var disposableSearcher: SingleIndexSearcher? func getInteractor(with infiniteScrollingController: InfiniteScrollable) -> HitsInteractor<JSON> { let paginator = Paginator<JSON>() let page1 = ["i1", "i2", "i3"].map { JSON.string($0) } paginator.pageMap = PageMap([1: page1]) let interactor = HitsInteractor(settings: .init(infiniteScrolling: .on(withOffset: 10), showItemsOnEmptyQuery: true), paginationController: paginator, infiniteScrollingController: infiniteScrollingController) return interactor } func testLeak() { let infiniteScrollingController = TestInfiniteScrollingController() infiniteScrollingController.pendingPages = [0, 2] let searcher = SingleIndexSearcher(client: SearchClient(appID: "", apiKey: ""), indexName: "") let interactor = getInteractor(with: infiniteScrollingController) disposableInteractor = interactor disposableSearcher = searcher let connection: Connection = HitsInteractor.SingleIndexSearcherConnection(interactor: interactor, searcher: searcher) connection.connect() } override func tearDown() { XCTAssertNil(disposableInteractor, "Leaked interactor") XCTAssertNil(disposableSearcher, "Leaked searcher") } func testConnect() { let infiniteScrollingController = TestInfiniteScrollingController() infiniteScrollingController.pendingPages = [0, 2] let searcher = SingleIndexSearcher(client: SearchClient(appID: "", apiKey: ""), indexName: "") let interactor = getInteractor(with: infiniteScrollingController) let connection: Connection = HitsInteractor.SingleIndexSearcherConnection(interactor: interactor, searcher: searcher) connection.connect() let tester = ConnectionTester(searcher: searcher, interactor: interactor, infiniteScrollingController: infiniteScrollingController, source: self) tester.check(isConnected: true) } func testDisconnect() { let infiniteScrollingController = TestInfiniteScrollingController() infiniteScrollingController.pendingPages = [0, 2] let searcher = SingleIndexSearcher(client: SearchClient(appID: "", apiKey: ""), indexName: "") let interactor = getInteractor(with: infiniteScrollingController) let connection: Connection = HitsInteractor.SingleIndexSearcherConnection(interactor: interactor, searcher: searcher) connection.connect() connection.disconnect() let tester = ConnectionTester(searcher: searcher, interactor: interactor, infiniteScrollingController: infiniteScrollingController, source: self) tester.check(isConnected: false) } func testConnectMethod() { let infiniteScrollingController = TestInfiniteScrollingController() infiniteScrollingController.pendingPages = [0, 2] let searcher = SingleIndexSearcher(client: SearchClient(appID: "", apiKey: ""), indexName: "") let interactor = getInteractor(with: infiniteScrollingController) interactor.connectSearcher(searcher) let tester = ConnectionTester(searcher: searcher, interactor: interactor, infiniteScrollingController: infiniteScrollingController, source: self) tester.check(isConnected: true) } } extension HitsInteractorSearcherConnectionTests { class ConnectionTester { let searcher: SingleIndexSearcher let interactor: HitsInteractor<JSON> let infiniteScrollingController: TestInfiniteScrollingController let source: XCTestCase init(searcher: SingleIndexSearcher, interactor: HitsInteractor<JSON>, infiniteScrollingController: TestInfiniteScrollingController, source: XCTestCase) { self.searcher = searcher self.interactor = interactor self.infiniteScrollingController = infiniteScrollingController self.source = source } func check(isConnected: Bool, file: StaticString = #file, line: UInt = #line) { testPageLoader(isConnected: isConnected, file: file, line: line) testQueryChanged(isConnected: isConnected, file: file, line: line) testResultsUpdated(isConnected: isConnected, file: file, line: line) testPendingPages(isConnected: isConnected, file: file, line: line) source.waitForExpectations(timeout: 2, handler: nil) } private func testPageLoader(isConnected: Bool, file: StaticString = #file, line: UInt = #line) { if isConnected { XCTAssertTrue(searcher === infiniteScrollingController.pageLoader, file: file, line: line) } else { XCTAssertNil(infiniteScrollingController.pageLoader, file: file, line: line) } } private func testQueryChanged(isConnected: Bool, file: StaticString = #file, line: UInt = #line) { let queryChangedExpectation = source.expectation(description: "query changed") queryChangedExpectation.isInverted = !isConnected interactor.onRequestChanged.subscribe(with: self) { _, _ in queryChangedExpectation.fulfill() } searcher.query = "query" searcher.indexQueryState.query.page = 0 infiniteScrollingController.pendingPages = [0] } private func testResultsUpdated(isConnected: Bool, file: StaticString = #file, line: UInt = #line) { let resultsUpdatedExpectation = source.expectation(description: "results updated") resultsUpdatedExpectation.isInverted = !isConnected interactor.onResultsUpdated.subscribe(with: self) { tester, _ in resultsUpdatedExpectation.fulfill() XCTAssertTrue(tester.infiniteScrollingController.pendingPages.isEmpty, file: file, line: line) } let searchResponse = SearchResponse(hits: [Hit(object: ["field": "value"])]) searcher.onResults.fire(searchResponse) } private func testPendingPages(isConnected: Bool, file: StaticString = #file, line: UInt = #line) { infiniteScrollingController.pendingPages = [0] searcher.onError.fire((searcher.indexQueryState.query, NSError())) if isConnected { XCTAssertTrue(infiniteScrollingController.pendingPages.isEmpty, file: file, line: line) } else { XCTAssertFalse(infiniteScrollingController.pendingPages.isEmpty, file: file, line: line) } } } }
38.463158
121
0.66434
0ea1a25af2ac57a91f89c54ca08d52cbf6e2a886
5,702
// // Smile.swift // Smile // // Created by Khoa Pham on 05/06/16. // Copyright © 2016 Fantageek. All rights reserved. // import Foundation // MARK: - List /// List all emojis public func list() -> [String] { let ranges = [ 0x1F601...0x1F64F, 0x2600...0x27B0, 0x23F0...0x23FA, 0x1F680...0x1F6C0, 0x1F170...0x1F251 ] var all = ranges.joined().map { return String(Character(UnicodeScalar($0)!)) } //⌚️⌨️⭐️ let solos = [0x231A, 0x231B, 0x2328, 0x2B50] all.append(contentsOf: solos.map({ String(Character(UnicodeScalar($0)!))})) return all } // MARK: - Emoji /// Check if a character is emoji public func isEmoji(character: String) -> Bool { return emojiList.values.contains(character) } /// Check if a string contains any emojis public func containsEmoji(string: String) -> Bool { let set = CharacterSet(charactersIn: emojiList.values.joined()) let range = string .smile_removingDigits .rangeOfCharacter(from: set) return range != nil } /// Get emoji from unicode value public func emoji(unicodeValues: [Int]) -> String { return unicodeValues.compactMap({ guard let scalar = UnicodeScalar($0) else { return nil } return String(scalar) }).joined() } /// Unmodify an emoji public func unmodify(emoji: String) -> String { guard let first = emoji.unicodeScalars.first?.value else { return emoji } return Smile.emoji(unicodeValues: [Int(first)]) } // MARK: - Name /// Return standard name for a emoji public func name(emoji: String) -> [String] { let string = NSMutableString(string: String(emoji)) var range = CFRangeMake(0, CFStringGetLength(string)) CFStringTransform(string, &range, kCFStringTransformToUnicodeName, false) return Utils.dropPrefix(string: String(string), subString: "\\N") .components(separatedBy: "\\N") .map { return Utils.remove(string: $0, set: (Set(["{", "}"]))) } } // MARK: - Flag /// Return emoji for a flag public func emoji(countryCode: String) -> String { let base = UnicodeScalar("🇦").value - UnicodeScalar("A").value return Utils.flatten(string: countryCode.uppercased(), base: base).joined() } // MARK: - Keywords /// Search emoji by keywords public func emojis(keywords: [String]) -> [String] { var result: [String] = [] list().forEach { emoji in keywords.forEach { keyword in name(emoji: emoji).forEach { name in if name.range(of: keyword) != nil { result.append(emoji) } } } } return result } // MARK: - Alias /// Return emoji for an alias public func emoji(alias: String) -> String? { return emojiList[alias] } /// Find alias of emoji public func alias(emoji: String) -> String? { for (key, value) in emojiList { if value == emoji { return key } } return nil } /// Replace alias within a string by emoji public func replaceAlias(string: String) -> String { guard let regex = try? NSRegularExpression(pattern: ":\\w*?:", options: .caseInsensitive) else { return string } let range = NSMakeRange(0, string.count) var mutableString = string regex.enumerateMatches(in: string, options: [], range: range) { (result, flags, context) in guard let range = result?.range else { return } let start = string.index(string.startIndex, offsetBy: range.location) let end = string.index(start, offsetBy: range.length) let alias = string[start..<end].replacingOccurrences(of: ":", with: "") guard let emoji = emoji(alias: alias) else { return } mutableString = mutableString.replacingOccurrences(of: ":\(alias):", with: emoji) } return mutableString } // MARK: - Category /// Determine the category of emoji public func category(emoji: String) -> String? { for (category, list) in emojiCategories { if list.contains(emoji) { return category } } return nil } // MARK: - Manipulation /// Extract all emojis within a string public func extractEmojis(string: String) -> String { return Utils.flatten(string: string).filter({ character in return isRelatedToEmoji(character: character) }).joined() } /// Remove all emojis within a string public func removeEmojis(string: String) -> String { let first = Utils.flattenCharacters(string: string).filter({ character in return !isRelatedToEmoji(character: character) }).joined() let second = Utils.flatten(string: first).filter({ character in return !isRelatedToEmoji(character: character) }).joined() return second } /// Assemble many emojis into one public func assemble(emojis: [String]) -> String { let simple = Utils.flatten(string: emojis.joined()) let joiner = Utils.insert(element: Smile.Sequence.Mark.zeroWidthJoiner, betweenArray: simple) let selector = Utils.add(element: Smile.Sequence.Mark.presentationSelector, array: joiner) if isEmoji(character: simple.joined()) { return simple.joined() } if isEmoji(character: joiner.joined()) { return joiner.joined() } if isEmoji(character: selector.joined()) { return selector.joined() } return emojis.joined() } /// Disassemble an emoji into many public func disassemble(emoji: String) -> [String] { return Utils.flatten(string: emoji).filter({ character in return isEmoji(character: character) }) } // MARK: - Helper /// Check if a character is emoji, or emoji sequence marks fileprivate func isRelatedToEmoji(character: String) -> Bool { return isEmoji(character: character) || list().contains(character) || Smile.Sequence.all.contains(character) } fileprivate extension String { var smile_removingDigits: String { return components(separatedBy: .decimalDigits).joined() } }
24.161017
98
0.676955
f71958129cd029504a67b81235fde49ded23dd42
901
// // AstronautView.swift // Moonshot // // Created by jrasmusson on 2021-05-07. // import SwiftUI struct AstronautView: View { let astronaut: Astronaut var body: some View { GeometryReader { geometry in ScrollView(.vertical) { VStack { Image(self.astronaut.id) .resizable() .scaledToFit() .frame(width: geometry.size.width) Text(self.astronaut.description) .padding() } } } .navigationBarTitle(Text(astronaut.name), displayMode: .inline) } } struct AstronautView_Previews: PreviewProvider { static let astronauts: [Astronaut] = Bundle.main.decode("astronauts.json") static var previews: some View { AstronautView(astronaut: astronauts[0]) } }
23.710526
78
0.54162
72e7b338c86aa01528602e41a5cb199fe13248a8
4,340
import Foundation import NIO import Dispatch import NIOSSL import AsyncHTTPClient public class TCPServer { private var host: String? private var port: Int? let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) static var httpClient: HTTPClient? init(host: String, port: Int) { self.host = host self.port = port TCPServer.httpClient = HTTPClient(eventLoopGroupProvider: .shared(group)) } private var serverBootstrap: ServerBootstrap { #if DEBUG || LOCAL return ServerBootstrap(group: group) .childChannelInitializer { channel in channel.pipeline.addHandler(BackPressureHandler()).flatMap { v in channel.pipeline.addHandler(ChatHandler()) } } .childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) #else let basePath = FileManager().currentDirectoryPath let certPath = basePath + "/fullchain.pem" let keyPath = basePath + "/privkey.pem" let certs = try! NIOSSLCertificate.fromPEMFile(certPath) .map { NIOSSLCertificateSource.certificate($0) } let tls = TLSConfiguration.forServer(certificateChain: certs, privateKey: .file(keyPath)) let sslContext = try? NIOSSLContext(configuration: tls) return ServerBootstrap(group: group) .childChannelInitializer { channel in channel.pipeline.addHandler(NIOSSLServerHandler(context: sslContext!)) .flatMap { _ in channel.pipeline.addHandler(BackPressureHandler()) .flatMap { _ in channel.pipeline.addHandler(ChatHandler()) } } } .childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1) #endif } func shutdown() { do { try group.syncShutdownGracefully() } catch let error { print("Could not gracefully shutdown, Forcing the exit (\(error.localizedDescription)") exit(0) } print("closed server") } func run() throws { guard let host = host else { throw TCPError.invalidHost } guard let port = port else { throw TCPError.invalidPort } // First argument is the program path let arguments = CommandLine.arguments let arg1 = arguments.dropFirst().first let arg2 = arguments.dropFirst(2).first enum BindTo { case ip(host: String, port: Int) case unixDomainSocket(path: String) } let bindTarget: BindTo switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) { case (.some(let h), _ , .some(let p)): /* we got two arguments, let's interpret that as host and port */ bindTarget = .ip(host: h, port: p) case (let portString?, .none, _): // Couldn't parse as number, expecting unix domain socket path. bindTarget = .unixDomainSocket(path: portString) case (_, let p?, _): // Only one argument --> port. bindTarget = .ip(host: host, port: p) default: bindTarget = .ip(host: host, port: port) } let channel = try { () -> Channel in switch bindTarget { case .ip(let host, let port): return try serverBootstrap.bind(host: host, port: port).wait() case .unixDomainSocket(let path): return try serverBootstrap.bind(unixDomainSocketPath: path).wait() } }() guard let localAddress = channel.localAddress else { fatalError("Address was unable to bind. Please check that the socket was not closed or that the address family was understood.") } print("Server started and listening on \(localAddress)") // This will never unblock as we don't close the ServerChannel. try channel.closeFuture.wait() } }
35.867769
140
0.571659
cc75b80e5fa7f82c36e948d2443e4db0dda0bf9d
2,757
// // PinterestLayout.swift // collection-view-layouts // // Created by sergey on 2/21/18. // Copyright © 2018 rubygarage. All rights reserved. // import UIKit public class PinterestLayout: BaseLayout { public var columnsCount = 2 // MARK: - ContentDynamicLayout override public func calculateCollectionViewFrames() { guard columnsCount > 0 else { fatalError("Value must be greater than zero") } guard let collectionView = collectionView, let delegate = delegate else { return } contentSize.width = collectionView.frame.size.width let cellsPaddingWidth = CGFloat(columnsCount - 1) * cellsPadding.vertical let cellWidth = (contentWidthWithoutPadding - cellsPaddingWidth) / CGFloat(columnsCount) var yOffsets = [CGFloat](repeating: contentPadding.vertical, count: columnsCount) for section in 0..<collectionView.numberOfSections { addAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, section: section, yOffsets: &yOffsets) let itemsCount = collectionView.numberOfItems(inSection: section) for item in 0 ..< itemsCount { let isLastItem = item == itemsCount - 1 let indexPath = IndexPath(item: item, section: section) let cellhHeight = delegate.cellSize(indexPath: indexPath).height let cellSize = CGSize(width: cellWidth, height: cellhHeight) let y = yOffsets.min()! let column = yOffsets.firstIndex(of: y)! let x = CGFloat(column) * (cellWidth + cellsPadding.horizontal) + contentPadding.horizontal let origin = CGPoint(x: x, y: y) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) attributes.frame = CGRect(origin: origin, size: cellSize) cachedAttributes.append(attributes) yOffsets[column] += cellhHeight + cellsPadding.vertical if isLastItem { let y = yOffsets.max()! for index in 0..<yOffsets.count { yOffsets[index] = y } } } addAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, section: section, yOffsets: &yOffsets) } contentSize.height = yOffsets.max()! + contentPadding.vertical - cellsPadding.vertical } }
37.767123
107
0.572724
56eba3534f46f6032f1ca67d98d035185e35d61e
5,414
// // ShapeTool.swift // CreativeSwift // // Created by Wirawit Rueopas on 1/22/2560 BE. // Copyright © 2560 Wirawit Rueopas. All rights reserved. // import UIKit /* Concept: Shape Drawing = Creatable --> Drawable --> Finishable Creatable = start shape, create UIBezierPath Drawable = add line, curve, arc, quad, ... Finishable = fill, stroke, fill and stroke */ /// A type that can create Shape. public protocol ShapeToolCreatable { /// Start closed shape at p. func createClosedShape(at p: CGPoint) -> ShapeToolDrawable func createClosedShapeAt(x: CGFloat, y: CGFloat) -> ShapeToolDrawable /// Start open shape at p. func createOpenShape(at p: CGPoint) -> ShapeToolDrawable func createOpenShapeAt(x: CGFloat, y: CGFloat) -> ShapeToolDrawable } /// A type that can draw Shape. Always call done() at the end. public protocol ShapeToolDrawable { func line(to p: CGPoint) -> ShapeToolDrawable func curve(to p: CGPoint, controlPoint1: CGPoint, controlPoint2: CGPoint) -> ShapeToolDrawable func quadCurve(to p: CGPoint, controlPoint: CGPoint) -> ShapeToolDrawable // MARK: Conveniences func lineTo(x: CGFloat, y: CGFloat) -> ShapeToolDrawable func arc(withCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> ShapeToolDrawable func curveTo(x: CGFloat, y: CGFloat, cx1: CGFloat, cy1: CGFloat, cx2: CGFloat, cy2: CGFloat) -> ShapeToolDrawable func quadCurveTo(x: CGFloat, y: CGFloat, cx: CGFloat, cy: CGFloat) -> ShapeToolDrawable /// Call this when done drawing. func done() -> ShapeToolFinishable } /// A type that can finish Shape drawing with fill, stroke or both. public protocol ShapeToolFinishable { /// Fill created shape. /// /// **Note that opened shape is closed automatically if you call this.** func fill() /// Fill and stroke created shape. /// /// **Note that opened shape is closed automatically if you call this.** func fillAndStroke() func stroke() func finish(fill: Bool, andThenStroke stroke: Bool) } /// A tool to begin new shape on given UIBezierPath. /// Checkout [How to draw with UIBezierPath.](https://developer.apple.com/library/content/documentation/2DDrawing/Conceptual/DrawingPrintingiOS/BezierPaths/BezierPaths.html) internal struct ShapeCanvas { fileprivate let path = UIBezierPath() fileprivate let isClosedShape: Bool fileprivate init(closed: Bool) { self.isClosedShape = closed } } /// Starting point, it creates Canvas and hands off ShapeToolCreatable internal struct ShapeTool {} extension ShapeTool: ShapeToolCreatable { public func createClosedShape(at p: CGPoint) -> ShapeToolDrawable { let tool = ShapeCanvas(closed: true) tool.path.move(to: p) return tool } public func createClosedShapeAt(x: CGFloat, y: CGFloat) -> ShapeToolDrawable { return createClosedShape(at: .init(x: x, y: y)) } public func createOpenShape(at p: CGPoint) -> ShapeToolDrawable { let tool = ShapeCanvas(closed: false) tool.path.move(to: p) return tool } public func createOpenShapeAt(x: CGFloat, y: CGFloat) -> ShapeToolDrawable { return createOpenShape(at: .init(x: x, y: y)) } } extension ShapeCanvas: ShapeToolDrawable { public func line(to p: CGPoint) -> ShapeToolDrawable { path.addLine(to: p) return self } public func curve(to p: CGPoint, controlPoint1: CGPoint, controlPoint2: CGPoint) -> ShapeToolDrawable { path.addCurve(to: p, controlPoint1: controlPoint1, controlPoint2: controlPoint2) return self } public func arc(withCenter center: CGPoint, radius: CGFloat, startAngle: CGFloat, endAngle: CGFloat, clockwise: Bool) -> ShapeToolDrawable { path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: clockwise) return self } public func quadCurve(to p: CGPoint, controlPoint: CGPoint) -> ShapeToolDrawable { path.addQuadCurve(to: p, controlPoint: controlPoint) return self } // MARK: Conveniences public func lineTo(x: CGFloat, y: CGFloat) -> ShapeToolDrawable { path.addLine(to: .init(x: x, y: y)) return self } public func curveTo(x: CGFloat, y: CGFloat, cx1: CGFloat, cy1: CGFloat, cx2: CGFloat, cy2: CGFloat) -> ShapeToolDrawable { path.addCurve(to: .init(x: x, y: y), controlPoint1: .init(x: cx1, y: cy1), controlPoint2: .init(x: cx2, y: cy2)) return self } public func quadCurveTo(x: CGFloat, y: CGFloat, cx: CGFloat, cy: CGFloat) -> ShapeToolDrawable { path.addQuadCurve(to: .init(x: x, y: y), controlPoint: .init(x: cx, y: cy)) return self } public func done() -> ShapeToolFinishable { if isClosedShape { path.close() } return self } } extension ShapeCanvas: ShapeToolFinishable { public func fill() { path.fill() } public func stroke() { path.stroke() } public func fillAndStroke() { path.fill() path.stroke() } public func finish(fill: Bool, andThenStroke stroke: Bool) { if fill { path.fill() } if stroke { path.stroke() } } }
31.660819
173
0.658478
db9963d8653c23cdf003728e7bcea2c568bbd827
1,839
// // ProfileViewController.swift // twitter_alamofire_demo // // Created by Joey Dafforn on 2/18/18. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit import AlamofireImage class ProfileViewController: UIViewController { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var twitterHandle: UILabel! @IBOutlet weak var taglineLabel: UITextView! @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var numTweetsLabel: UILabel! @IBOutlet weak var numFollowingLabel: UILabel! @IBOutlet weak var numFollowersLabel: UILabel! var user: User? override func viewDidLoad() { super.viewDidLoad() if let user = User.current { usernameLabel.text = user.name twitterHandle.text = "@\(user.screenName!)" profileImage.af_setImage(withURL: URL(string: user.profileImageURL)!) profileImage.layer.cornerRadius = 16 profileImage.clipsToBounds = true taglineLabel.text = user.description! numFollowersLabel.text = "\(user.followerCount!)" numFollowingLabel.text = "\(user.followingCount!)" numTweetsLabel.text = "\(user.numTweets!)" } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
31.706897
106
0.666123
e03bf3e05e4693307cf4341fdd53e257267fbe67
1,018
@testable import App extension Github.Metadata { static let mock: Self = .init( issues: [], openPullRequests: [], repo: .init(defaultBranch: "master", description: "desc", forksCount: 1, license: .init(key: "mit"), openIssues: 3, parent: nil, stargazersCount: 2 ) ) static func mock(for package: Package) -> Self { // populate with some mock data derived from the package .init( issues: [], openPullRequests: [], repo: .init(defaultBranch: "master", description: "This is package " + package.url, forksCount: package.url.count, license: .init(key: "mit"), openIssues: 3, parent: nil, stargazersCount: package.url.count + 1 ) ) } }
29.941176
70
0.441061
d7e1307c49593c72c16a6ab739630422f8051045
246
// // Weather+CoreDataClass.swift // WeatherApp // // Created by kay weng on 23/01/2017. // Copyright © 2017 snackcode.org. All rights reserved. // import Foundation import CoreData @objc(Weather) public class Weather: NSManagedObject { }
15.375
56
0.719512
16d4f252f9ea7662a88227010866e259c7168ee7
6,664
/* MIT License Copyright (c) 2017-2018 MessageKit 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 MapKit import MessageKit import MessageInputBar final class BasicExampleViewController: ChatViewController { override func configureMessageCollectionView() { super.configureMessageCollectionView() messagesCollectionView.messagesLayoutDelegate = self messagesCollectionView.messagesDisplayDelegate = self let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout // layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30)) // layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0)) layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30)) layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8)) } } // MARK: - MessagesDisplayDelegate extension BasicExampleViewController: MessagesDisplayDelegate { // MARK: - Text Messages func textColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor { return isFromCurrentSender(message: message) ? .white : .darkText } func detectorAttributes(for detector: DetectorType, and message: MessageType, at indexPath: IndexPath) -> [NSAttributedString.Key: Any] { return MessageLabel.defaultAttributes } func enabledDetectors(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> [DetectorType] { return [.url, .address, .phoneNumber, .date, .transitInformation,.hashtag,.mention] } // MARK: - All Messages func backgroundColor(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> UIColor { return isFromCurrentSender(message: message) ? .primaryColor : UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) } func messageStyle(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageStyle { let tail: MessageStyle.TailCorner = isFromCurrentSender(message: message) ? .bottomRight : .bottomLeft return .bubbleTail(tail, .curved) } func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) { let avatar = SampleData.shared.getAvatarFor(sender: message.sender) avatarView.set(avatar: avatar) } func configureAccessoryView(_ accessoryView: UIView, for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) { // Cells are reused, so only add a button here once. For real use you would need to // ensure any subviews are removed if not needed // guard accessoryView.subviews.isEmpty else { return } let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) button.setImage(UIImage(named: "delivery"), for: .normal) if message.isRead { button.tintColor = UIColor.purple } accessoryView.addSubview(button) button.frame = accessoryView.bounds button.isUserInteractionEnabled = false // respond to accessoryView tap through `MessageCellDelegate` accessoryView.layer.cornerRadius = accessoryView.frame.height / 2 accessoryView.backgroundColor = UIColor.primaryColor.withAlphaComponent(0.3) } // MARK: - Location Messages func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? { let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil) let pinImage = #imageLiteral(resourceName: "ic_map_marker") annotationView.image = pinImage annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2) return annotationView } func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? { return { view in view.layer.transform = CATransform3DMakeScale(2, 2, 2) UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: { view.layer.transform = CATransform3DIdentity }, completion: nil) } } func snapshotOptionsForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> LocationMessageSnapshotOptions { return LocationMessageSnapshotOptions(showsBuildings: true, showsPointsOfInterest: true, span: MKCoordinateSpan(latitudeDelta: 10, longitudeDelta: 10)) } } // MARK: - MessagesLayoutDelegate extension BasicExampleViewController: MessagesLayoutDelegate { func cellTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat { return 18 } func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat { return 20 } func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGFloat { return 16 } }
45.643836
169
0.729742
fbaa484af1775913f000d443de4c680f4c0bf626
6,500
// // SettingsViewModelTests.swift // URLRemote // // Created by Michal Švácha on 15/05/17. // Copyright © 2017 Svacha, Michal. All rights reserved. // import XCTest @testable import URLRemote class CategoryEditViewModelTests: XCTestCase { var viewModel: CategoryEditViewModel! override func setUp() { super.setUp() let entry1 = Entry(JSONString: "{\r\n\"firebaseKey\":\"abcdef\",\r\n\"order\":0,\r\n\"color\":4173881855,\r\n\"icon\":\"lightbulb_on\",\r\n\"name\":\"test\",\r\n\"requiresAuthentication\":true,\r\n\"user\":\"test_user\",\r\n\"password\":\"test_password\",\r\n\"type\":0,\r\n\"url\":\"https://www.seznam.cz\",\r\n\"customCriteria\":\"success\"\r\n}")! let entry2 = Entry(JSONString: "{\r\n\"firebaseKey\":\"ghijk\",\r\n\"order\":1,\r\n\"color\":4173881855,\r\n\"icon\":\"lightbulb_on\",\r\n\"name\":\"test\",\r\n\"requiresAuthentication\":true,\r\n\"user\":\"test_user\",\r\n\"password\":\"test_password\",\r\n\"type\":0,\r\n\"url\":\"https://www.seznam.cz\",\r\n\"customCriteria\":\"success\"\r\n}")! let entry3 = Entry(JSONString: "{\r\n\"firebaseKey\":\"lmnop\",\r\n\"order\":2,\r\n\"color\":4173881855,\r\n\"icon\":\"lightbulb_on\",\r\n\"name\":\"test\",\r\n\"requiresAuthentication\":true,\r\n\"user\":\"test_user\",\r\n\"password\":\"test_password\",\r\n\"type\":0,\r\n\"url\":\"https://www.seznam.cz\",\r\n\"customCriteria\":\"success\"\r\n}")! let category = Category(JSONString: "{\r\n\"firebaseKey\":\"abcdef\",\r\n\"order\":0,\r\n\"name\":\"category\",\r\n\"entryKeys\":[\"abcdef\",\"ghijk\",\"lmnop\"]\r\n}")! let dataSource = MockDataSource() dataSource.update(category) dataSource.update(entry1) dataSource.update(entry2) dataSource.update(entry3) viewModel = CategoryEditViewModel(dataSource: dataSource) viewModel.category = category } override func tearDown() { super.tearDown() } func testEntriesSetup() { XCTAssertTrue(viewModel.entries.count == 3) } func testCategoryRename() { XCTAssertEqual(viewModel.category!.name, "category") viewModel.renameCategory(name: "test") XCTAssertEqual(viewModel.category!.name, "test") } func testCategoryRemoval() { viewModel.removeCategory() XCTAssertEqual(viewModel.entries.count, 0) } func testReplacement() { XCTAssertTrue(viewModel.entries[2].firebaseKey == "lmnop") XCTAssertTrue(viewModel.entries[2].name == "test") XCTAssertTrue(viewModel.entries[2].icon == "lightbulb_on") let dataSource = viewModel.dataSource let entryReplacement = Entry(JSONString: "{\r\n\"firebaseKey\":\"lmnop\",\r\n\"order\":2,\r\n\"color\":4173881855,\r\n\"icon\":\"play\",\r\n\"name\":\"testReplacement\",\r\n\"requiresAuthentication\":true,\r\n\"user\":\"test_user\",\r\n\"password\":\"test_password\",\r\n\"type\":0,\r\n\"url\":\"https://www.seznam.cz\",\r\n\"customCriteria\":\"success\"\r\n}")! dataSource.update(entryReplacement) XCTAssertTrue(viewModel.entries[2].firebaseKey == "lmnop") XCTAssertTrue(viewModel.entries[2].name == "testReplacement") XCTAssertTrue(viewModel.entries[2].icon == "play") let entryNonExistent = Entry(JSONString: "{\r\n\"firebaseKey\":\"xyz\",\r\n\"order\":2,\r\n\"color\":4173881855,\r\n\"icon\":\"play\",\r\n\"name\":\"testReplacement\",\r\n\"requiresAuthentication\":true,\r\n\"user\":\"test_user\",\r\n\"password\":\"test_password\",\r\n\"type\":0,\r\n\"url\":\"https://www.seznam.cz\",\r\n\"customCriteria\":\"success\"\r\n}")! dataSource.update(entryNonExistent) let filtered = viewModel.entries.array .filter { $0.firebaseKey == "xyz" } XCTAssertTrue(filtered.count == 0) } func testAsyncShuffle() { XCTAssertTrue(viewModel.entries[0].firebaseKey == "abcdef") XCTAssertEqual(viewModel.entries[0].order, 0) XCTAssertTrue(viewModel.entries[1].firebaseKey == "ghijk") XCTAssertEqual(viewModel.entries[1].order, 1) XCTAssertTrue(viewModel.entries[2].firebaseKey == "lmnop") XCTAssertEqual(viewModel.entries[2].order, 2) let category = Category() category.firebaseKey = "testkey" viewModel.dataSource.move(viewModel.entries[0], from: viewModel.category!, to: category) XCTAssertTrue(viewModel.entries[0].firebaseKey == "ghijk") XCTAssertEqual(viewModel.entries[0].order, 0) XCTAssertTrue(viewModel.entries[1].firebaseKey == "lmnop") XCTAssertEqual(viewModel.entries[1].order, 1) } func testMove() { XCTAssertTrue(viewModel.entries[0].firebaseKey == "abcdef") XCTAssertTrue(viewModel.entries[0].order == 0) XCTAssertTrue(viewModel.entries[1].firebaseKey == "ghijk") XCTAssertTrue(viewModel.entries[1].order == 1) XCTAssertTrue(viewModel.entries[2].firebaseKey == "lmnop") XCTAssertTrue(viewModel.entries[2].order == 2) viewModel.moveItem(from: 2, to: 0) XCTAssertTrue(viewModel.entries[0].firebaseKey == "lmnop") XCTAssertTrue(viewModel.entries[0].order == 0) XCTAssertTrue(viewModel.entries[1].firebaseKey == "abcdef") XCTAssertTrue(viewModel.entries[1].order == 1) XCTAssertTrue(viewModel.entries[2].firebaseKey == "ghijk") XCTAssertTrue(viewModel.entries[2].order == 2) } func testRemove() { var dataArray = [Entry]() let tested = viewModel.dataSource.entries(under: viewModel.category!).observeNext { dataArray = $0 } /// Check that underlying data source starts with the same data XCTAssertTrue(dataArray.count == 3) viewModel.removeItem(index: 1) XCTAssertTrue(viewModel.entries.count == 2) /// Check that underlying data source has been altered as well XCTAssertTrue(dataArray.count == 2) /// View Model consistency check let orderArray = viewModel.entries.array.map { $0.order } XCTAssertTrue(orderArray[0] == 0 && orderArray[1] == 1) // Continued removal to reach needsShuffle == false on empty array viewModel.removeItem(index: 0) viewModel.removeItem(index: 0) XCTAssertTrue(viewModel.entries.isEmpty) tested.dispose() } }
48.87218
370
0.623846
2fb940e50222b51cc2ce6b5de9b13f1695cbf094
2,413
import Foundation import IndexStoreDB import Pathos #if canImport(Darwin) import func Darwin.fputs import func Darwin.exit import var Darwin.EXIT_FAILURE import var Darwin.stderr #else import func Glibc.fputs import func Glibc.exit import var Glibc.EXIT_FAILURE import var Glibc.stderr #endif import XCTest func bail(_ message: String) -> Never { fputs(message, stderr) exit(EXIT_FAILURE) } func shell(_ command: String) throws -> Data { let task = Process() task.executableURL = URL(fileURLWithPath: "/bin/bash") task.arguments = ["-c", command] let output = Pipe() task.standardOutput = output try task.run() task.waitUntilExit() return output.fileHandleForReading.readDataToEndOfFile() } func defaultPathToLibIndexStore() throws -> String { let outputData = try shell("swift -print-target-info") let json = try JSONSerialization.jsonObject(with: outputData) let pathToSwift = ((json as! [String: Any])["paths"] as! [String: Any])["runtimeResourcePath"] as! String #if os(macOS) return "\(Path(pathToSwift).parent.joined(with: "libIndexStore.dylib"))" #else return "\(Path(pathToSwift).parent.joined(with: "libIndexStore.so"))" #endif } var tempPath: String = "" do { tempPath = (try Path.makeTemporaryDirectory()).description } catch { bail("Failed to make a temporary directory") } let libIndexStore: IndexStoreLibrary do { libIndexStore = try IndexStoreLibrary(dylibPath: defaultPathToLibIndexStore()) } catch { bail("Could not initialize libIndexStore") } guard let indexStore = try? IndexStoreDB( storePath: ".build/debug/index/store", databasePath: tempPath, library: libIndexStore ) else { bail("Could not initialize index store") } indexStore.pollForUnitChangesAndWait() var defs = [String: [String]]() let occurs = indexStore.canonicalOccurrences( containing: "", anchorStart: false, anchorEnd: true, subsequence: false, ignoreCase: true ) .filter { occur in occur.roles.contains(.definition) && occur.location.isSystem && !occur.location.moduleName.isEmpty } for occur in occurs { defs[occur.location.moduleName, default: []].append("\(occur.symbol.name)\t\(occur.symbol.usr)") } print("Symbol Name\tUSR\tModule Name") for (module, list) in defs.sorted(by: { $0.key < $1.key }) { for symbol in list.sorted() { print("\(symbol)\t\(module)") } }
25.4
109
0.707418
1ddad6de762d544f88a0fd83929da9a86784a079
744
// // SonarItem.swift // Travelia // // Created by Juan David Cruz Serrano on 10/9/17. // Copyright © 2017 Juan David Cruz Serrano. All rights reserved. // import UIKit import Sonar class SonarItem: SonarItemView { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() self.imageView.layer.cornerRadius = self.imageView.frame.size.width/2 self.imageView.layer.masksToBounds = true self.imageView.contentMode = .scaleAspectFit } }
22.545455
77
0.659946
6421636b4d39c4e68d05f772e9d1c5efddf77c9e
966
import Foundation import CoreBluetooth @testable import RxBluetoothKit /// Deprecated, use _CentralManager.init(queue:options:onWillRestoreCentralManagerState:) instead @available(*, deprecated, renamed: "CentralManagerRestoredStateType") struct _RestoredState: CentralManagerRestoredStateType { let centralManagerRestoredState: _CentralManagerRestoredState var restoredStateData: [String: Any] { return centralManagerRestoredState.restoredStateData } var centralManager: _CentralManager { return centralManagerRestoredState.centralManager } var peripherals: [_Peripheral] { return centralManagerRestoredState.peripherals } var scanOptions: [String: AnyObject]? { return centralManagerRestoredState.scanOptions } var services: [_Service] { return centralManagerRestoredState.services } init(centralManagerRestoredState: _CentralManagerRestoredState) { self.centralManagerRestoredState = centralManagerRestoredState } }
40.25
97
0.81677
0e21c36db84c1320be80d0f40f356931947c69e2
1,008
// // Created by duan on 2018/3/7. // 2018 Copyright (c) RxSwiftCommunity. All rights reserved. // #if os(iOS) import UIKit import RxSwift import RxCocoa public extension ThemeProxy where Base: UIToolbar { /// (set only) bind a stream to barStyle public var barStyle: Observable<UIBarStyle> { get { return .empty() } set { let disposable = newValue .takeUntil(base.rx.deallocating) .observeOn(MainScheduler.instance) .bind(to: base.rx.barStyle) hold(disposable, for: "barStyle") } } /// (set only) bind a stream to barTintColor public var barTintColor: Observable<UIColor?> { get { return .empty() } set { let disposable = newValue .takeUntil(base.rx.deallocating) .observeOn(MainScheduler.instance) .bind(to: base.rx.barTintColor) hold(disposable, for: "barTintColor") } } } #endif
24.585366
61
0.578373
6a80de244e195ec2daa2459868f0fc7248992503
1,712
// // AchievementsPresenter.swift // Stash // // Created by Varun Mamindla on 4/18/21. // import Foundation protocol AchievementsPresenting { var title: String? { get } var noOfRows: Int { get } func onViewWillAppear() func achievementUIModel(for index: Int) -> AchievementViewState } final class AchievementsPresenter { private let interactor: AchievementsInteracting weak var view: AchievementsViewing? var achievementsInfo: AchievementInfo? init(view: AchievementsViewing, interactor: AchievementsInteracting = AchievementsInteractor()) { self.view = view self.interactor = interactor } var achievemnetsUIModel: [AchievementUIModel] { var uiModels = [AchievementUIModel]() uiModels = achievementsInfo?.achievements.map({ return AchievementUIModel(model: $0) }) ?? [] return uiModels } } extension AchievementsPresenter: AchievementsPresenting { var title: String? { return achievementsInfo?.title } var noOfRows: Int { return achievemnetsUIModel.count } func onViewWillAppear() { view?.showIndicator() interactor.fetchAchievemnts { [weak self] result in guard let strongSelf = self else { return } strongSelf.view?.hideIndicatior() switch result { case .failure: print("failure") case .success(let response): strongSelf.achievementsInfo = response strongSelf.view?.updateView() } } } func achievementUIModel(for index: Int) -> AchievementViewState { return achievemnetsUIModel[index] } }
27.174603
101
0.639603
23bd6c15ded75684b910ddebdfef0aa314c6e934
1,764
// // KeyboardAction+Test.swift // KeyboardKit // // Created by Daniel Saidi on 2019-05-11. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Quick import Nimble import KeyboardKit extension KeyboardAction { static var testActions: [KeyboardAction] { [ .none, .dismissKeyboard, .character(""), .characterMargin(""), .command, .control, .custom(named: ""), .dictation, .dismissKeyboard, .emoji(Emoji("")), .emojiCategory(.smileys), .escape, .function, .image(description: "", keyboardImageName: "", imageName: ""), .keyboardType(.alphabetic(.lowercased)), .keyboardType(.alphabetic(.uppercased)), .keyboardType(.alphabetic(.capsLocked)), .keyboardType(.numeric), .keyboardType(.symbolic), .keyboardType(.email), .keyboardType(.emojis), .keyboardType(.images), .keyboardType(.custom(named: "")), .moveCursorBackward, .moveCursorForward, .newLine, .nextKeyboard, .nextLocale, .option, .primary(.done), .primary(.go), .primary(.newLine), .primary(.ok), .primary(.search), .return, .shift(currentState: .lowercased), .shift(currentState: .uppercased), .shift(currentState: .capsLocked), .space, .systemImage(description: "", keyboardImageName: "", imageName: ""), .tab ] } }
27.138462
80
0.487528
08a1ea82efae34c49629515fb8798ceff224a810
5,364
// // IncrementalPhotosExporter.swift // PhotosExporter // // Created by Andreas Bentele on 21.03.18. // Copyright © 2018 Andreas Bentele. All rights reserved. // import Foundation /** * backup mode, like "Time Machine", which creates one folder per date and which is a real copy of the Photos Library data. */ class IncrementalPhotosExporter : PhotosExporter { override init(exporterConfig: ExporterConfig) { super.init(exporterConfig: exporterConfig) self.baseExportPath = exporterConfig.baseExportPath } private var latestPath: String { return "\(targetPath)/Latest" } override func initExport() throws { try super.initExport() } public var baseExportPath:String? public func initFlatFolderDescriptor(flatFolderPath: String) throws -> FlatFolderDescriptor { var lastCountSubFolders = 0 if fileManager.fileExists(atPath: flatFolderPath) { let urls = try fileManager.contentsOfDirectory( at: URL(fileURLWithPath: flatFolderPath), includingPropertiesForKeys: [.isDirectoryKey], options: [.skipsHiddenFiles] ) for url in urls { if let folderNumber = Int(url.lastPathComponent) { if (folderNumber >= lastCountSubFolders) { lastCountSubFolders = folderNumber+1 } } } logger.debug("lastCountSubFolders: \(lastCountSubFolders)") return FlatFolderDescriptor(folderName: flatFolderPath, countSubFolders: lastCountSubFolders) } throw FileNotFoundException.fileNotFound } override func exportFoldersFlat() throws { if exportOriginals { logger.info("export originals photos to \(inProgressPath)/\(originalsRelativePath)/\(flatRelativePath) folder") var candidatesToLinkTo: [FlatFolderDescriptor] = [] if let baseExportPath = baseExportPath { candidatesToLinkTo = try candidatesToLinkTo + flatFolderIfExists("\(baseExportPath)/\(originalsRelativePath)/\(flatRelativePath)") } candidatesToLinkTo = try candidatesToLinkTo + flatFolderIfExists("\(latestPath)/\(originalsRelativePath)/\(flatRelativePath)") try exportFolderFlat( flatPath: "\(inProgressPath)/\(originalsRelativePath)/\(flatRelativePath)", candidatesToLinkTo: candidatesToLinkTo, exportOriginals: true) } if exportCalculated { logger.info("export calculated photos to \(inProgressPath)/\(calculatedRelativePath)/\(flatRelativePath) folder") var candidatesToLinkTo: [FlatFolderDescriptor] = [] if let baseExportPath = baseExportPath { candidatesToLinkTo = try candidatesToLinkTo + flatFolderIfExists("\(baseExportPath)/\(calculatedRelativePath)/\(flatRelativePath)") } candidatesToLinkTo = try candidatesToLinkTo + flatFolderIfExists("\(latestPath)/\(calculatedRelativePath)/\(flatRelativePath)") if exportOriginals { candidatesToLinkTo = try candidatesToLinkTo + flatFolderIfExists("\(inProgressPath)/\(originalsRelativePath)/\(flatRelativePath)") } try exportFolderFlat( flatPath: "\(inProgressPath)/\(calculatedRelativePath)/\(flatRelativePath)", candidatesToLinkTo: candidatesToLinkTo, exportOriginals: false) } } func flatFolderIfExists(_ flatFolderPath: String) throws -> [FlatFolderDescriptor] { if fileManager.fileExists(atPath: flatFolderPath) { return [try initFlatFolderDescriptor(flatFolderPath: flatFolderPath)] } return [] } /** * Finish the filesystem structures; invariant: * if no folder "InProgress" but folders with date exist, and there is a symbolic link "Latest", there was no error. */ override func finishExport() throws { try super.finishExport() // remove the "Latest" symbolic link do { if fileManager.fileExists(atPath: latestPath) { try fileManager.removeItem(atPath: latestPath) } } catch { logger.error("Error removing link 'Latest': \(error) => abort export") throw error } // rename "InProgress" folder to export date let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss" let formattedDate = dateFormatter.string(from: Date()) let newBackupPath = "\(targetPath)/\(formattedDate)" do { try fileManager.moveItem(atPath: inProgressPath, toPath: newBackupPath) } catch { logger.error("Error renaming InProgress folder: \(error) => abort export") throw error } // create new "Latest" symbolic link do { try fileManager.createSymbolicLink(atPath: latestPath, withDestinationPath: newBackupPath) } catch { logger.error("Error recreating link 'Latest': \(error) => abort export") throw error } } }
37.774648
147
0.620433
9b0c5fc78f3e478b673b44c1de34f57b3565c612
2,640
// // ScaledFont.swift // ScaledFontSample // // Created by Thibaut Schmitt on 29/07/2020. // Copyright © 2020 Thibaut Schmitt. All rights reserved. // #if canImport(UIKit) import UIKit public final class SKScaledFont { private struct FontDescription: Decodable { let fontSize: CGFloat let fontName: String } private typealias StyleDictionary = [UIFont.TextStyle.RawValue: FontDescription] private var styleDictionary: StyleDictionary? public convenience init(style: KeyPath<SKScaledFontStyle, String>) { let fontStyle = SKScaledFontStyle() self.init(textStylesFilename: fontStyle[keyPath: style]) } /// Create a `ScaledFont` /// /// - Parameter fontName: Name of a plist file (without the extension) /// in the main bundle that contains the style dictionary used to /// scale fonts for each text style. private init(textStylesFilename: String) { // Compute filename let sizeFilename = "\(textStylesFilename)-\(Int(UIScreen.main.bounds.height))h" // Get configuration file if let url = Bundle.main.url(forResource: sizeFilename, withExtension: "plist"), let data = try? Data(contentsOf: url) { decodePlistData(data) } else if let url = Bundle.main.url(forResource: textStylesFilename, withExtension: "plist"), let data = try? Data(contentsOf: url) { decodePlistData(data) } } private func decodePlistData(_ data: Data) { let decoder = PropertyListDecoder() styleDictionary = try? decoder.decode(StyleDictionary.self, from: data) } /// Get the scaled font for the given text style using the /// style dictionary supplied at initialization. /// /// - Parameter textStyle: The `UIFontTextStyle` for the /// font. /// - Returns: A `UIFont` of the custom font that has been /// scaled for the users currently selected preferred /// text size. /// /// - Note: If the style dictionary does not have /// a font for this text style the default preferred /// font is returned. public func font(forTextStyle textStyle: UIFont.TextStyle) -> UIFont { guard let fontDescription = styleDictionary?[textStyle.rawValue], let font = UIFont(name: fontDescription.fontName, size: fontDescription.fontSize) else { return UIFont.preferredFont(forTextStyle: textStyle) } let fontMetrics = UIFontMetrics(forTextStyle: textStyle) return fontMetrics.scaledFont(for: font) } } #endif
36.164384
101
0.653409
67f55241c1586f50168e6e8e15171d1e41a37a6b
350
// // Copyright © 2021 Tasuku Tozawa. All rights reserved. // import Combine import Foundation public protocol ClipSearchHistoryService { func append(_ history: ClipSearchHistory) func remove(historyHaving id: UUID) func removeAll() func read() -> [ClipSearchHistory] func query() -> AnyPublisher<[ClipSearchHistory], Never> }
23.333333
60
0.725714
2047b470b4d443d34b60b16fbb2403bb971ac8e3
867
// // FollowViewController.swift // DouYuLive-Swift // // Created by lidong on 2018/8/5. // Copyright © 2018年 macbook. All rights reserved. // import UIKit class FollowViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.083333
106
0.672434
e49409cd1f786c76806a780ed693c10ea206b73a
696
// // DesignableTableView.swift // PetWorld // // Created by my mac on 7/3/17. // Copyright © 2017 GangsterSwagMuffins. All rights reserved. // import UIKit @IBDesignable class DesignableTableView: UITableView { @IBInspectable var backgroundImage: UIImage?{ didSet{ let imageView = UIImageView() imageView.image = backgroundImage self.backgroundView = imageView } } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
19.885714
78
0.609195
72ec9023685b2852391f4924794e08dd1f319713
6,539
import Foundation // MARK: - ThrowingLog /// 异常处理的方法集 public enum ThrowingLog { public static func debug(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) throws { try collect(level: .debug, subject: subject, file: file, function: function, line: line, time: time) } public static func info(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) throws { try collect(level: .info, subject: subject, file: file, function: function, line: line, time: time) } public static func warning(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) throws { try collect(level: .warning, subject: subject, file: file, function: function, line: line, time: time) } public static func error(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) throws { try collect(level: .error, subject: subject, file: file, function: function, line: line, time: time) } fileprivate static func collect(level: Message.Level, subject: Any?, file: String, function: String, line: Int, time: Date, process: ProcessInfo = ProcessInfo.processInfo, thread: Thread = Thread.current, threadID: UInt32 = pthread_mach_thread_np(pthread_self())) throws { let message: Message = .init(subject: subject, level: level, time: time, environment: .init(location: .init(file: file, line: line, function: function), threadInfo: .init(threadID: threadID, thread: thread, process: process))) try Collector.shared.collect(message) } } // MARK: - HandyLog /// 便捷的方法集 public enum HandyLog { public static func debug(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) { collect(level: .debug, subject: subject, file: file, function: function, line: line, time: time) } public static func info(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) { collect(level: .info, subject: subject, file: file, function: function, line: line, time: time) } public static func warning(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) { collect(level: .warning, subject: subject, file: file, function: function, line: line, time: time) } public static func error(_ subject: Any?, file: String = #file, function: String = #function, line: Int = #line, time: Date = Date()) { collect(level: .error, subject: subject, file: file, function: function, line: line, time: time) } fileprivate static func collect(level: Message.Level, subject: Any?, file: String, function: String, line: Int, time: Date) { do { try ThrowingLog.collect(level: level, subject: subject, file: file, function: function, line: line, time: time) } catch { if isDebug { print(error) } } } } extension HandyLog { /// 是否调试,调试模式会在标准输出中打印采集失败的原因 static var isDebug = false } // MARK: - ObjCLog @objc(DPObjCLog) public final class ObjCLog: NSObject { @objc public static func debug(_ subject: Any?, file: String, function: String, line: Int, time: Date) { HandyLog.debug(subject, file: file, function: function, line: line, time: time) } @objc public static func info(_ subject: Any?, file: String, function: String, line: Int, time: Date) { HandyLog.info(subject, file: file, function: function, line: line, time: time) } @objc public static func warning(_ subject: Any?, file: String, function: String, line: Int, time: Date) { HandyLog.warning(subject, file: file, function: function, line: line, time: time) } @objc public static func error(_ subject: Any?, file: String, function: String, line: Int, time: Date) { HandyLog.error(subject, file: file, function: function, line: line, time: time) } }
40.364198
123
0.414284
c1fab591ee005fde66c664774733be159a4633da
11,372
#!/usr/bin/env xcrun swift // Name: clq (Command Line Quiz) // Version: 0.0.5 // Release: 1 // License: CC-BA (Creative Commons By Attribution) // http://creativecommons.org/licenses/by/4.0/legalcode // Group: System // Source: N/A // URL: http://lateralblast.com.au/ // Distribution: UNIX // Vendor: UNIX // Packager: Richard Spindler <[email protected]> // Description: A POC swift code to turn a formatted csv file into multiple choice quiz import Darwin import Foundation extension Array { func shuffled() -> [Element] { var results = [Element]() var indexes = (0 ..< count).map { $0 } while indexes.count > 0 { let indexOfIndexes = Int(arc4random_uniform(UInt32(indexes.count))) let index = indexes[indexOfIndexes] results.append(self[index]) indexes.remove(at: indexOfIndexes) } return results } func sample() -> Element { let randomIndex = Int(arc4random()) % count return self[randomIndex] } } let script = CommandLine.arguments[0] func file_to_array(file: String) -> [String] { let path = NSString(string: file).expandingTildeInPath if let text = try? String(contentsOfFile:path, encoding: String.Encoding.utf8) { let lines = text.components(separatedBy: "\n") return lines } else { return [] } } func print_usage(file: String) -> Void { print("") print("Usage \(file)") print("") let lines = file_to_array(file: file) for line in lines { if var _ = line.range(of: "-[a-z,A-Z]", options: .regularExpression) { if line.range(of: "License|regularExpression", options: .regularExpression) == nil { var output = line.replacingOccurrences(of: "case", with: "") output = output.replacingOccurrences(of: "// ", with: "") output = output.replacingOccurrences(of: "^\\s+", with: "", options: .regularExpression) print(output) } } } print("") exit(0) } func print_version(file: String) -> Void { let lines = file_to_array(file: file) for line in lines { if var _ = line.range(of: "^// Version", options: .regularExpression) { var version = line.components(separatedBy: ":")[1] version = version.replacingOccurrences(of: " ", with: "") print(version) } } exit(0) } func list_quizes() -> Void { print("Available quizes:") let fd = FileManager.default fd.enumerator(atPath: "quizes")?.forEach({ (e) in if let e = e as? String, let url = URL(string: e) { print(url) } }) exit(0) } func wrap_text(text: String, indent: String) -> String { var count = 0 let fields = text.components(separatedBy: " ") var array = [String]() for field in fields { let length = field.characters.count if count + length < 80 { array.append("\(field) ") count = count + length } else { array.append("\(field)\n\(indent)") count = 0 } } let result = array.joined(separator: "") return result } func sort_answer(text: String) -> String { var result = text.replacingOccurrences(of: " |,", with: "", options: .regularExpression) var array = Array(result.characters) array = array.sorted { $0 < $1 } result = array.map({String(describing: $0)}).joined(separator: "") return result } func print_results(no_quest: Int, no_right: Int, no_wrong: Int) -> Void { let white = "\u{001B}[0;37m" var percentage :Double = 0 if no_quest != 0 { percentage = (Double(no_right) / Double(no_quest)) * 100 percentage = Double(round(10*percentage)/10) } print("\(white)") print("Results:") print("") print("Questions: \(no_quest)") print("Correct: \(no_right)") print("Wrong: \(no_wrong)") if no_quest != 0 { print("Percentage: \(percentage)") } print("") exit(0) } func handle_quiz(file: String, random: Int) -> Void { var no_quest = 0 var no_right = 0 var no_wrong = 0 let green = "\u{001B}[0;32m" let red = "\u{001B}[0;31m" let white = "\u{001B}[0;37m" var lines = file_to_array(file: file) if lines.count < 1 { print("") print("Quiz contains no questions") print("") exit(0) } var choices = [ "a", "b", "c", "d", "e" ] let f_nos = [ 2, 3, 4, 5, 6 ] var q_mix = [String]() if random > 0 { choices = choices.shuffled() lines = lines.shuffled() } if random == 2 { for line in lines { if line.characters.count > 0 { if var _ = line.range(of: "|", options: .regularExpression) { if let fields = line.components(separatedBy: "|") as [String]? { if let question = fields[0] as String? { if question != "Question" { for f_no in f_nos { let string = fields[f_no] if var _ = string.range(of: "[A-Z,a-z,0-9]", options: .regularExpression) { q_mix.append(string) } } } } } } } } } for line in lines { if line.characters.count > 0 { if var _ = line.range(of: "|", options: .regularExpression) { if let fields = line.components(separatedBy: "|") as [String]? { if var question = fields[0] as String? { if question != "Question" { var correct = String() var answer = String() var counter = 0 var t_answer = fields[1] t_answer = sort_answer(text: t_answer) t_answer = t_answer.lowercased() var array = [String]() let letters = Array(t_answer.characters) for letter in letters { let upper = String(letter).uppercased() let value = String(letter).unicodeScalars.first?.value var count: Int = Int(value!) count = count - 95 var string = fields[count] string = "\(upper): \(string)" string = wrap_text(text: string, indent: " ") array.append(string) } let t_correct = array.map({String(describing: $0)}).joined(separator: "") question = wrap_text(text: question, indent: "") print("\(white)\(question)") print("") switch random { case 1, 2: var r_answer = [String]() var r_correct = [String]() for choice in choices { let number: Int = 65 + counter var t_string = String() let letter = String(format: "%c", number) as String let value = String(choice).unicodeScalars.first?.value var count: Int = Int(value!) count = count - 95 var string = fields[count] let c_array = Array(t_answer.characters) if var _ = string.range(of: "[A-Z,a-z,0-9]", options: .regularExpression) { if c_array.contains(Character(choice.lowercased())) { r_answer.append(letter.lowercased()) var r_string = "\(letter) \(string)" r_string = wrap_text(text: r_string, indent: " ") t_string = string r_correct.append(r_string) } else { if random == 2 { var c_string = String() var c_check = 1 while c_check == 1 { c_string = q_mix.sample() if fields.contains(c_string) { c_check = 1 } else { c_check = 0 } } t_string = c_string } else { t_string = string } } string = wrap_text(text: t_string, indent: " ") print("\(letter): \(t_string)") counter = counter + 1 } } r_answer = r_answer.sorted { $0 < $1 } answer = r_answer.map({String(describing: $0)}).joined(separator: "") correct = r_correct.map({String(describing: $0)}).joined(separator: "") default: for choice in choices { let upper = String(choice).uppercased() let value = String(choice).unicodeScalars.first?.value var count: Int = Int(value!) count = count - 95 var string = fields[count] if var _ = string.range(of: "[A-Z,a-z,0-9]", options: .regularExpression) { string = wrap_text(text: string, indent: " ") print("\(upper): \(string)") } } correct = t_correct answer = t_answer } print("") print("Answer: ", terminator: "") var response = readLine() response = response!.lowercased() response = sort_answer(text: response!) no_quest = no_quest + 1 switch response! { case "q", "quit", "exit": no_quest = no_quest - 1 print_results(no_quest: no_quest, no_right: no_right, no_wrong: no_wrong) case answer: print("") print("\(green)\(correct)") no_right = no_right + 1 default: print("") print("\(red)\(correct)") no_wrong = no_wrong + 1 } } } print("") } } } } print_results(no_quest: no_quest, no_right: no_right, no_wrong: no_wrong) print("") } if CommandLine.arguments.count == 1 { print_usage(file: script) } var argument = CommandLine.arguments[1] switch argument { case "h", "-h": // Print Usage print_usage(file: script) case "V", "-V": // Print Version print_version(file: script) case "l", "-l": // List Quizes list_quizes() case "q", "-q": // Perform quiz if CommandLine.arguments.count > 2 { var quiz = CommandLine.arguments[2] var random = 0 if quiz.range(of: "quizes/", options: .regularExpression) == nil { quiz = "quizes/\(quiz)" } if CommandLine.arguments.count == 4 { let mode = CommandLine.arguments[3] switch mode { case "s", "-s", "--shuffle": random = 1 case "r", "-r", "--random": random = 2 default: random = 0 } } else { random = 0 } handle_quiz(file: quiz, random: random) } else { print("No quiz specified") } default: print_usage(file: script); }
32.962319
100
0.497626
fb86952f8c9ea3d744a5f267e11532f1beae7731
12,779
// Evolver.swift // Genetics // // Copyright (c) 2018 Colin Campbell // // 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 /// An error produced by an instances of `Evolver`. public enum EvolverError: Error, CustomStringConvertible { public var description: String { switch self { case .populationCount: return "A population must have at least one member." case .crossoverPointCount(let count, let chromosomeLength): return "Crossover point count \(count) must be less than chromosome's length \(chromosomeLength)." case .elitismCount(let count, let populationSize): return "Elitism count \(count) must be less than or equal to populationSize \(populationSize)." } } /// An error thrown when attempting to evolve a population with no chromosomes. case populationCount /// An error thrown when a point crossover's count is not less than the number of elements in a chromosome. case crossoverPointCount(count: Int, chromosomeLength: Int) /// An error thrown when the elitism count is not less than or equal to the population size. case elitismCount(count: Int, populationSize: Int) } /// Evolves a population. public final class Evolver { // MARK: Properties /// The evolver's configuration. public var configuration: EvolverConfiguration /// Whether or not the evolver should perform crossover. private var shouldCrossover: Bool { return Double(arc4random()) / Double(UInt32.max) <= configuration.crossoverRate } /// Whether or not the evolver should perform mutation. private var shouldMutate: Bool { return Double(arc4random()) / Double(UInt32.max) < configuration.mutationRate } // MARK: Initializers /// Initializes an `Evolver`. /// /// - Parameter configuration: The evolver's configuration. public init(configuration: EvolverConfiguration) { self.configuration = configuration } } extension Evolver { /// Evolves a population. /// /// - Parameters: /// - population: The population to evolve. /// - shouldContinue: This closure is called after each evolution cycle and returns whether or not the evolver should continue evolving the population. /// Passing nil for this parameter evolves the population once. public func evolve(population: inout Population, shouldContinue: ((_ configuration: inout EvolverConfiguration, _ population: Population) -> Bool)? = nil) throws { guard population.populationSize > 0 else { throw EvolverError.populationCount } if case let CrossoverMethod.point(count) = configuration.crossoverMethod, count >= population.chromosomes[0].count { throw EvolverError.crossoverPointCount(count: count, chromosomeLength: population.chromosomes[0].count) } if case let ElitismType.apply(count) = configuration.elitism, count > population.populationSize { throw EvolverError.elitismCount(count: count, populationSize: population.populationSize) } calculateFitnesses(in: &population) repeat { let newChromosomes = breedSingleGeneration(from: &population) population.chromosomes = newChromosomes population.generation += 1 calculateFitnesses(in: &population) } while shouldContinue == nil ? false : shouldContinue!(&configuration, population) } } extension Evolver { /// Calculates the fitness of a chromosome and sets the chromosome's `fitness` and `weight` properties. /// /// - Parameter population: A population of chromosomes. private func calculateFitnesses(in population: inout Population) { for i in 0 ..< population.populationSize { let error = configuration.fitnessFunction(population.chromosomes[i]) if error < 0.0 { print("Warning: negative error value \(error) may cause strange results.") } if error == .nan || error == .infinity || error == .signalingNaN { population.chromosomes[i].error = Double.greatestFiniteMagnitude } else { population.chromosomes[i].error = error } population.chromosomes[i].weight = Double.greatestFiniteMagnitude - population.chromosomes[i].error } population.chromosomes.sort(by: { $0.error > $1.error }) } /// Breeds a single generation of chromosomes. /// /// - Parameter population: A population of chromosomes. /// - Returns: A new generation of chromosomes. private func breedSingleGeneration(from population: inout Population) -> [Chromosome] { var newChromosomes = [Chromosome]() applyElitism(to: population, placeIn: &newChromosomes) for _ in newChromosomes.count ..< population.populationSize { newChromosomes.append(breedChild(from: &population)) } return newChromosomes } /// Applies elitism to a population of chromosomes. /// /// - Parameters: /// - population: A population of chromosomes. /// - newChromosomes: The array to add the selected chromosomes to. private func applyElitism(to population: Population, placeIn newChromosomes: inout [Chromosome]) { guard case let ElitismType.apply(count) = configuration.elitism, count > 0 else { return } for i in 0 ..< count { newChromosomes.append(population.chromosomes[population.populationSize - i - 1]) } } /// Breeds a child chromosome from a population. /// /// - Parameter population: A population of chromosomes. /// - Returns: A child chromosome. private func breedChild(from population: inout Population) -> Chromosome { var child: Chromosome if shouldCrossover { child = crossover(between: selectParent(from: &population), and: selectParent(from: &population)) } else { child = selectParent(from: &population) } if shouldMutate { child = configuration.mutationFunction(child) } return child } /// Selects a parent from a population for breeding. /// /// - Parameter population: A population of chromosomes. /// - Returns: A parent chromosome. private func selectParent(from population: inout Population) -> Chromosome { switch configuration.selectionMethod { case .custom(let function): return function(population.chromosomes) case .rank: return rankSelection(from: &population) case .roulette: return rouletteSelection(from: &population) case .tournament: return tournamentSelection(from: &population) } } /// Performs crossover between two chromosomes. /// /// - Note: Order does not matter. /// /// - Parameters: /// - firstChromosome: The first chromosome. /// - secondChromosome: The second chromosome. /// - Returns: A hybrid chromosome. private func crossover(between firstChromosome: Chromosome, and secondChromosome: Chromosome) -> Chromosome { switch configuration.crossoverMethod { case .custom(let function): return function(firstChromosome, secondChromosome) case .point(let count): return pointCrossover(between: firstChromosome, and: secondChromosome, points: count) case .uniform: return uniformCrossover(between: firstChromosome, and: secondChromosome) } } } // MARK: Selection functions extension Evolver { /// Performs rank selection on a population. /// /// - Parameter population: A population of chromosomes. /// - Returns: A chromosome. private func rankSelection(from population: inout Population) -> Chromosome { for i in 0 ..< population.populationSize { population.chromosomes[i].weight = Double(i + 1) } let total = UInt32(population.chromosomes.map { $0.weight }.reduce(0, +)) let rand = Double(arc4random_uniform(total)) var sum: Double = 0.0 for chromosome in population.chromosomes { sum += chromosome.weight if rand < sum { return chromosome } } return Chromosome() } /// Performs roulette selection on a population. /// /// - Parameter population: A population of chromosomes. /// - Returns: A chromosome. private func rouletteSelection(from population: inout Population) -> Chromosome { let total = population.chromosomes.map { $0.weight }.reduce(0, +) for i in 0 ..< population.populationSize { population.chromosomes[i].weight = population.chromosomes[i].weight / total } let count = population.chromosomes.filter({ $0.weight < 0.0 }).count if count > 0 { print("Population contains \(count) chromosomes with fitness < 0.0 which may result in bad roulette selection.") guard let min = population.chromosomes.min(by: { $0.weight < $1.weight }) else { return Chromosome(repeatElement(0.0, count: population.chromosomes[0].count)) } for i in 0 ..< population.populationSize { population.chromosomes[i].weight += min.weight } } let rand = Double(arc4random()) / Double(UInt32.max) var sum: Double = 0.0 for chromosome in population.chromosomes { sum += chromosome.weight if rand < sum { return chromosome } } return population.chromosomes[0] } /// Performs tournament selection on a population. /// /// - Parameter population: A population of chromosomes. /// - Returns: A chromosome. private func tournamentSelection(from population: inout Population) -> Chromosome { population.chromosomes.shuffle() let rand = arc4random_uniform(UInt32(population.chromosomes.count - 1)) + 1 let tournamentGroup = [Chromosome](population.chromosomes[0 ..< Int(rand)]) return tournamentGroup.max(by: { $0.weight < $1.weight })! } } // MARK: Crossover functions extension Evolver { /// Performs point crossover between two chromosomes. /// /// - Note: Order does not matter. /// /// - Parameters: /// - firstChromosome: The first chromosome. /// - secondChromosome: The second chromosome. /// - points: The number of crossover points. /// - Returns: A hybrid chromosome. private func pointCrossover(between firstChromosome: Chromosome, and secondChromosome: Chromosome, points: Int) -> Chromosome { var child = Chromosome(repeatElement(0.0, count: firstChromosome.count)) var indexes = [Int](repeating: 0, count: firstChromosome.count - 1) for i in 0 ..< firstChromosome.count - 1 { indexes[i] = i + 1 } if indexes.count > 1 { for i in 0 ..< Int(indexes.count) - 1 { let j = Int(arc4random_uniform(UInt32(indexes.count) - UInt32(i))) + i if i == j { continue } indexes.swapAt(i, j) } } var crossoverPoints = [Int](indexes[0 ..< points]) crossoverPoints.sort(by: { $0 < $1 }) crossoverPoints.insert(0, at: 0) crossoverPoints.append(firstChromosome.count) for i in 0 ..< crossoverPoints.count - 1 { for j in crossoverPoints[i] ..< crossoverPoints[i + 1] { child[j] = i % 2 == 0 ? firstChromosome[j] : secondChromosome[j] } } return child } /// Performs uniform crossover between two chromosomes. /// /// - Note: Order does not matter. /// /// - Parameters: /// - firstChromosome: The first chromosome. /// - secondCrossover: The second chromosome. /// - Returns: A hybrid chromosome. private func uniformCrossover(between firstChromosome: Chromosome, and secondCrossover: Chromosome) -> Chromosome { var child = Chromosome(repeatElement(0.0, count: firstChromosome.count)) for i in 0 ..< firstChromosome.count { child[i] = arc4random_uniform(2) == 1 ? firstChromosome[i] : secondCrossover[i] } return child } }
34.631436
165
0.68143
76c5d375f8a30580b2397043bf6a71cd41117bb4
2,691
// // NVActivityIndicatorAnimationBallsBounce.swift // NVActivityIndicatorView // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #if canImport(UIKit) import UIKit class NVActivityIndicatorAnimationBallDoubleBounce: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor, secondaryColor: UIColor, lineWidth: CGFloat) { for index in (0...1) { bouncingBall(in: layer, size: size, color: color, startingAt: CACurrentMediaTime() + Double(index)) } } fileprivate func bouncingBall(in layer: CALayer, size: CGSize, color: UIColor, startingAt: CFTimeInterval) { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.duration = 2 scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.values = [-1, 0, -1] scaleAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) scaleAnimation.repeatCount = HUGE scaleAnimation.isRemovedOnCompletion = false let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color) let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height) scaleAnimation.beginTime = startingAt circle.frame = frame circle.opacity = 0.6 circle.add(scaleAnimation, forKey: "animation") layer.addSublayer(circle) } } #endif
42.046875
119
0.703084
4643916c5a7d2711c462f6bf5628d8ac73b00434
876
@testable import CouchTrackerCore import Moya import TMDBSwift let tmdbProviderMock = TMDBProviderMock() func createTMDBProviderMock(error: Error? = nil) -> TMDBProviderMock { return TMDBProviderMock(error: error) } final class TMDBProviderMock: TMDBProvider { lazy var movies: MoyaProvider<Movies> = MoyaProviderMock<Movies>.createProvider(error: error, target: Movies.self) lazy var shows: MoyaProvider<Shows> = MoyaProviderMock<Shows>.createProvider(error: error, target: Shows.self) lazy var configuration: MoyaProvider<ConfigurationService> = MoyaProviderMock<ConfigurationService>.createProvider(error: error, target: ConfigurationService.self) lazy var episodes: MoyaProvider<Episodes> = MoyaProviderMock<Episodes>.createProvider(error: error, target: Episodes.self) private let error: Error? init(error: Error? = nil) { self.error = error } }
38.086957
165
0.788813
bf2ea986b6f0b29ed5cfc2f2f3aaae83d5b3f365
461
// // UIColorExt.swift // Food-Delivery-Frontend-iOS // // Created by Bülent Barış Kılıç on 21.08.2021. // import UIKit extension UIColor { convenience init(hex: Int) { let components = ( R: CGFloat((hex >> 16) & 0xff) / 255, G: CGFloat((hex >> 08) & 0xff) / 255, B: CGFloat((hex >> 00) & 0xff) / 255 ) self.init(red: components.R, green: components.G, blue: components.B, alpha: 1) } }
21.952381
87
0.548807
69073819553a3c3ca4a10d6c866501ea3bc61da9
152
// // Macor.swift // empty // // Created by apple on 2019/1/11. // Copyright © 2019 xu. All rights reserved. // // 一些宏定义 入导航栏高度 import Foundation
12.666667
45
0.638158
38925ed9a3b089bbd7696b87b772ece4501f2bdf
1,212
// // ChuckNorrisJokesAppReduxUITests.swift // ChuckNorrisJokesAppReduxUITests // // Created by Mariusz Sut on 06/07/2019. // Copyright © 2019 Mariusz Sut. All rights reserved. // import XCTest class ChuckNorrisJokesAppReduxUITests: 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 // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // 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() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.628571
182
0.70297
c1ace2a2225a13cd98aef552a6971b9c896e162a
220
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing import Foundation extension NSSet { init<d: b> ( )
27.5
87
0.759091
7a0b7362d9aed432876ef31e9f0fd2eac881ec13
18,868
// // XCUIElement+Swipe.swift // AutoMate // // Created by Bartosz Janda on 06.04.2017. // Copyright © 2017 PGS Software. All rights reserved. // // swiftlint:disable file_length import Foundation import XCTest extension XCUIElement { // MARK: Properties /// Default number of swipes. public class var defaultSwipesCount: Int { return 15 } // MARK: Methods #if os(iOS) /// Perform swipe gesture on this view by swiping between provided points. /// /// It is an alternative to `swipeUp`, `swipeDown`, `swipeLeft` and `swipeBottom` methods provided by `XCTest`. /// It lets you specify coordinates on the screen (relative to the view on which the method is called). /// /// **Example:** /// /// ```swift /// let scroll = app.scrollViews.element /// scroll.swipe(from: CGVector(dx: 0, dy: 0), to: CGVector(dx: 1, dy: 1)) /// ``` /// /// - Parameters: /// - startVector: Relative point from which to start swipe. /// - stopVector: Relative point to end swipe. public func swipe(from startVector: CGVector, to stopVector: CGVector) { let pt1 = coordinate(withNormalizedOffset: startVector) let pt2 = coordinate(withNormalizedOffset: stopVector) pt1.press(forDuration: 0.05, thenDragTo: pt2) } #endif #if os(iOS) /// Swipes scroll view to reveal given element. /// /// **Example:** /// /// ```swift /// let scroll = app.scrollViews.element /// let button = scroll.buttons.element /// scroll.swipe(to: button) /// ``` /// /// - note: /// `XCTest` automatically does the scrolling during `tap()`, but the method is still useful in some situations, for example to reveal element from behind keyboard, navigation bar or user defined element. /// - note: /// This method assumes that element is scrollable and at least partially visible on the screen. /// /// - Parameters: /// - element: Element to scroll to. /// - avoid: Table of `AvoidableElement` that should be avoid while swiping, by default keyboard and navigation bar are passed. /// - app: Application instance to use when searching for keyboard to avoid. /// - orientation: Device orientation. public func swipe(to element: XCUIElement, avoid viewsToAvoid: [AvoidableElement] = [.keyboard, .navigationBar], from app: XCUIApplication = XCUIApplication(), orientation: UIDeviceOrientation = XCUIDevice.shared.orientation) { let scrollableArea = self.scrollableArea(avoid: viewsToAvoid, from: app, orientation: orientation) // Distance from scrollable area center to element center. func distanceVector() -> CGVector { return scrollableArea.center.vector(to: element.frame.center) } // Scroll until center of the element will be visible. var oldDistance = distanceVector().manhattanDistance while !scrollableArea.contains(element.frame.center) { // Max swipe offset in both directions. let maxOffset = maxSwipeOffset(in: scrollableArea) // Max possible distance to swipe (in points). // It cannot be bigger than `maxOffset`. let vector = distanceVector() let maxVector = CGVector( dx: max(min(vector.dx, maxOffset.width), -maxOffset.width), dy: max(min(vector.dy, maxOffset.height), -maxOffset.height) ) // Max possible distance to swipe (normalized). let maxNormalizedVector = normalize(vector: maxVector) // Center point. let center = centerPoint(in: scrollableArea) // Start and stop vectors. let (startVector, stopVector) = swipeVectors(from: center, vector: maxNormalizedVector) // Swipe. swipe(from: startVector, to: stopVector) // Stop scrolling if distance to element was not changed. let newDistance = distanceVector().manhattanDistance guard oldDistance > newDistance else { break } oldDistance = newDistance } } #endif #if os(iOS) /// Swipes scroll view to given direction until condition will be satisfied. /// /// A useful method to scroll collection view to reveal an element. /// In collection view, only a few cells are available in the hierarchy. /// To scroll to given element you have to provide swipe direction. /// It is not possible to detect when the end of the scroll was reached, that is why the maximum number of swipes is required (by default 10). /// The method will stop when the maximum number of swipes is reached or when the condition will be satisfied. /// /// **Example:** /// /// ```swift /// let collectionView = app.collectionViews.element /// let element = collectionView.staticTexts["More"] /// collectionView.swipe(to: .down, until: element.exists) /// ``` /// /// - Parameters: /// - direction: Swipe direction. /// - times: Maximum number of swipes (by default 10). /// - viewsToAvoid: Table of `AvoidableElement` that should be avoid while swiping, by default keyboard and navigation bar are passed. /// - app: Application instance to use when searching for keyboard to avoid. /// - orientation: Device orientation. /// - condition: The condition to satisfy. public func swipe(to direction: SwipeDirection, times: Int = XCUIElement.defaultSwipesCount, avoid viewsToAvoid: [AvoidableElement] = [.keyboard, .navigationBar], from app: XCUIApplication = XCUIApplication(), orientation: UIDeviceOrientation = XCUIDevice.shared.orientation, until condition: @autoclosure () -> Bool) { let scrollableArea = self.scrollableArea(avoid: viewsToAvoid, from: app, orientation: orientation) // Swipe `times` times in the provided direction. for _ in 0..<times { // Stop scrolling when condition will be satisfied. guard !condition() else { break } // Max swipe offset in both directions. let maxOffset = maxSwipeOffset(in: scrollableArea) /// Calculates vector for given direction. let vector: CGVector switch direction { case .up: vector = CGVector(dx: 0, dy: -maxOffset.height) case .down: vector = CGVector(dx: 0, dy: maxOffset.height) case .left: vector = CGVector(dx: -maxOffset.width, dy: 0) case .right: vector = CGVector(dx: maxOffset.width, dy: 0) } // Max possible distance to swipe (normalized). let maxNormalizedVector = normalize(vector: vector) // Center point. let center = centerPoint(in: scrollableArea) // Start and stop vectors. let (startVector, stopVector) = swipeVectors(from: center, vector: maxNormalizedVector) // Swipe. swipe(from: startVector, to: stopVector) } } #endif #if os(iOS) /// Swipes scroll view to given direction until element would exist. /// /// A useful method to scroll collection view to reveal an element. /// In collection view, only a few cells are available in the hierarchy. /// To scroll to given element you have to provide swipe direction. /// It is not possible to detect when the end of the scroll was reached, that is why the maximum number of swipes is required (by default 10). /// The method will stop when the maximum number of swipes is reached or when the given element will appear in the view hierarchy. /// /// **Example:** /// /// ```swift /// let collectionView = app.collectionViews.element /// let element = collectionView.staticTexts["More"] /// collectionView.swipe(to: .down, untilExist: element) /// ``` /// /// - note: /// This method will not scroll until the view will be visible. To do this call `swipe(to:untilVisible:times:avoid:app:)` after this method. /// /// - Parameters: /// - direction: Swipe direction. /// - element: Element to swipe to. /// - times: Maximum number of swipes (by default 10). /// - viewsToAvoid: Table of `AvoidableElement` that should be avoid while swiping, by default keyboard and navigation bar are passed. /// - app: Application instance to use when searching for keyboard to avoid. public func swipe(to direction: SwipeDirection, untilExist element: XCUIElement, times: Int = XCUIElement.defaultSwipesCount, avoid viewsToAvoid: [AvoidableElement] = [.keyboard, .navigationBar], from app: XCUIApplication = XCUIApplication()) { swipe(to: direction, times: times, avoid: viewsToAvoid, from: app, until: element.exists) } #endif #if os(iOS) /// Swipes scroll view to given direction until element would be visible. /// /// A useful method to scroll collection view to reveal an element. /// In collection view, only a few cells are available in the hierarchy. /// To scroll to given element you have to provide swipe direction. /// It is not possible to detect when the end of the scroll was reached, that is why the maximum number of swipes is required (by default 10). /// The method will stop when the maximum number of swipes is reached or when the given element will be visible. /// /// **Example:** /// /// ```swift /// let collectionView = app.collectionViews.element /// let element = collectionView.staticTexts["More"] /// collectionView.swipe(to: .down, untilVisible: element) /// ``` /// /// - note: /// This method will not scroll until the view will be visible. To do this call `swipe(to:avoid:from:)` after this method. /// /// - Parameters: /// - direction: Swipe direction. /// - element: Element to swipe to. /// - times: Maximum number of swipes (by default 10). /// - viewsToAvoid: Table of `AvoidableElement` that should be avoid while swiping, by default keyboard and navigation bar are passed. /// - app: Application instance to use when searching for keyboard to avoid. public func swipe(to direction: SwipeDirection, untilVisible element: XCUIElement, times: Int = XCUIElement.defaultSwipesCount, avoid viewsToAvoid: [AvoidableElement] = [.keyboard, .navigationBar], from app: XCUIApplication = XCUIApplication()) { swipe(to: direction, times: times, avoid: viewsToAvoid, from: app, until: element.isVisible) } #endif } // MARK: - Internal #if os(iOS) extension XCUIElement { // MARK: Properties /// Proportional horizontal swipe length. /// /// - note: /// To avoid swipe to back `swipeLengthX` is lower than `swipeLengthY`. var swipeLengthX: CGFloat { return 0.7 } /// Proportional vertical swipe length. var swipeLengthY: CGFloat { return 0.7 } // MARK: Methods /// Calculates scrollable area of the element by removing overlapping elements like keybard or navigation bar. /// /// - Parameters: /// - viewsToAvoid: Table of `AvoidableElement` that should be avoid while swiping, by default keyboard and navigation bar are passed. /// - app: Application instance to use when searching for keyboard to avoid. /// - orientation: Device orientation. /// - Returns: Scrollable area of the element. func scrollableArea(avoid viewsToAvoid: [AvoidableElement] = [.keyboard, .navigationBar], from app: XCUIApplication = XCUIApplication(), orientation: UIDeviceOrientation) -> CGRect { let scrollableArea = viewsToAvoid.reduce(frame) { $1.overlapReminder(of: $0, in: app, orientation: orientation) } // assert(scrollableArea.height > 0, "Scrollable view is completely hidden.") return scrollableArea } /// Maximum available swipe offsets (in points) in the scrollable area. /// /// It takes `swipeLengthX` and `swipeLengthY` to calculate values. /// /// - Parameter scrollableArea: Scrollable area of the element. /// - Returns: Maximum available swipe offsets (in points). func maxSwipeOffset(in scrollableArea: CGRect) -> CGSize { return CGSize( width: scrollableArea.width * swipeLengthX, height: scrollableArea.height * swipeLengthY ) } /// Normalize vector. From points to normalized values (<0;1>). /// /// - Parameter vector: Vector to normalize. /// - Returns: Normalized vector. func normalize(vector: CGVector) -> CGVector { return CGVector( dx: vector.dx / frame.width, dy: vector.dy / frame.height ) } /// Returns center point of the scrollable area in the element in the normalized coordinate space. /// /// - Parameter scrollableArea: Scrollable area of the element. /// - Returns: Center point of the scrollable area in the element in the normalized coordinate space. func centerPoint(in scrollableArea: CGRect) -> CGPoint { return CGPoint( x: (scrollableArea.midX - frame.minX) / frame.width, y: (scrollableArea.midY - frame.minY) / frame.height ) } /// Calculates swipe vectors from center point and swipe vector. /// /// Generated vectors can be used by `swipe(from:,to:)`. /// /// - Parameters: /// - center: Center point of the scrollable area. Use `centerPoint(with:)` to calculate this value. /// - vector: Swipe vector in the normalized coordinate space. /// - Returns: Swipes vector to use by `swipe(from:,to:)`. func swipeVectors(from center: CGPoint, vector: CGVector) -> (startVector: CGVector, stopVector: CGVector) { // Start vector. let startVector = CGVector( dx: center.x + vector.dx / 2, dy: center.y + vector.dy / 2 ) // Stop vector. let stopVector = CGVector( dx: center.x - vector.dx / 2, dy: center.y - vector.dy / 2 ) return (startVector, stopVector) } /// Calculates frame for given orientation. /// Due an open [issue](https://openradar.appspot.com/31529903). Coordinates works correctly only in portrait orientation. /// /// - Parameters: /// - orientation: Device /// - app: Application instance to use when searching for keyboard to avoid. /// - Returns: Calculated frame for given orientation. func frame(for orientation: UIDeviceOrientation, in app: XCUIApplication) -> CGRect { // Supports only landscape left, landscape right and upside down. // For all other unsupported orientations the default frame returned. guard orientation == .landscapeLeft || orientation == .landscapeRight || orientation == .portraitUpsideDown else { return frame } switch orientation { case .landscapeLeft: return CGRect(x: frame.minY, y: app.frame.width - frame.maxX, width: frame.height, height: frame.width) case .landscapeRight: return CGRect(x: app.frame.height - frame.maxY, y: frame.minX, width: frame.height, height: frame.width) case .portraitUpsideDown: return CGRect(x: app.frame.width - frame.maxX, y: app.frame.height - frame.maxY, width: frame.width, height: frame.height) default: preconditionFailure("Not supported orientation") } } } #endif // MARK: - AvoidableElement #if os(iOS) /// Each case relates to element of user interface that can overlap scrollable area. /// /// - `navigationBar`: equivalent of `UINavigationBar`. /// - `keyboard`: equivalent of `UIKeyboard`. /// - `other(XCUIElement, CGRectEdge)`: equivalent of user defined `XCUIElement` with `CGRectEdge` on which it appears. /// If more than one navigation bar or any other predefined `AvoidableElement` is expected, use `.other` case. /// Predefined cases assume there is only one element of their type. public enum AvoidableElement { /// Equivalent of `UINavigationBar`. case navigationBar /// Equivalent of `UIKeyboard`. case keyboard /// Equivalent of user defined `XCUIElement` with `CGRectEdge` on which it appears. case other(element: XCUIElement, edge: CGRectEdge) /// Edge on which `XCUIElement` appears. var edge: CGRectEdge { switch self { case .navigationBar: return .minYEdge case .keyboard: return .maxYEdge case .other(_, let edge): return edge } } /// Finds `XCUIElement` depending on case. /// /// - Parameter app: XCUIAppliaction to search through, `XCUIApplication()` by default. /// - Returns: `XCUIElement` equivalent of enum case. func element(in app: XCUIApplication = XCUIApplication()) -> XCUIElement { switch self { case .navigationBar: return app.navigationBars.element case .keyboard: return app.keyboards.element case .other(let element, _): return element } } /// Calculates rect that reminds scrollable through substract overlaping part of `XCUIElement`. /// /// - Parameters: /// - rect: CGRect that is overlapped. /// - app: XCUIApplication in which overlapping element can be found. /// - Returns: Part of rect not overlapped by element. func overlapReminder(of rect: CGRect, in app: XCUIApplication, orientation: UIDeviceOrientation) -> CGRect { let overlappingElement = element(in: app) guard overlappingElement.exists else { return rect } let overlappingElementFrame: CGRect if case .keyboard = self { overlappingElementFrame = overlappingElement.frame(for: orientation, in: app) } else { overlappingElementFrame = overlappingElement.frame } let overlap: CGFloat switch edge { case .maxYEdge: overlap = rect.maxY - overlappingElementFrame.minY case .minYEdge: overlap = overlappingElementFrame.maxY - rect.minY default: return rect } return rect.divided(atDistance: max(overlap, 0), from: edge).remainder } } #endif // MARK: - SwipeDirection /// Swipe direction. /// /// - `up`: Swipe up. /// - `down`: Swipe down. /// - `left`: Swipe to the left. /// - `right`: Swipe to the right. public enum SwipeDirection { /// Swipe up. case up // swiftlint:disable:this identifier_name /// Swipe down. case down /// Swipe to the left. case left /// Swipe to the right. case right }
41.468132
250
0.640237
8f88563a05db27b6b1d2d8b8af58ed7109cce2b8
7,124
import WMF @objc(WMFNewsViewController) class NewsViewController: ColumnarCollectionViewController { fileprivate static let cellReuseIdentifier = "NewsCollectionViewCell" fileprivate static let headerReuseIdentifier = "NewsCollectionViewHeader" let stories: [WMFFeedNewsStory] let dataStore: MWKDataStore @objc required init(stories: [WMFFeedNewsStory], dataStore: MWKDataStore) { self.stories = stories self.dataStore = dataStore super.init() title = WMFLocalizedString("in-the-news-title", value:"In the news", comment:"Title for the 'In the news' notification & feed section") navigationItem.backBarButtonItem = UIBarButtonItem(title: WMFLocalizedString("back", value:"Back", comment:"Generic 'Back' title for back button\n{{Identical|Back}}"), style: .plain, target:nil, action:nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) not supported") } override func viewDidLoad() { super.viewDidLoad() register(NewsCollectionViewCell.self, forCellWithReuseIdentifier: NewsViewController.cellReuseIdentifier, addPlaceholder: false) register(UINib(nibName: NewsViewController.headerReuseIdentifier, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: NewsViewController.headerReuseIdentifier, addPlaceholder: false) collectionView?.allowsSelection = false } } // MARK: - UICollectionViewDataSource extension NewsViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return stories.count } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewsViewController.cellReuseIdentifier, for: indexPath) guard let newsCell = cell as? NewsCollectionViewCell else { return cell } if let layout = collectionViewLayout as? WMFColumnarCollectionViewLayout { cell.layoutMargins = layout.readableMargins } let story = stories[indexPath.section] newsCell.configure(with: story, dataStore: dataStore, theme: theme, layoutOnly: false) return newsCell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { switch kind { case UICollectionElementKindSectionHeader: let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NewsViewController.headerReuseIdentifier, for: indexPath) guard let header = view as? NewsCollectionViewHeader else { return view } header.label.text = headerTitle(for: indexPath.section) header.apply(theme: theme) return header default: //FIXME: According to docs looks like this will crash - "The view that is returned must be retrieved from a call to -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath:" return UICollectionReusableView() } } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? NewsCollectionViewCell else { return } cell.selectionDelegate = self } override func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? NewsCollectionViewCell else { return } cell.selectionDelegate = nil } static let headerDateFormatter: DateFormatter = { let headerDateFormatter = DateFormatter() headerDateFormatter.locale = Locale.autoupdatingCurrent headerDateFormatter.timeZone = TimeZone(secondsFromGMT: 0) headerDateFormatter.setLocalizedDateFormatFromTemplate("dMMMM") // Year is invalid on news content dates, we can only show month and day return headerDateFormatter }() func headerTitle(for section: Int) -> String? { let story = stories[section] guard let date = story.midnightUTCMonthAndDay else { return nil } return NewsViewController.headerDateFormatter.string(from: date) } } // MARK: - WMFColumnarCollectionViewLayoutDelegate extension NewsViewController { override func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> WMFLayoutEstimate { return WMFLayoutEstimate(precalculated: false, height: headerTitle(for: section) == nil ? 0 : 50) } override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> WMFLayoutEstimate { return WMFLayoutEstimate(precalculated: false, height: 350) } } // MARK: - SideScrollingCollectionViewCellDelegate extension NewsViewController: SideScrollingCollectionViewCellDelegate { func sideScrollingCollectionViewCell(_ sideScrollingCollectionViewCell: SideScrollingCollectionViewCell, didSelectArticleWithURL articleURL: URL) { wmf_pushArticle(with: articleURL, dataStore: dataStore, theme: self.theme, animated: true) } } // MARK: - UIViewControllerPreviewingDelegate extension NewsViewController { override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let collectionView = collectionView, let indexPath = collectionView.indexPathForItem(at: location), let cell = collectionView.cellForItem(at: indexPath) as? NewsCollectionViewCell else { return nil } let pointInCellCoordinates = collectionView.convert(location, to: cell) let index = cell.subItemIndex(at: pointInCellCoordinates) guard index != NSNotFound, let view = cell.viewForSubItem(at: index) else { return nil } let story = stories[indexPath.section] guard let previews = story.articlePreviews, index < previews.count else { return nil } previewingContext.sourceRect = view.convert(view.bounds, to: collectionView) let article = previews[index] return WMFArticleViewController(articleURL: article.articleURL, dataStore: dataStore, theme: self.theme) } override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { wmf_push(viewControllerToCommit, animated: true) } }
47.178808
239
0.719399
4a2d31039b7153f671f359facf07501f6b281652
141
/* Copyright 2017 Urban Airship and Contributors */ import AirshipAppExtensions class NotificationService: UAMediaAttachmentExtension { }
17.625
55
0.822695
e8b540ded505fa7510eee5be6a58d8d5c2f71fe0
3,205
import XCTest @testable import IpAddress import BigInt class IPv6MappedTest { let ip: IPAddress; let s: String; let sstr: String; let string: String; let u128: BigUInt; let address: String; var valid_mapped = [String: BigUInt](); var valid_mapped_ipv6 = [String: BigUInt](); var valid_mapped_ipv6_conversion = [String: String](); init(ip: IPAddress, s: String, sstr: String, string: String, u128: BigUInt, address: String) { self.ip = ip; self.s = s; self.sstr = sstr; self.string = string; self.u128 = u128; self.address = address; } } class Ipv6MappedTests: XCTestCase { func setup()-> IPv6MappedTest { let ipv6 = IPv6MappedTest( ip: Ipv6Mapped.create("::172.16.10.1")!, s: "::ffff:172.16.10.1", sstr: "::ffff:172.16.10.1/32", string: "0000:0000:0000:0000:0000:ffff:ac10:0a01/128", u128: BigUInt("281473568475649")!, address: "::ffff:ac10:a01/128" ); ipv6.valid_mapped["::13.1.68.3"] = BigUInt("281470899930115")!; ipv6.valid_mapped["0:0:0:0:0:ffff:129.144.52.38"] = BigUInt("281472855454758")!; ipv6.valid_mapped["::ffff:129.144.52.38"] = BigUInt("281472855454758")!; ipv6.valid_mapped_ipv6["::ffff:13.1.68.3"] = BigUInt("281470899930115")!; ipv6.valid_mapped_ipv6["0:0:0:0:0:ffff:8190:3426"] = BigUInt("281472855454758")!; ipv6.valid_mapped_ipv6["::ffff:8190:3426"] = BigUInt("281472855454758")!; ipv6.valid_mapped_ipv6_conversion["::ffff:13.1.68.3"] = "13.1.68.3"; ipv6.valid_mapped_ipv6_conversion["0:0:0:0:0:ffff:8190:3426"] = "129.144.52.38"; ipv6.valid_mapped_ipv6_conversion["::ffff:8190:3426"] = "129.144.52.38"; return ipv6; } func test_initialize() { let s = setup(); XCTAssertNotNil(IPAddress.parse("::172.16.10.1")!); for (ip, u128) in s.valid_mapped { // println("-{}--{}", ip, u128); XCTAssertNotNil(IPAddress.parse(ip)); XCTAssertEqual(u128, IPAddress.parse(ip)!.host_address); } for (ip, u128) in s.valid_mapped_ipv6 { // println("===={}=={:x}", ip, u128); XCTAssertNotNil(IPAddress.parse(ip)); XCTAssertEqual(u128, IPAddress.parse(ip)!.host_address); } } func test_mapped_from_ipv6_conversion() { for (ip6, ip4) in setup().valid_mapped_ipv6_conversion { XCTAssertEqual(ip4, IPAddress.parse(ip6)!.mapped!.to_s()); } } func test_attributes() { let s = setup(); XCTAssertEqual(s.address, s.ip.to_string()); XCTAssertEqual(128, s.ip.prefix.num); XCTAssertEqual(s.s, s.ip.to_s_mapped()); XCTAssertEqual(s.sstr, s.ip.to_string_mapped()); XCTAssertEqual(s.string, s.ip.to_string_uncompressed()); XCTAssertEqual(s.u128, s.ip.host_address); } func test_method_ipv6() { XCTAssertTrue(setup().ip.is_ipv6()); } func test_mapped() { XCTAssertTrue(setup().ip.is_mapped()); } static var allTests : [(String, (Ipv6MappedTests) -> () throws -> Void)] { return [ ("test_initialize", test_initialize), ("test_mapped_from_ipv6_conversion", test_mapped_from_ipv6_conversion), ("test_attributes", test_attributes), ("test_method_ipv6", test_method_ipv6), ("test_mapped", test_mapped), ] } }
34.095745
96
0.651482
56ea95625e36f8a75dd78fc03380bec58309eb7e
7,180
//// // 🦠 Corona-Warn-App // import XCTest import OpenCombine @testable import ENA class StatisticsProviderTests: CWATestCase { private var subscriptions = [AnyCancellable]() /// Tests the static mock data and general fetching mechanism func testFetchStaticStats() { let fetchedFromClientExpectation = expectation(description: "stats fetched from client") fetchedFromClientExpectation.expectedFulfillmentCount = 1 let store = MockTestStore() XCTAssertNil(store.appConfigMetadata) let client = CachingHTTPClientMock() client.fetchStatistics(etag: "foo") { result in switch result { case .success(let response): // StatisticsFetchingResponse XCTAssertEqual(response.stats.keyFigureCards.count, 11) XCTAssertEqual(response.stats.cardIDSequence.count, response.stats.keyFigureCards.count) case .failure(let error): XCTFail(error.localizedDescription) } fetchedFromClientExpectation.fulfill() } waitForExpectations(timeout: .medium) } func testFetchLiveStats() { let fetchedFromClientExpectation = expectation(description: "stats fetched from client") fetchedFromClientExpectation.expectedFulfillmentCount = 1 let store = MockTestStore() XCTAssertNil(store.statistics) let client = CachingHTTPClient() client.fetchStatistics(etag: "foo") { result in switch result { case .success(let response): // StatisticsFetchingResponse XCTAssertEqual(response.stats.keyFigureCards.count, 4) XCTAssertEqual(response.stats.cardIDSequence.count, response.stats.keyFigureCards.count) // check that we dont fetch mock data XCTAssertNotEqual(CachingHTTPClientMock.staticStatistics, response.stats) // caching is not done here but in `StatisticsProvider`! XCTAssertNil(store.statistics) case .failure(let error): XCTFail(error.localizedDescription) } fetchedFromClientExpectation.fulfill() } waitForExpectations(timeout: .medium) } func testStatisticsProviding() throws { let valueReceived = expectation(description: "Value received") valueReceived.expectedFulfillmentCount = 1 let store = MockTestStore() let client = CachingHTTPClientMock() let provider = StatisticsProvider(client: client, store: store) provider.statistics() .sink(receiveCompletion: { result in switch result { case .finished: break case .failure(let error): XCTFail(error.localizedDescription) } }, receiveValue: { stats in XCTAssertEqual(stats.keyFigureCards.count, 11) XCTAssertEqual(stats.cardIDSequence.count, stats.keyFigureCards.count) valueReceived.fulfill() }) .store(in: &subscriptions) waitForExpectations(timeout: .medium) } func testStatisticsProvidingHTTPErrors() throws { let responseReceived = expectation(description: "responseReceived") responseReceived.expectedFulfillmentCount = 1 let store = MockTestStore() let client = CachingHTTPClientMock() client.onFetchStatistics = { _, completeWith in // fake a broken backend let error = URLSessionError.serverError(503) completeWith(.failure(error)) } let provider = StatisticsProvider(client: client, store: store) provider.statistics() .sink(receiveCompletion: { result in switch result { case .finished: XCTFail("Did not expect a success") case .failure(let error): switch error { case URLSessionError.serverError(let code): XCTAssertEqual(code, 503) responseReceived.fulfill() default: XCTFail("Expected a different error") } } }, receiveValue: { _ in XCTFail("Did not expect a value") }) .store(in: &subscriptions) waitForExpectations(timeout: .medium) } func testStatisticsProvidingHttp304() throws { let checkpoint = expectation(description: "Value received") checkpoint.expectedFulfillmentCount = 2 // provide an already 'cached' data set let store = MockTestStore() store.statistics = StatisticsMetadata( stats: CachingHTTPClientMock.staticStatistics, eTag: "fake", timestamp: try XCTUnwrap(301.secondsAgo)) // Fake, backend returns HTTP 304 let client = CachingHTTPClientMock() client.onFetchStatistics = { _, completeWith in let error = URLSessionError.notModified completeWith(.failure(error)) checkpoint.fulfill() } // Request statistics... let provider = StatisticsProvider(client: client, store: store) provider.statistics() .sink(receiveCompletion: { result in switch result { case .finished: break case .failure(let error): XCTFail("Expected a no error, got: \(error)") } }, receiveValue: { stats in XCTAssertEqual(stats.keyFigureCards.count, 11) XCTAssertEqual(stats.cardIDSequence.count, stats.keyFigureCards.count) checkpoint.fulfill() }) .store(in: &subscriptions) waitForExpectations(timeout: .medium) } func testStatisticsProvidingCacheDecay() throws { let checkpoint = expectation(description: "Value received") checkpoint.expectedFulfillmentCount = 2 // provide an already 'cached' data set that's older than the max cache time for stats (300s) let store = MockTestStore() store.statistics = StatisticsMetadata( stats: CachingHTTPClientMock.staticStatistics, eTag: "fake", timestamp: try XCTUnwrap(301.secondsAgo)) // Fake, backend returns new data let client = CachingHTTPClientMock() client.onFetchStatistics = { _, completeWith in let response = StatisticsFetchingResponse(CachingHTTPClientMock.staticStatistics, "fake2") completeWith(.success(response)) checkpoint.fulfill() } // Request statistics... let provider = StatisticsProvider(client: client, store: store) provider.statistics() .sink(receiveCompletion: { result in switch result { case .finished: break case .failure(let error): XCTFail("Expected a no error, got: \(error)") } }, receiveValue: { stats in XCTAssertEqual(stats.keyFigureCards.count, 11) XCTAssertEqual(stats.cardIDSequence.count, stats.keyFigureCards.count) XCTAssertEqual(store.statistics?.lastStatisticsETag, "fake2") checkpoint.fulfill() }) .store(in: &subscriptions) waitForExpectations(timeout: .medium) } func testStatisticsProvidingInvalidCacheState() throws { let checkpoint = expectation(description: "Value received") checkpoint.expectedFulfillmentCount = 2 // Empty store let store = MockTestStore() // Simulate response for given ETag let client = CachingHTTPClientMock() client.onFetchStatistics = { _, completeWith in let error = URLSessionError.notModified completeWith(.failure(error)) checkpoint.fulfill() } // Request statistics... let provider = StatisticsProvider(client: client, store: store) provider.statistics() .sink(receiveCompletion: { result in switch result { case .finished: XCTFail("Expected an error!") case .failure(let error): switch error { case URLSessionError.notModified: checkpoint.fulfill() default: XCTFail("Expected a different error") } } }, receiveValue: { _ in XCTFail("not expected") }) .store(in: &subscriptions) waitForExpectations(timeout: .medium) } }
29.916667
95
0.731755
7abbddf5d8c7303a8abd0dcb470a936522f7932a
921
// // ParseConstants.swift // ParseSwift // // Created by Corey Baker on 9/7/20. // Copyright © 2020 Parse Community. All rights reserved. // import Foundation enum ParseConstants { static let sdk = "swift" static let version = "1.8.1" static let hashingKey = "parseSwift" static let fileManagementDirectory = "parse/" static let fileManagementPrivateDocumentsDirectory = "Private Documents/" static let fileManagementLibraryDirectory = "Library/" static let fileDownloadsDirectory = "Downloads" static let batchLimit = 50 #if os(iOS) static let deviceType = "ios" #elseif os(macOS) static let deviceType = "osx" #elseif os(tvOS) static let deviceType = "tvos" #elseif os(watchOS) static let deviceType = "applewatch" #elseif os(Linux) static let deviceType = "linux" #elseif os(Android) static let deviceType = "android" #endif }
27.088235
77
0.685125
33dd79f0e632fcd7c4634d9f77dc90e6bb55c8a5
14,259
/* * ██╗ ██╗ █████╗ ██╗ ██╗███████╗███████╗ * ██║ ██║██╔══██╗██║ ██║██╔════╝██╔════╝ * ██║ █╗ ██║███████║██║ ██║█████╗ ███████╗ * ██║███╗██║██╔══██║╚██╗ ██╔╝██╔══╝ ╚════██║ * ╚███╔███╔╝██║ ██║ ╚████╔╝ ███████╗███████║ * ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═══╝ ╚══════╝╚══════╝ * * ██████╗ ██╗ █████╗ ████████╗███████╗ ██████╗ ██████╗ ███╗ ███╗ * ██╔══██╗██║ ██╔══██╗╚══██╔══╝██╔════╝██╔═══██╗██╔══██╗████╗ ████║ * ██████╔╝██║ ███████║ ██║ █████╗ ██║ ██║██████╔╝██╔████╔██║ * ██╔═══╝ ██║ ██╔══██║ ██║ ██╔══╝ ██║ ██║██╔══██╗██║╚██╔╝██║ * ██║ ███████╗██║ ██║ ██║ ██║ ╚██████╔╝██║ ██║██║ ╚═╝ ██║ * ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ * */ import Foundation import CommonCrypto public typealias Base58 = String public typealias Base64 = String public typealias Bytes = [UInt8] public typealias PublicKey = String public typealias PrivateKey = String public typealias Seed = String public typealias Address = String public struct KeyPair { public let publicKey: PublicKey public let privateKey: PrivateKey } public enum WavesCryptoConstants { public static let publicKeyLength: Int = 32 public static let privateKeyLength: Int = 32 public static let signatureLength: Int = 64 internal static let keyLength: Int = 32 internal static let addressVersion: UInt8 = 1 internal static let checksumLength: Int = 4 internal static let hashLength: Int = 20 internal static let addressLength: Int = 1 + 1 + hashLength + checksumLength } public protocol WavesCryptoProtocol { /** BLAKE2 are cryptographic hash function - Parameter: input byte array of input data - Returns: byte array of hash values */ func blake2b256(input: Bytes) -> Bytes /** Keccak are secure hash algorithm - Parameter: input byte array of input data - Returns: byte array of hash values */ func keccak256(input: Bytes) -> Bytes /** SHA-256 are cryptographic hash function - Parameter: input byte array of input data - Returns: byte array of hash values */ func sha256(input: Bytes) -> Bytes /** Base58 binary-to-text encoding function used to represent large integers as alphanumeric text. Compared to Base64 like in base64encode(), the following similar-looking letters are omitted: 0 (zero), O (capital o), I (capital i) and l (lower case L) as well as the non-alphanumeric characters + (plus) and / (slash) - Parameter: input byte array containing binary data to encode - Returns: encoded string containing Base58 characters */ func base58encode(input: Bytes) -> String? /** Base58 text-to-binary function used to restore data encoded by Base58, reverse of base58encode() - Parameter: input encoded Base58 string - Returns: decoded byte array */ func base58decode(input: String) -> Bytes? /** Base64 binary-to-text encoding function used to represent binary data in an ASCII string format by translating it into a radix-64 representation. The implementation uses A–Z, a–z, and 0–9 for the first 62 values and '+', '/' - Parameter: input byte array containing binary data to encode. - Returns: String containing Base64 characters */ func base64encode(input: Bytes) -> String /** Base64 text-to-binary function used to restore data encoded by Base64, reverse of base64encode() - Parameter: input encoded Base64 string - Returns: decoded byte array */ func base64decode(input: String) -> Bytes? /** Random Seed-phrase generator from 2048 prepared words. It is a list of words which store all the information needed to recover a private key - Returns: a new randomly generated BIP39 seed-phrase */ func randomSeed() -> Seed /** - Returns: a public and private key-pair by seed-phrase */ func keyPair(seed: Seed) -> KeyPair? /** - Returns: a public key as String by seed-phrase */ func publicKey(seed: Seed) -> PublicKey? /** - Returns: a private key as String by seed-phrase */ func privateKey(seed: Seed) -> PrivateKey? /** - Returns: a new generated Waves address as String from the publicKey and chainId */ func address(publicKey: PublicKey, chainId: UInt8?) -> Address? /** - Returns: a new generated Waves address as String from the seed-phrase */ func address(seed: Seed, chainId: UInt8?) -> Address? /** - Parameter: privateKey is a key to an address that gives access to the management of the tokens on that address as String. It is string encoded by Base58 from byte array. - Returns: signature for the bytes by privateKey as byte array */ func signBytes(bytes: Bytes, privateKey: PrivateKey) -> Bytes? /** - Returns: signature for the bytes by seed-phrase as byte array */ func signBytes(bytes: Bytes, seed: Seed) -> Bytes? /** - Returns: true if signature is a valid signature of bytes by publicKey */ func verifySignature(publicKey: PublicKey, bytes: Bytes, signature: Bytes) -> Bool /** - Returns: true if publicKey is a valid public key */ func verifyPublicKey(publicKey: PublicKey) -> Bool /** Checks address for a valid by optional chainId and publicKey params If params non null it iss will be checked. - Parameter: address a unique identifier of an account on the Waves blockchain - Parameter: chainId it is id of blockchain network 'W' for production and 'T' for test net - Parameter: publicKey - Returns: true if address is a valid Waves address for optional chainId and publicKey */ func verifyAddress(address: Address, chainId: UInt8?, publicKey: PublicKey?) -> Bool } public class WavesCrypto: WavesCryptoProtocol { public init() {} public static let shared: WavesCrypto = WavesCrypto() public func address(publicKey: PublicKey, chainId: UInt8?) -> Address? { guard let publicKeyDecode = base58decode(input: publicKey) else { return nil } let bytes = secureHash(publicKeyDecode) let publicKeyHash = Array(bytes[0..<WavesCryptoConstants.hashLength]) let withoutChecksum: Bytes = [WavesCryptoConstants.addressVersion, UInt8(chainId ?? 0)] + publicKeyHash let checksum = calcCheckSum(withoutChecksum) return base58encode(input: withoutChecksum + checksum) } public func address(seed: Seed, chainId: UInt8?) -> Address? { guard let key = publicKey(seed: seed) else { return nil } return address(publicKey: key, chainId: chainId) } public func signBytes(bytes: Bytes, privateKey: PrivateKey) -> Bytes? { guard let privateKeyDecode = base58decode(input: privateKey) else { return nil } return Array(Curve25519.sign(Data(bytes), withPrivateKey: Data(privateKeyDecode))) } public func signBytes(bytes: Bytes, seed: Seed) -> Bytes? { guard let pair = keyPair(seed: seed) else { return nil } return signBytes(bytes: bytes, privateKey: pair.privateKey) } public func verifySignature(publicKey: PublicKey, bytes: Bytes, signature: Bytes) -> Bool { guard let publicKeyDecode = base58decode(input: publicKey) else { return false } return Ed25519.verifySignature(Data(signature), publicKey: Data(publicKeyDecode), data: Data(bytes)) } public func verifyPublicKey(publicKey: PublicKey) -> Bool { guard let publicKeyDecode = base58decode(input: publicKey) else { return false } return publicKeyDecode.count == WavesCryptoConstants.keyLength } public func verifyAddress(address: Address, chainId: UInt8?, publicKey: PublicKey?) -> Bool { if let publicKey = publicKey { return self.verifyPublicKey(publicKey: publicKey) } guard let bytes = base58decode(input: address) else { return false } if bytes.count == WavesCryptoConstants.addressLength && bytes[0] == WavesCryptoConstants.addressVersion && bytes[1] == UInt8(chainId ?? 0) { let checkSum = Array(bytes[bytes.count - WavesCryptoConstants.checksumLength..<bytes.count]) let checkSumGenerated = calcCheckSum(Array(bytes[0..<bytes.count - WavesCryptoConstants.checksumLength])) return checkSum == checkSumGenerated } return false } } // MARK: - Methods are creating keys extension WavesCrypto { public func keyPair(seed: Seed) -> KeyPair? { let seedData = Data(seedHash(Array(seed.utf8))) guard let pair = Curve25519.generateKeyPair(seedData) else { return nil } guard let privateKeyData = pair.privateKey() else { return nil } let privateKeyBytes = privateKeyData.withUnsafeBytes { [UInt8]($0) } guard let publicKeyData = pair.publicKey() else { return nil } let publicKeyBytes = publicKeyData.withUnsafeBytes { [UInt8]($0) } guard let privateKey = base58encode(input: privateKeyBytes) else { return nil } guard let publicKey = base58encode(input: publicKeyBytes) else { return nil } return KeyPair(publicKey: publicKey, privateKey: privateKey) } public func publicKey(seed: Seed) -> PublicKey? { return keyPair(seed: seed)?.publicKey } public func privateKey(seed: Seed) -> PrivateKey? { return keyPair(seed: seed)?.privateKey } public func randomSeed() -> Seed { return generatePhrase() } } // MARK: - Methods Hash extension WavesCrypto { public func blake2b256(input: Bytes) -> Bytes { var data = Data(count: WavesCryptoConstants.keyLength) var key: UInt8 = 0 data.withUnsafeMutableBytes { (rawPointer) -> Void in guard let bytes = rawPointer.bindMemory(to: UInt8.self).baseAddress else { return } crypto_generichash_blake2b(bytes, WavesCryptoConstants.keyLength, input, UInt64(input.count), &key, 0) } return Array(data) } public func keccak256(input: Bytes) -> Bytes { var data = Data(count: WavesCryptoConstants.keyLength) data.withUnsafeMutableBytes { (rawPointer) -> Void in guard let bytes = rawPointer.bindMemory(to: UInt8.self).baseAddress else { return } keccak(Array(input), Int32(input.count), bytes, 32) } return Array(data) } public func sha256(input: Bytes) -> Bytes { let len = Int(CC_SHA256_DIGEST_LENGTH) var digest = [UInt8](repeating: 0, count: len) CC_SHA256(input, CC_LONG(input.count), &digest) return Array(digest[0..<len]) } } // MARK: - Method for encode/decode base58/64 extension WavesCrypto { public func base58encode(input: Bytes) -> String? { let result = Base58Encoder.encode(input) if result.count == 0 { return nil } return result } public func base58decode(input: String) -> Bytes? { let result = Base58Encoder.decode(input) if result.count == 0 { return nil } return result } public func base64encode(input: Bytes) -> String { return Data(input).base64EncodedString() } public func base64decode(input: String) -> Bytes? { var clearInput = input if let range = input.range(of: "base64:") { clearInput.removeSubrange(range) } guard let data = Data(base64Encoded: clearInput) else { return nil } return Array(data) } } // MARK: - Hash for seed private extension WavesCrypto { func secureHash(_ input: Bytes) -> Bytes { return keccak256(input: blake2b256(input: input)) } func seedHash(_ seed: Bytes) -> Bytes { let nonce: [UInt8] = [0, 0, 0, 0] let input = nonce + seed return sha256(input: secureHash(input)) } func calcCheckSum(_ withoutChecksum: Bytes) -> Bytes { return Array(secureHash(withoutChecksum)[0..<WavesCryptoConstants.checksumLength]) } } // MARK: - Generate Phrase private extension WavesCrypto { private func randomBytes(_ length: Int) -> Bytes { var data = Data(count: length) data.withUnsafeMutableBytes { (rawPointer) -> Void in guard let bytes = rawPointer.bindMemory(to: UInt8.self).baseAddress else { return } let _ = SecRandomCopyBytes(kSecRandomDefault, length, bytes) } return Array(data) } private func bytesToBits(_ data: Bytes) -> [Bool] { var bits: [Bool] = [] for i in 0..<data.count { for j in 0..<8 { bits.append((data[i] & UInt8(1 << (7 - j))) != 0) } } return bits } private func generatePhrase() -> String { let nbWords = 15; let len = nbWords / 3 * 4; let entropy = randomBytes(len) let hash = sha256(input: entropy) let hashBits = bytesToBits(hash) let entropyBits = bytesToBits(entropy) let checksumLengthBits = entropyBits.count / 32 let concatBits = entropyBits + hashBits[0..<checksumLengthBits] var words: [String] = [] let nwords = concatBits.count / 11 for i in 0..<nwords { var index = 0 for j in 0..<11 { index <<= 1 if concatBits[(i * 11) + j] { index |= 0x1 } } words += [Words.list[index]] } return words.joined(separator: " ") } }
31.476821
117
0.587348
d7dbe7c13581be916ccb3df65c83dd9ab02bc526
1,412
// // CodeSystems.swift // HealthRecords // // Generated from FHIR 1.0.2.7202 // Copyright 2020 Apple 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 FMCore /** This value set is provided as an exemplar. The value set to instantiate this attribute should be drawn from a terminologically robust code system that consists of or contains concepts to support the procedure performance process. URL: http://hl7.org/fhir/procedure-progress-status-code ValueSet: http://hl7.org/fhir/ValueSet/procedure-progress-status-codes */ public enum ProcedureProgressStatusCodes: String, FHIRPrimitiveType { /// A patient is in the Operating Room. case A = "a" /// The patient is prepared for a procedure. case B = "b" /// The patient is under anesthesia. case C = "c" /// D case D = "d" /// E case E = "e" /// The patient is in the recovery room. case F = "f" }
28.816327
120
0.716714
cc44f28152bb4df3d0260588927dd1252f3a09e8
469
// // ItemUpdateDBService.swift // ComicsInfoCore // // Created by Aleksandar Dinic on 04/02/2021. // Copyright © 2021 Aleksandar Dinic. All rights reserved. // import class NIO.EventLoopFuture import Foundation protocol ItemUpdateDBService { func update<Item: ComicInfoItem>(_ query: UpdateItemQuery<Item>) -> EventLoopFuture<Item> func updateSummaries<Summary: ItemSummary>(_ query: UpdateSummariesQuery<Summary>) -> EventLoopFuture<[Summary]> }
24.684211
116
0.750533
f535bfc0cfc8be931239b98a4e0f2d7c6c0158a7
2,266
// // Copyright © 2015 Big Nerd Ranch // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let itemStore = ItemStore() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool { // Override point for customization after application launch. let imageStore = ImageStore() let navController = window!.rootViewController as! UINavigationController let itemsController = navController.topViewController as! ItemsViewController itemsController.itemStore = itemStore itemsController.imageStore = imageStore 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) { let success = itemStore.saveChanges() if (success) { print("Saved all of the Items") } else { print("Could not save any of the Items") } } 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:. } }
41.2
285
0.718447
08e317edebff5279329842e7a7b054eaf5c2d855
2,139
// // AppDelegate.swift // StudyControl // // Created by Bob Liu on 6/21/15. // Copyright © 2015 Akagi201. 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:. } }
45.510638
285
0.753623
87d67bf2631bcded2ea9d9c5a1ccecea77856df8
1,099
// // DetailViewController.swift // SocialAppCleanSwift // // Created by Christian Slanzi on 26.11.20. // import UIKit protocol IDetailViewController: class { // do someting... } class DetailViewController: UIViewController { var interactor: IDetailInteractor! var router: IDetailRouter! let titleLabel: UILabel = { let view = UILabel() view.translatesAutoresizingMaskIntoConstraints = false view.text = "DETAIL" return view }() override func viewDidLoad() { super.viewDidLoad() // do someting... view.addSubview(titleLabel) setupConstraints() } func setupConstraints() { NSLayoutConstraint.activate([ titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor), titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor) ]) } } extension DetailViewController: IDetailViewController { // do someting... } extension DetailViewController { // do someting... } extension DetailViewController { // do someting... }
21.134615
77
0.654231
f55325aa9821c144081ab8864678523ce577c38f
11,075
// RUN: %target-typecheck-verify-swift enum Exception : Error { case A } // Basic syntax /////////////////////////////////////////////////////////////// func bar() throws -> Int { return 0 } func foo() -> Int { return 0 } // Currying /////////////////////////////////////////////////////////////////// func curry1() { } func curry1Throws() throws { } func curry2() -> () -> () { return curry1 } func curry2Throws() throws -> () -> () { return curry1 } func curry3() -> () throws -> () { return curry1Throws } func curry3Throws() throws -> () throws -> () { return curry1Throws } var a : () -> () -> () = curry2 var b : () throws -> () -> () = curry2Throws var c : () -> () throws -> () = curry3 var d : () throws -> () throws -> () = curry3Throws // Partial application //////////////////////////////////////////////////////// protocol Parallelogram { static func partialApply1(_ a: Int) throws } func partialApply2<T: Parallelogram>(_ t: T) { _ = T.partialApply1 } // Overload resolution///////////////////////////////////////////////////////// func barG<T>(_ t : T) throws -> T { return t } func fooG<T>(_ t : T) -> T { return t } var bGE: (_ i: Int) -> Int = barG // expected-error{{invalid conversion from throwing function of type '(_) throws -> _' to non-throwing function type '(Int) -> Int'}} var bg: (_ i: Int) throws -> Int = barG var fG: (_ i: Int) throws -> Int = fooG func fred(_ callback: (UInt8) throws -> ()) throws { } func rachel() -> Int { return 12 } func donna(_ generator: () throws -> Int) -> Int { return generator() } // expected-error {{call can throw, but it is not marked with 'try' and the error is not handled}} _ = donna(rachel) func barT() throws -> Int { return 0 } // expected-note{{}} func barT() -> Int { return 0 } // expected-error{{invalid redeclaration of 'barT()'}} func fooT(_ callback: () throws -> Bool) {} //OK func fooT(_ callback: () -> Bool) {} // Throwing and non-throwing types are not equivalent. struct X<T> { } // expected-note {{arguments to generic parameter 'T' ('(String) -> Int' and '(String) throws -> Int') are expected to be equal}} // expected-note@-1 {{arguments to generic parameter 'T' ('(String) throws -> Int' and '(String) -> Int') are expected to be equal}} func specializedOnFuncType1(_ x: X<(String) throws -> Int>) { } func specializedOnFuncType2(_ x: X<(String) -> Int>) { } func testSpecializedOnFuncType(_ xThrows: X<(String) throws -> Int>, xNonThrows: X<(String) -> Int>) { specializedOnFuncType1(xThrows) // ok specializedOnFuncType1(xNonThrows) // expected-error{{cannot convert value of type 'X<(String) -> Int>' to expected argument type 'X<(String) throws -> Int>'}} specializedOnFuncType2(xThrows) // expected-error{{cannot convert value of type 'X<(String) throws -> Int>' to expected argument type 'X<(String) -> Int>'}} specializedOnFuncType2(xNonThrows) // ok } // Subtyping func subtypeResult1(_ x: (String) -> ((Int) -> String)) { } func testSubtypeResult1(_ x1: (String) -> ((Int) throws -> String), x2: (String) -> ((Int) -> String)) { subtypeResult1(x1) // expected-error{{cannot convert value of type '(String) -> ((Int) throws -> String)' to expected argument type '(String) -> ((Int) -> String)'}} subtypeResult1(x2) } func subtypeResult2(_ x: (String) -> ((Int) throws -> String)) { } func testSubtypeResult2(_ x1: (String) -> ((Int) throws -> String), x2: (String) -> ((Int) -> String)) { subtypeResult2(x1) subtypeResult2(x2) } func subtypeArgument1(_ x: (_ fn: ((String) -> Int)) -> Int) { } func testSubtypeArgument1(_ x1: (_ fn: ((String) -> Int)) -> Int, x2: (_ fn: ((String) throws -> Int)) -> Int) { subtypeArgument1(x1) subtypeArgument1(x2) } func subtypeArgument2(_ x: (_ fn: ((String) throws -> Int)) -> Int) { } func testSubtypeArgument2(_ x1: (_ fn: ((String) -> Int)) -> Int, x2: (_ fn: ((String) throws -> Int)) -> Int) { subtypeArgument2(x1) // expected-error{{cannot convert value of type '(((String) -> Int)) -> Int' to expected argument type '(((String) throws -> Int)) -> Int'}} subtypeArgument2(x2) } // Closures var c1 = {() throws -> Int in 0} var c2 : () throws -> Int = c1 // ok var c3 : () -> Int = c1 // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}} var c4 : () -> Int = {() throws -> Int in 0} // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}} var c5 : () -> Int = { try c2() } // expected-error{{invalid conversion from throwing function of type '() throws -> Int' to non-throwing function type '() -> Int'}} var c6 : () throws -> Int = { do { _ = try c2() } ; return 0 } var c7 : () -> Int = { do { try c2() } ; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}} var c8 : () -> Int = { do { _ = try c2() } catch _ { var x = 0 } ; return 0 } // expected-warning {{initialization of variable 'x' was never used; consider replacing with assignment to '_' or removing it}} var c9 : () -> Int = { do { try c2() } catch Exception.A { var x = 0 } ; return 0 }// expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}} var c10 : () -> Int = { throw Exception.A; return 0 } // expected-error{{invalid conversion from throwing function of type '() throws -> _' to non-throwing function type '() -> Int'}} var c11 : () -> Int = { try! c2() } var c12 : () -> Int? = { try? c2() } // Initializers struct A { init(doomed: ()) throws {} } func fi1() throws { A(doomed: ()) // expected-error {{call can throw but is not marked with 'try'}} // expected-warning{{unused}} // expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }} } struct B { init() throws {} init(foo: Int) {} } B(foo: 0) // expected-warning{{unused}} // rdar://problem/33040113 - Provide fix-it for missing "try" when calling throwing Swift function class E_33040113 : Error {} func rdar33040113() throws -> Int { throw E_33040113() } let _ = rdar33040113() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }} // expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }} // expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }} enum MSV : Error { case Foo, Bar, Baz case CarriesInt(Int) } func genError() throws -> Int { throw MSV.Foo } struct IllegalContext { var x1: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} let x2 = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} var x3 = try genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} let x4: Int = try genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} var x5 = B() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} var x6 = try B() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} var x7 = { // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} return try genError() }() var x8: Int = { do { return genError() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} // expected-note@-2 {{did you mean to handle error as optional value?}} // expected-note@-3 {{did you mean to disable error propagation?}} } catch { return 0 } }() var x9: Int = { do { return try genError() } catch { return 0 } }() var x10: B = { do { return try B() } catch { return B(foo: 0) } }() lazy var y1: Int = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} lazy var y2 = genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} lazy var y3 = try genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} lazy var y4: Int = try genError() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} lazy var y5 = B() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} lazy var y6 = try B() // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} lazy var y7 = { // expected-error {{call can throw, but errors cannot be thrown out of a property initializer}} return try genError() }() lazy var y8: Int = { do { return genError() // expected-error {{call can throw but is not marked with 'try'}} // expected-note@-1 {{did you mean to use 'try'?}} // expected-note@-2 {{did you mean to handle error as optional value?}} // expected-note@-3 {{did you mean to disable error propagation?}} } catch { return 0 } }() lazy var y9: Int = { do { return try genError() } catch { return 0 } }() lazy var y10: B = { do { return try B() } catch { return B(foo: 0) } }() func foo(_ x: Int = genError()) {} // expected-error {{call can throw, but errors cannot be thrown out of a default argument}} func catcher() throws { do { _ = try genError() } catch MSV.CarriesInt(genError()) { // expected-error {{call can throw, but errors cannot be thrown out of a catch pattern}} } catch MSV.CarriesInt(let i) where i == genError() { // expected-error {{call can throw, but errors cannot be thrown out of a catch guard expression}} } } } // Crash in 'uncovered try' diagnostic when calling a function value - rdar://46973064 struct FunctionHolder { let fn: () throws -> () func receive() { do { _ = fn() // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{did you mean to use 'try'?}} // expected-note@-3 {{did you mean to handle error as optional value?}} // expected-note@-4 {{did you mean to disable error propagation?}} _ = "\(fn())" // expected-error@-1 {{call can throw but is not marked with 'try'}} // expected-note@-2 {{did you mean to use 'try'?}} // expected-note@-3 {{did you mean to handle error as optional value?}} // expected-note@-4 {{did you mean to disable error propagation?}} } catch {} } }
39.27305
213
0.610113
5b59ca6e5da174ce298a18fbc7514d716a39f29b
5,407
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation extension Rocket.Profile { /** Get the details of the active profile, including watched, bookmarked and rated items. */ public enum GetProfile { public static let service = APIService<Response>(id: "getProfile", tag: "profile", method: "GET", path: "/account/profile", hasBody: false, authorization: Authorization(type: "profileAuth", scope: "Catalog")) public final class Request: APIRequest<Response> { public init() { super.init(service: GetProfile.service) } } public enum Response: APIResponseValue, CustomStringConvertible, CustomDebugStringConvertible { public typealias SuccessType = ProfileDetail /** Details of the active profile. */ case status200(ProfileDetail) /** Bad request. */ case status400(ServiceError) /** Invalid access token. */ case status401(ServiceError) /** Forbidden. */ case status403(ServiceError) /** Not found. */ case status404(ServiceError) /** Internal server error. */ case status500(ServiceError) /** Service error. */ case defaultResponse(statusCode: Int, ServiceError) public var success: ProfileDetail? { switch self { case .status200(let response): return response default: return nil } } public var failure: ServiceError? { switch self { case .status400(let response): return response case .status401(let response): return response case .status403(let response): return response case .status404(let response): return response case .status500(let response): return response case .defaultResponse(_, let response): return response default: return nil } } /// either success or failure value. Success is anything in the 200..<300 status code range public var responseResult: APIResponseResult<ProfileDetail, ServiceError> { if let successValue = success { return .success(successValue) } else if let failureValue = failure { return .failure(failureValue) } else { fatalError("Response does not have success or failure response") } } public var response: Any { switch self { case .status200(let response): return response case .status400(let response): return response case .status401(let response): return response case .status403(let response): return response case .status404(let response): return response case .status500(let response): return response case .defaultResponse(_, let response): return response } } public var statusCode: Int { switch self { case .status200: return 200 case .status400: return 400 case .status401: return 401 case .status403: return 403 case .status404: return 404 case .status500: return 500 case .defaultResponse(let statusCode, _): return statusCode } } public var successful: Bool { switch self { case .status200: return true case .status400: return false case .status401: return false case .status403: return false case .status404: return false case .status500: return false case .defaultResponse: return false } } public init(statusCode: Int, data: Data) throws { let decoder = JSONDecoder() switch statusCode { case 200: self = try .status200(decoder.decode(ProfileDetail.self, from: data)) case 400: self = try .status400(decoder.decode(ServiceError.self, from: data)) case 401: self = try .status401(decoder.decode(ServiceError.self, from: data)) case 403: self = try .status403(decoder.decode(ServiceError.self, from: data)) case 404: self = try .status404(decoder.decode(ServiceError.self, from: data)) case 500: self = try .status500(decoder.decode(ServiceError.self, from: data)) default: self = try .defaultResponse(statusCode: statusCode, decoder.decode(ServiceError.self, from: data)) } } public var description: String { return "\(statusCode) \(successful ? "success" : "failure")" } public var debugDescription: String { var string = description let responseString = "\(response)" if responseString != "()" { string += "\n\(responseString)" } return string } } } }
38.621429
216
0.544479
89d625a3910c45e5778455ea55f311eda89d9348
4,157
import AST /// Enumerates the kinds of tokens. public enum TokenKind: String { // MARK: Literals case number case string case bool // MARK: Identifiers case identifier // MARK: Operators case pow = "**" case mul = "*" case div = "/" case mod = "%" case add = "+" case sub = "-" case lshift = "<<" case rshift = ">>" case urshift = ">>>" case lt = "<" case le = "<=" case ge = ">=" case gt = ">" case `in` case instanceof case eq = "==" case ne = "!=" case seq = "===" case sne = "!==" case not = "!" case invert = "~" case band = "&" case bxor = "^" case bor = "|" case and = "&&" case or = "||" case inc = "++" case dec = "--" case typeof case void case delete case await case copy = "=" case borrow = "&-" case arrow = "=>" case dot = "." case comma = "," case colon = ":" case semicolon = ";" case questionMark = "?" case ellipsis = "..." case newline case eof case leftParen = "(" case rightParen = ")" case leftBrace = "{" case rightBrace = "}" case leftBracket = "[" case rightBracket = "]" // MARK: Keywords case `let` case const case mutable case async case function case `static` case `class` case new case `while` case `for` case `break` case `continue` case `return` case yield case `if` case `else` case `switch` case `case` // MARK: Error tokens case unknown case unterminatedBlockComment case unterminatedStringLiteral } /// Represents a token. public struct Token { public init(kind: TokenKind, value: String? = nil, range: SourceRange) { self.kind = kind self.value = value self.range = range } /// Whether or not the token is a statement delimiter. public var isStatementDelimiter: Bool { return kind == .newline || kind == .semicolon } /// Whether or not the token is an prefix operator. public var isPrefixOperator: Bool { return asPrefixOperator != nil } /// The token as a prefix operator. public var asPrefixOperator: PrefixOperator? { return PrefixOperator(rawValue: kind.rawValue) } /// Whether or not the token is an postfix operator. public var isPostfixOperator: Bool { return asPostfixOperator != nil } /// The token as a postfix operator. public var asPostfixOperator: PostfixOperator? { return PostfixOperator(rawValue: kind.rawValue) } /// Whether or not the token is an infix operator. public var isInfixOperator: Bool { return asInfixOperator != nil } /// The token as an infix operator. public var asInfixOperator: InfixOperator? { return InfixOperator(rawValue: kind.rawValue) } /// Whether or not the token is a binding operator. public var isBindingOperator: Bool { return asBindingOperator != nil } /// The token as a binding operator. public var asBindingOperator: BindingOperator? { return BindingOperator(rawValue: kind.rawValue) } /// The kind of the token. public let kind: TokenKind /// The optional value of the token. public let value: String? /// The range of characters that compose the token in the source file. public let range: SourceRange } extension Token: Equatable { public static func == (lhs: Token, rhs: Token) -> Bool { return (lhs.kind == rhs.kind) && (lhs.value == rhs.value) && (lhs.range == rhs.range) } } extension Token: CustomStringConvertible { public var description: String { return kind.rawValue } }
23.485876
93
0.533798
48731c75f5cfaa29abcad3f916038485b8c8606a
1,559
// // GetAllIssuesApiManager.swift // QAHelper // // Created by Vishnu Vardhan PV on 17/11/16. // Copyright © 2016 QBurst. All rights reserved. // import Foundation import Alamofire class GetAllIssuesApiManager: ApiManager { typealias ApiCallback = (GetAllIssuesResponse?, Error?) -> Void class func getAllIssues(userName: String, password: String, startIndex: Int, callback: @escaping ApiCallback) { var headers: HTTPHeaders = [:] if let authorizationHeader = Request.authorizationHeader(user: userName, password: password) { headers[authorizationHeader.key] = authorizationHeader.value } let url = Constants.Api.jiraUrl + Constants.ApiNames.allIssues let projectName = JiraAccountDetails.sharedInstance.projectKey let maxResults = 10 let jql = "jql=project=\(projectName) AND issuetype=Bug&maxResults=\(maxResults)&startAt=\(startIndex)" let bugListUrl = url + jql let encodedUrl = bugListUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) executeRequest(encodedUrl!, parameters:nil, headers: headers) { (response, error) in if let error = error { callback(nil, error) } else { if let json = response?.result.value as? [String: Any] { let issues: GetAllIssuesResponse? = GetAllIssuesResponse(JSON: json) debugPrint(issues?.issues?[0] as Any) callback(issues, nil) } } } } }
36.255814
115
0.643361
14b0cc585b35c41a955dc8401dd68e8c673b7bcf
2,190
// // AppDelegate.swift // SkeletonViewExample // // Created by Juanpe Catalán on 02/11/2017. // Copyright © 2017 SkeletonView. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> 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 invalidate graphics rendering callbacks. 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 active 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.595745
285
0.757078
33cf1b75aebb66d424828ba39a24ed50c188891f
2,379
// // OutlineItem.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2016-05-12. // // --------------------------------------------------------------------------- // // © 2016-2020 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import AppKit.NSFont struct OutlineItem: Equatable { struct Style: OptionSet { let rawValue: Int static let bold = Style(rawValue: 1 << 0) static let italic = Style(rawValue: 1 << 1) static let underline = Style(rawValue: 1 << 2) } var title: String var range: NSRange var style: Style = [] var isSeparator: Bool { return self.title == .separator } } extension OutlineItem { func attributedTitle(for baseFont: NSFont, attributes: [NSAttributedString.Key: Any] = [:]) -> NSAttributedString { assert(!self.isSeparator) var font = baseFont var attributes = attributes if self.style.contains(.bold) { font = NSFontManager.shared.convert(font, toHaveTrait: .boldFontMask) } if self.style.contains(.italic) { font = NSFontManager.shared.convert(font, toHaveTrait: .italicFontMask) } if self.style.contains(.underline) { attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue } attributes[.font] = font return NSAttributedString(string: self.title, attributes: attributes) } } extension Array where Element == OutlineItem { func indexOfItem(for characterRange: NSRange, allowsSeparator: Bool = true) -> Index? { return self.lastIndex { $0.range.location <= characterRange.location && (allowsSeparator || !$0.isSeparator ) } } }
27.034091
119
0.606557
e8e8b8f74abf725f7499f2eeca681bfd7da40c31
1,547
// // UpcomingResponseModel.swift // MovieDataBase // // Created by Judar Lima on 20/07/19. // Copyright © 2019 Judar Lima. All rights reserved. // import Foundation struct UpcomingResponseModel: Decodable { struct Movie: Decodable { let voteCount: Int? let id: Int? let video: Bool? let voteAverage: Double? let title: String? let popularity: Double? let posterPath: String? let originalLanguage: String? let originalTitle: String? let genreIDS: [Int]? let backdropPath: String? let adult: Bool? let overview: String? let releaseDate: String? enum CodingKeys: String, CodingKey { case voteCount = "vote_count" case id, video case voteAverage = "vote_average" case title, popularity case posterPath = "poster_path" case originalLanguage = "original_language" case originalTitle = "original_title" case genreIDS = "genre_ids" case backdropPath = "backdrop_path" case adult, overview case releaseDate = "release_date" } } struct Dates: Decodable { let maximum, minimum: String } let movies: [Movie] let page: Int let totalResults: Int let totalPages: Int enum CodingKeys: String, CodingKey { case movies = "results" case totalResults = "total_results" case page case totalPages = "total_pages" } }
25.783333
55
0.594053
f4e96f4589e0f1ddf6b26230f92143f8cc4b8b00
1,995
// // PipelinelatestRun.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct PipelinelatestRun: Codable { public var artifacts: [PipelinelatestRunartifacts]? public var durationInMillis: Int? public var estimatedDurationInMillis: Int? public var enQueueTime: String? public var endTime: String? public var _id: String? public var organization: String? public var pipeline: String? public var result: String? public var runSummary: String? public var startTime: String? public var state: String? public var type: String? public var commitId: String? public var _class: String? public init(artifacts: [PipelinelatestRunartifacts]?, durationInMillis: Int?, estimatedDurationInMillis: Int?, enQueueTime: String?, endTime: String?, _id: String?, organization: String?, pipeline: String?, result: String?, runSummary: String?, startTime: String?, state: String?, type: String?, commitId: String?, _class: String?) { self.artifacts = artifacts self.durationInMillis = durationInMillis self.estimatedDurationInMillis = estimatedDurationInMillis self.enQueueTime = enQueueTime self.endTime = endTime self._id = _id self.organization = organization self.pipeline = pipeline self.result = result self.runSummary = runSummary self.startTime = startTime self.state = state self.type = type self.commitId = commitId self._class = _class } public enum CodingKeys: String, CodingKey { case artifacts case durationInMillis case estimatedDurationInMillis case enQueueTime case endTime case _id = "id" case organization case pipeline case result case runSummary case startTime case state case type case commitId case _class } }
28.913043
337
0.667168
2137e693480d14ba2ffde6e1f416c1ff6a599775
1,812
// // ViewController.swift // calculator // // Created by Sukie on 4/10/16. // Copyright © 2016 Sukie. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var lblResult: UITextField! var result = Float() var currentNumber = Float() var currentOp = String() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. currentOp = "=" lblResult.text = ("\(result)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func btnNumberinput(sender: UIButton) { currentNumber = currentNumber * 10 + Float(Int(sender.titleLabel!.text!)!) lblResult.text = ("\(currentNumber)") } @IBAction func btnOperation(sender: UIButton) { switch currentOp { case "=": result = currentNumber case "+": result = result + currentNumber case "-": result = result - currentNumber case "*": result = result * currentNumber case "/": result = result / currentNumber default: print("error") } currentNumber = 0 lblResult.text = ("\(result)") if(sender.titleLabel!.text == "="){ result = 0 } currentOp = sender.titleLabel!.text! as String! } @IBAction func btnClear(sender: UIButton) { result = 0 currentNumber = 0 currentOp = "+" lblResult.text = ("\(result)") } }
21.317647
82
0.528146
61a4efe21f8eb9c1166a126af8dd4bc60bb5e269
897
// PatternKit © 2017–21 Constantino Tsarouhas /// Creates a range pattern. /// /// - Parameter lowerBound: The smallest element that is matched. /// - Parameter upperBound: The element greater than the largest element that is matched. /// /// - Returns: A range pattern matching elements between `lowerBound` and `upperBound`, exclusive. public func ..< <Subject>(lowerBound: Subject.Element, upperBound: Subject.Element) -> RangePattern<Subject> { .init(lowerBound..<upperBound) } /// Creates a range pattern. /// /// - Parameter lowerBound: The smallest element that is matched. /// - Parameter upperBound: The largest element that is matched. /// /// - Returns: A range pattern matching elements between `lowerBound` and `upperBound`, inclusive. public func ... <Subject>(lowerBound: Subject.Element, upperBound: Subject.Element) -> RangePattern<Subject> { .init(lowerBound...upperBound) }
40.772727
110
0.736901
907366a53992cd4e3cd265401f554368b5f8f960
1,366
// This file was generated from JSON Schema using quicktype, do not modify it directly. // To parse the JSON, add this file to your project and do: // // let arDatum = try ArDatum(json) import Foundation // MARK: - ArDatum struct ArDatum: Codable { let encIDCredPubShare: String enum CodingKeys: String, CodingKey { case encIDCredPubShare = "encIdCredPubShare" } } // MARK: ArDatum convenience initializers and mutators extension ArDatum { init(data: Data) throws { self = try newJSONDecoder().decode(ArDatum.self, from: data) } 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) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( encIDCredPubShare: String? = nil ) -> ArDatum { return ArDatum( encIDCredPubShare: encIDCredPubShare ?? self.encIDCredPubShare ) } 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) } }
26.784314
87
0.641288
abc1589e6da10f8ec15832f6b02601f37edccd78
675
// // Constants.swift // Mixpanel // // Created by Yarden Eitan on 7/8/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation #if !os(OSX) import UIKit #endif // os(OSX) struct QueueConstants { static var queueSize = 5000 } struct APIConstants { static let batchSize = 50 static let minRetryBackoff = 60.0 static let maxRetryBackoff = 600.0 static let failuresTillBackoff = 2 } struct BundleConstants { static let ID = "com.mixpanel.Mixpanel" } struct InAppNotificationsConstants { static let miniInAppHeight: CGFloat = 65 static let miniBottomPadding: CGFloat = 10 static let miniSidePadding: CGFloat = 15 }
19.852941
51
0.70963
1c801eb80de38024d072fbaa3eaa980637cb33d5
528
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "VersionBump", products: [ .executable(name: "VersionBump", targets: ["VersionBump"]) ], dependencies: [ .package(url: "https://github.com/kareman/SwiftShell.git", from: "4.1.2"), .package(url: "https://github.com/sharplet/Regex.git", from: "2.0.0") ], targets: [ .target( name: "VersionBump", dependencies: ["SwiftShell", "Regex"], path: "./") ] )
26.4
82
0.558712
0a311175e6d9e881f7863bacd1fad486b83aedce
5,550
// // ContentView.swift // CircularProgressView // // Created by Mahdi // import SwiftUI struct ContentView: View { /// The radius of the bigger circle everything is drawn on. let radius: CGFloat = 120 /// The Progress. @State private var progress: CGFloat = 0.333 /* 0 <= progress <= 1 */ /// Angle number 1. @State private var angle1: Angle = .zero /// Angle number 2. @State private var angle2: Angle = .radians(3 * .pi / 2) /// The stroke's width. @State private var lineWidth: CGFloat = 8 /// Right to left or left to right progressing. @State private var rightToLeft: Bool = false /// The angle to offset `angle.start` and `angles.end` with. /// This will just turn the circle to make creating some arcs possible. @State private var offsetAngle: Angle = .radians(.pi / 4) /// The geometry used to draw shapes. @State private var geo: ProgressGeometry = .zero var body: some View { populateProgressGeometry() return VStack(spacing: 2) { /// Progress View CircleArc(startAngle: geo.angles.start, endAngle: geo.angles.end, lineWidth: lineWidth) .frame(width: radius * 2, height: radius * 2) .foregroundColor(.gray) .overlay( CircleArc( startAngle: geo.progressAngles.start, endAngle: geo.progressAngles.end, lineWidth: lineWidth ).foregroundColor(.blue) ) .overlay( Circle() .frame(width: geo.indicatorRadius * 2, height: geo.indicatorRadius * 2) .foregroundColor(.green) .offset(x: radius) /// My calculations are pod-clockwise, but `rotationEffect(_:)` works /// clockwise (apple's fault), thats the reason of the `-` sign. .rotationEffect(-geo.circleAngle) ) .overlay( Image(systemName: "airplane") .resizable() .frame(maxWidth: geo.indicatorRadius, maxHeight: geo.indicatorRadius) .scaledToFit() /// This keeps the plane always pointing to the same point, even when rotated. .rotationEffect(geo.circleAngle + (rightToLeft ? .radians(.pi) : .zero)) .foregroundColor(.red) .offset(x: radius) /// My calculations are pod-clockwise, but `rotationEffect(_:)` works /// clockwise (apple's fault), thats the reason of the `-` sign. .rotationEffect(-geo.circleAngle) ) /// Controllers VStack { HStack { Button("right to left: \(rightToLeft.description)") { rightToLeft.toggle() } .padding(6) Button("toggle progress") { if progress.rounded(.toNearestOrEven) == 0 { progress = 1 } else { progress = 0 } } .padding(6) } .font(.headline) Group { Text("progress: \(progress)") Slider(value: $progress, in: (0.001)...1) Text("\(angle1 > angle2 ? "end" : "start"): \(angle1.degrees)") Slider(value: .init( get: { angle1.degrees }, set: { angle1 = .degrees($0) } ), in: 0...360) Text("\(angle1 > angle2 ? "start" : "end"): \(angle2.degrees)") Slider(value: .init( get: { angle2.degrees }, set: { angle2 = .degrees($0) } ), in: (0.1)...359.9) Text("offset angle: \(offsetAngle.degrees)") Slider(value: .init( get: { offsetAngle.degrees }, set: { offsetAngle = .degrees($0) } ), in: (0.1)...359.9) Text("width: \(lineWidth)") Slider(value: $lineWidth, in: 1...40) } } .padding(.horizontal) } .animation(.easeInOut.speed(0.5)) .onChange(of: progress) { newValue in /// Progress == 0 might result in animation errors. if newValue == 0 { progress = 0.001 } } } private func populateProgressGeometry() { DispatchQueue.main.async { self.geo = .init( progress: self.progress, radius: self.radius, angle1: self.angle1, angle2: self.angle2, lineWidth: self.lineWidth, rightToLeft: self.rightToLeft, offsetAngle: self.offsetAngle ) } } } // Preview Provider struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
37.755102
99
0.451532
1d33cf048bcc04e454121188b848c8c09db3ca17
1,498
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 686. Repeated String Match // Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1. // Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc". // Example 1: // Input: a = "abcd", b = "cdabcdab" // Output: 3 // Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it. // Example 2: // Input: a = "a", b = "aa" // Output: 2 // Example 3: // Input: a = "a", b = "a" // Output: 1 // Example 4: // Input: a = "abc", b = "wxyz" // Output: -1 // Constraints: // 1 <= a.length <= 10^4 // 1 <= b.length <= 10^4 // a and b consist of lower-case English letters. func repeatedStringMatch(_ A: String, _ B: String) -> Int { let (A, B) = (Array(A), Array(B)) for startA in A.indices { var j = B.startIndex while j < B.endIndex, B[j] == A[(startA + j) % A.count] { j += 1 } if j == B.endIndex { var k = (startA + j) / A.count if (startA + j) % A.count != 0 { k += 1 } return k } else if j >= A.count { return -1 } } return -1 } }
30.571429
214
0.522029
bfb7cc642199702ec72070a92d9ba8d66404f3f4
3,512
// swift-tools-version:5.3 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "hummingbird", platforms: [.iOS(.v12), .tvOS(.v12)], products: [ .library(name: "Hummingbird", targets: ["Hummingbird"]), .library(name: "HummingbirdFoundation", targets: ["HummingbirdFoundation"]), .library(name: "HummingbirdJobs", targets: ["HummingbirdJobs"]), .library(name: "HummingbirdXCT", targets: ["HummingbirdXCT"]), .executable(name: "PerformanceTest", targets: ["PerformanceTest"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-log.git", from: "1.4.0"), .package(url: "https://github.com/apple/swift-metrics.git", "1.0.0"..<"3.0.0"), .package(url: "https://github.com/apple/swift-nio.git", from: "2.33.0"), .package(url: "https://github.com/swift-server/swift-service-lifecycle.git", from: "1.0.0-alpha.9"), .package(url: "https://github.com/hummingbird-project/hummingbird-core.git", .upToNextMinor(from: "0.12.1")), ], targets: [ .target(name: "Hummingbird", dependencies: [ .product(name: "HummingbirdCore", package: "hummingbird-core"), .product(name: "Lifecycle", package: "swift-service-lifecycle"), .product(name: "LifecycleNIOCompat", package: "swift-service-lifecycle"), .product(name: "Logging", package: "swift-log"), .product(name: "Metrics", package: "swift-metrics"), .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOPosix", package: "swift-nio"), .product(name: "NIOHTTP1", package: "swift-nio"), ]), .target(name: "HummingbirdFoundation", dependencies: [ .byName(name: "Hummingbird"), .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOPosix", package: "swift-nio"), .product(name: "NIOFoundationCompat", package: "swift-nio"), ]), .target(name: "HummingbirdJobs", dependencies: [ .byName(name: "Hummingbird"), .product(name: "Logging", package: "swift-log"), ]), .target(name: "HummingbirdXCT", dependencies: [ .byName(name: "Hummingbird"), .product(name: "HummingbirdCoreXCT", package: "hummingbird-core"), .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOEmbedded", package: "swift-nio"), .product(name: "NIOPosix", package: "swift-nio"), .product(name: "NIOHTTP1", package: "swift-nio"), ]), .target(name: "PerformanceTest", dependencies: [ .byName(name: "Hummingbird"), .byName(name: "HummingbirdFoundation"), .product(name: "NIOPosix", package: "swift-nio"), ]), // test targets .testTarget(name: "HummingbirdTests", dependencies: [ .byName(name: "Hummingbird"), .byName(name: "HummingbirdFoundation"), .byName(name: "HummingbirdXCT"), ]), .testTarget(name: "HummingbirdFoundationTests", dependencies: [ .byName(name: "HummingbirdFoundation"), .byName(name: "HummingbirdXCT"), ]), .testTarget(name: "HummingbirdJobsTests", dependencies: [ .byName(name: "HummingbirdJobs"), .byName(name: "HummingbirdXCT"), ]), ] )
48.109589
117
0.589123
e9c524f11f3ba39a5358531319694036b2012f43
11,415
// // TLPhotoLibrary.swift // TLPhotosPicker // // Created by wade.hawk on 2017. 5. 3.. // Copyright © 2017년 wade.hawk. All rights reserved. // import Foundation import Photos protocol TLPhotoLibraryDelegate: class { func loadCameraRollCollection(collection: TLAssetsCollection) func loadCompleteAllCollection(collections: [TLAssetsCollection]) func focusCollection(collection: TLAssetsCollection) } class TLPhotoLibrary { weak var delegate: TLPhotoLibraryDelegate? = nil lazy var imageManager: PHCachingImageManager = { return PHCachingImageManager() }() deinit { // print("deinit TLPhotoLibrary") } // @discardableResult // func livePhotoAsset(asset: PHAsset, size: CGSize = CGSize(width: 720, height: 1280), progressBlock: Photos.PHAssetImageProgressHandler? = nil, completionBlock:@escaping (PHLivePhoto,Bool)-> Void ) -> PHImageRequestID { // let options = PHLivePhotoRequestOptions() // options.deliveryMode = .opportunistic // options.isNetworkAccessAllowed = true // options.progressHandler = progressBlock // let scale = min(UIScreen.main.scale,2) // let targetSize = CGSize(width: size.width*scale, height: size.height*scale) // let requestId = self.imageManager.requestLivePhoto(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: options) { (livePhoto, info) in // let complete = (info?["PHImageResultIsDegradedKey"] as? Bool) == false // if let livePhoto = livePhoto { // completionBlock(livePhoto,complete) // } // } // return requestId // } @discardableResult // func videoAsset(asset: PHAsset, size: CGSize = CGSize(width: 720, height: 1280), progressBlock: Photos.PHAssetImageProgressHandler? = nil, completionBlock:@escaping (AVPlayerItem?, [AnyHashable : Any]?) -> Void ) -> PHImageRequestID { // let options = PHVideoRequestOptions() // options.isNetworkAccessAllowed = true // options.deliveryMode = .automatic // options.progressHandler = progressBlock // let requestId = self.imageManager.requestPlayerItem(forVideo: asset, options: options, resultHandler: { playerItem, info in // completionBlock(playerItem,info) // }) // return requestId // } // @discardableResult func imageAsset(asset: PHAsset, size: CGSize = CGSize(width: 160, height: 160), options: PHImageRequestOptions? = nil, completionBlock:@escaping (UIImage,Bool)-> Void ) -> PHImageRequestID { var options = options if options == nil { options = PHImageRequestOptions() options?.isSynchronous = false options?.deliveryMode = .opportunistic options?.isNetworkAccessAllowed = true } let scale = min(UIScreen.main.scale,2) let targetSize = CGSize(width: size.width*scale, height: size.height*scale) let requestId = self.imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: options) { image, info in let complete = (info?["PHImageResultIsDegradedKey"] as? Bool) == false if let image = image { completionBlock(image,complete) } } return requestId } func cancelPHImageRequest(requestId: PHImageRequestID) { self.imageManager.cancelImageRequest(requestId) } // @discardableResult // class func cloudImageDownload(asset: PHAsset, size: CGSize = PHImageManagerMaximumSize, progressBlock: @escaping (Double) -> Void, completionBlock:@escaping (UIImage?)-> Void ) -> PHImageRequestID { // let options = PHImageRequestOptions() // options.isSynchronous = false // options.isNetworkAccessAllowed = true // options.deliveryMode = .opportunistic // options.version = .current // options.resizeMode = .exact // options.progressHandler = { (progress,error,stop,info) in // progressBlock(progress) // } // let requestId = PHCachingImageManager().requestImageData(for: asset, options: options) { (imageData, dataUTI, orientation, info) in // if let data = imageData,let _ = info { // completionBlock(UIImage(data: data)) // }else{ // completionBlock(nil)//error // } // } // return requestId // } // // @discardableResult class func fullResolutionImageData(asset: PHAsset) -> UIImage? { let options = PHImageRequestOptions() options.isSynchronous = true options.resizeMode = .none options.isNetworkAccessAllowed = false options.version = .current var image: UIImage? = nil _ = PHCachingImageManager().requestImageData(for: asset, options: options) { (imageData, dataUTI, orientation, info) in if let data = imageData { image = UIImage(data: data) } } return image } } extension PHFetchOptions { func merge(predicate: NSPredicate) { if let storePredicate = self.predicate { self.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [storePredicate, predicate]) }else { self.predicate = predicate } } } //MARK: - Load Collection extension TLPhotoLibrary { func getOption(configure: TLPhotosPickerConfigure) -> PHFetchOptions { let options = configure.fetchOption ?? PHFetchOptions() options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] if let mediaType = configure.mediaType { let mediaTypePredicate = configure.maxVideoDuration != nil && mediaType == PHAssetMediaType.video ? NSPredicate(format: "mediaType = %i AND duration < %f", mediaType.rawValue, configure.maxVideoDuration! + 1) : NSPredicate(format: "mediaType = %i", mediaType.rawValue) options.merge(predicate: mediaTypePredicate) } else if !configure.allowedVideo { let mediaTypePredicate = NSPredicate(format: "mediaType = %i", PHAssetMediaType.image.rawValue) options.merge(predicate: mediaTypePredicate) } else if let duration = configure.maxVideoDuration { let mediaTypePredicate = NSPredicate(format: "mediaType = %i OR (mediaType = %i AND duration < %f)", PHAssetMediaType.image.rawValue, PHAssetMediaType.video.rawValue, duration + 1) options.merge(predicate: mediaTypePredicate) } return options } func fetchResult(collection: TLAssetsCollection?, configure: TLPhotosPickerConfigure) -> PHFetchResult<PHAsset>? { guard let phAssetCollection = collection?.phAssetCollection else { return nil } let options = getOption(configure: configure) return PHAsset.fetchAssets(in: phAssetCollection, options: options) } func fetchCollection(configure: TLPhotosPickerConfigure) { let useCameraButton = configure.usedCameraButton let options = getOption(configure: configure) func getAlbum(subType: PHAssetCollectionSubtype, result: inout [TLAssetsCollection]) { let fetchCollection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: subType, options: nil) var collections = [PHAssetCollection]() fetchCollection.enumerateObjects { (collection, index, _) in //Why this? : Can't getting image for cloud shared album if collection.assetCollectionSubtype != .albumCloudShared { collections.append(collection) } } for collection in collections { if !result.contains(where: { $0.localIdentifier == collection.localIdentifier }) { var assetsCollection = TLAssetsCollection(collection: collection) assetsCollection.fetchResult = PHAsset.fetchAssets(in: collection, options: options) if assetsCollection.count > 0 { result.append(assetsCollection) } } } } @discardableResult func getSmartAlbum(subType: PHAssetCollectionSubtype, useCameraButton: Bool = false, result: inout [TLAssetsCollection]) -> TLAssetsCollection? { let fetchCollection = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: subType, options: nil) if let collection = fetchCollection.firstObject, !result.contains(where: { $0.localIdentifier == collection.localIdentifier }) { var assetsCollection = TLAssetsCollection(collection: collection) assetsCollection.fetchResult = PHAsset.fetchAssets(in: collection, options: options) if assetsCollection.count > 0 || useCameraButton { result.append(assetsCollection) return assetsCollection } } return nil } DispatchQueue.global(qos: .userInteractive).async { [weak self] in var assetCollections = [TLAssetsCollection]() //Camera Roll let camerarollCollection = getSmartAlbum(subType: .smartAlbumUserLibrary, useCameraButton: useCameraButton, result: &assetCollections) if var cameraRoll = camerarollCollection { cameraRoll.useCameraButton = useCameraButton assetCollections[0] = cameraRoll DispatchQueue.main.async { self?.delegate?.focusCollection(collection: cameraRoll) self?.delegate?.loadCameraRollCollection(collection: cameraRoll) } } //Selfies if #available(iOS 9.0, *) { getSmartAlbum(subType: .smartAlbumSelfPortraits, result: &assetCollections) } else { // Fallback on earlier versions } //Panoramas getSmartAlbum(subType: .smartAlbumPanoramas, result: &assetCollections) //Favorites getSmartAlbum(subType: .smartAlbumFavorites, result: &assetCollections) //get all another albums getAlbum(subType: .any, result: &assetCollections) if configure.allowedVideo { //Videos getSmartAlbum(subType: .smartAlbumVideos, result: &assetCollections) } //Album let albumsResult = PHCollectionList.fetchTopLevelUserCollections(with: nil) albumsResult.enumerateObjects({ (collection, index, stop) -> Void in guard let collection = collection as? PHAssetCollection else { return } var assetsCollection = TLAssetsCollection(collection: collection) assetsCollection.fetchResult = PHAsset.fetchAssets(in: collection, options: options) if assetsCollection.count > 0, !assetCollections.contains(where: { $0.localIdentifier == collection.localIdentifier }) { assetCollections.append(assetsCollection) } }) DispatchQueue.main.async { self?.delegate?.loadCompleteAllCollection(collections: assetCollections) } } } }
46.975309
280
0.637232
f4db4cc8a760b1505ec598cb4fb9e5fb6ab34235
9,646
// // VideoPlayerView.swift // YouTubePlayer // // Created by Giles Van Gruisen on 12/21/14. // Copyright (c) 2014 Giles Van Gruisen. All rights reserved. // import UIKit public enum YouTubePlayerState: String { case Unstarted = "-1" case Ended = "0" case Playing = "1" case Paused = "2" case Buffering = "3" case Queued = "4" } public enum YouTubePlayerEvents: String { case YouTubeIframeAPIReady = "onYouTubeIframeAPIReady" case Ready = "onReady" case StateChange = "onStateChange" case PlaybackQualityChange = "onPlaybackQualityChange" } public enum YouTubePlaybackQuality: String { case Small = "small" case Medium = "medium" case Large = "large" case HD720 = "hd720" case HD1080 = "hd1080" case HighResolution = "highres" } public protocol YouTubePlayerDelegate { func playerReady(videoPlayer: YouTubePlayerView) func playerStateChanged(videoPlayer: YouTubePlayerView, playerState: YouTubePlayerState) func playerQualityChanged(videoPlayer: YouTubePlayerView, playbackQuality: YouTubePlaybackQuality) } private extension NSURL { func queryStringComponents() -> [String: AnyObject] { var dict = [String: AnyObject]() // Check for query string if let query = self.query { // Loop through pairings (separated by &) for pair in query.componentsSeparatedByString("&") { // Pull key, val from from pair parts (separated by =) and set dict[key] = value let components = pair.componentsSeparatedByString("=") dict[components[0]] = components[1] } } return dict } } public func videoIDFromYouTubeURL(videoURL: NSURL) -> String? { if let host = videoURL.host, pathComponents = videoURL.pathComponents where pathComponents.count > 1 && host.hasSuffix("youtu.be") { return pathComponents[1] as? String } return videoURL.queryStringComponents()["v"] as? String } /** Embed and control YouTube videos */ public class YouTubePlayerView: UIView, UIWebViewDelegate { public typealias YouTubePlayerParameters = [String: AnyObject] private var webView: UIWebView! /** The readiness of the player */ private(set) public var ready = false /** The current state of the video player */ private(set) public var playerState = YouTubePlayerState.Unstarted /** The current playback quality of the video player */ private(set) public var playbackQuality = YouTubePlaybackQuality.Small /** Used to configure the player */ public var playerVars = YouTubePlayerParameters() /** Used to respond to player events */ public var delegate: YouTubePlayerDelegate? // MARK: Various methods for initialization override public init(frame: CGRect) { super.init(frame: frame) printLog("initframe") buildWebView(playerParameters()) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) buildWebView(playerParameters()) } override public func layoutSubviews() { super.layoutSubviews() // Remove web view in case it's within view hierarchy, reset frame, add as subview webView.removeFromSuperview() webView.frame = bounds addSubview(webView) } // MARK: Web view initialization private func buildWebView(parameters: [String: AnyObject]) { webView = UIWebView() webView.allowsInlineMediaPlayback = true webView.mediaPlaybackRequiresUserAction = false webView.delegate = self webView.scrollView.scrollEnabled = false } // MARK: Load player public func loadVideoURL(videoURL: NSURL) { if let videoID = videoIDFromYouTubeURL(videoURL) { loadVideoID(videoID) } } public func loadVideoID(videoID: String) { var playerParams = playerParameters() playerParams["videoId"] = videoID loadWebViewWithParameters(playerParams) } public func loadPlaylistID(playlistID: String) { // No videoId necessary when listType = playlist, list = [playlist Id] playerVars["listType"] = "playlist" playerVars["list"] = playlistID loadWebViewWithParameters(playerParameters()) } // MARK: Player controls public func play() { evaluatePlayerCommand("playVideo()") } public func pause() { evaluatePlayerCommand("pauseVideo()") } public func stop() { evaluatePlayerCommand("stopVideo()") } public func clear() { evaluatePlayerCommand("clearVideo()") } public func seekTo(seconds: Float, seekAhead: Bool) { evaluatePlayerCommand("seekTo(\(seconds), \(seekAhead))") } // MARK: Playlist controls public func previousVideo() { evaluatePlayerCommand("previousVideo()") } public func nextVideo() { evaluatePlayerCommand("nextVideo()") } private func evaluatePlayerCommand(command: String) { let fullCommand = "player." + command + ";" webView.stringByEvaluatingJavaScriptFromString(fullCommand) } // MARK: Player setup private func loadWebViewWithParameters(parameters: YouTubePlayerParameters) { // Get HTML from player file in bundle let rawHTMLString = htmlStringWithFilePath(playerHTMLPath())! // Get JSON serialized parameters string let jsonParameters = serializedJSON(parameters)! // Replace %@ in rawHTMLString with jsonParameters string let htmlString = rawHTMLString.stringByReplacingOccurrencesOfString("%@", withString: jsonParameters, options: [], range: nil) // Load HTML in web view webView.loadHTMLString(htmlString, baseURL: NSURL(string: "about:blank")) } private func playerHTMLPath() -> String { return NSBundle(forClass: self.classForCoder).pathForResource("YTPlayer", ofType: "html")! } private func htmlStringWithFilePath(path: String) -> String? { // Error optional for error handling var error: NSError? // Get HTML string from path let htmlString: NSString? do { htmlString = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 htmlString = nil } // Check for error if let error = error { printLog("Lookup error: no HTML file found for path, \(path)") } return htmlString! as String } // MARK: Player parameters and defaults private func playerParameters() -> YouTubePlayerParameters { return [ "height": "100%", "width": "100%", "events": playerCallbacks(), "playerVars": playerVars ] } private func playerCallbacks() -> YouTubePlayerParameters { return [ "onReady": "onReady", "onStateChange": "onStateChange", "onPlaybackQualityChange": "onPlaybackQualityChange", "onError": "onPlayerError" ] } private func serializedJSON(object: AnyObject) -> String? { // Empty error var error: NSError? // Serialize json into NSData let jsonData: NSData? do { jsonData = try NSJSONSerialization.dataWithJSONObject(object, options: NSJSONWritingOptions.PrettyPrinted) } catch let error1 as NSError { error = error1 jsonData = nil } // Check for error and return nil if let error = error { printLog("Error parsing JSON") return nil } // Success, return JSON string return NSString(data: jsonData!, encoding: NSUTF8StringEncoding) as? String } // MARK: JS Event Handling private func handleJSEvent(eventURL: NSURL) { // Grab the last component of the queryString as string let data: String? = eventURL.queryStringComponents()["data"] as? String if let host = eventURL.host, let event = YouTubePlayerEvents(rawValue: host) { // Check event type and handle accordingly switch event { case .YouTubeIframeAPIReady: ready = true break case .Ready: delegate?.playerReady(self) break case .StateChange: if let newState = YouTubePlayerState(rawValue: data!) { playerState = newState delegate?.playerStateChanged(self, playerState: newState) } break case .PlaybackQualityChange: if let newQuality = YouTubePlaybackQuality(rawValue: data!) { playbackQuality = newQuality delegate?.playerQualityChanged(self, playbackQuality: newQuality) } break default: break } } } // MARK: UIWebViewDelegate public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url = request.URL // Check if ytplayer event and, if so, pass to handleJSEvent if let url = url where url.scheme == "ytplayer" { handleJSEvent(url) } return true } } private func printLog(str: String) { print("[YouTubePlayer] \(str)") }
28.370588
144
0.623678
db12fd6654919d2fe8604b58c286c58bbb44002e
654
import SwiftUI struct SimpleStepper: View { @State private var sleepHours = 7.0 // makes variable sleepHours as 7.0 var body: some View { VStack { // groups views vertically Stepper("How many hours did you sleep last night?", value: $sleepHours, in: 0...24, step: 0.25) // displays stepper setting sleepHours from 0 to 24 with step of 0.25 .padding() // puts padding around stepper to ensure it doesn't touch the sides of screen Text("You slept \(sleepHours, specifier: "%.2f") hours last night.") // displays text and prints sleepHours rounded to 2 decimal places } } }
43.6
177
0.643731
50d022e6b646bef70da5b875bb88b0d92997cfc7
695
class Model{ var numberToGuess = 0 var attempts = [Int]() func addGuessedNumber(guess guessedNumber:Int!) { attempts.append(guessedNumber) } func compare(guess guessedNumber:Int!) -> Int! { var result = 0 if guessedNumber < numberToGuess { result = -1 } else if guessedNumber > numberToGuess { result = 1 } return result } func isValid(guess guessedNumber:Int!) -> Bool!{ if(guessedNumber == nil){ return false } if guessedNumber < 101 && guessedNumber > -1 { return true } return false } }
21.71875
54
0.515108
3801887e4539341138100ad574665dd574213477
3,138
// // Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved. // The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (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 extension IDXClient { /// Configuration options for an IDXClient. /// /// This class is used to define the configuration, as defined in your Okta application settings, that will be used to interact with the Okta Identity Engine API. @objc(IDXClientConfiguration) public final class Configuration: NSObject, Codable { /// The issuer URL. @objc public let issuer: String /// The application's client ID. @objc public let clientId: String /// The application's client secret, if required. @objc public let clientSecret: String? /// The access scopes required by the client. @objc public let scopes: [String] /// The application's redirect URI. @objc public let redirectUri: String /// Initializes an IDX configuration object. /// - Parameters: /// - issuer: The issuer URL. /// - clientId: The application's client ID. /// - clientSecret: The application's client secret, if required. /// - scopes: The application's access scopes. /// - redirectUri: The application's redirect URI. @objc public init(issuer: String, clientId: String, clientSecret: String?, scopes: [String], redirectUri: String) { self.issuer = issuer self.clientId = clientId self.clientSecret = clientSecret self.scopes = scopes self.redirectUri = redirectUri super.init() } public override var description: String { let logger = DebugDescription(self) let components = [ logger.address(), "\(#keyPath(issuer)): \(issuer)", "\(#keyPath(clientId)): \(clientId)", "\(#keyPath(scopes)): \(scopes)", "\(#keyPath(redirectUri)): \(redirectUri)" ] return logger.brace(components.joined(separator: "; ")) } public override var debugDescription: String { let components = [ "\(#keyPath(clientSecret)): \(clientSecret ?? "-")" ] return """ \(description) { \(DebugDescription(self).format(components, indent: 4)) } """ } } }
37.357143
166
0.56979
f84a79b43f7af0baede0e2845cd764353516db38
1,760
/// Copyright (c) 2019 Razeware LLC /// /// 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. /// /// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, /// distribute, sublicense, create a derivative work, and/or sell copies of the /// Software in any work that is designed, intended, or marketed for pedagogical or /// instructional purposes related to programming, coding, application development, /// or information technology. Permission for such use, copying, modification, /// merger, publication, distribution, sublicensing, creation of derivative works, /// or sale is expressly withheld. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. public struct QuestionGroup { public let questions: [Question] public let title: String }
53.333333
83
0.75625
20746f5ba799ca86980ea9ee9ad43e0eda6670de
256
// // SocialMedia.swift // TestApp // // Created by Keyhan on 5/17/19. // Copyright © 2019 Keyhan. All rights reserved. // import Foundation // MARK: - Social Media struct SocialMedia: Codable { let youtubeChannel, twitter, facebook: [String]? }
17.066667
52
0.679688
16d6098c1af1166b40ddb257ec978316486a5f68
1,358
// // AppDelegate.swift // BMI Calculator // // Created by Sergey Romanchuk on 14.06.21. // 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. } }
36.702703
179
0.746686
184aaa619a3f9f7540fa81bb6d6f9cb409d9a5c9
3,560
// // Indicator.swift // CWPhotoBrowserDemo // // Created by chenwei on 2017/9/2. // Copyright © 2017年 cwwise. All rights reserved. // import UIKit /// 进度指示器 public protocol Indicator { var viewCenter: CGPoint { get set } var view: UIView { get } } extension Indicator { public var viewCenter: CGPoint { get { return view.center } set { view.center = newValue } } } public class ProgressIndicator: UIView { public var progress: CGFloat = 0 { didSet { fanshapedLayer.path = makeProgressPath(progress).cgPath } } private var circleLayer: CAShapeLayer private var fanshapedLayer: CAShapeLayer public convenience init() { let frame = CGRect(x: 0, y: 0, width: 50, height: 50) self.init(frame: frame) } public override init(frame: CGRect) { circleLayer = CAShapeLayer() fanshapedLayer = CAShapeLayer() super.init(frame: frame) setupUI() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { backgroundColor = UIColor.clear let strokeColor = UIColor(white: 1, alpha: 0.8).cgColor circleLayer.strokeColor = strokeColor circleLayer.fillColor = UIColor.clear.cgColor circleLayer.path = makeCirclePath().cgPath layer.addSublayer(circleLayer) fanshapedLayer.fillColor = strokeColor layer.addSublayer(fanshapedLayer) } private func makeCirclePath() -> UIBezierPath { let arcCenter = CGPoint(x: bounds.midX, y: bounds.midY) let path = UIBezierPath(arcCenter: arcCenter, radius: 25, startAngle: 0, endAngle: CGFloat.pi * 2, clockwise: true) path.lineWidth = 2 return path } private func makeProgressPath(_ progress: CGFloat) -> UIBezierPath { let center = CGPoint(x: bounds.midX, y: bounds.midY) let radius = bounds.midY - 2.5 let path = UIBezierPath() path.move(to: center) path.addLine(to: CGPoint(x: bounds.midX, y: center.y - radius)) path.addArc(withCenter: center, radius: radius, startAngle: -CGFloat.pi / 2, endAngle: -CGFloat.pi / 2 + CGFloat.pi * 2 * progress, clockwise: true) path.close() path.lineWidth = 1 return path } } extension ProgressIndicator: Indicator { public var view: UIView { return self } } public class TextIndicator: UIView { private let activityIndicatorView: UIActivityIndicatorView private let textLabel: UILabel public override init(frame: CGRect) { let indicatorStyle = UIActivityIndicatorViewStyle.gray activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:indicatorStyle) activityIndicatorView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin, .flexibleTopMargin] textLabel = UILabel() textLabel.font = UIFont.systemFont(ofSize: 11) super.init(frame: frame) self.addSubview(activityIndicatorView) self.addSubview(textLabel) } public convenience init() { let frame = CGRect(x: 0, y: 0, width: 50, height: 50) self.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
26.176471
156
0.624719
769245e6bf30926721bc0605064cda0db1008a0c
1,208
// // MAVResultCommonEnum.swift // MAVLink Protocol Swift Library // // Generated from ardupilotmega.xml, common.xml, uAvionix.xml on Tue Jan 17 2017 by mavgen_swift.py // https://github.com/modnovolyk/MAVLinkSwift // /// result from a mavlink command public enum MAVResult: Int { /// Command ACCEPTED and EXECUTED case accepted = 0 /// Command TEMPORARY REJECTED/DENIED case temporarilyRejected = 1 /// Command PERMANENTLY DENIED case denied = 2 /// Command UNKNOWN/UNSUPPORTED case unsupported = 3 /// Command executed, but failed case failed = 4 } extension MAVResult: Enumeration { public static var typeName = "MAV_RESULT" public static var typeDescription = "result from a mavlink command" public static var allMembers = [accepted, temporarilyRejected, denied, unsupported, failed] public static var membersDescriptions = [("MAV_RESULT_ACCEPTED", "Command ACCEPTED and EXECUTED"), ("MAV_RESULT_TEMPORARILY_REJECTED", "Command TEMPORARY REJECTED/DENIED"), ("MAV_RESULT_DENIED", "Command PERMANENTLY DENIED"), ("MAV_RESULT_UNSUPPORTED", "Command UNKNOWN/UNSUPPORTED"), ("MAV_RESULT_FAILED", "Command executed, but failed")] public static var enumEnd = UInt(5) }
34.514286
343
0.749172
61cba21ede746af38065a03977ff41c7c0c172df
5,946
/*: # Package Manager Test Naming Conventions * Proposal: [SE-0129](0129-package-manager-test-naming-conventions.md) * Author: [Anders Bertelrud](https://github.com/abertelrud) * Review Manager: [Daniel Dunbar](https://github.com/ddunbar) * Status: **Implemented (Swift 3)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-build-dev/Week-of-Mon-20160725/000572.html) ## Introduction The Swift Package Manager uses a convention-based rather than a declarative approach for various aspects of package configuration. This is as true of the naming and structure of tests as of other kinds of targets. However, the current conventions are somewhat inconsistent and unintuitive, and they also do not provide enough flexibility. This proposal seeks to address these problems through updated conventions. ## Motivation ### Predictability of test target names Module names for test targets are currently formed by appending the suffix `TestSuite` to the name of the corresponding directory under the top-level `Tests` directory in the package. This makes it non-obvious to know what name to pass to `swift package test` in order to run just one set of tests. This is also the case for any other context in which the module name is needed. ### Ability to declare test target dependencies The way in which the test module name is formed also makes it difficult to add target dependencies that specify the name of the test. This makes it hard to make a test depend on a library, such as a helper library containing shared code for use by the tests. Another consequence of unconditionally appending a `TestSuite` suffix to every module under the `Tests` directory is that it becomes impossible to add modules under `Tests` that define helper libraries for use only by tests. ### Reportability of errors In order for error messages to be understandable and actionable, they should refer to names the user can see and control. Also, the naming convention needs to have a reliable way of determining user intent so that error messages can be made as clear as possible. ## Proposed solution The essence of the proposed solution is to make the naming of tests be more predictable and more under the package author's control. This is achieved in part by simplifying the naming conventions, and in part by reducing the number of differences between the conventions for the the `Tests` and the `Sources` top-level directories. First, the naming convention will be changed so a module will be considered a test if it: 1. is located under the `Tests` directory 2. has a name that ends with `Tests` A future proposal may want to loosen the restriction so that tests can also be located under `Sources`, if we feel that there is any use for that. As part of this proposal, SwiftPM will emit an error for any tests located under `Sources`. Allowing non-test targets under the `Tests` directory will unblock future improvements to allow test-only libraries to be located there. It will also unblock the potential to support test executables in the future, though this proposal does not specifically address that. Like any other target, a test will be able to be mentioned in a dependency declaration. As a convenience, if there is a target named `Foo` and a test target named `FooTests`, a dependency between the two will be automatically established. It will still be allowed to have a `FooTests` test without a corresponding `Foo` source module. This can be useful for integration tests or for fixtures, etc. ## Detailed design 1. Change the naming conventions so that a module will be considered a test if it: - is located under the top-level `Tests` directory, and - has a name that ends with `Tests` 2. Allow a target dependency to refer to the name of a test target, which will allow package authors to create dependencies between tests and libraries. 3. Add an implicit dependency between any test target a non-test target that has the same name but without the `Tests` suffix. 4. For now, make it an error to have executables or libraries under `Tests` (for technical reasons, a `LinuxMain.swift` source file is permitted, and indeed expected, under the `Tests` top-level directory). The intent is to loosen this restriction in a future proposal, to allow test-specific libraries and test executables under `Tests`. 5. For now, make it an error to have tests under `Sources`. We may loosen this this restriction at some point, but would need to define what it would mean from a conceptual point of view to have tests under `Sources` instead of `Tests`. 6. Improve error reporting to reflect the new conventions. This includes adding more checks, and also auditing all the error messages relating to testing to see if there is more information that should be displayed. ## Impact on existing code The change in naming conventions does mean that any module under the top-level `Tests` directory whose name ends with the suffix `Tests` will be considered a test module. The fact that this proposal does not involve allowing tests to be located under `Sources`, and the fact that any module under `Tests` already had an unconditional `TestSuite` suffix string appended, makes it unlikely that any current non-test module under `Tests` would suddenly be considered a test. Any module with a `Tests` suffix under `Sources` would need to be renamed. Any current package that refers to a test module using a `TestSuite` suffix will need to be changed. ## Alternatives considered An alternative that was considered was to enhance the PackageDescription API to let package authors explicitly tag targets as tests. While we might still want to add this for cases in which the author doesn't want to use any of the naming conventions, we don't want such an API to be the only way to specify tests. ---------- [Previous](@previous) | [Next](@next) */
44.044444
113
0.777834