repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
csujedihy/Flicks | Pods/Cosmos/Cosmos/CosmosLayerHelper.swift | 3 | 908 | import UIKit
/// Helper class for creating CALayer objects.
class CosmosLayerHelper {
/**
Creates a text layer for the given text string and font.
- parameter text: The text shown in the layer.
- parameter font: The text font. It is also used to calculate the layer bounds.
- parameter color: Text color.
- returns: New text layer.
*/
class func createTextLayer(text: String, font: UIFont, color: UIColor) -> CATextLayer {
let size = NSString(string: text).sizeWithAttributes([NSFontAttributeName: font])
let layer = CATextLayer()
layer.bounds = CGRect(origin: CGPoint(), size: size)
layer.anchorPoint = CGPoint()
layer.string = text
layer.font = CGFontCreateWithFontName(font.fontName)
layer.fontSize = font.pointSize
layer.foregroundColor = color.CGColor
layer.contentsScale = UIScreen.mainScreen().scale
return layer
}
}
| gpl-3.0 | d3258469d0805e4932db165a34e3bce3 | 28.290323 | 89 | 0.699339 | 4.562814 | false | false | false | false |
Look-ARound/LookARound2 | Pods/HDAugmentedReality/HDAugmentedReality/Classes/ARPresenterTransform.swift | 1 | 5994 | //
// ARPresenter+Stacking.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 13/04/2017.
// Copyright © 2017 Danijel Huis. All rights reserved.
//
import Foundation
import UIKit
/**
Responsible for transform/layout of annotations, usually after they have been layouted by ARPresenter.
e.g. stacking.
ARPresenterTransform can change arPositionOffset of annotations, or set transform.
*/
public protocol ARPresenterTransform: class
{
/// ARresenter, it is set when setting presenterTransform on presenter.
var arPresenter: ARPresenter! { set get }
func preLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
func postLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
}
open class ARPresenterStackTransform: ARPresenterTransform
{
open var arPresenter: ARPresenter!
public init() {}
public func preLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
}
public func postLayout(arStatus: ARStatus, reloadType: ARViewController.ReloadType, needsRelayout: Bool)
{
if needsRelayout
{
self.stackAnnotationViews()
}
}
/**
Stacks annotationViews vertically if they are overlapping. This works by comparing frames of annotationViews.
This must be called if parameters that affect relative x,y of annotations changed.
- if azimuths on annotations are calculated(This can change relative horizontal positions of annotations)
- when adjustVerticalOffsetParameters is called because that can affect relative vertical positions of annotations
Pitch/heading of the device doesn't affect relative positions of annotationViews.
*/
open func stackAnnotationViews()
{
guard self.arPresenter.annotationViews.count > 0 else { return }
guard let arStatus = self.arPresenter.arViewController?.arStatus else { return }
// Sorting makes stacking faster
let sortedAnnotationViews = self.arPresenter.annotationViews.sorted(by: { $0.frame.origin.y > $1.frame.origin.y })
let centerX = self.arPresenter.bounds.size.width * 0.5
let totalWidth = CGFloat( arStatus.hPixelsPerDegree * 360 )
let rightBorder = centerX + totalWidth / 2
let leftBorder = centerX - totalWidth / 2
// This is simple brute-force comparing of frames, compares annotationView1 to all annotationsViews beneath(before) it, if overlap is found,
// annotationView1 is moved above it. This is done until annotationView1 is not overlapped by any other annotationView beneath it. Then it moves to
// the next annotationView.
for annotationView1 in sortedAnnotationViews
{
//===== Alternate frame
// Annotation views are positioned left(0° - -180°) and right(0° - 180°) from the center of the screen. So if annotationView1
// is on -180°, its x position is ~ -6000px, and if annoationView2 is on 180°, its x position is ~ 6000px. These two annotationViews
// are basically on the same position (180° = -180°) but simply by comparing frames -6000px != 6000px we cannot know that.
// So we are construcing alternate frame so that these near-border annotations can "see" each other.
var hasAlternateFrame = false
let left = annotationView1.frame.origin.x;
let right = left + annotationView1.frame.size.width
// Assuming that annotationViews have same width
if right > (rightBorder - annotationView1.frame.size.width)
{
annotationView1.arAlternateFrame = annotationView1.frame
annotationView1.arAlternateFrame.origin.x = annotationView1.frame.origin.x - totalWidth
hasAlternateFrame = true
}
else if left < (leftBorder + annotationView1.frame.size.width)
{
annotationView1.arAlternateFrame = annotationView1.frame
annotationView1.arAlternateFrame.origin.x = annotationView1.frame.origin.x + totalWidth
hasAlternateFrame = true
}
//====== Detecting collision
var hasCollision = false
let y = annotationView1.frame.origin.y;
var i = 0
while i < sortedAnnotationViews.count
{
let annotationView2 = sortedAnnotationViews[i]
if annotationView1 == annotationView2
{
// If collision, start over because movement could cause additional collisions
if hasCollision
{
hasCollision = false
i = 0
continue
}
break
}
let collision = annotationView1.frame.intersects(annotationView2.frame)
if collision
{
annotationView1.frame.origin.y = annotationView2.frame.origin.y - annotationView1.frame.size.height - 5
annotationView1.arAlternateFrame.origin.y = annotationView1.frame.origin.y
hasCollision = true
}
else if hasAlternateFrame && annotationView1.arAlternateFrame.intersects(annotationView2.frame)
{
annotationView1.frame.origin.y = annotationView2.frame.origin.y - annotationView1.frame.size.height - 5
annotationView1.arAlternateFrame.origin.y = annotationView1.frame.origin.y
hasCollision = true
}
i = i + 1
}
annotationView1.arPositionOffset.y = annotationView1.frame.origin.y - y;
}
}
}
| apache-2.0 | 19e340ad59acdd6f07812b3d96e69e9c | 42.686131 | 155 | 0.631579 | 5.016764 | false | false | false | false |
onmyway133/Github.swift | GithubSwiftTests/Classes/ClientSpec.swift | 1 | 1603 | //
// ClientSpec.swift
// GithubSwift
//
// Created by Khoa Pham on 29/03/16.
// Copyright © 2016 Fantageek. All rights reserved.
//
import GithubSwift
import Quick
import Nimble
import Mockingjay
import RxSwift
import Sugar
class ClientSpec: QuickSpec {
override func spec() {
describe("without a user") {
var client: Client!
beforeEach {
client = Client(server: Server.dotComServer)
}
it("should create a client") {
expect(client).notTo(beNil())
expect(client.user).to(beNil())
expect(client.isAuthenticated).to(beFalsy())
}
}
describe("authenticated") {
var client: Client!
var user: User!
beforeEach {
user = User(rawLogin: "octokit-testing-user", server: Server.dotComServer)
client = Client(authenticatedUser: user, token: "")
}
it("should create client") {
expect(client).toNot(beNil())
expect(user).toNot(beNil())
expect(client.user).to(equal(user))
expect(client.isAuthenticated).to(beTrue())
}
}
describe("unauthenticated") {
var client: Client!
var user: User!
beforeEach {
user = User(rawLogin: "octokit-testing-user", server: Server.dotComServer)
client = Client(unauthenticatedUser: user)
}
it("should create client") {
expect(client).toNot(beNil())
expect(user).toNot(beNil())
expect(client.user).to(equal(user))
expect(client.isAuthenticated).to(beFalse())
}
}
}
}
| mit | 482579457ae234ba140f0728a85f5961 | 22.217391 | 82 | 0.591136 | 4.238095 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/QueryEntities.swift | 1 | 2986 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** QueryEntities. */
public struct QueryEntities: Encodable {
/// The entity query feature to perform. Supported features are `disambiguate` and `similar_entities`.
public var feature: String?
/// A text string that appears within the entity text field.
public var entity: QueryEntitiesEntity?
/// Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`.
public var context: QueryEntitiesContext?
/// The number of results to return. The default is `10`. The maximum is `1000`.
public var count: Int?
/// The number of evidence items to return for each result. The default is `0`. The maximum number of evidence items per query is 10,000.
public var evidenceCount: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case feature = "feature"
case entity = "entity"
case context = "context"
case count = "count"
case evidenceCount = "evidence_count"
}
/**
Initialize a `QueryEntities` with member variables.
- parameter feature: The entity query feature to perform. Supported features are `disambiguate` and `similar_entities`.
- parameter entity: A text string that appears within the entity text field.
- parameter context: Entity text to provide context for the queried entity and rank based on that association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`.
- parameter count: The number of results to return. The default is `10`. The maximum is `1000`.
- parameter evidenceCount: The number of evidence items to return for each result. The default is `0`. The maximum number of evidence items per query is 10,000.
- returns: An initialized `QueryEntities`.
*/
public init(feature: String? = nil, entity: QueryEntitiesEntity? = nil, context: QueryEntitiesContext? = nil, count: Int? = nil, evidenceCount: Int? = nil) {
self.feature = feature
self.entity = entity
self.context = context
self.count = count
self.evidenceCount = evidenceCount
}
}
| mit | 7f9337c0bae7f6073002df60bc848421 | 44.938462 | 247 | 0.711989 | 4.463378 | false | false | false | false |
criticalmaps/criticalmaps-ios | CriticalMapsKit/Tests/TwitterFeedFeatureTests/TwitterFeedFeatureCoreTests.swift | 1 | 10716 | import ApiClient
import Combine
import ComposableArchitecture
import CustomDump
import SharedDependencies
import SharedModels
import TwitterFeedFeature
import UIApplicationClient
import XCTest
@MainActor
final class TwitterFeedCoreTests: XCTestCase {
func test_onAppear_shouldFetchTwitterData() async throws {
let decoder: JSONDecoder = .twitterFeedDecoder
let tweetData = try XCTUnwrap(twitterFeedData)
let feed = try decoder.decode(TwitterFeed.self, from: tweetData)
let store = TestStore(
initialState: TwitterFeedFeature.State(),
reducer: TwitterFeedFeature()
)
store.dependencies.twitterService.getTweets = { feed.statuses }
await _ = store.send(.onAppear)
await store.receive(.fetchData) {
$0.twitterFeedIsLoading = true
}
await store.receive(.fetchDataResponse(.success(feed.statuses))) {
$0.twitterFeedIsLoading = false
$0.tweets = IdentifiedArray(uniqueElements: feed.statuses)
}
}
func test_tweetDecodingTest() throws {
let decoder: JSONDecoder = .twitterFeedDecoder
let tweetData = try XCTUnwrap(twitterFeedData)
let feed = try decoder.decode(TwitterFeed.self, from: tweetData)
XCTAssertNoDifference(
feed,
TwitterFeed(statuses: [
Tweet(
id: "1452287570415693850",
text: "RT @CriticalMassR: @CriticalMaps Venerdì 29 ottobre, festa per la riapertura della",
createdAt: Date(timeIntervalSinceReferenceDate: 656780113.0),
user: .init(
name: "Un Andrea Qualunque",
screenName: "0_0_A_B_0_0",
profileImageUrl: "https://pbs.twimg.com/profile_images/1452271548644134918/YCKQHQRL_normal.jpg"
)
)
])
)
}
}
let twitterFeedData = #"""
{
"statuses": [
{
"created_at": "Sun Oct 24 14:55:13 +0000 2021",
"id": 1452287570415693800,
"id_str": "1452287570415693850",
"text": "RT @CriticalMassR: @CriticalMaps Venerdì 29 ottobre, festa per la riapertura della",
"truncated": false,
"entities": {
"hashtags": [
{
"text": "Ciclofficina",
"indices": [
83,
96
]
}
],
"symbols": [],
"user_mentions": [
{
"screen_name": "CriticalMassR",
"name": "#CriticalMassRoma",
"id": 3063043545,
"id_str": "3063043545",
"indices": [
3,
17
]
},
{
"screen_name": "CriticalMaps",
"name": "Critical Maps",
"id": 2881177769,
"id_str": "2881177769",
"indices": [
19,
32
]
}
],
"urls": []
},
"metadata": {
"iso_language_code": "it",
"result_type": "recent"
},
"source": "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 2824973992,
"id_str": "2824973992",
"name": "Un Andrea Qualunque",
"screen_name": "0_0_A_B_0_0",
"location": "Roma, Lazio",
"description": "Curiosità atta a migliorare questo mondo. Amo il Mediterraneo e tutti i suoi popoli.",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 24,
"friends_count": 372,
"listed_count": 0,
"created_at": "Sun Oct 12 12:32:19 +0000 2014",
"favourites_count": 192,
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"verified": false,
"statuses_count": 112,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "C0DEED",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/1452271548644134918/YCKQHQRL_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1452271548644134918/YCKQHQRL_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/2824973992/1509895265",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none",
"withheld_in_countries": []
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"retweeted_status": {
"created_at": "Sun Oct 24 14:17:11 +0000 2021",
"id": 1452277997453590500,
"id_str": "1452277997453590541",
"text": "@CriticalMaps Venerdì 29 ottobre",
"truncated": true,
"entities": {
"hashtags": [
{
"text": "Ciclofficina",
"indices": [
64,
77
]
}
],
"symbols": [],
"user_mentions": [
{
"screen_name": "CriticalMaps",
"name": "Critical Maps",
"id": 2881177769,
"id_str": "2881177769",
"indices": [
0,
13
]
}
],
"urls": [
{
"url": "https://t.co/D7PFyPBCp2",
"expanded_url": "https://twitter.com/i/web/status/1452277997453590541",
"display_url": "twitter.com/i/web/status/1…",
"indices": [
117,
140
]
}
]
},
"metadata": {
"iso_language_code": "it",
"result_type": "recent"
},
"source": "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": 2881177769,
"in_reply_to_user_id_str": "2881177769",
"in_reply_to_screen_name": "CriticalMaps",
"user": {
"id": 3063043545,
"id_str": "3063043545",
"name": "#CriticalMassRoma",
"screen_name": "CriticalMassR",
"location": "https://www.facebook.com/group",
"description": "https://t.co/jaQM8xZQpU",
"url": "https://t.co/TwygvcjXc3",
"entities": {
"url": {
"urls": [
{
"url": "https://t.co/TwygvcjXc3",
"expanded_url": "http://criticalmassroma.caster.fm",
"display_url": "criticalmassroma.caster.fm",
"indices": [
0,
23
]
}
]
},
"description": {
"urls": [
{
"url": "https://t.co/jaQM8xZQpU",
"expanded_url": "https://www.facebook.com/CriticalMassRM/",
"display_url": "facebook.com/CriticalMassRM/",
"indices": [
0,
23
]
}
]
}
},
"protected": false,
"followers_count": 1020,
"friends_count": 1543,
"listed_count": 27,
"created_at": "Wed Feb 25 19:35:19 +0000 2015",
"favourites_count": 2162,
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"verified": false,
"statuses_count": 2068,
"lang": null,
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "0099B9",
"profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png",
"profile_background_tile": true,
"profile_image_url": "http://pbs.twimg.com/profile_images/610546977202241536/axclfbgj_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/610546977202241536/axclfbgj_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/3063043545/1424893766",
"profile_link_color": "0099B9",
"profile_sidebar_border_color": "000000",
"profile_sidebar_fill_color": "000000",
"profile_text_color": "000000",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none",
"withheld_in_countries": []
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 2,
"favorite_count": 3,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "it"
},
"is_quote_status": false,
"retweet_count": 2,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "it"
}
]
}
"""#.data(using: .utf8)
| mit | a95b8512c925b0102272aee229ee7a0a | 33.548387 | 117 | 0.491877 | 3.907333 | false | false | false | false |
adrfer/swift | validation-test/compiler_crashers_2_fixed/0003-rdar20564378.swift | 3 | 4390 | // RUN: not %target-swift-frontend %s -parse
public protocol Q_SequenceDefaultsType {
typealias Element
typealias Generator : GeneratorType
func generate() -> Generator
}
extension Q_SequenceDefaultsType {
public final func underestimateCount() -> Int { return 0 }
public final func preprocessingPass<R>(body: (Self)->R) -> R? {
return nil
}
/// Create a ContiguousArray containing the elements of `self`,
/// in the same order.
public final func copyToContiguousArray() -> ContiguousArray<Generator.Element> {
let initialCapacity = underestimateCount()
var result = _ContiguousArrayBuffer<Generator.Element>(
count: initialCapacity, minimumCapacity: 0)
var g = self.generate()
while let x = g.next() {
result += CollectionOfOne(x)
}
return ContiguousArray(result)
}
/// Initialize the storage at baseAddress with the contents of this
/// sequence.
public final func initializeRawMemory(
baseAddress: UnsafeMutablePointer<Generator.Element>
) {
var p = baseAddress
var g = self.generate()
while let element = g.next() {
p.initialize(element)
p += 1
}
}
public final static func _constrainElement(Generator.Element) {}
}
/// A type that can be iterated with a `for`\ ...\ `in` loop.
///
/// `SequenceType` makes no requirement on conforming types regarding
/// whether they will be destructively "consumed" by iteration. To
/// ensure non-destructive iteration, constrain your *sequence* to
/// `CollectionType`.
public protocol Q_SequenceType : Q_SequenceDefaultsType {
/// A type that provides the *sequence*\ 's iteration interface and
/// encapsulates its iteration state.
typealias Generator : GeneratorType
/// Return a *generator* over the elements of this *sequence*.
///
/// Complexity: O(1)
func generate() -> Generator
/// Return a value less than or equal to the number of elements in
/// self, **nondestructively**.
///
/// Complexity: O(N)
func underestimateCount() -> Int
/// If `self` is multi-pass (i.e., a `CollectionType`), invoke the function
/// on `self` and return its result. Otherwise, return `nil`.
func preprocessingPass<R>(body: (Self)->R) -> R?
/// Create a ContiguousArray containing the elements of `self`,
/// in the same order.
func copyToContiguousArray() -> ContiguousArray<Element>
/// Initialize the storage at baseAddress with the contents of this
/// sequence.
func initializeRawMemory(
baseAddress: UnsafeMutablePointer<Element>
)
static func _constrainElement(Element)
}
public extension GeneratorType {
typealias Generator = Self
public final func generate() -> Generator {
return self
}
}
public protocol Q_CollectionDefaultsType : Q_SequenceType {
typealias Index : ForwardIndexType
subscript(position: Index) -> Element {get}
var startIndex: Index {get}
var endIndex: Index {get}
}
extension Q_CollectionDefaultsType {
public final func count() -> Index.Distance {
return distance(startIndex, endIndex)
}
public final func underestimateCount() -> Int {
let n = count().toIntMax()
return n > IntMax(Int.max) ? Int.max : Int(n)
}
public final func preprocessingPass<R>(body: (Self)->R) -> R? {
return body(self)
}
/*
typealias Generator = Q_IndexingGenerator<Self>
public final func generate() -> Q_IndexingGenerator<Self> {
return Q_IndexingGenerator(pos: self.startIndex, elements: self)
}
*/
}
public struct Q_IndexingGenerator<C: Q_CollectionDefaultsType> : GeneratorType {
public typealias Element = C.Element
var pos: C.Index
let elements: C
public mutating func next() -> Element? {
if pos == elements.endIndex {
return nil
}
let ret = elements[pos]
pos += 1
return ret
}
}
public protocol Q_CollectionType : Q_CollectionDefaultsType {
func count() -> Index.Distance
subscript(position: Index) -> Element {get}
}
extension Array : Q_CollectionType {
public func copyToContiguousArray() -> ContiguousArray<Element> {
return ContiguousArray(self~>_copyToNativeArrayBuffer())
}
}
struct Boo : Q_CollectionType {
let startIndex: Int = 0
let endIndex: Int = 10
func generate() -> Q_IndexingGenerator<Boo> {
return Q_IndexingGenerator(pos: self.startIndex, elements: self)
}
subscript(i: Int) -> String {
return "Boo"
}
}
| apache-2.0 | cd5efcc81273cfed196b9816157998f5 | 26.4375 | 83 | 0.690433 | 4.320866 | false | false | false | false |
slavapestov/swift | test/Interpreter/SDK/objc_extensions.swift | 1 | 1165 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
extension NSObject {
func frob() {
print("I've been frobbed!")
}
var asHerself : NSObject {
return self
}
var blackHoleWithHawkingRadiation : NSObject? {
get {
print("e+")
return nil
}
set {
print("e-")
}
}
}
var o = NSObject()
func drop(x: NSObject?) {}
// CHECK: true
print(o.respondsToSelector("frob"))
// CHECK: true
print(o.respondsToSelector("asHerself"))
// CHECK: false
print(o.respondsToSelector("setAsHerself:"))
// CHECK: true
print(o.respondsToSelector("blackHoleWithHawkingRadiation"))
// CHECK: true
print(o.respondsToSelector("setBlackHoleWithHawkingRadiation:"))
// Test #selector for referring to methods.
// CHECK: true
print(o.respondsToSelector(#selector(NSObject.frob)))
// CHECK: I've been frobbed!
o.frob()
// CHECK: true
print(o === o.asHerself)
// CHECK: e+
drop(o.blackHoleWithHawkingRadiation)
// CHECK: e-
o.blackHoleWithHawkingRadiation = NSObject()
// Use of extensions via bridging
let str = "Hello, world"
// CHECK: I've been frobbed!
str.frob()
| apache-2.0 | 7534d198df066a789f5673941626a12f | 18.745763 | 64 | 0.685837 | 3.488024 | false | false | false | false |
elpassion/el-space-ios | ELSpaceTests/TestCases/ViewModels/ActivityTypeViewModelSpec.swift | 1 | 4317 | import Quick
import Nimble
@testable import ELSpace
class ActivityTypeViewModelSpec: QuickSpec {
override func spec() {
describe("ActivityTypeViewModel") {
var sut: ActivityTypeViewModel!
context("time report") {
beforeEach {
sut = ActivityTypeViewModel(type: .normal, isUserInteractionEnabled: false)
}
it("should be proper type") {
expect(sut.type).to(equal(ReportType.normal))
}
it("shoud have proper title") {
expect(sut.title).to(equal("TIME REPORT"))
}
it("should have proper image for selected") {
expect(sut.imageSelected).to(equal(UIImage(named: "time_report_selected")))
}
it("should have proper image for unselected") {
expect(sut.imageUnselected).to(equal(UIImage(named: "time_report_unselected")))
}
}
context("vacation") {
beforeEach {
sut = ActivityTypeViewModel(type: .paidVacations, isUserInteractionEnabled: false)
}
it("should be proper type") {
expect(sut.type).to(equal(ReportType.paidVacations))
}
it("shoud have proper title") {
expect(sut.title).to(equal("VACATION"))
}
it("should have proper image for selected") {
expect(sut.imageSelected).to(equal(UIImage(named: "vacation_selected")))
}
it("should have proper image for unselected") {
expect(sut.imageUnselected).to(equal(UIImage(named: "vacation_unselected")))
}
}
context("day off") {
beforeEach {
sut = ActivityTypeViewModel(type: .unpaidDayOff, isUserInteractionEnabled: false)
}
it("should be proper type") {
expect(sut.type).to(equal(ReportType.unpaidDayOff))
}
it("shoud have proper title") {
expect(sut.title).to(equal("DAY OFF"))
}
it("should have proper image for selected") {
expect(sut.imageSelected).to(equal(UIImage(named: "day_off_selected")))
}
it("should have proper image for unselected") {
expect(sut.imageUnselected).to(equal(UIImage(named: "day_off_unselected")))
}
}
context("sick leave") {
beforeEach {
sut = ActivityTypeViewModel(type: .sickLeave, isUserInteractionEnabled: false)
}
it("should be proper type") {
expect(sut.type).to(equal(ReportType.sickLeave))
}
it("shoud have proper title") {
expect(sut.title).to(equal("SICK LEAVE"))
}
it("should have proper image for selected") {
expect(sut.imageSelected).to(equal(UIImage(named: "sick_leave_selected")))
}
it("should have proper image for unselected") {
expect(sut.imageUnselected).to(equal(UIImage(named: "sick_leave_unselected")))
}
}
context("conference") {
beforeEach {
sut = ActivityTypeViewModel(type: .conference, isUserInteractionEnabled: false)
}
it("should be proper type") {
expect(sut.type).to(equal(ReportType.conference))
}
it("shoud have proper title") {
expect(sut.title).to(equal("CONFERENCE"))
}
it("should have proper image for selected") {
expect(sut.imageSelected).to(equal(UIImage(named: "conference_selected")))
}
it("should have proper image for unselected") {
expect(sut.imageUnselected).to(equal(UIImage(named: "conference_unselected")))
}
}
}
}
}
| gpl-3.0 | de13c7441918d48ced4f0c8672b84fa2 | 34.097561 | 102 | 0.491545 | 5.226392 | false | false | false | false |
SwiftGFX/SwiftMath | Sources/Vector3+nosimd.swift | 1 | 4085 | //
// Vector3f+nosimd.swift
// SwiftMath
//
// Created by Andrey Volodin on 07.10.16.
//
//
#if NOSIMD
#if (os(OSX) || os(iOS) || os(tvOS) || os(watchOS))
import Darwin
#elseif os(Linux) || os(Android)
import Glibc
#endif
@frozen
public struct Vector3f {
public var x: Float = 0.0
public var y: Float = 0.0
public var z: Float = 0.0
public var r: Float { get { return x } set { x = newValue } }
public var g: Float { get { return y } set { y = newValue } }
public var b: Float { get { return z } set { z = newValue } }
public var s: Float { get { return x } set { x = newValue } }
public var t: Float { get { return y } set { y = newValue } }
public var p: Float { get { return z } set { z = newValue } }
public subscript(x: Int) -> Float {
get {
if x == 0 { return self.x }
if x == 1 { return self.y }
if x == 2 { return self.z }
fatalError("Index outside of bounds")
}
set {
if x == 0 { self.x = newValue; return }
if x == 1 { self.y = newValue; return }
if x == 2 { self.z = newValue; return }
fatalError("Index outside of bounds")
}
}
public init() {}
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x
self.y = y
self.z = z
}
public init(_ scalar: Float) {
self.init(scalar, scalar, scalar)
}
public init(x: Float, y: Float, z: Float) {
self.init(x, y, z)
}
}
extension Vector3f {
public var lengthSquared: Float {
return x * x + y * y + z * z
}
public var length: Float {
return sqrt(self.lengthSquared)
}
public func dot(_ v: Vector3f) -> Float {
return x * v.x + y * v.y + z * v.z
}
public func cross(_ v: Vector3f) -> Vector3f {
return Vector3f(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)
}
public var normalized: Vector3f {
let lengthSquared = self.lengthSquared
if lengthSquared ~= 0 || lengthSquared ~= 1 {
return self
}
return self / sqrt(lengthSquared)
}
public func interpolated(with v: Vector3f, by t: Float) -> Vector3f {
return self + (v - self) * t
}
public static prefix func -(v: Vector3f) -> Vector3f {
return Vector3f(-v.x, -v.y, -v.z)
}
public static func +(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z)
}
public static func -(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z)
}
public static func *(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z)
}
public static func *(lhs: Vector3f, rhs: Float) -> Vector3f {
return Vector3f(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs)
}
public static func /(lhs: Vector3f, rhs: Vector3f) -> Vector3f {
return Vector3f(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z)
}
public static func /(lhs: Vector3f, rhs: Float) -> Vector3f {
return Vector3f(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs)
}
public static func ~=(lhs: Vector3f, rhs: Vector3f) -> Bool {
return lhs.x ~= rhs.x && lhs.y ~= rhs.y && lhs.z ~= rhs.z
}
public static func *(lhs: Vector3f, rhs: Matrix3x3f) -> Vector3f {
return Vector3f(
lhs.x * rhs.m11 + lhs.y * rhs.m21 + lhs.z * rhs.m31,
lhs.x * rhs.m12 + lhs.y * rhs.m22 + lhs.z * rhs.m32,
lhs.x * rhs.m13 + lhs.y * rhs.m23 + lhs.z * rhs.m33
)
}
public static func *(lhs: Matrix3x3f, rhs: Vector3f) -> Vector3f {
return rhs * lhs
}
}
extension Vector3f: Equatable {
public static func ==(lhs: Vector3f, rhs: Vector3f) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
}
#endif
| bsd-2-clause | 29e88b54976feace11e6c5a3d7fe0eb1 | 27.368056 | 80 | 0.521175 | 3.171584 | false | false | false | false |
trill-lang/trill | Sources/IRGen/FunctionIRGen.swift | 2 | 11033 | ///
/// FunctionIRGen.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import AST
import LLVM
import Foundation
extension IRGenerator {
func createEntryBlockAlloca(_ function: Function,
type: IRType,
name: String,
storage: Storage,
initial: IRValue? = nil) -> VarBinding {
let currentBlock = builder.insertBlock
let entryBlock = function.entryBlock!
if let firstInst = entryBlock.firstInstruction {
builder.position(firstInst, block: entryBlock)
}
let alloca = builder.buildAlloca(type: type, name: name)
if let block = currentBlock {
builder.positionAtEnd(of: block)
}
if let initial = initial {
builder.buildStore(initial, to: alloca)
}
return VarBinding(ref: alloca,
storage: storage,
read: { self.builder.buildLoad(alloca) },
write: { self.builder.buildStore($0, to: alloca) })
}
@discardableResult
func codegenFunctionPrototype(_ expr: FuncDecl) -> Function {
let mangled = Mangler.mangle(expr)
if let existing = module.function(named: mangled) {
return existing
}
var argTys = [IRType]()
for arg in expr.args {
var type = resolveLLVMType(arg.type)
if arg.isImplicitSelf && storage(for: arg.type) != .reference {
type = PointerType(pointee: type)
}
argTys.append(type)
}
let type = resolveLLVMType(expr.returnType)
let fType = FunctionType(argTypes: argTys, returnType: type, isVarArg: expr.hasVarArgs)
return builder.addFunction(mangled, type: fType)
}
public func visitBreakStmt(_ expr: BreakStmt) -> Result {
guard let target = currentBreakTarget else {
fatalError("break outside loop")
}
return builder.buildBr(target)
}
public func visitContinueStmt(_ stmt: ContinueStmt) -> Result {
guard let target = currentContinueTarget else {
fatalError("continue outside loop")
}
return builder.buildBr(target)
}
func synthesizeIntializer(_ decl: InitializerDecl, function: Function) -> IRValue {
let type = decl.returnType.type
guard let body = decl.body,
body.stmts.isEmpty,
type != .error,
let typeDecl = context.decl(for: type) else {
fatalError("must synthesize an empty initializer")
}
let entryBB = function.appendBasicBlock(named: "entry")
builder.positionAtEnd(of: entryBB)
var retLLVMType = resolveLLVMType(type)
if typeDecl.isIndirect {
retLLVMType = (retLLVMType as! PointerType).pointee
}
var initial = retLLVMType.undef()
for (idx, arg) in decl.args.enumerated() {
var param = function.parameter(at: idx)!
param.name = arg.name.name
initial = builder.buildInsertValue(aggregate: initial,
element: param,
index: idx,
name: "init-insert")
}
if typeDecl.isIndirect {
let result = codegenAlloc(type: type).ref
builder.buildStore(initial, to: result)
builder.buildRet(result)
} else {
builder.buildRet(initial)
}
return function
}
public func visitOperatorDecl(_ decl: OperatorDecl) -> Result {
return visitFuncDecl(decl)
}
public func visitFuncDecl(_ decl: FuncDecl) -> Result {
let function = codegenFunctionPrototype(decl)
if decl === context.mainFunction {
mainFunction = function
}
if decl.has(attribute: .foreign) { return function }
if let initializer = decl as? InitializerDecl, let body = decl.body, body.stmts.isEmpty {
return synthesizeIntializer(initializer, function: function)
}
let entrybb = function.appendBasicBlock(named: "entry", in: llvmContext)
let retbb = function.appendBasicBlock(named: "return", in: llvmContext)
let returnType = decl.returnType.type
let type = resolveLLVMType(decl.returnType)
var res: VarBinding? = nil
let storageKind = storage(for: returnType)
let isReferenceInitializer = decl is InitializerDecl && storageKind == .reference
withFunction {
builder.positionAtEnd(of: entrybb)
if decl.returnType != .void {
if isReferenceInitializer {
res = codegenAlloc(type: returnType)
} else {
res = createEntryBlockAlloca(function, type: type,
name: "res", storage: storageKind)
}
if decl is InitializerDecl {
let selfBinding: VarBinding
if isReferenceInitializer {
selfBinding = VarBinding(ref: res!.ref,
storage: res!.storage,
read: { res!.ref },
write: res!.write)
} else {
selfBinding = res!
}
varIRBindings["self"] = selfBinding
}
}
for (idx, arg) in decl.args.enumerated() {
var param = function.parameter(at: idx)!
param.name = arg.name.name
let type = arg.type
let argType = resolveLLVMType(type)
let storageKind = storage(for: type)
let read: () -> IRValue
if arg.isImplicitSelf && storageKind == .reference {
read = { param }
} else {
read = { self.builder.buildLoad(param) }
}
var ptr = VarBinding(ref: param,
storage: storageKind,
read: read,
write: { self.builder.buildStore($0, to: param) })
if !arg.isImplicitSelf {
ptr = createEntryBlockAlloca(function,
type: argType,
name: arg.name.name,
storage: storageKind,
initial: param)
}
varIRBindings[arg.name] = ptr
}
currentFunction = FunctionState(
function: decl,
functionRef: function,
returnBlock: retbb,
resultAlloca: res?.ref
)
_ = visit(decl.body!)
let insertBlock = builder.insertBlock!
// break to the return block
if !insertBlock.endsWithTerminator {
builder.buildBr(retbb)
}
// build the ret in the return block.
retbb.moveAfter(function.lastBlock!)
builder.positionAtEnd(of: retbb)
if decl.has(attribute: .noreturn) {
builder.buildUnreachable()
} else if decl.returnType.type == .void {
builder.buildRetVoid()
} else {
let val: IRValue
if isReferenceInitializer {
val = res!.ref
} else {
val = builder.buildLoad(res!.ref, name: "resval")
}
builder.buildRet(val)
}
currentFunction = nil
}
passManager.run(on: function)
return function
}
public func visitFuncCallExpr(_ expr: FuncCallExpr) -> Result {
guard let decl = expr.decl else { fatalError("no decl on funccall") }
if decl === IntrinsicFunctions.typeOf {
return codegenTypeOfCall(expr)
}
var function: IRValue? = nil
var args = expr.args
let findImplicitSelf: (FuncCallExpr) -> Expr? = { expr in
guard let decl = expr.decl as? MethodDecl else { return nil }
if decl.has(attribute: .static) { return nil }
switch decl {
case _ as SubscriptDecl:
return expr.lhs
default:
if let property = expr.lhs as? PropertyRefExpr {
return property.lhs
}
return nil
}
}
/// Creates intermediary AST nodes that get the address of the provided
/// expr.
let createAddressOf: (Expr, DataType) -> Expr = {
let operatorExpr = PrefixOperatorExpr(op: .ampersand, rhs: $0)
operatorExpr.type = .pointer(type: $1)
return operatorExpr
}
if
let method = decl as? MethodDecl,
var implicitSelf = findImplicitSelf(expr) {
/// We need to get the address of the implicit self if and only if
/// - The implicit self is a value type, or
/// - It is a reference type directly referencing `self` in an
/// initializer.
if storage(for: method.parentType) == .value {
implicitSelf = createAddressOf(implicitSelf, method.parentType)
} else if let varExpr = implicitSelf.semanticsProvidingExpr as? VarExpr,
varExpr.isSelf,
currentFunction!.function is InitializerDecl {
implicitSelf = createAddressOf(implicitSelf, method.parentType)
}
args.insert(Argument(val: implicitSelf, label: nil), at: 0)
}
if decl.isPlaceholder {
function = visit(expr.lhs)
} else {
function = codegenFunctionPrototype(decl)
}
if function == nil {
function = visit(expr.lhs)
}
var argVals = [IRValue]()
for (idx, arg) in args.enumerated() {
var val = visit(arg.val)!
var type = arg.val.type
if case .array(let field, _) = type {
let alloca = createEntryBlockAlloca(currentFunction!.functionRef!,
type: val.type,
name: "",
storage: .value,
initial: val)
type = .pointer(type: field)
val = builder.buildBitCast(alloca.ref, type: PointerType(pointee: resolveLLVMType(field)))
}
if let declArg = decl.args[safe: idx], declArg.type == .any {
val = codegenPromoteToAny(value: val, type: type)
}
argVals.append(val)
}
let name = decl.returnType.type == .void ? "" : "calltmp"
let call = builder.buildCall(function!, args: argVals, name: name)
if decl.has(attribute: .noreturn) {
builder.buildUnreachable()
}
return call
}
public func visitParamDecl(_ decl: ParamDecl) -> Result {
fatalError("handled while generating function")
}
public func visitReturnStmt(_ expr: ReturnStmt) -> Result {
guard let currentFunction = currentFunction,
let currentDecl = currentFunction.function else {
fatalError("return outside function?")
}
var store: IRValue? = nil
if !(expr.value is VoidExpr) {
var val = visit(expr.value)!
let type = expr.value.type
if type != .error,
case .any = context.canonicalType(currentDecl.returnType.type) {
val = codegenPromoteToAny(value: val, type: type)
}
if !(currentDecl is InitializerDecl) {
store = builder.buildStore(val, to: currentFunction.resultAlloca!)
}
}
defer {
builder.buildBr(currentFunction.returnBlock!)
}
return store
}
}
| mit | 3c333170c11d86138dcbe6085249185a | 33.052469 | 98 | 0.584519 | 4.379913 | false | false | false | false |
lijian5509/KnowLedgeSummarize | 李健凡iOS知识总结 /swift绘图板/swift绘图板/PaintingBrushSettingsView.swift | 1 | 1613 | //
// PaintingBrushSettingsView.swift
// swift绘图板
//
// Created by mini on 15/11/26.
// Copyright © 2015年 mini. All rights reserved.
//
import UIKit
class PaintingBrushSettingsView: UIView {
var strokeWidthChangedBlock: ((strokeWidth: CGFloat) -> Void)?
var strokeColorChangedBlock: ((strokeColor: UIColor) -> Void)?
@IBOutlet weak var colorPicker: RGBColorPicker!
@IBOutlet weak var strokeColorPreView: UIView!
@IBOutlet weak var strokeWidthSlider: UISlider!
override func awakeFromNib() {
super.awakeFromNib()
self.strokeColorPreView.layer.borderColor = UIColor.blackColor().CGColor
self.strokeColorPreView.layer.borderWidth = 1
self.colorPicker.colorChangedBlcok = {
[unowned self] (color: UIColor) in
self.strokeColorPreView.backgroundColor = color
if let strokeColorChangedBlock = self.strokeColorChangedBlock {
strokeColorChangedBlock(strokeColor: color)
}
}
self.strokeWidthSlider.addTarget(self, action: "strokeWidthChanged:", forControlEvents: .ValueChanged)
}
override var backgroundColor: UIColor? {
didSet {
self.strokeColorPreView.backgroundColor = self.backgroundColor
self.colorPicker.setCurrentColor(self.backgroundColor!)
super.backgroundColor = oldValue
}
}
func strokeWidthChanged(slider: UISlider) {
if let strokeWidthChangedBlock = self.strokeWidthChangedBlock {
strokeWidthChangedBlock(strokeWidth: CGFloat(slider.value))
}
}
}
| gpl-3.0 | 21d21daa11e16ac6e73e05acb0b25dc5 | 33.869565 | 110 | 0.680798 | 4.935385 | false | false | false | false |
coolsamson7/inject | Inject/logger/LogFormatter.swift | 1 | 4813 | //
// LogFormatter.swift
// Inject
//
// Created by Andreas Ernst on 18.07.16.
// Copyright © 2016 Andreas Ernst. All rights reserved.
//
/// `LogFormatter` is used to compose a format for a log entry. A number of funcs are provided that reference the individual parts of a log entry - level, message,timestamp, etc. -
/// The complete layout is achieved by simply concatenating the individual results with the '+' operator. A second '+' operator will handle strings.
open class LogFormatter {
// MARK: local classes
struct Color {
// MARK: Instance data
var r : Int
var g : Int
var b : Int
init(r : Int, g : Int, b : Int) {
self.r = r
self.g = g
self.b = b
}
}
// MARK: static data
static var colors: [Color] = [
Color(r: 120, g: 120, b: 120),
Color(r: 0, g: 180, b: 180),
Color(r: 0, g: 150, b: 0),
Color(r: 255, g: 190, b: 0),
Color(r: 255, g: 0, b: 0),
Color(r: 160, g: 32, b: 240)
]
static let ESCAPE = "\u{001b}["
static let RESET_FG = ESCAPE + "fg;" // Clear any foreground color
static let RESET_BG = ESCAPE + "bg;" // Clear any background color
static let RESET = ESCAPE + ";" // Clear any foreground or background color
// class funcs
open static func colorize<T>(_ object: T, level: LogManager.Level) -> String {
let color = colors[level.rawValue - 1] // starts with OFF
return "\(ESCAPE)fg\(color.r),\(color.g),\(color.b);\(object)\(RESET)"
}
// formatting api
/// return a formatter that contains a fixed string
/// - Parameter vale: a string value
/// - Returns: the formatter
open class func string(_ value : String) -> LogFormatter{
return LogFormatter { (entry) -> String in value }
}
/// return a formatter referencing the level part
/// - Returns: the formatter
open class func level() -> LogFormatter {
return LogFormatter { $0.level.description }
}
/// return a formatter referencing the logger part
/// - Returns: the formatter
open class func logger() -> LogFormatter {
return LogFormatter { $0.logger }
}
/// return a formatter referencing the thread part
/// - Returns: the formatter
open class func thread() -> LogFormatter {
return LogFormatter { $0.thread }
}
/// return a formatter referencing the file part
/// - Returns: the formatter
open class func file() -> LogFormatter {
return LogFormatter { $0.file }
}
/// return a formatter referencing the function part
/// - Returns: the formatter
open class func function() -> LogFormatter {
return LogFormatter { $0.function }
}
/// return a formatter referencing the line part
/// - Returns: the formatter
open class func line() -> LogFormatter {
return LogFormatter { String($0.line) }
}
/// return a formatter referencing the column part
/// - Returns: the formatter
open class func column() -> LogFormatter {
return LogFormatter { String($0.column) }
}
/// return a formatter referencing the timestamp part
/// - Parameter pattern: the date pattern which defaults to "dd/M/yyyy, H:mm:s"
/// - Returns: the formatter
open class func timestamp(_ pattern : String = "dd/M/yyyy, H:mm:s") -> LogFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = pattern
return LogFormatter { return dateFormatter.string(from: $0.timestamp) }
}
/// return a formatter referencing the message part
/// Returns: the formatter
open class func message() -> LogFormatter {
func message(_ logEntry : LogManager.LogEntry) -> String {
let builder = StringBuilder()
builder.append(logEntry.message)
if let error = logEntry.error {
builder.append(" ").append("\(error)")
}
if let stacktrace = logEntry.stacktrace {
builder.append("\n").append(stacktrace)
}
return builder.toString()
}
return LogFormatter { message($0) }
}
// data
let format : (LogManager.LogEntry) -> String
// init
public init(format : @escaping (LogManager.LogEntry) -> String) {
self.format = format
}
}
// LogFormatter
/// concatenate two formatters
public func + (left: LogFormatter, right: LogFormatter) -> LogFormatter {
return LogFormatter {return left.format($0) + right.format($0)}
}
/// concatenate a formatter and a string
public func + (left: LogFormatter, right: String) -> LogFormatter {
return LogFormatter {return left.format($0) + right}
}
| mit | 4e4f0356419ae6b82bc0b52261d86b09 | 29.649682 | 180 | 0.602452 | 4.406593 | false | false | false | false |
toohotz/IQKeyboardManager | Demo/Swift_Demo/ViewController/CollectionViewDemoController.swift | 1 | 2209 | //
// CollectionViewDemoController.swift
// IQKeyboardManager
//
// Created by InfoEnum02 on 20/04/15.
// Copyright (c) 2015 Iftekhar. All rights reserved.
//
import UIKit
class CollectionViewDemoController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UIPopoverPresentationControllerDelegate {
@IBOutlet private var collectionView : UICollectionView!
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell : UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("TextFieldCollectionViewCell", forIndexPath: indexPath)
let textField : UITextField = cell.viewWithTag(10) as! UITextField
textField.placeholder = "\(indexPath.section) \(indexPath.row)"
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
if identifier == "SettingsNavigationController" {
let controller = segue.destinationViewController
controller.modalPresentationStyle = .Popover
controller.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
let heightWidth = max(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds));
controller.preferredContentSize = CGSizeMake(heightWidth, heightWidth)
controller.popoverPresentationController?.delegate = self
}
}
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
func prepareForPopoverPresentation(popoverPresentationController: UIPopoverPresentationController) {
self.view.endEditing(true)
}
override func shouldAutorotate() -> Bool {
return true
}
}
| mit | 8338836627d6342a07ba89ea2f576e10 | 37.086207 | 152 | 0.692168 | 6.88162 | false | false | false | false |
awind/Pixel | Pixel/CommentTableViewCell.swift | 1 | 1118 | //
// CommentTableViewCell.swift
// Pixel
//
// Created by SongFei on 15/12/13.
// Copyright © 2015年 SongFei. All rights reserved.
//
import UIKit
class CommentTableViewCell: UITableViewCell {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var commentView: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// self.avatarImageView.layer.masksToBounds = true
// self.avatarImageView.layer.cornerRadius = (avatarImageView.frame.size.height) / 2
// self.avatarImageView.clipsToBounds = true
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func bindDataBy(comment: Comment) {
avatarImageView.tag = comment.userId
commentView.text = comment.commentBody
usernameLabel.text = comment.fullName
avatarImageView.sd_setImageWithURL(NSURL(string: comment.avatar)!)
}
}
| apache-2.0 | 23da8e41bdb052700ad8735e3b91585a | 26.875 | 91 | 0.678924 | 4.704641 | false | false | false | false |
VeinGuo/VGPlayer | VGPlayer/Classes/MediaCache/VGPlayerResourceLoaderManager.swift | 1 | 3793 | //
// VGPlayerResourceLoaderManager.swift
// Pods
//
// Created by Vein on 2017/6/28.
//
//
import Foundation
import AVFoundation
public protocol VGPlayerResourceLoaderManagerDelegate: class {
func resourceLoaderManager(_ loadURL: URL, didFailWithError error: Error?)
}
open class VGPlayerResourceLoaderManager: NSObject {
open weak var delegate: VGPlayerResourceLoaderManagerDelegate?
fileprivate var loaders = Dictionary<String, VGPlayerResourceLoader>()
fileprivate let kCacheScheme = "VGPlayerMideaCache"
public override init() {
super.init()
}
open func cleanCache() {
loaders.removeAll()
}
open func cancelLoaders() {
for (_, value) in loaders {
value.cancel()
}
loaders.removeAll()
}
internal func key(forResourceLoaderWithURL url: URL) -> String? {
guard url.absoluteString.hasPrefix(kCacheScheme) else { return nil }
return url.absoluteString
}
internal func loader(forRequest request: AVAssetResourceLoadingRequest) -> VGPlayerResourceLoader? {
guard let requestKey = key(forResourceLoaderWithURL: request.request.url!) else { return nil }
let loader = loaders[requestKey]
return loader
}
open func assetURL(_ url: URL?) -> URL? {
guard let assetUrl = url else { return nil }
let assetURL = URL(string: kCacheScheme.appending(assetUrl.absoluteString))
return assetURL
}
open func playerItem(_ url: URL) -> AVPlayerItem {
let assetURL = self.assetURL(url)
let urlAsset = AVURLAsset(url: assetURL!, options: nil)
urlAsset.resourceLoader.setDelegate(self, queue: DispatchQueue.main)
let playerItem = AVPlayerItem(asset: urlAsset)
if #available(iOS 9.0, *) {
playerItem.canUseNetworkResourcesForLiveStreamingWhilePaused = true
}
return playerItem
}
}
// MARK: - AVAssetResourceLoaderDelegate
extension VGPlayerResourceLoaderManager: AVAssetResourceLoaderDelegate {
public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
if let resourceURL = loadingRequest.request.url {
if resourceURL.absoluteString.hasPrefix(kCacheScheme) {
var loader = self.loader(forRequest: loadingRequest)
if loader == nil {
var originURLString = resourceURL.absoluteString
originURLString = originURLString.replacingOccurrences(of: kCacheScheme, with: "")
let originURL = URL(string: originURLString)
loader = VGPlayerResourceLoader(url: originURL!)
loader?.delegate = self
let key = self.key(forResourceLoaderWithURL: resourceURL)
loaders[key!] = loader
// fix https://github.com/vitoziv/VIMediaCache/pull/29
}
loader?.add(loadingRequest)
return true
}
}
return false
}
public func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) {
let loader = self.loader(forRequest: loadingRequest)
loader?.cancel()
loader?.remove(loadingRequest)
}
}
// MARK: - VGPlayerResourceLoaderDelegate
extension VGPlayerResourceLoaderManager: VGPlayerResourceLoaderDelegate {
public func resourceLoader(_ resourceLoader: VGPlayerResourceLoader, didFailWithError error: Error?) {
resourceLoader.cancel()
delegate?.resourceLoaderManager(resourceLoader.url, didFailWithError: error)
}
}
| mit | af82497c5b05d3eb0214639e2edf02c0 | 35.12381 | 168 | 0.661745 | 5.349788 | false | false | false | false |
heshamsalman/ReusableViews | ReusableViews/Classes/ReusableView.swift | 1 | 2675 | //
// ReusableView.swift
// ReusableViews
//
// Created by Hesham Salman on 5/11/17
//
//
import Foundation
/// A reusable, recycled view.
public protocol ReusableView: class {
/// Reuse identifier for a recycled view.
static var defaultReuseIdentifier: String { get }
}
public extension ReusableView where Self: UIView {
/// The reuse identifier for the class.
/// The same as the class name.
static var defaultReuseIdentifier: String {
return String(describing: self)
}
}
/// A view controller or other object that can be instantiated from the storyboard
public protocol StoryboardCompatibleView: class {
static var storyboardIdentifier: String { get }
}
public extension StoryboardCompatibleView where Self: UIViewController {
/// Defaults to the same name as the class
static var storyboardIdentifier: String {
return String(describing: self)
}
}
/// A view loadable from a nib
public protocol NibLoadableView: class {
/// Name for the nib
static var nibName: String { get }
}
public extension NibLoadableView where Self: UIView {
/// Defaults to the same name as the class
static var nibName: String {
return String(describing: self)
}
/// Instantiates and loads from nib a view that conforms to NibLoadableView
///
/// Can fail if the nib cannot be loaded from the view:
/// - Usually caused by not matching the name of the nib file with the name of the view
/// - Similar & overly long file names confuse Xcode. For example, AdHocNibLoadableView and AdHocNibLoadableViewController will confuse
/// Xcode and prevent it from instantiating files correctly.
///
/// - Parameters:
/// - viewIndex: index of the view, by default 0
/// Currently, additional indexes are unsupported due to the requirement that nibName is the same as className
/// - owner: by default nil
/// - options: by default nil
/// - Returns: an instantiated view
static func create(viewIndex: Int = 0, owner: Any? = nil, options: [AnyHashable: Any]? = nil) -> Self {
let bundle = Bundle(for: Self.self)
guard let nib = bundle.loadNibNamed(Self.nibName, owner: owner, options: options as? [UINib.OptionsKey : Any]) else {
fatalError("nib file \(Self.nibName) is missing")
}
guard let view = nib[viewIndex] as? Self else {
fatalError("Could not instantiate \(Self.self) from nib -- have you conformed to the NibLoadable protocol?")
}
return view
}
}
extension UIViewController: StoryboardCompatibleView { }
extension UITableViewCell: ReusableView { }
extension UICollectionReusableView: ReusableView { }
extension UITableViewHeaderFooterView: ReusableView { }
| mit | b99f660086021c5e63edc0f69a36d2c8 | 33.74026 | 139 | 0.716636 | 4.518581 | false | false | false | false |
jwzhuang/KanManHua | KanManHua/RegexHtml.swift | 1 | 735 | //
// RegexPattern.swift
// KanManHua
//
// Created by JingWen on 2016/11/11.
// Copyright © 2016年 JingWen. All rights reserved.
//
import Foundation
class RegexHtml{
class func regex(htmlSrc:String, pattern:String) -> String {
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: htmlSrc, options: [], range: NSMakeRange(0, htmlSrc.characters.count))
var groups: [String] = []
matches.forEach({ (textCheckingResult) in
groups.append( (htmlSrc as NSString).substring(with: textCheckingResult.rangeAt(1)) )
})
if groups.count == 0{
return "0"
}
return groups[0]
}
}
| mit | 82b4f1059a900172ba70292ee699b780 | 29.5 | 110 | 0.628415 | 3.914439 | false | false | false | false |
uasys/swift | test/SILGen/downcast_reabstraction.swift | 1 | 1236 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// CHECK-LABEL: sil hidden @_T022downcast_reabstraction19condFunctionFromAnyyypF
// CHECK: checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_owned (@in ()) -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]]
// CHECK: [[YES]]:
// CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @_T0ytytIxir_Ix_TR
// CHECK: [[SUBST_VAL:%.*]] = partial_apply [[REABSTRACT]]([[ORIG_VAL]])
func condFunctionFromAny(_ x: Any) {
if let f = x as? () -> () {
f()
}
}
// CHECK-LABEL: sil hidden @_T022downcast_reabstraction21uncondFunctionFromAnyyypF : $@convention(thin) (@in Any) -> () {
// CHECK: unconditional_checked_cast_addr Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_owned (@in ()) -> @out ()
// CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]]
// CHECK: [[REABSTRACT:%.*]] = function_ref @_T0ytytIxir_Ix_TR
// CHECK: [[SUBST_VAL:%.*]] = partial_apply [[REABSTRACT]]([[ORIG_VAL]])
// CHECK: apply [[SUBST_VAL]]()
func uncondFunctionFromAny(_ x: Any) {
(x as! () -> ())()
}
| apache-2.0 | 04d7e6e70bf8e5f08fbd6f45c08aca35 | 50.5 | 176 | 0.541262 | 3.21875 | false | false | false | false |
Yogayu/EmotionNote | EmotionNote/EmotionNote/Note.swift | 1 | 2184 | //
// Note.swift
// EmotionNote
//
// Created by youxinyu on 15/12/3.
// Copyright © 2015年 yogayu.github.io. All rights reserved.
//
import UIKit
class Note: NSObject, NSCoding {
// MARK: Properties
var content: String
var emotion: String
var emotionPhoto: UIImage?
var time: String
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("notes")
// MARK: Types
struct PropertyKey {
static let contentKey = "content"
static let emotionKey = "emotion"
static let emotionPhotoKey = "emotionPhoto"
static let timeKey = "time"
}
// MARK: Initialization
init?(content: String, emotion: String, emotionPhoto: UIImage?, time: String) {
// Initialize stored properties.
self.content = content
self.emotion = emotion
self.emotionPhoto = emotionPhoto
self.time = time
super.init()
if content.isEmpty{
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(content,
forKey: PropertyKey.contentKey)
aCoder.encodeObject(emotion,
forKey: PropertyKey.emotionKey)
aCoder.encodeObject(emotionPhoto,
forKey: PropertyKey.emotionPhotoKey)
aCoder.encodeObject(time,
forKey: PropertyKey.timeKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let content = aDecoder.decodeObjectForKey(
PropertyKey.contentKey) as! String
let emotion = aDecoder.decodeObjectForKey(
PropertyKey.emotionKey) as! String
let emotionPhoto = aDecoder.decodeObjectForKey(
PropertyKey.emotionPhotoKey) as? UIImage
let time = aDecoder.decodeObjectForKey(
PropertyKey.timeKey) as! String
// Must call designated initializer.
self.init(content: content, emotion: emotion, emotionPhoto: emotionPhoto, time: time)
}
} | mit | 05f7483002a1898fd35032730d5cab53 | 30.623188 | 123 | 0.642824 | 4.890135 | false | false | false | false |
mightydeveloper/swift | test/Interpreter/initializers.swift | 9 | 2919 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
// Test initialization and initializer inheritance.
var depth = 0
func printAtDepth(s: String) {
for i in 0..<depth { print("*", terminator: "") }
print(s)
}
class A {
var int: Int
var string: String
convenience init() {
printAtDepth("Starting A.init()")
++depth
self.init(int:5)
--depth
printAtDepth("Ending A.init()")
}
convenience init(int i:Int) {
printAtDepth("Starting A.init withInt(\(i))")
++depth
self.init(int:i, string:"hello")
--depth
printAtDepth("Ending A.init withInt(\(i))")
}
init(int i:Int, string: String) {
printAtDepth("Starting A.init withInt(\(i)) string(\(string))")
self.int = i
self.string = string
printAtDepth("Ending A.init withInt(\(i)) string(\(string))")
}
deinit {
printAtDepth("A.deinit")
}
}
class B : A {
var double: Double
convenience override init(int i:Int, string: String) {
printAtDepth("Starting B.init withInt(\(i)) string(\(string))")
++depth
self.init(int: i, string:string, double:3.14159)
--depth
printAtDepth("Ending B.init withInt(\(i)) string(\(string))")
}
init(int i:Int, string: String, double:Double) {
printAtDepth("Starting B.init withInt(\(i)) string(\(string)) double(\(double))")
self.double = double
++depth
super.init(int: i, string: string)
--depth
printAtDepth("Ending B.init withInt(\(i)) string(\(string)) double(\(double))")
}
deinit {
printAtDepth("B.deinit")
}
}
class C : B {
override init(int i:Int, string: String, double: Double) {
printAtDepth("Starting C.init withInt(\(i)) string(\(string)) double(\(double))")
++depth
super.init(int: i, string: string, double: double)
--depth
printAtDepth("Ending C.init withInt(\(i)) string(\(string)) double(\(double))")
}
deinit {
printAtDepth("C.deinit")
}
}
print("-----Constructing C()-----")
// CHECK: Starting A.init()
// CHECK: *Starting A.init withInt(5)
// CHECK: **Starting B.init withInt(5) string(hello)
// CHECK: ***Starting C.init withInt(5) string(hello) double(3.14159)
// CHECK: ****Starting B.init withInt(5) string(hello) double(3.14159)
// CHECK: *****Starting A.init withInt(5) string(hello)
// CHECK: *****Ending A.init withInt(5) string(hello)
// CHECK: ****Ending B.init withInt(5) string(hello) double(3.14159)
// CHECK: ***Ending C.init withInt(5) string(hello) double(3.14159)
// CHECK: **Ending B.init withInt(5) string(hello)
// CHECK: *Ending A.init withInt(5)
// CHECK: Ending A.init()
// CHECK: C.deinit
// CHECK: B.deinit
// CHECK: A.deinit
C()
// rdar://problem/18877135
class Foo: FloatLiteralConvertible {
required init(floatLiteral: Float) { }
func identify() { print("Foo") }
}
class Bar: Foo {
override func identify() { print("Bar") }
}
let x: Bar = 1.0
x.identify() // CHECK-LABEL: Bar
| apache-2.0 | 1848d6d17985b824634d76bbc4e13af0 | 24.605263 | 85 | 0.635834 | 3.394186 | false | false | false | false |
ycfreeman/ReSwift | ReSwift/CoreTypes/Store.swift | 2 | 5142 | //
// Store.swift
// ReSwift
//
// Created by Benjamin Encz on 11/11/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Foundation
/**
This class is the default implementation of the `Store` protocol. You will use this store in most
of your applications. You shouldn't need to implement your own store.
You initialize the store with a reducer and an initial application state. If your app has multiple
reducers you can combine them by initializng a `MainReducer` with all of your reducers as an
argument.
*/
open class Store<State: StateType>: StoreType {
typealias SubscriptionType = Subscription<State>
// swiftlint:disable todo
// TODO: Setter should not be public; need way for store enhancers to modify appState anyway
/*private (set)*/ public var state: State! {
didSet {
subscriptions = subscriptions.filter { $0.subscriber != nil }
subscriptions.forEach {
// if a selector is available, subselect the relevant state
// otherwise pass the entire state to the subscriber
$0.subscriber?._newState(state: $0.selector?(state) ?? state)
}
}
}
public var dispatchFunction: DispatchFunction!
private var reducer: Reducer<State>
var subscriptions: [SubscriptionType] = []
private var isDispatching = false
public required convenience init(reducer: @escaping Reducer<State>, state: State?) {
self.init(reducer: reducer, state: state, middleware: [])
}
public required init(
reducer: @escaping Reducer<State>,
state: State?,
middleware: [Middleware]
) {
self.reducer = reducer
// Wrap the dispatch function with all middlewares
self.dispatchFunction = middleware
.reversed()
.reduce({ [unowned self] action in
return self._defaultDispatch(action: action)
}) {
[weak self] dispatchFunction, middleware in
let getState = { self?.state }
return middleware(self?.dispatch, getState)(dispatchFunction)
}
if let state = state {
self.state = state
} else {
dispatch(ReSwiftInit())
}
}
private func _isNewSubscriber(subscriber: AnyStoreSubscriber) -> Bool {
let contains = subscriptions.contains(where: { $0.subscriber === subscriber })
if contains {
print("Store subscriber is already added, ignoring.")
return false
}
return true
}
open func subscribe<S: StoreSubscriber>(_ subscriber: S)
where S.StoreSubscriberStateType == State {
subscribe(subscriber, selector: nil)
}
open func subscribe<SelectedState, S: StoreSubscriber>
(_ subscriber: S, selector: ((State) -> SelectedState)?)
where S.StoreSubscriberStateType == SelectedState {
if !_isNewSubscriber(subscriber: subscriber) { return }
subscriptions.append(Subscription(subscriber: subscriber, selector: selector))
if let state = self.state {
subscriber._newState(state: selector?(state) ?? state)
}
}
open func unsubscribe(_ subscriber: AnyStoreSubscriber) {
if let index = subscriptions.index(where: { return $0.subscriber === subscriber }) {
subscriptions.remove(at: index)
}
}
open func _defaultDispatch(action: Action) -> Any {
guard !isDispatching else {
raiseFatalError(
"ReSwift:IllegalDispatchFromReducer - Reducers may not dispatch actions.")
}
isDispatching = true
let newState = reducer(action, state)
isDispatching = false
state = newState
return action
}
@discardableResult
open func dispatch(_ action: Action) -> Any {
let returnValue = dispatchFunction(action)
return returnValue
}
@discardableResult
open func dispatch(_ actionCreatorProvider: @escaping ActionCreator) -> Any {
let action = actionCreatorProvider(state, self)
if let action = action {
dispatch(action)
}
return action as Any
}
open func dispatch(_ asyncActionCreatorProvider: @escaping AsyncActionCreator) {
dispatch(asyncActionCreatorProvider, callback: nil)
}
open func dispatch(_ actionCreatorProvider: @escaping AsyncActionCreator,
callback: DispatchCallback?) {
actionCreatorProvider(state, self) { actionProvider in
let action = actionProvider(self.state, self)
if let action = action {
self.dispatch(action)
callback?(self.state)
}
}
}
public typealias DispatchCallback = (State) -> Void
public typealias ActionCreator = (_ state: State, _ store: Store) -> Action?
public typealias AsyncActionCreator = (
_ state: State,
_ store: Store,
_ actionCreatorCallback: @escaping ((ActionCreator) -> Void)
) -> Void
}
| mit | e32699694e684175afd7651d929ad43d | 30.157576 | 99 | 0.619724 | 5.100198 | false | false | false | false |
testpress/ios-app | ios-app/UI/BaseTableViewController.swift | 1 | 4674 | //
// BaseTableViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import TTGSnackbar
import UIKit
import ObjectMapper
import XLPagerTabStrip
protocol BaseTableViewDelegate {
func loadItems()
}
class BaseTableViewController<T: Mappable>: UITableViewController {
var activityIndicator: UIActivityIndicatorView! // Progress bar
var emptyView: EmptyView!
var items = [T]()
var tableViewDelegate: BaseTableViewDelegate!
var useInterfaceBuilderSeperatorInset = false
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator = UIUtils.initActivityIndicator(parentView: self.view)
activityIndicator?.center = CGPoint(x: view.center.x, y: view.center.y - 150)
// Set table view backgroud
emptyView = EmptyView.getInstance()
tableView.backgroundView = emptyView
emptyView.frame = tableView.frame
if !useInterfaceBuilderSeperatorInset {
UIUtils.setTableViewSeperatorInset(tableView, size: 15)
}
tableView.tableFooterView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
if (items.isEmpty) {
activityIndicator?.startAnimating()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (items.isEmpty) {
tableViewDelegate.loadItems()
}
}
func onLoadFinished(items: [T]) {
self.items = items
self.tableView.reloadData()
if (self.activityIndicator?.isAnimating)! {
self.activityIndicator?.stopAnimating()
}
}
func handleError(_ error: TPError) {
var retryHandler: (() -> Void)?
if error.kind == .network {
retryHandler = {
self.activityIndicator?.startAnimating()
self.tableViewDelegate.loadItems()
}
}
let (image, title, description) = error.getDisplayInfo()
if (activityIndicator?.isAnimating)! {
activityIndicator?.stopAnimating()
}
if items.count == 0 {
emptyView.setValues(image: image, title: title, description: description,
retryHandler: retryHandler)
} else {
TTGSnackbar(message: description, duration: .middle).show()
}
tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if items.count == 0 {
tableView.backgroundView?.isHidden = false
} else {
tableView.backgroundView?.isHidden = true
}
return items.count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return tableViewCell(cellForRowAt: indexPath)
}
func tableViewCell(cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return UITableViewCell()
}
func refreshWithProgress() {
activityIndicator?.startAnimating()
tableViewDelegate.loadItems()
}
func setEmptyText() {
emptyView.setValues(image: Images.LearnFlatIcon.image, description: Strings.NO_ITEMS_EXIST)
}
}
| mit | 44504cd1722ceb8e1a869534432ab568 | 32.862319 | 99 | 0.648406 | 5.169248 | false | false | false | false |
AndrewBennet/readinglist | ReadingList/ViewControllers/Settings/Privacy.swift | 1 | 4015 | import Foundation
import SwiftUI
class PrivacySettings: ObservableObject {
@Published var sendCrashReports = UserEngagement.sendCrashReports {
didSet { UserEngagement.sendCrashReports = sendCrashReports }
}
@Published var sendAnalytics = UserEngagement.sendAnalytics {
didSet { UserEngagement.sendAnalytics = sendAnalytics }
}
}
struct Privacy: View {
@EnvironmentObject var hostingSplitView: HostingSettingsSplitView
@ObservedObject var settings = PrivacySettings()
@State var crashReportsAlertDisplated = false
@State var analyticsAlertDisplayed = false
var inset: Bool {
hostingSplitView.isSplit
}
var body: some View {
SwiftUI.List {
Section(
header: HeaderText("Privacy Policy", inset: inset)
) {
NavigationLink(destination: PrivacyPolicy()) {
Text("View Privacy Policy")
}
}
Section(
header: HeaderText("Reporting", inset: inset),
footer: FooterText("""
Crash reports can be automatically sent to help me detect and fix issues. Analytics can \
be used to help gather usage statistics for different features. This never includes any \
details of your books.\
\(BuildInfo.thisBuild.type != .testFlight ? "" : " If Beta testing, these cannot be disabled.")
""", inset: inset)) {
Toggle(isOn: Binding(get: { settings.sendCrashReports }, set: { newValue in
if !newValue {
crashReportsAlertDisplated = true
} else {
settings.sendCrashReports = true
UserEngagement.logEvent(.enableCrashReports)
}
})) {
Text("Send Crash Reports")
}.alert(isPresented: $crashReportsAlertDisplated) {
crashReportsAlert
}
Toggle(isOn: Binding(get: { settings.sendAnalytics }, set: { newValue in
if !newValue {
analyticsAlertDisplayed = true
} else {
settings.sendAnalytics = true
UserEngagement.logEvent(.enableAnalytics)
}
})) {
Text("Send Analytics")
}.alert(isPresented: $analyticsAlertDisplayed) {
analyticsAlert
}
}
}.possiblyInsetGroupedListStyle(inset: inset)
.navigationBarTitle("Privacy")
}
var crashReportsAlert: Alert {
Alert(
title: Text("Turn Off Crash Reports?"),
message: Text("""
Anonymous crash reports alert me if this app crashes, to help me fix bugs. \
This never includes any information about your books. Are you \
sure you want to turn this off?
"""),
primaryButton: .default(Text("Leave On")) {
settings.sendCrashReports = true
},
secondaryButton: .destructive(Text("Turn Off")) {
settings.sendCrashReports = false
UserEngagement.logEvent(.disableCrashReports)
}
)
}
var analyticsAlert: Alert {
Alert(
title: Text("Turn Off Analytics?"),
message: Text("""
Anonymous usage statistics help prioritise development. This never includes \
any information about your books. Are you sure you want to turn this off?
"""),
primaryButton: .default(Text("Leave On")) {
settings.sendAnalytics = true
},
secondaryButton: .destructive(Text("Turn Off")) {
settings.sendAnalytics = false
UserEngagement.logEvent(.disableAnalytics)
}
)
}
}
| gpl-3.0 | b683f153d9bd5ad633712e419f70a024 | 36.877358 | 111 | 0.542964 | 5.81042 | false | false | false | false |
AttackOnJasper/swift-tvOS-demo | swift-tvOS-demo/TopShelf/ServiceProvider.swift | 1 | 1252 | //
// ServiceProvider.swift
// TopShelf
//
// Created by Jasper Wang on 16/1/15.
// Copyright © 2016年 Jasper. All rights reserved.
//
import Foundation
import TVServices
class ServiceProvider: NSObject, TVTopShelfProvider {
override init() {
super.init()
}
// MARK: - TVTopShelfProvider protocol
var topShelfStyle: TVTopShelfContentStyle {
// Return desired Top Shelf style.
return .Inset
}
var topShelfItems: [TVContentItem] {
var ContentItems = [TVContentItem]()
for (var i = 0; i < 8; i++) {
let identifier = TVContentIdentifier(identifier: "VOD", container: nil)!
let contentItem = TVContentItem(contentIdentifier: identifier )!
if let url = NSURL(string: "http://www.brianjcoleman.com/code/images/feature-\(i).jpg") {
contentItem.imageURL = url
contentItem.title = "Movie Title"
contentItem.displayURL = NSURL(string: "VideoApp://video/\(i)");
contentItem.playURL = NSURL(string: "VideoApp://video/\(i)");
}
ContentItems.append(contentItem)
}
return ContentItems
}
}
| apache-2.0 | bbcee1c8bca3a4e228ea10ce36c57a99 | 25.574468 | 101 | 0.577262 | 4.397887 | false | false | false | false |
senfi/KSTokenView | KSTokenView/KSUtils.swift | 1 | 3312 | //
// KSUtils.swift
// KSTokenView
//
// Created by Khawar Shahzad on 01/01/2015.
// Copyright (c) 2015 Khawar Shahzad. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import UIKit
let KSTextEmpty = "\u{200B}"
class KSUtils : NSObject {
class func getRect(str: NSString, width: CGFloat, height: CGFloat, font: UIFont) -> CGRect {
let rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
rectangleStyle.alignment = NSTextAlignment.Center
let rectangleFontAttributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: rectangleStyle]
return str.boundingRectWithSize(CGSizeMake(width, height), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil)
}
class func getRect(str: NSString, width: CGFloat, font: UIFont) -> CGRect {
let rectangleStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
rectangleStyle.alignment = NSTextAlignment.Center
let rectangleFontAttributes = [NSFontAttributeName: font, NSParagraphStyleAttributeName: rectangleStyle]
return str.boundingRectWithSize(CGSizeMake(width, CGFloat(MAXFLOAT)), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: rectangleFontAttributes, context: nil)
}
class func widthOfString(str: String, font: UIFont) -> CGFloat {
var attrs = [NSFontAttributeName: font]
var attributedString = NSMutableAttributedString(string:str, attributes:attrs)
return attributedString.size().width
}
class func isIpad() -> Bool {
return UIDevice.currentDevice().userInterfaceIdiom == .Pad
}
class func constrainsEnabled(view: UIView) -> Bool {
if (view.constraints().count > 0) {
return true
} else {
return false
}
}
}
extension UIColor {
func darkendColor(darkRatio: CGFloat) -> UIColor {
var h: CGFloat = 0.0, s: CGFloat = 0.0, b: CGFloat = 0.0, a: CGFloat = 0.0
if (getHue(&h, saturation: &s, brightness: &b, alpha: &a)) {
return UIColor(hue: h, saturation: s, brightness: b*darkRatio, alpha: a)
} else {
return self
}
}
}
| mit | 21ce92f1b8409379c29bf412328282dd | 43.756757 | 182 | 0.723732 | 4.580913 | false | false | false | false |
roambotics/swift | SwiftCompilerSources/Sources/Optimizer/DataStructures/BasicBlockRange.swift | 2 | 5569 | //===--- BasicBlockRange.swift - a range of basic blocks ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
/// A range of basic blocks.
///
/// The `BasicBlockRange` defines a range from a dominating "begin" block to one or more "end" blocks.
/// The range is "exclusive", which means that the "end" blocks are not part of the range.
///
/// The `BasicBlockRange` is in the same spirit as a linear range, but as the control flow is a graph
/// and not a linear list, there can be "exit" blocks from within the range.
///
/// One or more "potential" end blocks can be inserted.
/// Though, not all inserted blocks end up as "end" blocks.
///
/// There are several kind of blocks:
/// * begin: it is a single block which dominates all blocks of the range
/// * range: all blocks from which there is a path from the begin block to any of the end blocks
/// * ends: all inserted blocks which are at the end of the range
/// * exits: all successor blocks of range blocks which are not in the range themselves
/// * interiors: all inserted blocks which are not end blocks.
///
/// In the following example, let's assume `B` is the begin block and `I1`, `I2` and `I3`
/// were inserted as potential end blocks:
///
/// B
/// / \
/// I1 I2
/// / \
/// I3 X
///
/// Then `I1` and `I3` are "end" blocks. `I2` is an interior block and `X` is an exit block.
/// The range consists of `B` and `I2`. Note that the range does not include `I1` and `I3`
/// because it's an _exclusive_ range.
///
/// This type should be a move-only type, but unfortunately we don't have move-only
/// types yet. Therefore it's needed to call `deinitialize()` explicitly to
/// destruct this data structure, e.g. in a `defer {}` block.
struct BasicBlockRange : CustomStringConvertible, NoReflectionChildren {
/// The dominating begin block.
let begin: BasicBlock
/// The inclusive range, i.e. the exclusive range plus the end blocks.
private(set) var inclusiveRange: Stack<BasicBlock>
/// The exclusive range, i.e. not containing the end blocks.
var range: LazyFilterSequence<Stack<BasicBlock>> {
inclusiveRange.lazy.filter { contains($0) }
}
/// All inserted blocks.
private(set) var inserted: Stack<BasicBlock>
private var wasInserted: BasicBlockSet
private var inExclusiveRange: BasicBlockSet
private var worklist: BasicBlockWorklist
init(begin: BasicBlock, _ context: PassContext) {
self.begin = begin
self.inclusiveRange = Stack(context)
self.inserted = Stack(context)
self.wasInserted = BasicBlockSet(context)
self.inExclusiveRange = BasicBlockSet(context)
self.worklist = BasicBlockWorklist(context)
worklist.pushIfNotVisited(begin)
}
/// Insert a potential end block.
mutating func insert(_ block: BasicBlock) {
if wasInserted.insert(block) {
inserted.append(block)
}
worklist.pushIfNotVisited(block)
while let b = worklist.pop() {
inclusiveRange.append(b)
if b != begin {
for pred in b.predecessors {
worklist.pushIfNotVisited(pred)
inExclusiveRange.insert(pred)
}
}
}
}
/// Insert a sequence of potential end blocks.
mutating func insert<S: Sequence>(contentsOf other: S) where S.Element == BasicBlock {
for block in other {
insert(block)
}
}
/// Returns true if the exclusive range contains `block`.
func contains(_ block: BasicBlock) -> Bool { inExclusiveRange.contains(block) }
/// Returns true if the inclusive range contains `block`.
func inclusiveRangeContains (_ block: BasicBlock) -> Bool {
worklist.hasBeenPushed(block)
}
/// Returns true if the range is valid and that's iff the begin block dominates all blocks of the range.
var isValid: Bool {
let entry = begin.function.entryBlock
return begin == entry ||
// If any block in the range is not dominated by `begin`, the range propagates back to the entry block.
!inclusiveRangeContains(entry)
}
/// Returns the end blocks.
var ends: LazyFilterSequence<Stack<BasicBlock>> {
inserted.lazy.filter { !contains($0) }
}
/// Returns the exit blocks.
var exits: LazySequence<FlattenSequence<
LazyMapSequence<LazyFilterSequence<Stack<BasicBlock>>,
LazyFilterSequence<SuccessorArray>>>> {
range.flatMap {
$0.successors.lazy.filter {
!inclusiveRangeContains($0) || $0 == begin
}
}
}
/// Returns the interior blocks.
var interiors: LazyFilterSequence<Stack<BasicBlock>> {
inserted.lazy.filter { contains($0) && $0 != begin }
}
var description: String {
return (isValid ? "" : "<invalid>\n") +
"""
begin: \(begin.name)
range: \(range)
inclrange: \(inclusiveRange)
ends: \(ends)
exits: \(exits)
interiors: \(interiors)
"""
}
/// TODO: once we have move-only types, make this a real deinit.
mutating func deinitialize() {
worklist.deinitialize()
inExclusiveRange.deinitialize()
wasInserted.deinitialize()
inserted.deinitialize()
inclusiveRange.deinitialize()
}
}
| apache-2.0 | 6013914b44a50199d07e63d863b698b4 | 33.80625 | 109 | 0.658646 | 4.128243 | false | false | false | false |
novi/mysql-swift | Sources/MySQL/AutoincrementID.swift | 1 | 2306 | //
// AutoincrementID.swift
// MySQL
//
// Created by Yusuke Ito on 6/27/16.
// Copyright © 2016 Yusuke Ito. All rights reserved.
//
import SQLFormatter
public enum AutoincrementID<I: IDType> {
case noID
case ID(I)
public var id: I {
switch self {
case .noID: fatalError("\(self) has no ID")
case .ID(let id): return id
}
}
}
extension AutoincrementID: Equatable {
static public func ==<I>(lhs: AutoincrementID<I>, rhs: AutoincrementID<I>) -> Bool {
switch (lhs, rhs) {
case (.noID, .noID): return true
case (.ID(let lhs), .ID(let rhs) ): return lhs.id == rhs.id
default: return false
}
}
}
extension AutoincrementID: CustomStringConvertible {
// where I: CustomStringConvertible
// is not supported yet
public var description: String {
switch self {
case .noID: return "noID"
case .ID(let id):
if let idVal = id as? CustomStringConvertible {
return idVal.description
} else {
return "\(id)"
}
}
}
}
extension AutoincrementID {
public init(_ id: I) {
self = .ID(id)
}
}
/*
extension AutoincrementID where I: SQLRawStringDecodable {
static func fromSQLValue(string: String) throws -> AutoincrementID<I> {
return AutoincrementID(try I.fromSQLValue(string: string))
}
}*/
extension AutoincrementID: QueryParameter {
public func queryParameter(option: QueryParameterOption) throws -> QueryParameterType {
switch self {
case .noID: return ""
case .ID(let id): return try id.queryParameter(option: option)
}
}
public var omitOnQueryParameter: Bool {
switch self {
case .noID: return true
case .ID: return false
}
}
}
/// MARK: Codable support
extension AutoincrementID: Decodable where I: Decodable {
public init(from decoder: Decoder) throws {
self = .ID(try I(from: decoder))
}
}
extension AutoincrementID: Encodable where I: Encodable {
public func encode(to encoder: Encoder) throws {
switch self {
case .noID:
break // nothing to encode
case .ID(let id):
try id.encode(to: encoder)
}
}
}
| mit | 70ce3e569b730e7aaa914386258200d8 | 22.762887 | 91 | 0.595228 | 3.86745 | false | false | false | false |
brokenseal/WhereIsMaFood | WhereIsMaFood/RestaurantsDataSource.swift | 1 | 4558 | //
// RestaurantsDataSource.swift
// WhereIsMaFood
//
// Created by Davide Callegari on 27/07/17.
// Copyright © 2017 Davide Callegari. All rights reserved.
//
import MapKit
import Foundation
import CoreLocation
class RestaurantsDataSource {
private let app: App
var currentDataSet: RestaurantsDataSet = [] {
didSet {
self.app.trigger(
App.Message.newRestaurantsDataSet,
object: self.currentDataSet
)
}
}
let dataGenerator: RestaurantDataSetGeneratorProtocol
init(
app: App,
dataGenerator: RestaurantDataSetGeneratorProtocol
) {
self.app = app
self.dataGenerator = dataGenerator
}
func selectRestaurantData(at: Int) {
let selected = currentDataSet[at]
currentDataSet = currentDataSet.map { dataSet in
if dataSet == selected {
return dataSet.clone(selected: true)
} else {
return dataSet.clone(selected: false)
}
}
}
func getSelectedRestaurantData() -> RestaurantData? {
for restaurantData in currentDataSet {
if restaurantData.selected == true {
return restaurantData
}
}
return nil
}
func select(_ restauranData: RestaurantData) {
let toBeSelected = restauranData
currentDataSet = currentDataSet.map { dataSet in
if dataSet == toBeSelected {
return dataSet.clone(selected: true)
} else {
return dataSet.clone(selected: false)
}
}
}
func updateData(
for region: MKCoordinateRegion,
searchQuery: String = ""
) {
self.dataGenerator.getDataSet(
ofLength: 30,
for: region,
searchQuery: searchQuery
) { [weak self] error, updatedDataSet in
// FIXME: bailout?
guard let this = self else { return }
if error != nil {
print("\(error!.localizedDescription)")
this.app.trigger(App.Message.warnUser, object: "Error while searching for restaurants")
return
}
// FIXME: bailout?
guard let dataSet = updatedDataSet else { return }
this.currentDataSet = dataSet
}
}
}
struct RestaurantData: Equatable {
let name: String
let type: String
let shortDescription: String
let location: CLLocation
let url: URL?
var selected: Bool
static func == (
lhs: RestaurantData,
rhs: RestaurantData
) -> Bool {
return lhs.name == rhs.name
&& lhs.type == rhs.type
&& lhs.shortDescription == rhs.shortDescription
&& lhs.url == rhs.url
}
func clone(selected: Bool?) -> RestaurantData {
return RestaurantData(
name: name,
type: type,
shortDescription: shortDescription,
location: location,
url: url,
selected: selected ?? self.selected
)
}
}
typealias RestaurantsDataSet = [RestaurantData]
protocol RestaurantDataSetGeneratorProtocol {
func getDataSet(
ofLength: Int,
for region: MKCoordinateRegion,
searchQuery: String,
completion: @escaping (Error?, RestaurantsDataSet?) -> Void
) -> Void
}
class MKRestaurantDataSetGenerator: RestaurantDataSetGeneratorProtocol {
func getDataSet(
ofLength: Int,
for region: MKCoordinateRegion,
searchQuery: String = "",
completion: @escaping (Error?, RestaurantsDataSet?) -> Void
) -> Void {
mkSearch(searchQuery: searchQuery, region: region) { response, error in
if let error = error {
completion(error, nil)
return
}
if let response = response {
let UNKNOWN = "Unknown"
let restaurantsDataSet = response.mapItems.map { mapItem in
return RestaurantData(
name: mapItem.name ?? UNKNOWN,
type: UNKNOWN, //areasOfInterest?
shortDescription: UNKNOWN,
location: CLLocation(
latitude: mapItem.placemark.coordinate.latitude,
longitude: mapItem.placemark.coordinate.longitude
),
url: mapItem.url,
selected: false
)
}
completion(nil, restaurantsDataSet)
return
}
completion(ErrorsManager.appError(), nil)
}
}
}
func mkSearch(
searchQuery: String,
region: MKCoordinateRegion,
completion: @escaping MKLocalSearchCompletionHandler
) {
let searchRequest = MKLocalSearchRequest()
searchRequest.naturalLanguageQuery = "restaurant \(searchQuery)"
searchRequest.region = region
let localSearch = MKLocalSearch(request: searchRequest)
localSearch.start(completionHandler: completion)
}
| mit | 46a616284aff1cd116ca7ed3d19d049d | 23.766304 | 95 | 0.642089 | 4.626396 | false | false | false | false |
jphacks/KM_03 | iOS/LimitedSpace/LimitedSpace/Classes/Model/LSConnection.swift | 1 | 1936 | //
// LSConnection.swift
// LimitedSpace
//
// Copyright © 2015年 Ryunosuke Kirikihira. All rights reserved.
//
import UIKit
import Alamofire
import CoreLocation
enum LSAPI :String {
case BaseUrl = "https://limited-space.herokuapp.com"
case getLS = "/api/getLimitedSpaces"
case registLS = "/api/createLimitedSpace"
static func getURL(api :LSAPI) -> String {
return LSAPI.BaseUrl.rawValue + api.rawValue
}
}
class LSConnection: NSObject {
class func getLSItemWithAPI(location :CLLocation, handler :((data :NSDictionary)->Void)?) {
let param = [
"lat" : location.coordinate.latitude,
"lng" : location.coordinate.longitude
]
Alamofire.request(.GET, LSAPI.getURL(.getLS), parameters: param, encoding: .JSON, headers: nil).responseJSON { (req, res, result) -> Void in
guard let data = result.data else { return }
let json = JSON(data)
// handler?(data: json)
}
}
class func registLimitedSpace(data :[String:AnyObject], handler :(()->Void)?) {
let name = data["name"] as? String
let span = data["span"] as? Int
let radius = data["radius"] as? Int
let lat = data["lat"] as? Double
let lng = data["lng"] as? Double
let icon = data["icon"] as? NSData
guard case (_?, _?, _?, _?, _?, _?) = (name, span, radius, lat, lng, icon) else { return }
let param :[String:AnyObject] = [
"name" : name!,
"span" : span!,
"radius" : radius!,
"lat" : lat!,
"lng" : lng!,
// "icon" : icon!,
"icon_type" : 0
]
Alamofire.request(.POST, LSAPI.getURL(.registLS), parameters: param, encoding: .JSON, headers: nil).responseJSON { (req, res, result) -> Void in
print(res)
}
}
}
| mit | 020e8048e571c6916887a640399ddffb | 30.177419 | 152 | 0.547336 | 3.961066 | false | false | false | false |
pikacode/EBBannerView | EBBannerView/SwiftClasses/EBSystemBanner.swift | 1 | 8745 | //
// EBSystemBanner.swift
// Pods-SwiftDemo
//
// Created by pikacode on 2019/12/30.
//
import UIKit
import AudioToolbox
public enum EBBannerStyle: Int, CaseIterable {
case iOS8 = 8
case iOS9 = 9
case iOS10 = 10
case iOS11 = 11
case iOS12 = 12
case iOS13 = 13
}
public class EBSystemBanner: NSObject {
/// Fast way to show `content` with all default values
///
/// EBSystemBanner.show("some content")
@discardableResult
public static func show(_ content: String) -> EBSystemBanner { return EBSystemBanner().content(content).show() }
/// Create an instance and then Set the properties below instead of default values
///
/// EBSystemBanner()
/// .style(.iOS13)
/// .title("Jack")
/// .content("How are you?")
/// .show()
///
/// To customize the default values, set the properties of EBSystemBannerMaker.default
///
/// EBSystemBannerMaker.default.appName = "Custom App Name"
///
/// Some properties in the banner
/// ┌──────────────────────┐
/// │┌──┐ |
/// ││ icon | appName date |
/// │└──┘ |
/// │ title |
/// │ content |
/// └──────────────────────┘
public func style(_ style: EBBannerStyle) -> EBSystemBanner { return then { $0.maker.style = style } }
public func icon(_ icon: UIImage?) -> EBSystemBanner { return then { $0.maker.icon = icon } }
public func appName(_ appName: String?) -> EBSystemBanner { return then { $0.maker.appName = appName } }
public func title(_ title: String?) -> EBSystemBanner { return then { $0.maker.title = title } }
public func content(_ content: String?) -> EBSystemBanner { return then { $0.maker.content = content } }
public func date(_ date: String?) -> EBSystemBanner { return then { $0.maker.date = date } }
public func showDuration(_ duration: TimeInterval) -> EBSystemBanner { return then { $0.maker.showDuration = duration } }
public func hideDuration(_ duration: TimeInterval) -> EBSystemBanner { return then { $0.maker.hideDuration = duration } }
public func stayDuration(_ duration: TimeInterval) -> EBSystemBanner { return then { $0.maker.stayDuration = duration } }
public func spreadStayDuration(_ duration: TimeInterval) -> EBSystemBanner { return then { $0.maker.spreadStayDuration = duration } }
/// Pass an object to banner and then get it on click
///
/// let obj = CustomObject()
/// EBSystemBanner()
/// .object(obj)
/// .content("How are you?")
/// .show()
/// .onClick {
/// print($0.object!)
/// }
public func object(_ object: Any?) -> EBSystemBanner { return then { $0.maker.object = object } }
/// Play a sound when a banner appears
///
/// // .id(1312) is the stytem sound `Tritone`, which is also the default value
/// // To find all system ids, visit http://iphonedevwiki.net/index.php/AudioServices
/// EBSystemBanner()
/// .sound(.id(1312))
/// .content("something")
/// .show()
///
/// // A custom sound in your main bundle
/// EBSystemBanner()
/// .sound(.name("MySound.mp3"))
/// .content("some")
/// .show()
public func sound(_ sound: EBBannerSound) -> EBSystemBanner { return then { $0.maker.sound = sound } }
public func vibrateOnMute(_ bool: Bool) -> EBSystemBanner { return then { $0.maker.vibrateOnMute = bool } }
/// when click a long text banner, spread it for all height or hide it, true = expand/false = hide, default is true
public func showDetailsOrHideWhenClickLongText(_ bool: Bool) -> EBSystemBanner { return then { $0.maker.showDetailsOrHideWhenClickLongText = bool } }
@discardableResult
public func onClick(_ block: @escaping (EBSystemBanner) -> ()) -> EBSystemBanner { return then { $0.maker.onClick = block } }
@discardableResult
public func show() -> EBSystemBanner {
view.show()
return self
}
/// observe this notification to get a banner in your code when clicked
static let onClickNotification: Notification.Name = Notification.Name(rawValue: "EBBannerViewOnClickNotification")
/// private
private lazy var maker = EBSystemBannerMaker.default.then{ $0.banner = self }
private lazy var view: EBSystemBannerView = {
let window = EBBannerWindow.shared
var bannerView = EBSystemBanner.sharedBannerViews.filter{ $0.style == style }.first
if bannerView == nil {
let views = Bundle(for: EBSystemBanner.self).loadNibNamed("EBSystemBannerView", owner: nil, options: nil)!
let index = min(style.rawValue - 9, views.count - 1)
let view = views[index] as! EBSystemBannerView
view.addNotification()
view.addGestureRecognizer()
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowRadius = 3.5
view.layer.shadowOpacity = 0.35
view.layer.shadowOffset = .zero
EBSystemBanner.sharedBannerViews.append(view)
bannerView = view
}
bannerView?.maker = maker
if style == .iOS9 {
bannerView?.dateLabel.textColor = UIColor.color(at: bannerView!.dateLabel.center).withAlphaComponent(0.7)
let lineCenter = bannerView!.lineView.center
bannerView?.lineView.backgroundColor = UIColor.color(at: CGPoint(x: lineCenter.x, y: lineCenter.y - 7)).withAlphaComponent(0.5)
}
return bannerView!
}()
}
extension EBSystemBanner: EBThen {}
extension EBSystemBannerMaker: EBThen {}
// MARK: - private method
extension EBSystemBanner {
private static var sharedBannerViews = [EBSystemBannerView]()
//u don't have to call hide, this only use for (long_text && forbidAutoHiddenWhenSwipeDown = true)
func hide() {
view.hide()
}
private static var current: EBSystemBannerView? {
let view = EBBannerWindow.shared.rootViewController?.view.subviews.last
if let aview = view as? EBSystemBannerView, view?.superview != nil {
let banner = sharedBannerViews.filter{ $0 == aview }.first
return banner
} else {
return nil
}
}
}
// MARK: - convenience get method
extension EBSystemBanner {
public var style: EBBannerStyle { return maker.style }
public var icon: UIImage? { return maker.icon }
public var appName: String? { return maker.appName }
public var title: String? { return maker.title }
public var content: String? { return maker.content }
public var date: String? { return maker.date }
public var showDuration: TimeInterval { return maker.showDuration }
public var hideDuration: TimeInterval { return maker.hideDuration }
public var stayDuration: TimeInterval { return maker.stayDuration }
public var spreadStayDuration: TimeInterval { return maker.spreadStayDuration }
public var object: Any? { return maker.object }
public var sound: EBBannerSound { return maker.sound }
public var vibrateOnMute: Bool { return maker.vibrateOnMute }
public var showDetailsOrHideWhenClickLongText: Bool { return maker.showDetailsOrHideWhenClickLongText }
public var onClick: (EBSystemBanner) -> () { return maker.onClick }
}
//偷偷写个then,没人看到我 没人看到我🙈
protocol EBThen {}
extension EBThen where Self: AnyObject {
func then(_ block: (Self) throws -> Void) rethrows -> Self {
try block(self)
return self
}
}
| mit | 085a8ebd3677c8c73a766c898767f48e | 40.487923 | 153 | 0.561248 | 4.568085 | false | false | false | false |
h-n-y/BigNerdRanch-SwiftProgramming | chapter-2/BronzeChallenge.playground/Contents.swift | 1 | 534 | import Cocoa
var population: Int = 112_432
var message: String
var hasPostOffice: Bool = true
if population < 10_000 {
message = "\(population) is a small town!"
} else if population >= 10_000 && population < 50_000 {
message = "\(population) is a medium town!"
} else if population >= 50_000 && population < 100_000 {
message = "\(population) is pretty big!"
} else {
message = "\(population) is huge!"
}
print(message)
if !hasPostOffice {
print("Where do we buy stamps?")
} | mit | 6e578d299defd2c86bfedb33362be300 | 18.107143 | 56 | 0.61236 | 3.734266 | false | false | false | false |
WangYang-iOS/YiDeXuePin_Swift | DiYa/DiYa/Class/Tools/Managers/YYGoodsManager.swift | 1 | 2360 | //
// YYGoodsManager.swift
// DiYa
//
// Created by wangyang on 2017/12/14.
// Copyright © 2017年 wangyang. All rights reserved.
//
import UIKit
var _goodsSelectView : YYGoodsSkuView!
var _shadowView : UIView!
var _complete: ((_ skuValue: String, _ number: Int)->())?
class YYGoodsManager: NSObject {
static let shareManagre = YYGoodsManager()
private override init() {}
}
extension YYGoodsManager {
func showGoodsSelectView(goodsModel : GoodsModel, skuCategoryList:[SkuCategoryModel], goodsSkuList:[GoodsSkuModel], complete:((_ skuValue: String, _ number: Int)->())?) {
_complete = complete
let window = (UIApplication.shared.delegate as! AppDelegate).window
_shadowView = UIView()
_shadowView.frame = RECT(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
_shadowView.backgroundColor = UIColor.hexString(colorString: "000000", alpha: 0.3)
window?.addSubview(_shadowView)
let tap = UITapGestureRecognizer.init(target: self, action: #selector(hiddenSelectView))
_shadowView.addGestureRecognizer(tap)
_goodsSelectView = YYGoodsSkuView.loadXib1() as! YYGoodsSkuView
_goodsSelectView.delegate = self
window?.addSubview(_goodsSelectView)
_goodsSelectView.goodsModel = goodsModel
_goodsSelectView.skuList = skuCategoryList
_goodsSelectView.goodsSkuList = goodsSkuList
_goodsSelectView.changeNumberView.number = 1;
_goodsSelectView.frame = RECT(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: _goodsSelectView.goodsSkuViewHieght)
UIView.animate(withDuration: 0.25) {
_goodsSelectView.frame = RECT(x: 0, y: SCREEN_HEIGHT - _goodsSelectView.goodsSkuViewHieght, width: SCREEN_WIDTH, height: _goodsSelectView.goodsSkuViewHieght)
}
}
@objc func hiddenSelectView() {
_shadowView.removeFromSuperview()
UIView.animate(withDuration: 0.25, animations: {
_goodsSelectView.frame = RECT(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: _goodsSelectView.goodsSkuViewHieght)
}) { (finish) in
_goodsSelectView.removeFromSuperview()
}
}
}
extension YYGoodsManager : YYGoodsSkuViewDelegate {
func didSelectedGoodsWith(skuValue: String, number: Int) {
_complete?(skuValue,number)
}
}
| mit | 9152ab9935d449469e16d172f971a455 | 38.949153 | 174 | 0.682647 | 4.084922 | false | false | false | false |
Punch-In/PunchInIOSApp | PunchIn/MKLabel.swift | 1 | 3170 | //
// MKLabel.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/29/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
public class MKLabel: UILabel {
@IBInspectable public var maskEnabled: Bool = true {
didSet {
mkLayer.enableMask(maskEnabled)
}
}
@IBInspectable public var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable public var rippleAniDuration: Float = 0.75
@IBInspectable public var backgroundAniDuration: Float = 1.0
@IBInspectable public var rippleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable public var backgroundAniEnabled: Bool = true {
didSet {
if !backgroundAniEnabled {
mkLayer.enableOnlyCircleLayer()
}
}
}
@IBInspectable public var ripplePercent: Float = 0.9 {
didSet {
mkLayer.ripplePercent = ripplePercent
}
}
@IBInspectable public var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable public var rippleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(rippleLayerColor)
}
}
@IBInspectable public var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
override public var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
private func setup() {
mkLayer.setCircleLayerColor(rippleLayerColor)
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
public func animateRipple(location: CGPoint? = nil) {
if let point = location {
mkLayer.didChangeTapLocation(point)
} else if rippleLocation == .TapLocation {
rippleLocation = .Center
}
mkLayer.animateScaleForCircleLayer(0.65, toScale: 1.0, timingFunction: rippleAniTimingFunction, duration: CFTimeInterval(self.rippleAniDuration))
mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(self.backgroundAniDuration))
}
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
if let firstTouch = touches.first as UITouch! {
let location = firstTouch.locationInView(self)
animateRipple(location)
}
}
}
| mit | 08b96c5cc3d7549f144d88d07e70e33c | 31.346939 | 153 | 0.650158 | 5.137763 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | ISaMaterialLogIn/Classes/ISaCircleLoader.swift | 1 | 3743 | //
// ISaCircleLoader.swift
// Pods
//
// Created by Francesco on 01/12/16.
//
//
import Foundation
import UIKit
@IBDesignable
public class ISaCircleLoader: UIView {
public override var layer: CAShapeLayer {
get {
return super.layer as! CAShapeLayer
}
}
override public class var layerClass: AnyClass { return CAShapeLayer.self }
override public func layoutSubviews() {
super.layoutSubviews()
layer.fillColor = nil
layer.strokeColor = UIColor.white.cgColor
layer.lineWidth = 1.5
setPath()
}
public override func didMoveToWindow() {
animate()
}
private func setPath() {
layer.path = UIBezierPath(ovalIn: bounds.insetBy(dx: layer.lineWidth / 2, dy: layer.lineWidth / 2)).cgPath
}
struct Delay {
let secondsSincePriorDelay: CFTimeInterval
let start: CGFloat
let length: CGFloat
init(_ secondsSincePriorDelay: CFTimeInterval, _ start: CGFloat, _ length: CGFloat) {
self.secondsSincePriorDelay = secondsSincePriorDelay
self.start = start
self.length = length
}
}
var delays: [Delay] {
return [
Delay(0.0, 0.000, 0.7),
Delay(0.2, 0.500, 0.5),
Delay(0.2, 1.000, 0.3),
Delay(0.2, 1.500, 0.1),
Delay(0.2, 1.875, 0.1),
Delay(0.2, 2.250, 0.3),
Delay(0.2, 2.625, 0.5),
Delay(0.2, 3.000, 0.7),
]
}
func animate() {
var time: CFTimeInterval = 0
var times = [CFTimeInterval]()
var start: CGFloat = 0
var rotations = [CGFloat]()
var strokeEnds = [CGFloat]()
let totalSeconds = self.delays.reduce(0) { $0 + $1.secondsSincePriorDelay }
for Delay in self.delays {
time += Delay.secondsSincePriorDelay
times.append(time / totalSeconds)
start = Delay.start
rotations.append(start * 2 * CGFloat(M_PI))
strokeEnds.append(Delay.length)
}
times.append(times.last!)
rotations.append(rotations[0])
strokeEnds.append(strokeEnds[0])
animateKeyPath(keyPath: "strokeEnd", duration: totalSeconds, times: times, values: strokeEnds)
animateKeyPath(keyPath: "transform.rotation", duration: totalSeconds, times: times, values: rotations)
//animateStrokeHueWithDuration(duration: totalSeconds * 5)
}
func animateKeyPath(keyPath: String, duration: CFTimeInterval, times: [CFTimeInterval], values: [CGFloat]) {
let animation = CAKeyframeAnimation(keyPath: keyPath)
animation.keyTimes = times as [NSNumber]?
animation.values = values
animation.calculationMode = kCAAnimationLinear
animation.duration = duration
animation.repeatCount = Float.infinity
layer.add(animation, forKey: animation.keyPath)
}
func animateStrokeHueWithDuration(duration: CFTimeInterval) {
let count = 36
let animation = CAKeyframeAnimation(keyPath: "strokeColor")
let keyTimes = (0 ... count).map { CFTimeInterval($0) / CFTimeInterval(count) }
animation.keyTimes = keyTimes as [NSNumber]?
animation.values = (0 ... count).map {
UIColor(hue: CGFloat($0) / CGFloat(count), saturation: 1, brightness: 1, alpha: 1).cgColor
}
animation.duration = duration
animation.calculationMode = kCAAnimationLinear
animation.repeatCount = Float.infinity
layer.add(animation, forKey: animation.keyPath)
}
}
| mit | 6ea293a31afb15b2f38318d7ff59ebfd | 31.267241 | 114 | 0.590703 | 4.53697 | false | false | false | false |
ZevEisenberg/Padiddle | Experiments/Timing Curve.playground/Contents.swift | 1 | 744 | #if os(OSX)
"AppKit"
import AppKit
#else
"UIKit"
import UIKit
#endif
func rotationFraction(forFraction x: Double) -> Double {
let a = 6.0
let numerator = atan(a * (x - 0.5))
let denominator = 2 * atan(a / 2)
return numerator / denominator + 0.5
}
// Algorithm suggested by Sam Critchlow here: https://www.facebook.com/ZevEisenberg/posts/10209176689033901?comment_id=10209197282908735&comment_tracking=%7B%22tn%22%3A%22R0%22%7D
let duration: Double = 2
let framesPerSecond = 60.0
let frameCount = duration * framesPerSecond
let frameFractions = stride(from: 0, through: 1.0, by: 1.0 / frameCount)
let fractions = frameFractions.map {
rotationFraction(forFraction: Double($0))
}
fractions.map {
$0
}
| mit | 1d98d7ead5a3da8438d33841286bcaa5 | 23.8 | 179 | 0.697581 | 3.061728 | false | false | false | false |
kgellci/Shift | Shift/Classes/ShiftUI.swift | 1 | 5553 | //
// ShiftUI.swift
// Pods
//
// Created by Kris Gellci on 5/19/17.
//
//
import UIKit
// View
open class ShiftView: UIView, Shiftable {
public var shiftLayer = ShiftLayer()
public override init(frame: CGRect) {
super.init(frame: frame)
setupShift()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShift()
}
open override func layoutSubviews() {
super.layoutSubviews()
shiftLayer.frame = bounds
}
}
// Button
open class ShiftButton: UIButton, Shiftable {
public var shiftLayer = ShiftLayer()
public var maskToText = false {
didSet {
if maskToText {
self.maskToImage = false
self.mask = self.titleLabel
} else {
self.mask = nil
}
}
}
public var maskToImage = false {
didSet {
if maskToImage {
self.maskToText = false
self.mask = self.imageView
} else {
self.mask = nil
}
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupShift()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShift()
}
open override func layoutSubviews() {
super.layoutSubviews()
shiftLayer.frame = bounds
}
}
// Label
open class ShiftLabel: UILabel, Shiftable {
public var shiftLayer = ShiftLayer()
public override init(frame: CGRect) {
super.init(frame: frame)
setupShift()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShift()
}
open override func layoutSubviews() {
super.layoutSubviews()
shiftLayer.frame = bounds
}
}
// Label
open class ShiftMaskableLabel: ShiftView {
public let textLabel = UILabel()
public var maskToText = false {
didSet {
if maskToText {
self.mask = self.textLabel
} else {
self.mask = nil
}
}
}
open override var intrinsicContentSize: CGSize {
return textLabel.intrinsicContentSize
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLabel()
}
private func setupLabel() {
addSubview(textLabel)
textLabel.shifFillParent()
}
public func setText(_ text: String) {
textLabel.text = text
textLabel.sizeToFit()
invalidateIntrinsicContentSize()
}
}
// TextField
open class ShiftTextfield: UITextField, Shiftable {
public var shiftLayer = ShiftLayer()
public override init(frame: CGRect) {
super.init(frame: frame)
setupShift()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShift()
}
open override func layoutSubviews() {
super.layoutSubviews()
shiftLayer.frame = bounds
}
}
// TextView
open class ShiftTextView: UITextView, Shiftable {
public var shiftLayer = ShiftLayer()
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setupShift()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShift()
}
open override func layoutSubviews() {
super.layoutSubviews()
shiftLayer.frame = bounds
}
}
// ImageView
open class ShiftImageView: UIImageView, Shiftable {
public var shiftLayer = ShiftLayer()
public var maskToImage = false {
didSet {
maskLayer?.removeFromSuperlayer()
if maskToImage {
let mask = CALayer()
mask.contents = image?.cgImage
mask.frame = bounds
layer.mask = mask
layer.masksToBounds = true
}
}
}
private var maskLayer: CALayer?
public override init(frame: CGRect) {
super.init(frame: frame)
setupShift()
}
public override init(image: UIImage?) {
super.init(image: image)
setupShift()
}
public override init(image: UIImage?, highlightedImage: UIImage?) {
super.init(image: image, highlightedImage: highlightedImage)
setupShift()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupShift()
}
open override func layoutSubviews() {
super.layoutSubviews()
shiftLayer.frame = bounds
maskLayer?.frame = bounds
}
}
extension UIView {
func shifFillParent() {
guard let bounds = superview?.bounds else { return }
self.frame = bounds
shiftPinToSuperview(.bottom)
shiftPinToSuperview(.top)
shiftPinToSuperview(.left)
shiftPinToSuperview(.right)
}
func shiftPinToSuperview(_ attribute: NSLayoutAttribute) {
let constraint = NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: self.superview, attribute: attribute, multiplier: 1.0, constant: 0)
self.superview?.addConstraint(constraint)
}
}
| mit | 48eb0644bda02302614a32b75ce32c91 | 22.331933 | 172 | 0.579507 | 4.766524 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame | JKWayfairPriceGame/GravityTransition.swift | 1 | 1696 | //
// GravityTransition.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli Backup on 8/19/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import UIKit
import Foundation
extension UIView {
func makeGravityTransition(updateView: () -> Void) {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, 0)
self.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let currentViewScreenshot = UIGraphicsGetImageFromCurrentImageContext()
let frontConverImageView = UIImageView(image: currentViewScreenshot)
frontConverImageView.frame = self.bounds
self.addSubview(frontConverImageView)
updateView()
frontConverImageView.addGravity()
}
func addGravity() {
if let superView = self.superview {
let dynamicAnimator = UIDynamicAnimator(referenceView: superview!)
let gravityBehaviour = UIGravityBehavior(items: [self])
let dynamicItemBehaviour = UIDynamicItemBehavior(items: [self])
dynamicItemBehaviour.allowsRotation = true
gravityBehaviour.gravityDirection = CGVectorMake (-2, 5)
gravityBehaviour.action = {
if (self.frame.intersects(superView.frame) == false) {
self.removeFromSuperview()
dynamicAnimator.removeAllBehaviors()
}
}
dynamicAnimator.removeAllBehaviors()
dynamicItemBehaviour.addAngularVelocity(CGFloat(5), forItem: self)
dynamicAnimator.addBehavior(dynamicItemBehaviour)
dynamicAnimator.addBehavior(gravityBehaviour)
}
}
} | mit | 329fb61fd3ad4c4702a63c97e91fd75c | 36.688889 | 79 | 0.660177 | 5.612583 | false | false | false | false |
trill-lang/ClangSwift | Sources/Clang/Utilities.swift | 1 | 1820 | #if SWIFT_PACKAGE
import cclang
#endif
internal extension Bool {
func asClang() -> Int32 {
return self ? 1 : 0
}
}
extension CXString {
func asSwiftOptionalNoDispose() -> String? {
guard self.data != nil else { return nil }
guard let cStr = clang_getCString(self) else { return nil }
let swiftStr = String(cString: cStr)
return swiftStr.isEmpty ? nil : swiftStr
}
func asSwiftOptional() -> String? {
defer { clang_disposeString(self) }
return asSwiftOptionalNoDispose()
}
func asSwiftNoDispose() -> String {
return asSwiftOptionalNoDispose() ?? ""
}
func asSwift() -> String {
return asSwiftOptional() ?? ""
}
}
extension Collection where Iterator.Element == String {
func withUnsafeCStringBuffer<Result>(
_ f: (UnsafeMutableBufferPointer<UnsafePointer<Int8>?>) throws -> Result)
rethrows -> Result {
var arr = [UnsafePointer<Int8>?]()
defer {
for cStr in arr {
free(UnsafeMutablePointer(mutating: cStr))
}
}
for str in self {
str.withCString { cStr in
arr.append(UnsafePointer(strdup(cStr)))
}
}
return try arr.withUnsafeMutableBufferPointer { buf in
return try f(UnsafeMutableBufferPointer(start: buf.baseAddress,
count: buf.count))
}
}
}
internal class Box<T> {
public var value: T
init(_ value: T) { self.value = value }
}
extension AnyRandomAccessCollection {
/// Creates a type-erased collection formed from lazy applications of
/// `indexingOperation` to index from zero up to, but not including, `count`.
init<T>(count: T, indexingOperation: @escaping (T) -> Element) where T: Strideable & ExpressibleByIntegerLiteral, T.Stride: SignedInteger {
self.init((0..<count).lazy.map(indexingOperation))
}
}
| mit | b53c10c5585b3ad4e9d746dff02a55cd | 27 | 142 | 0.653846 | 4.183908 | false | false | false | false |
crossroadlabs/Foundation3 | Foundation3/Bundle.swift | 1 | 3107 | //===--- Bundle.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
#if swift(>=3.0)
#if os(Linux)
public typealias Bundle = NSBundle
public extension Bundle {
public /*not inherited*/ convenience init(for aClass: Swift.AnyClass) {
self.init(forClass: aClass)
}
public class func main() -> Bundle {
return self.mainBundle()
}
}
public extension Bundle {
public class func pathsForResources(ofType ext: String?, inDirectory subpath: String) -> [String] {
return self.pathsForResourcesOfType(ext, inDirectory: subpath)
}
public func pathsForResources(ofType ext: String?, inDirectory subpath: String?) -> [String] {
return self.pathsForResourcesOfType(ext, inDirectory: subpath)
}
public func pathsForResources(ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> [String] {
return self.pathsForResourcesOfType(ext, inDirectory: subpath, forLocalization: localizationName)
}
}
#endif
#else
public typealias Bundle = NSBundle
public extension Bundle {
public /*not inherited*/ convenience init(for aClass: Swift.AnyClass) {
self.init(forClass: aClass)
}
public class func main() -> Bundle {
return self.mainBundle()
}
}
public extension Bundle {
@objc(pathsForResourcesOfType3:inDirectory:)
public class func pathsForResources(ofType ext: String?, inDirectory subpath: String) -> [String] {
return self.pathsForResourcesOfType(ext, inDirectory: subpath)
}
@objc(pathsForResourcesOfType3:inDirectory:)
public func pathsForResources(ofType ext: String?, inDirectory subpath: String?) -> [String] {
return self.pathsForResourcesOfType(ext, inDirectory: subpath)
}
@objc(pathsForResourcesOfType3:inDirectory:forLocalization:)
public func pathsForResources(ofType ext: String?, inDirectory subpath: String?, forLocalization localizationName: String?) -> [String] {
return self.pathsForResourcesOfType(ext, inDirectory: subpath, forLocalization: localizationName)
}
}
#endif
| apache-2.0 | 9305d87747bf4e380e71d3be97e5dca6 | 37.358025 | 149 | 0.620856 | 5.329331 | false | false | false | false |
alessiobrozzi/firefox-ios | Client/Frontend/Browser/SearchLoader.swift | 4 | 4985 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
private let log = Logger.browserLogger
private let URLBeforePathRegex = try! NSRegularExpression(pattern: "^https?://([^/]+)/", options: [])
// TODO: Swift currently requires that classes extending generic classes must also be generic.
// This is a workaround until that requirement is fixed.
typealias SearchLoader = _SearchLoader<AnyObject, AnyObject>
/**
* Shared data source for the SearchViewController and the URLBar domain completion.
* Since both of these use the same SQL query, we can perform the query once and dispatch the results.
*/
class _SearchLoader<UnusedA, UnusedB>: Loader<Cursor<Site>, SearchViewController> {
fileprivate let profile: Profile
fileprivate let urlBar: URLBarView
fileprivate var inProgress: Cancellable?
init(profile: Profile, urlBar: URLBarView) {
self.profile = profile
self.urlBar = urlBar
super.init()
}
fileprivate lazy var topDomains: [String] = {
let filePath = Bundle.main.path(forResource: "topdomains", ofType: "txt")
return try! String(contentsOfFile: filePath!).components(separatedBy: "\n")
}()
var query: String = "" {
didSet {
if query.isEmpty {
self.load(Cursor(status: .success, msg: "Empty query"))
return
}
if let inProgress = inProgress {
inProgress.cancel()
self.inProgress = nil
}
let deferred = self.profile.history.getSitesByFrecencyWithHistoryLimit(100, bookmarksLimit: 5, whereURLContains: query)
inProgress = deferred as? Cancellable
deferred.uponQueue(DispatchQueue.main) { result in
self.inProgress = nil
// Failed cursors are excluded in .get().
if let cursor = result.successValue {
// First, see if the query matches any URLs from the user's search history.
self.load(cursor)
for site in cursor {
if let url = site?.url,
let completion = self.completionForURL(url) {
self.urlBar.setAutocompleteSuggestion(completion)
return
}
}
// If there are no search history matches, try matching one of the Alexa top domains.
for domain in self.topDomains {
if let completion = self.completionForDomain(domain) {
self.urlBar.setAutocompleteSuggestion(completion)
return
}
}
}
}
}
}
fileprivate func completionForURL(_ url: String) -> String? {
// Extract the pre-path substring from the URL. This should be more efficient than parsing via
// NSURL since we need to only look at the beginning of the string.
// Note that we won't match non-HTTP(S) URLs.
guard let match = URLBeforePathRegex.firstMatch(in: url, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: url.characters.count)) else {
return nil
}
// If the pre-path component (including the scheme) starts with the query, just use it as is.
let prePathURL = (url as NSString).substring(with: match.rangeAt(0))
if prePathURL.startsWith(query) {
return prePathURL
}
// Otherwise, find and use any matching domain.
// To simplify the search, prepend a ".", and search the string for ".query".
// For example, for http://en.m.wikipedia.org, domainWithDotPrefix will be ".en.m.wikipedia.org".
// This allows us to use the "." as a separator, so we can match "en", "m", "wikipedia", and "org",
let domain = (url as NSString).substring(with: match.rangeAt(1))
return completionForDomain(domain)
}
fileprivate func completionForDomain(_ domain: String) -> String? {
let domainWithDotPrefix: String = ".\(domain)"
if let range = domainWithDotPrefix.range(of: ".\(query)", options: NSString.CompareOptions.caseInsensitive, range: nil, locale: nil) {
// We don't actually want to match the top-level domain ("com", "org", etc.) by itself, so
// so make sure the result includes at least one ".".
let matchedDomain: String = domainWithDotPrefix.substring(from: domainWithDotPrefix.index(range.lowerBound, offsetBy: 1))
if matchedDomain.contains(".") {
return matchedDomain + "/"
}
}
return nil
}
}
| mpl-2.0 | 1abb758ce3374b0e9f3e6b8ecb94e188 | 42.347826 | 178 | 0.60662 | 4.921027 | false | false | false | false |
343max/WorldTime | WorldTime/LocationsEditor/LocationsListDataSource.swift | 1 | 3278 | // Copyright 2014-present Max von Webel. All Rights Reserved.
import UIKit
protocol LocationsListDataSourceDelegate: class {
func didChange(locations: [Location])
func didSelect(location: Location, index: Int)
}
class LocationsListDataSource: LocationsDataSource, UITableViewDataSource, UITableViewDelegate {
static let timeFormatter = DateFormatter.shortTime()
let reuseIdentifier = "LocationSetupCell"
weak var delegate: LocationsListDataSourceDelegate?
func updateTime(cell: UITableViewCell, location: Location) {
cell.detailTextLabel?.text = location.timeZone.GMTdiff
}
func add(location: Location, tableView: UITableView) {
let indexPath = IndexPath(row: locations.count, section: 0)
locations.append(location)
tableView.insertRows(at: [ indexPath as IndexPath ], with: .automatic)
self.delegate?.didChange(locations: locations)
}
func update(location: Location, index: Int, tableView: UITableView) {
let indexPath = IndexPath(row: index, section: 0)
locations[index] = location
tableView.reloadRows(at: [ indexPath as IndexPath ], with: .automatic)
self.delegate?.didChange(locations: locations)
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return locations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell
if let dequeuedCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) {
cell = dequeuedCell
} else {
cell = UITableViewCell(style: .value1, reuseIdentifier: reuseIdentifier)
}
let location = locations[indexPath.row]
cell.textLabel?.text = location.name
cell.accessoryType = .disclosureIndicator
self.updateTime(cell: cell, location: location)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .delete:
locations.remove(at: indexPath.row)
tableView.deleteRows(at: [ indexPath as IndexPath ], with: .automatic)
case .insert, .none:
fatalError("not implemented")
}
self.delegate?.didChange(locations: locations)
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let location = locations[sourceIndexPath.row]
locations.remove(at: sourceIndexPath.row)
locations.insert(location, at: destinationIndexPath.row)
self.delegate?.didChange(locations: locations)
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.delegate?.didSelect(location: locations[indexPath.row], index: indexPath.row)
}
}
| mit | 00bc5625088dc30158e14c2fb40422a5 | 35.422222 | 127 | 0.692495 | 5.178515 | false | false | false | false |
michaelradtke/NSData-ByteView | Sources/Types.swift | 1 | 1853 | //
// Types.swift
//
// Copyright (c) 2015 Michael Radtke
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
//
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
//
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public typealias Byte = UInt8
public typealias SingleWord = UInt16
public typealias DoubleWord = UInt32
public typealias Long = UInt64
public enum HexStringError: Error {
case insufficientLength
case insufficientCharacters
}
typealias ByteArray = [Byte]
typealias SingleWordArray = [SingleWord]
typealias DoubleWordArray = [DoubleWord]
typealias LongArray = [Long]
typealias BooleanArray = [Bool]
typealias BytesOfSingleWord = (b0: Byte, b1: Byte)
typealias BytesOfDoubleWord = (b0: Byte, b1: Byte, b2: Byte, b3:Byte)
typealias BytesOfLong = (b0: Byte, b1: Byte, b2: Byte, b3:Byte, b4: Byte, b5: Byte, b6: Byte, b7:Byte)
| mit | c494ccec759295fca36f6938fa43f8ef | 37.604167 | 108 | 0.72531 | 3.925847 | false | false | false | false |
lee0741/Glider | Glider/Timestamp.swift | 1 | 1133 | //
// Timestamp.swift
// Glider
//
// Created by Yancen Li on 2/24/17.
// Copyright © 2017 Yancen Li. All rights reserved.
//
import Foundation
func dateformatter(date: Double) -> String {
let date1: Date = Date()
let date2: Date = Date(timeIntervalSince1970: date)
let calender: Calendar = Calendar.current
let components: DateComponents = calender.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date2, to: date1)
var returnString: String = ""
if components.year! >= 1 {
returnString = String(describing: components.year!) + " years ago"
} else if components.month! >= 1 {
returnString = String(describing: components.month!) + " months ago"
} else if components.day! >= 1 {
returnString = String(describing: components.day!) + " days ago"
} else if components.hour! >= 1 {
returnString = String(describing: components.hour!) + " hours ago"
} else if components.minute! >= 1 {
returnString = String(describing: components.minute!) + " minutes ago"
} else if components.second! < 60 {
returnString = "a minute ago"
}
return returnString
}
| mit | 3f290fa36b2d0a880ff85418a36a285f | 30.444444 | 130 | 0.668728 | 3.785953 | false | false | false | false |
vitortexc/MyAlertController | MyAlertController/MyAlertContent.swift | 1 | 1704 | //
// MyAlertContent.swift
// MyAlertController
//
// Created by Vitor Carrasco on 08/05/17.
// Copyright © 2017 Empresinha. All rights reserved.
//
// 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
internal extension UIView {
@objc func setupView() {
self.translatesAutoresizingMaskIntoConstraints = false
var auxHeight : CGFloat = 0
let views = ["content": self]
var metrics : [String:Any] = [:]
var constraints = [NSLayoutConstraint]()
// switch self {
// case is UILabel:
// break
// default:
// break
// }
constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-(==20@900)-[content]-(==20@900)-|", options: [], metrics: metrics, views: views)
if self.frame.size.height > 0 {
auxHeight = self.frame.size.height
metrics["height"] = auxHeight
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[content(height)]", options: [], metrics: metrics, views: views)
} else if !(self is UITextField) && !(self is UILabel) {
auxHeight = 60
metrics["height"] = auxHeight
constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[content(height)]", options: [], metrics: metrics, views: views)
}
NSLayoutConstraint.activate(constraints)
}
}
| mit | 2a60674dd63fd4db4835c30d9eb18179 | 32.392157 | 151 | 0.701116 | 3.933025 | false | false | false | false |
KelvinJin/AnimatedCollectionViewLayout | Sources/AnimatedCollectionViewLayout/Animators/CubeAttributesAnimator.swift | 1 | 3050 | //
// CubeAttributesAnimator.swift
// AnimatedCollectionViewLayout
//
// Created by Jin Wang on 8/2/17.
// Copyright © 2017 Uthoft. All rights reserved.
//
import UIKit
/// An animator that applies a cube transition effect when you scroll.
public struct CubeAttributesAnimator: LayoutAttributesAnimator {
/// The perspective that will be applied to the cells. Must be negative. -1/500 by default.
/// Recommended range [-1/2000, -1/200].
public var perspective: CGFloat
/// The higher the angle is, the _steeper_ the cell would be when transforming.
public var totalAngle: CGFloat
public init(perspective: CGFloat = -1 / 500, totalAngle: CGFloat = .pi / 2) {
self.perspective = perspective
self.totalAngle = totalAngle
}
public func animate(collectionView: UICollectionView, attributes: AnimatedCollectionViewLayoutAttributes) {
let position = attributes.middleOffset
guard let contentView = attributes.contentView else { return }
if abs(position) >= 1 {
contentView.layer.transform = CATransform3DIdentity
contentView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
} else if attributes.scrollDirection == .horizontal {
let rotateAngle = totalAngle * position
let anchorPoint = CGPoint(x: position > 0 ? 0 : 1, y: 0.5)
// As soon as we changed anchor point, we'll need to either update frame/position
// or transform to offset the position change. frame doesn't work for iOS 14 any
// more so we'll use transform.
let anchorPointOffsetValue = contentView.layer.bounds.width / 2
let anchorPointOffset = position > 0 ? -anchorPointOffsetValue : anchorPointOffsetValue
var transform = CATransform3DMakeTranslation(anchorPointOffset, 0, 0)
transform.m34 = perspective
transform = CATransform3DRotate(transform, rotateAngle, 0, 1, 0)
contentView.layer.transform = transform
contentView.layer.anchorPoint = anchorPoint
} else {
let rotateAngle = totalAngle * position
let anchorPoint = CGPoint(x: 0.5, y: position > 0 ? 0 : 1)
// As soon as we changed anchor point, we'll need to either update frame/position
// or transform to offset the position change. frame doesn't work for iOS 14 any
// more so we'll use transform.
let anchorPointOffsetValue = contentView.layer.bounds.height / 2
let anchorPointOffset = position > 0 ? -anchorPointOffsetValue : anchorPointOffsetValue
var transform = CATransform3DMakeTranslation(0, anchorPointOffset, 0)
transform.m34 = perspective
transform = CATransform3DRotate(transform, rotateAngle, -1, 0, 0)
contentView.layer.transform = transform
contentView.layer.anchorPoint = anchorPoint
}
}
}
| mit | b69f1058a7ef29937b8c8fe3548903ff | 44.507463 | 111 | 0.642834 | 4.957724 | false | false | false | false |
zenangst/Faker | Pod/Tests/Specs/Generators/GeneratorSpec.swift | 1 | 1562 | import Quick
import Nimble
class GeneratorSpec: QuickSpec {
override func spec() {
describe("Generator") {
var generator: Generator!
beforeEach {
generator = Generator(parser: Parser())
}
it("has parser") {
expect(generator.parser).notTo(beNil())
}
describe("filling") {
describe("#numerify") {
it("replaces # with random numbers") {
let numerified = generator.numerify("12####")
expect(numerified.toInt()).notTo(beNil())
expect(find(numerified, "#")).to(beNil())
expect(numerified).to(match("^12\\d{4}$"))
}
}
describe("#letterify") {
it("replaces ? with random letters") {
let letterified = generator.letterify("This is awes?me")
expect(find(letterified, "?")).to(beNil())
expect(letterified).to(match("^This is awes[A-Za-z]me$"))
}
}
describe("#bothify") {
it("replaces # with random numbers and ? with random letters") {
let bothified = generator.bothify("#th of ?pril")
expect(find(bothified, "#")).to(beNil())
expect(find(bothified, "?")).to(beNil())
expect(bothified).to(match("^\\dth of [A-Za-z]pril$"))
}
}
describe("#AlphaNumerify") {
it("removes special characters") {
let latin = generator.alphaNumerify("Øghdasæå!y_=a")
expect(latin).to(equal("ghdasy_a"))
}
}
}
}
}
}
| mit | 5bd2398867d161c23453883b6fd76c91 | 27.87037 | 74 | 0.52213 | 4.049351 | false | false | false | false |
vladimirkofman/TableTie | TableTie/Row.swift | 1 | 1454 | //
// Row.swift
// TableTie
//
// Created by Vladimir Kofman on 21/04/2017.
// Copyright © 2017 Vladimir Kofman. All rights reserved.
//
import UIKit
/**
All row items to be displayed should conform to this protocol.
*/
public protocol Row: AnyRow {
associatedtype Cell: UITableViewCell
/// "Private" method, please don't override
func _dequeueCell(tableView: UITableView, reuseIdentifier: String) -> UITableViewCell
/**
The only required method to override. Please provide the correct type for cell parameter. The cell will be automatically created and registered for reuse.
*/
func configure(cell: Cell)
}
public extension Row {
func _dequeueCell(tableView: UITableView) -> UITableViewCell {
return _dequeueCell(tableView: tableView, reuseIdentifier: reuseIdentifier)
}
func _dequeueCell(tableView: UITableView, reuseIdentifier: String) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
if cell == nil {
tableView.register(Cell.self, forCellReuseIdentifier: reuseIdentifier)
cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
}
return cell ?? UITableViewCell()
}
}
public extension Row {
func _configure(cell: UITableViewCell) {
guard let cell = cell as? Cell else { return }
configure(cell: cell)
}
}
| mit | af62bb49a4a21aa1566ab7956a7af625 | 28.653061 | 159 | 0.678596 | 4.976027 | false | true | false | false |
LonelyHusky/SCWeibo | SCWeibo/Classes/View/Home/View/SCStatusPictureView.swift | 1 | 3833 | //
// SCStatusPictureView.swift
// SCWeibo
//
// Created by 云卷云舒丶 on 16/7/25.
//
//
import UIKit
// 每一个条目之间的间距
let SCStatusPictureItemMargin : CGFloat = 5
//每一条目的宽高
let SCStatusPictureItemWH : CGFloat = (SCReenW - 2 * SCStatusCellMargin - 2 * SCStatusPictureItemMargin) / 3
class SCStatusPictureView: UICollectionView {
private let pictureCellId = "pictureCellId"
var pic_urls: [SCStatusPhontoInfo]?{
didSet{
reloadData()
}
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
backgroundColor = RandomColor
// 注册Cell
registerClass(SCStatusPictureViewCell.self, forCellWithReuseIdentifier: pictureCellId)
//设置数据源
self.dataSource = self
// 每个条目之间的大小
let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width:SCStatusPictureItemWH , height: SCStatusPictureItemWH)
// 间隙
layout.minimumLineSpacing = SCStatusPictureItemMargin
layout.minimumInteritemSpacing = SCStatusPictureItemMargin
}
}
extension SCStatusPictureView : UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return pic_urls?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellId, forIndexPath: indexPath) as! SCStatusPictureViewCell
cell.backgroundColor = RandomColor
cell.photoInfo = pic_urls![indexPath.item]
return cell
}
}
//自定义配图的cell
class SCStatusPictureViewCell : UICollectionViewCell{
var photoInfo : SCStatusPhontoInfo?{
didSet{
pictureImage.sd_setImageWithURL(NSURL(string: photoInfo?.thumbnail_pic ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))
//判断是否为动图
// if let url = photoInfo?.thumbnail_pic where url.hasSuffix(".gif") {
// gifImage.hidden = false
// }else{
// gifImage.hidden = true
// }
gifImage.hidden = !(photoInfo?.thumbnail_pic ?? "").hasSuffix(".gif")
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
contentView.addSubview(pictureImage)
contentView.addSubview(gifImage)
pictureImage.snp_makeConstraints { (make) in
make.edges.equalTo(contentView)
}
gifImage.snp_makeConstraints { (make) in
make.trailing.bottom.equalTo(contentView)
}
}
// MARK: - 懒加载
private lazy var pictureImage : UIImageView = {
let imageView = UIImageView(image: UIImage(named: "timeline_card_top_background"))
imageView.contentMode = .ScaleAspectFill
// 把超出部分去掉
imageView.clipsToBounds = true
return imageView
}()
private lazy var gifImage : UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}
| mit | 8a79424608f28cb55a89ce373263b65f | 24.923077 | 156 | 0.627192 | 4.896962 | false | false | false | false |
ppervoy/iOStests | MyCalendar/DaysTableViewController.swift | 1 | 1287 | //
// DaysTableViewController.swift
// MyCalendar
//
// Created by J Nastos on 12/14/15.
// Copyright © 2015 J Nastos. All rights reserved.
//
import Foundation
import UIKit
class DaysTableViewController : UITableViewController {
var monthNumber = -1
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 31
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Basic")!
cell.textLabel?.text = "\(indexPath.row + 1)"
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "DaySegue") {
let selectedRow = tableView.indexPathForSelectedRow?.row
if let dest = segue.destinationViewController as? SingleDayTableViewController {
dest.title = "\(selectedRow! + 1)"
dest.monthNumber = monthNumber
dest.dayNumber = selectedRow! + 1
}
}
}
} | gpl-3.0 | 8feccf5b12a3ed7ee423c391633f7a94 | 28.25 | 118 | 0.631415 | 5.380753 | false | false | false | false |
clappr/clappr-ios | Tests/Clappr_Tests/Classes/Helper/SwiftVersionTests.swift | 1 | 2095 | import Quick
import Nimble
class SwiftVersionTests: QuickSpec {
override func spec() {
describe("Podspec and .swift-version") {
context("when read swift version") {
it("matches") {
let versionFromPodspec = extractSwiftVersionFromPodspec()
let versionFromFile = extractVersionFromFile()
expect(versionFromPodspec).to(equal(versionFromFile))
}
}
}
func switfVersionContents() -> String {
let swiftVersionPath = Bundle.init(for: type(of: self)).path(forResource: ".swift-version", ofType: "")!
return try! String(contentsOfFile: swiftVersionPath)
}
func extractVersionFromFile() -> String {
let contents = switfVersionContents()
return contents.capturedGroups(withRegex: "(.+)").first!
}
func podspecContents() -> String {
let podspecPath = Bundle(for: type(of: self)).path(forResource: "Clappr", ofType: "podspec")!
return try! String(contentsOfFile: podspecPath)
}
func extractSwiftVersionFromPodspec() -> String {
let podspec = podspecContents()
let podSpecSwiftVersion = matches(for: "s?\\.swift_version*\\s?=\\s?['\"](.+)['\"]", in: podspec).first!
let version = podSpecSwiftVersion.capturedGroups(withRegex: "['\"](.+)['\"]").first!
return version
}
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
}
}
| bsd-3-clause | 35d045b17f8740a6b1c3a4a9451573bf | 39.288462 | 116 | 0.528401 | 5.023981 | false | false | false | false |
juheon0615/GhostHandongSwift | HandongAppSwift/CVCalendar/CVCalendarContentViewController.swift | 11 | 6686 | //
// CVCalendarContentViewController.swift
// CVCalendar Demo
//
// Created by Eugene Mozharovsky on 12/04/15.
// Copyright (c) 2015 GameApp. All rights reserved.
//
import UIKit
typealias Identifier = String
class CVCalendarContentViewController: UIViewController {
// MARK: - Constants
let Previous = "Previous"
let Presented = "Presented"
let Following = "Following"
// MARK: - Public Properties
let calendarView: CalendarView
let scrollView: UIScrollView
var presentedMonthView: MonthView
var bounds: CGRect {
return scrollView.bounds
}
var currentPage = 1
var pageChanged: Bool {
get {
return currentPage == 1 ? false : true
}
}
var pageLoadingEnabled = true
var presentationEnabled = true
var lastContentOffset: CGFloat = 0
var direction: CVScrollDirection = .None
init(calendarView: CalendarView, frame: CGRect) {
self.calendarView = calendarView
scrollView = UIScrollView(frame: frame)
presentedMonthView = MonthView(calendarView: calendarView, date: NSDate())
presentedMonthView.updateAppearance(frame)
super.init(nibName: nil, bundle: nil)
scrollView.contentSize = CGSizeMake(frame.width * 3, frame.height)
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.layer.masksToBounds = true
scrollView.pagingEnabled = true
scrollView.delegate = self
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI Refresh
extension CVCalendarContentViewController {
func updateFrames(frame: CGRect) {
if frame != CGRectZero {
scrollView.frame = frame
scrollView.removeAllSubviews()
scrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height)
}
calendarView.hidden = false
}
}
// MARK: - Abstract methods
/// UIScrollViewDelegate
extension CVCalendarContentViewController: UIScrollViewDelegate { }
/// Convenience API.
extension CVCalendarContentViewController {
func performedDayViewSelection(dayView: DayView) { }
func togglePresentedDate(date: NSDate) { }
func presentNextView(view: UIView?) { }
func presentPreviousView(view: UIView?) { }
func updateDayViews(hidden: Bool) { }
}
// MARK: - Contsant conversion
extension CVCalendarContentViewController {
func indexOfIdentifier(identifier: Identifier) -> Int {
let index: Int
switch identifier {
case Previous: index = 0
case Presented: index = 1
case Following: index = 2
default: index = -1
}
return index
}
}
// MARK: - Date management
extension CVCalendarContentViewController {
func dateBeforeDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
let calendar = NSCalendar.currentCalendar()
components.month -= 1
let dateBefore = calendar.dateFromComponents(components)!
return dateBefore
}
func dateAfterDate(date: NSDate) -> NSDate {
let components = Manager.componentsForDate(date)
let calendar = NSCalendar.currentCalendar()
components.month += 1
let dateAfter = calendar.dateFromComponents(components)!
return dateAfter
}
func matchedMonths(lhs: Date, _ rhs: Date) -> Bool {
return lhs.year == rhs.year && lhs.month == rhs.month
}
func matchedWeeks(lhs: Date, _ rhs: Date) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.week == rhs.week)
}
func matchedDays(lhs: Date, _ rhs: Date) -> Bool {
return (lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day)
}
}
// MARK: - AutoLayout Management
extension CVCalendarContentViewController {
private func layoutViews(views: [UIView], toHeight height: CGFloat) {
self.scrollView.frame.size.height = height
self.calendarView.layoutIfNeeded()
for view in views {
view.layoutIfNeeded()
}
}
func updateHeight(height: CGFloat, animated: Bool) {
var viewsToLayout = [UIView]()
if let calendarSuperview = calendarView.superview {
for constraintIn in calendarSuperview.constraints() {
if let constraint = constraintIn as? NSLayoutConstraint {
if let firstItem = constraint.firstItem as? UIView, let secondItem = constraint.secondItem as? CalendarView {
viewsToLayout.append(firstItem)
}
}
}
}
for constraintIn in calendarView.constraints() {
if let constraint = constraintIn as? NSLayoutConstraint where constraint.firstAttribute == NSLayoutAttribute.Height {
calendarView.layoutIfNeeded()
constraint.constant = height
if animated {
UIView.animateWithDuration(0.2, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.layoutViews(viewsToLayout, toHeight: height)
}) { _ in
self.presentedMonthView.frame.size = self.presentedMonthView.potentialSize
self.presentedMonthView.updateInteractiveView()
}
} else {
layoutViews(viewsToLayout, toHeight: height)
presentedMonthView.updateInteractiveView()
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
break
}
}
}
func updateLayoutIfNeeded() {
if presentedMonthView.potentialSize.height != scrollView.bounds.height {
updateHeight(presentedMonthView.potentialSize.height, animated: true)
} else if presentedMonthView.frame.size != scrollView.frame.size {
presentedMonthView.frame.size = presentedMonthView.potentialSize
presentedMonthView.updateInteractiveView()
}
}
}
extension UIView {
func removeAllSubviews() {
for subview in subviews {
if let view = subview as? UIView {
view.removeFromSuperview()
}
}
}
} | mit | 9f1463bf87f211c9dfa7c10db07eee20 | 30.247664 | 129 | 0.613072 | 5.585631 | false | false | false | false |
ahoppen/swift | test/Incremental/Verifier/single-file-private/AnyObject.swift | 4 | 5093 | // UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// UNSUPPORTED: CPU=armv7k && OS=ios
// Exclude iOS-based 32-bit platforms because the Foundation overlays introduce
// an extra dependency on _KeyValueCodingAndObservingPublishing only for 64-bit
// platforms.
// REQUIRES: objc_interop
// RUN: %empty-directory(%t)
// RUN: cd %t && %target-swift-frontend(mock-sdk: %clang-importer-sdk) -c -module-name main -verify-incremental-dependencies -primary-file %s -o /dev/null
import Foundation
// expected-provides {{LookupFactory}}
// expected-provides {{NSObject}}
// expected-provides {{Selector}}
// expected-provides {{Bool}}
// expected-provides {{==}}
// expected-provides {{Equatable}}
// expected-provides {{Hasher}}
// expected-provides {{_ObjectiveCBridgeable}}
// expected-provides{{Hashable}}
// expected-member {{ObjectiveC.NSObject.NSObject}}
// expected-superclass {{ObjectiveC.NSObject}}
// expected-conformance {{ObjectiveC.NSObjectProtocol}}
// expected-member {{ObjectiveC.NSObjectProtocol.NSObject}}
// expected-member {{ObjectiveC.NSObject.Bool}}
// expected-conformance {{Swift.Hashable}}
// expected-conformance {{Swift.Equatable}}
// expected-member {{Swift._ExpressibleByBuiltinIntegerLiteral.init}}
@objc private class LookupFactory: NSObject {
// expected-provides {{AssignmentPrecedence}}
// expected-provides {{IntegerLiteralType}}
// expected-provides {{FloatLiteralType}}
// expected-provides {{Int}}
// expected-member {{ObjectiveC.NSObject.someMember}}
// expected-member {{ObjectiveC.NSObject.Int}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMember}}
// expected-member {{ObjectiveC.NSObjectProtocol.Int}}
// expected-member {{main.LookupFactory.Int}}
@objc var someMember: Int = 0
// expected-member {{ObjectiveC.NSObject.someMethod}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethod}}
@objc func someMethod() {}
// expected-member {{ObjectiveC.NSObject.init}}
// expected-member {{ObjectiveC.NSObject.deinit}}
// expected-member {{ObjectiveC.NSObjectProtocol.init}}
// expected-member {{ObjectiveC.NSObjectProtocol.deinit}}
// expected-member {{main.LookupFactory.init}}
// expected-member {{main.LookupFactory.deinit}}
// expected-member {{main.LookupFactory.someMember}}
// expected-member {{main.LookupFactory.someMethod}}
}
// expected-member {{Swift.ExpressibleByNilLiteral.callAsFunction}}
// expected-member {{Swift.CustomReflectable.callAsFunction}}
// expected-member {{Swift._ObjectiveCBridgeable.callAsFunction}}
// expected-member {{Swift.Optional<Wrapped>.callAsFunction}}
// expected-member {{Swift.CustomDebugStringConvertible.callAsFunction}}
// expected-member {{Swift.Equatable.callAsFunction}}
// expected-member {{Swift.Hashable.callAsFunction}}
// expected-member {{Swift.Encodable.callAsFunction}}
// expected-member {{Swift.Decodable.callAsFunction}}
// expected-member {{Swift.Hashable._rawHashValue}}
// expected-member {{ObjectiveC.NSObject.hash}}
// expected-member {{Swift.Equatable.hashValue}}
// expected-member{{Swift.Hashable.hashValue}}
// expected-member{{Swift.Hashable.hash}}
// expected-member{{ObjectiveC.NSObjectProtocol.==}}
// expected-member {{ObjectiveC.NSObjectProtocol.hashValue}}
// expected-member {{ObjectiveC.NSObjectProtocol.Hasher}}
// expected-member {{Swift.Equatable._rawHashValue}}
// expected-member {{ObjectiveC.NSObject.hashValue}}
// expected-member {{ObjectiveC.NSObjectProtocol.Bool}}
// expected-member {{ObjectiveC.NSObject.==}}
// expected-member {{Swift.Equatable.==}}
// expected-member {{ObjectiveC.NSObject.Hasher}}
// expected-member {{ObjectiveC.NSObjectProtocol.hash}}
// expected-member {{Swift.Hashable.init}}
// expected-member {{Swift.Hashable.deinit}}
// expected-member {{Swift.Equatable.init}}
// expected-member {{Swift.Equatable.deinit}}
// expected-member {{Swift.Hashable.==}}
// expected-member {{Swift.Equatable.hash}}
// expected-member {{ObjectiveC.NSObject._rawHashValue}}
// expected-member {{ObjectiveC.NSObjectProtocol._rawHashValue}}
// expected-provides {{AnyObject}}
func lookupOnAnyObject(object: AnyObject) { // expected-provides {{lookupOnAnyObject}}
_ = object.someMember // expected-dynamic-member {{someMember}}
object.someMethod() // expected-dynamic-member {{someMethod}}
}
// expected-member {{Swift.Hashable.someMethod}}
// expected-member {{Swift.Equatable.someMethod}}
// expected-member {{Swift.Equatable.someMember}}
// expected-member {{Swift.Hashable.someMember}}
// expected-member {{Swift.Sendable.callAsFunction}}
// expected-member {{ObjectiveC.NSObject.someMethodWithDeprecatedOptions}}
// expected-member {{ObjectiveC.NSObject.someMethodWithPotentiallyUnavailableOptions}}
// expected-member {{ObjectiveC.NSObject.someMethodWithUnavailableOptions}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethodWithUnavailableOptions}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethodWithPotentiallyUnavailableOptions}}
// expected-member {{ObjectiveC.NSObjectProtocol.someMethodWithDeprecatedOptions}}
| apache-2.0 | 89f2aa58775df3f35bde91082147d2f1 | 45.724771 | 154 | 0.759866 | 4.312447 | false | false | false | false |
wftllc/hahastream | Haha Stream/Extensions/Channel+LocalImage.swift | 1 | 2179 | import Foundation
import UIKit
extension Channel: LocalImage {
public func saveLocalImage(_ completion: @escaping ((_ url: URL?, _ error: Error?) -> ())) {
DispatchQueue.global().async {
do {
let data = self.generateImageData()
try data.write(to: self.singleImageLocalURL)
DispatchQueue.main.async {
completion(self.singleImageLocalURL, nil)
}
}
catch {
DispatchQueue.main.async {
completion(nil, error)
}
}
}
}
fileprivate func generateImageData() -> Data {
let height: CGFloat = 608;
let width = height * 404
let str:NSString = NSString(string: self.title)
let style = NSMutableParagraphStyle();
style.alignment = .center
var attr: [NSAttributedStringKey: Any] = [
.paragraphStyle: style,
.foregroundColor: UIColor.darkGray,
]
if let font = UIFont(name: UIFont.preferredFont(forTextStyle: .title1).fontName, size: 90) {
attr[.font] = font
}
let textSize = str.size(withAttributes: attr)
let contextSize = CGSize(width: width, height: height)
let renderer = UIGraphicsImageRenderer(size: contextSize)
let textRect = CGRect(origin: CGPoint(x: width/2 - textSize.width/2, y: height/2-textSize.height/2), size: textSize);
let data = renderer.pngData { (context) in
context.cgContext.setFillColor(UIColor.white.cgColor)
context.cgContext.fill(CGRect(origin: CGPoint(x:0, y:0), size: contextSize))
context.cgContext.setShouldSmoothFonts(true)
context.cgContext.setFillColor(UIColor.lightGray.cgColor)
str.draw(in: textRect, withAttributes: attr)
}
return data;
}
public var localImageExists: Bool {
// return false
return FileManager.default.fileExists(atPath: singleImageLocalURL.path);
}
public var singleImageLocalURL: URL {
let name = "channel-\(self.uuid)"
let fileURL = self.getCacheDirectory().appendingPathComponent(name).appendingPathExtension("png")
return fileURL;
}
fileprivate func getCacheDirectory() -> URL {
let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let path = paths[0]
return path;
// return path.appendingPathComponent("games", isDirectory: true)
}
}
| mit | 1ae9aa693e3ae08f5ac60cce9e7b33b1 | 27.671053 | 119 | 0.705369 | 3.662185 | false | false | false | false |
ZacharyKhan/ZKNavigationController | ZKNavigationController/Classes/ZKIcon.swift | 1 | 672 | //
// ZKIcon.swift
// ZKNavigationPopup
//
// Created by Zachary Khan on 7/25/16.
// Copyright © 2016 ZacharyKhan. All rights reserved.
//
import UIKit
public class ZKIcon: UIImageView {
override public init(image: UIImage?) {
super.init(image: image)
self.frame = CGRect(x: 0, y: 0, width: 45, height: 45)
self.clipsToBounds = true
self.layer.cornerRadius = self.frame.width / 2
self.layer.borderColor = UIColor.whiteColor().CGColor
self.layer.borderWidth = 2
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | de2afba0dfc8d239db427fad978f5632 | 22.964286 | 62 | 0.622951 | 3.901163 | false | false | false | false |
tschob/HSAudioPlayer | HSAudioPlayer/Core/Public/Player/HSAudioPlayer+MPMediaItem.swift | 1 | 2694 | //
// HSAudioPlayer+MPMediaItem.swift
// HSAudioPlayer
//
// Created by Hans Seiffert on 02.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import MediaPlayer
extension HSAudioPlayer {
// MARK: - Play
public func play(mediaItem mediaItem: MPMediaItem) {
if let _playerItem = HSMediaItemAudioPlayerItem(mediaItem: mediaItem) {
self.play(_playerItem)
}
}
public func play(mediaItems mediaItems: [MPMediaItem], startPosition: Int) {
// Play first item directly and add the other items to the queue in the background
if let firstPlayableItem = HSMediaItemAudioPlayerItem.firstPlayableItem(mediaItems, startPosition: startPosition) {
// Play the first player item directly
self.play(firstPlayableItem.playerItem)
// Split the items into array which contain the ones which have to be prepended and appended them to the queue
var mediaItemsToPrepend = Array(mediaItems)
mediaItemsToPrepend.removeRange(firstPlayableItem.index..<mediaItemsToPrepend.count)
var mediaItemsToAppend = Array(mediaItems)
mediaItemsToAppend.removeRange(0..<(firstPlayableItem.index + 1))
// Append the remaining items to queue in the background
// As we creation of the items takes some time, we avoid a blocked UI
self.addToQueueInBackground(prepend: mediaItemsToPrepend, append: mediaItemsToAppend, queueGeneration: self.queueGeneration)
}
}
private func addToQueueInBackground(prepend mediaItemsToPrepend: [MPMediaItem], append mediaItemsToAppend: [MPMediaItem], queueGeneration: Int) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let itemsToPrepend = HSMediaItemAudioPlayerItem.playerItems(mediaItemsToPrepend, startPosition: 0)
let tiemsToAppend = HSMediaItemAudioPlayerItem.playerItems(mediaItemsToAppend, startPosition: 0)
dispatch_async(dispatch_get_main_queue()) {
self.prepend(itemsToPrepend.items, queueGeneration: queueGeneration)
self.append(tiemsToAppend.items, queueGeneration: queueGeneration)
}
}
}
// MARK: - Helper
public func isPlaying(mediaItem mediaItem: MPMediaItem) -> Bool {
return self.isPlaying(persistentID: mediaItem.persistentID)
}
public func isPlaying(mediaItemCollection: MPMediaItemCollection) -> Bool {
for mediaItem in mediaItemCollection.items {
if (self.isPlaying(mediaItem: mediaItem) == true) {
return true
}
}
return false
}
public func isPlaying(persistentID persistentID: MPMediaEntityPersistentID) -> Bool {
if (self.isPlaying() == true),
let _currentMediaItem = self.currentPlayerItem() as? HSMediaItemAudioPlayerItem {
return ("\(persistentID)" == _currentMediaItem.identifier())
}
return false
}
}
| mit | 6526e2911138ac1678cf6d1ab945b69f | 37.471429 | 146 | 0.767174 | 3.94868 | false | false | false | false |
taketo1024/SwiftyAlgebra | Tests/SwmCoreTests/Numbers/ComplexTests.swift | 1 | 4794 | //
// SwiftyMathTests.swift
// SwiftyMathTests
//
// Created by Taketo Sano on 2017/05/03.
// Copyright © 2017年 Taketo Sano. All rights reserved.
//
import XCTest
@testable import SwmCore
class ComplexTests: XCTestCase {
typealias A = 𝐂
func testFromInt() {
let a = A(from: 5)
assertApproxEqual(a, A(5, 0))
}
func testFromReal() {
let a = A(𝐑(3.14))
assertApproxEqual(a, A(3.14, 0))
}
func testFromPolar() {
let a = A(r: 2, θ: π / 4)
XCTAssertTrue(a.isApproximatelyEqualTo(A(√2, √2)))
}
func testSum() {
let a = A(1, 2)
let b = A(3, 4)
assertApproxEqual(a + b, A(4, 6))
}
func testZero() {
let a = A(3, 4)
let o = A.zero
assertApproxEqual(o + o, o)
assertApproxEqual(a + o, a)
assertApproxEqual(o + a, a)
}
func testNeg() {
let a = A(3, 4)
assertApproxEqual(-a, A(-3, -4))
}
func testConj() {
let a = A(3, 4)
assertApproxEqual(a.conjugate, A(3, -4))
}
func testMul() {
let a = A(2, 3)
let b = A(4, 5)
assertApproxEqual(a * b, A(-7, 22))
}
func testId() {
let a = A(2, 1)
let e = A.identity
assertApproxEqual(e * e, e)
assertApproxEqual(a * e, a)
assertApproxEqual(e * a, a)
}
func testInv() {
let a = A(3, 4)
assertApproxEqual(a.inverse!, A(0.12, -0.16))
let o = A.zero
XCTAssertNil(o.inverse)
}
func testDiv() {
let a = A(2, 3)
let b = A(3, 4)
XCTAssertTrue((a / b).isApproximatelyEqualTo(A(0.72, 0.04), error: 0.0001))
}
func testPow() {
let a = A(2, 1)
assertApproxEqual(a.pow(0), A.identity)
assertApproxEqual(a.pow(1), A(2, 1))
assertApproxEqual(a.pow(2), A(3, 4))
assertApproxEqual(a.pow(3), A(2, 11))
assertApproxEqual(a.pow(-1), A(0.4, -0.2))
assertApproxEqual(a.pow(-2), A(0.12, -0.16))
assertApproxEqual(a.pow(-3), A(0.016, -0.088))
}
func testAbs() {
let a = A(2, 4)
assertApproxEqual(a.abs, √20)
assertApproxEqual((-a).abs, √20)
assertApproxEqual(a.conjugate.abs, √20)
}
func testArg() {
let a = A(1, 1)
assertApproxEqual(a.arg, π / 4)
}
func testRandom() {
var results: Set<A> = []
for _ in 0 ..< 100 {
let x = A.random()
results.insert(x)
}
XCTAssertTrue(results.isUnique)
XCTAssertTrue(results.contains{ $0.realPart > 0 && $0.imaginaryPart > 0 })
XCTAssertTrue(results.contains{ $0.realPart > 0 && $0.imaginaryPart < 0 })
XCTAssertTrue(results.contains{ $0.realPart < 0 && $0.imaginaryPart > 0 })
XCTAssertTrue(results.contains{ $0.realPart < 0 && $0.imaginaryPart < 0 })
}
func testRandomInRange() {
let range: Range<Double> = -100 ..< 100
var results: Set<A> = []
for _ in 0 ..< 100 {
let x = A.random(in: range)
results.insert(x)
XCTAssertTrue(range.contains(x.realPart))
XCTAssertTrue(range.contains(x.imaginaryPart))
}
XCTAssertTrue(results.isUnique)
XCTAssertTrue(results.contains{ $0.realPart > 0 && $0.imaginaryPart > 0 })
XCTAssertTrue(results.contains{ $0.realPart > 0 && $0.imaginaryPart < 0 })
XCTAssertTrue(results.contains{ $0.realPart < 0 && $0.imaginaryPart > 0 })
XCTAssertTrue(results.contains{ $0.realPart < 0 && $0.imaginaryPart < 0 })
}
func testRandomInClosedRange() {
let range: ClosedRange<Double> = -100 ... 100
var results: Set<A> = []
for _ in 0 ..< 100 {
let x = A.random(in: range)
results.insert(x)
XCTAssertTrue(range.contains(x.realPart))
XCTAssertTrue(range.contains(x.imaginaryPart))
}
XCTAssertTrue(results.isUnique)
XCTAssertTrue(results.contains{ $0.realPart > 0 && $0.imaginaryPart > 0 })
XCTAssertTrue(results.contains{ $0.realPart > 0 && $0.imaginaryPart < 0 })
XCTAssertTrue(results.contains{ $0.realPart < 0 && $0.imaginaryPart > 0 })
XCTAssertTrue(results.contains{ $0.realPart < 0 && $0.imaginaryPart < 0 })
}
private func assertApproxEqual(_ x: 𝐑, _ y: 𝐑, error e: 𝐑 = 0.0001) {
XCTAssertTrue(x.isApproximatelyEqualTo(y, error: e))
}
private func assertApproxEqual(_ x: 𝐂, _ y: 𝐂, error e: 𝐑 = 0.0001) {
XCTAssertTrue(x.isApproximatelyEqualTo(y, error: e))
}
}
| cc0-1.0 | c70274221f466bae2b3d7f660d0b65c2 | 27.987805 | 83 | 0.530921 | 3.531947 | false | true | false | false |
UncleJoke/JKPinTu-Swift | JKPinTu-Swift/ViewControllers/Huaban/JKHBImageListViewController.swift | 1 | 4839 | //
// JKHBImageListViewController.swift
// PingTu-swift
//
// Created by bingjie-macbookpro on 15/12/10.
// Copyright © 2015年 Bingjie. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher
import MJRefresh
import MBProgressHUD
final class JKHBImageListViewController: UICollectionViewController {
private var tags = [JKHBTagDetailInfo]()
var tagName:String? = ""
convenience init(){
let layout = UICollectionViewFlowLayout()
let width = SCREEN_WIDTH/3 - 2
layout.itemSize = CGSizeMake(width, width * 1.5)
layout.sectionInset = UIEdgeInsetsZero
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 2
layout.scrollDirection = .Vertical
self.init(collectionViewLayout:layout)
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = UIColor.whiteColor()
self.collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
self.collectionView!.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(JKHBImageListViewController.headerRefresh))
self.collectionView!.mj_footer = MJRefreshBackNormalFooter(refreshingTarget: self, refreshingAction: #selector(JKHBImageListViewController.footerRefresh))
self.collectionView!.mj_header.beginRefreshing()
}
func headerRefresh(){
self.sendRequest(0)
}
func footerRefresh(){
var seq = 0
if self.tags.count != 0{
let lastObjc = self.tags.last
seq = lastObjc!.seq == 0 ? 0 : lastObjc!.seq
}
self.sendRequest(seq)
}
func sendRequest(seq:Int){
let max = seq == 0 ? "" : "\(seq)"
Alamofire.request(.GET, "http://api.huaban.com/fm/wallpaper/pins", parameters: ["limit": 21 , "tag":self.tagName! , "max": max]).jk_responseSwiftyJSON { (request, response, JSON_obj, error) -> Void in
if JSON_obj == JSON.null {
return
}
let pins = (JSON_obj.object as! NSDictionary)["pins"]
let tempTags = JKHBTagDetailInfo.parseDataFromHuaban(pins as! Array)
self.tags = seq != 0 ? (self.tags + tempTags) : tempTags
self.collectionView?.reloadData()
self.collectionView!.mj_header.endRefreshing()
self.collectionView!.mj_footer.endRefreshing()
}
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.tags.count
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("UICollectionViewCell", forIndexPath: indexPath)
cell.contentView.backgroundColor = UIColor.whiteColor()
var imageView = cell.contentView.viewWithTag(1111) as? UIImageView
if(imageView == nil){
imageView = UIImageView(frame: cell.bounds)
imageView!.tag = 1111
imageView?.clipsToBounds = true
imageView?.contentMode = .ScaleAspectFill
cell.contentView.addSubview(imageView!)
}
let tag = self.tags[indexPath.row]
imageView!.kf_setImageWithURL(NSURL(string: tag.thumbnailImageURL)!)
return cell
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
collectionView.deselectItemAtIndexPath(indexPath, animated: true)
let tag = self.tags[indexPath.row]
let url = NSURL(string: tag.originalImageURL)
KingfisherManager.sharedManager.downloader.downloadImageWithURL(url!, progressBlock: { (receivedSize, totalSize) -> () in
// let progress = Float(receivedSize)/Float(totalSize)
}) { [unowned self] (image, error, imageURL, originalData) -> () in
(self.navigationController as! JKHBNavigationController).dismissClick({ [unowned self] () -> Void in
if((self.navigationController as! JKHBNavigationController).imageBlock != nil){
(self.navigationController as! JKHBNavigationController).imageBlock!(image!)
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | af78bd5cf9c2ecdfd2ac1fa8d9aa40eb | 37.688 | 208 | 0.647436 | 5.245119 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00452-nanl.random.swift | 1 | 1534 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
> (object1: A {
}
let a {
protocol A : A: $0) -> T) -> ()
}
import Foundation
protocol d {
struct d<D> Void>(f<U -> T>(v: ()
protocol b {
func a
var d = { c
extension NSSet {
import Foundation
protocol d where g, b {
var e: Int
var e!.b {
}
var e: P {
func a(c) {
import Foundation
}
if c : I.init(e: T>) -> () -> {
}
import Foundation
}
}
func g<A? = 0
self.c == F>(g.E == b
return self.E == F>) -> Void>() -> Int -> S<T>(t: A.h = a(f: P {
typealias e where T: c()
}
self.E == c() {
}
}
print(x: c>? {
var d = ""
}
}
var d where g<T>: NSObject {
func a(array: C {
}
}
extension NSSet {
typealias h> V {
protocol a {
let h == nil
e {
}(#object2)
print()
b
struct c = a
}
enum A {
init(#object1: P {
struct S {
}
protocol d = 0
}
func b: B<T) -> : String = a(n: C
class d
struct e = B<Q<T.b {
var f.R
}
for b {
struct e where T: T! {
func f() {
struct D : H.init()
}
}
protocol P {
return g(e: A? = A> (self.dynamicType)")
typealias h
func f, b {
}
}
typealias h> [unowned self] {
protocol e where H.d
case b in x }
}
}
func b
}
}
func b(f: c
func compose<f : P {
}
extension NSSet {
struct S<I : T>()
}
let c {
}
func f<T: e: U : T
dei
| apache-2.0 | 3c14e93ab0153d3fbd1491d1cac3816e | 14.188119 | 79 | 0.607562 | 2.565217 | false | false | false | false |
arunlj561/AJIBDesignables | Example/Pods/AJIBDesignables/AJIBDesignables/Classes/UIView+Base.swift | 2 | 4184 | //
// UIViewBase.swift
// IBInspectable
//
// Created by Arun Jangid on 24/02/16.
// Copyright © 2016 Arun Jangid. All rights reserved.
//
import Foundation
import UIKit
enum sides : String{
case top = "top"
case right = "right"
case left = "left"
case bottom = "bottom"
case all = "default"
}
extension UIView{
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set{
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor {
get {
return UIColor.init(cgColor: self.layer.borderColor!)
}
set {
layer.borderColor = newValue.cgColor
}
}
@IBInspectable var shadowColor: UIColor{
get{
return UIColor.init(cgColor: layer.shadowColor!)
}
set{
self.layer.shadowColor = newValue.cgColor
}
}
@IBInspectable var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
self.layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOffset: CGSize{
get {
return self.layer.shadowOffset
}
set{
self.layer.shadowOffset = newValue
}
}
@IBInspectable var shadowOpacity: Float{
get {
return layer.shadowOpacity
}
set{
self.layer.shadowOpacity = newValue
}
}
@IBInspectable var borderSide: String {
get {
return self.borderSide
}
set{
self.addBorder(self.borderWidth, borderColor: self.borderColor.cgColor , borderSide: newValue)
}
}
func addShadow(_ cornerRadius:CGFloat, shadowColor:UIColor, shadowOffset:CGSize, shadowOpacity:Float, shadowRadius:CGFloat){
self.layer.shadowPath = UIBezierPath(roundedRect: self.layer.bounds, cornerRadius: cornerRadius).cgPath
self.layer.cornerRadius = cornerRadius
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOffset = shadowOffset
self.layer.shadowOpacity = shadowOpacity
self.layer.shadowRadius = shadowRadius
}
func addBorder(_ borderWidth:CGFloat, borderColor:CGColor, borderSide: String){
let borderPath = UIBezierPath()
let borderLayer = CAShapeLayer()
switch borderSide {
case sides.top.rawValue:
borderPath.move(to: CGPoint(x: 0, y: 0))
borderPath.addLine(to: CGPoint(x: self.frame.width, y: 0))
break
case sides.right.rawValue:
borderPath.move(to: CGPoint(x: self.frame.width, y: 0))
borderPath.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
break
case sides.left.rawValue:
borderPath.move(to: CGPoint(x: 0, y: 0))
borderPath.addLine(to: CGPoint(x: 0, y: self.frame.height))
break
case sides.bottom.rawValue:
borderPath.move(to: CGPoint(x: 0, y: self.frame.height))
borderPath.addLine(to: CGPoint(x: self.frame.width, y: self.frame.height))
break
default:
self.layer.borderColor = borderColor
self.layer.borderWidth = borderWidth
break
}
borderLayer.path = borderPath.cgPath
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.lineWidth = borderWidth
borderLayer.strokeColor = borderColor
self.layer.borderColor = UIColor.clear.cgColor
self.layer.borderWidth = borderWidth
self.layer.insertSublayer(borderLayer, at: 0)
}
func updateView(){
}
}
| mit | 80394ad3d50f0b8fca98287f39e0dde3 | 24.820988 | 128 | 0.55869 | 4.979762 | false | false | false | false |
swordray/ruby-china-ios | RubyChina/Classes/Controllers/TopicsController.swift | 1 | 10332 | //
// TopicsController.swift
// RubyChina
//
// Created by Jianqiu Xiao on 2018/3/23.
// Copyright © 2018 Jianqiu Xiao. All rights reserved.
//
import Alamofire
class TopicsController: ViewController {
private var activityIndicatorView: ActivityIndicatorView!
private var isRefreshing = false { didSet { didSetRefreshing() } }
private var networkErrorView: NetworkErrorView!
public var node: Node? { didSet { didSetNode(oldValue) } }
private var noContentView: NoContentView!
private var segmentedControl: UISegmentedControl!
private var tableView: UITableView!
private var topics: [Topic] = []
private var topicsIsLoaded = false
override init() {
super.init()
navigationItem.leftBarButtonItems = [
UIBarButtonItem(image: UIImage(systemName: "list.bullet"), style: .plain, target: self, action: #selector(showNodes)),
UIBarButtonItem(barButtonSystemItem: .compose, target: self, action: #selector(newTopic)),
]
title = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String
}
override func loadView() {
tableView = UITableView()
tableView.cellLayoutMarginsFollowReadableWidth = true
tableView.dataSource = self
tableView.delegate = self
tableView.refreshControl = UIRefreshControl()
tableView.refreshControl?.addTarget(self, action: #selector(fetchData), for: .valueChanged)
tableView.register(TopicsCell.self, forCellReuseIdentifier: TopicsCell.description())
tableView.tableHeaderView = UIView()
tableView.tableHeaderView?.snp.makeConstraints { make in
make.width.equalToSuperview()
make.height.equalTo(44)
}
tableView.tableFooterView = UIView()
view = tableView
activityIndicatorView = ActivityIndicatorView()
view.addSubview(activityIndicatorView)
networkErrorView = NetworkErrorView()
networkErrorView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(fetchData)))
view.addSubview(networkErrorView)
noContentView = NoContentView()
noContentView.textLabel?.text = "无内容"
view.addSubview(noContentView)
segmentedControl = UISegmentedControl(items: ["默认", "最新", "热门", "精华"])
segmentedControl.addTarget(self, action: #selector(refetchData), for: .valueChanged)
segmentedControl.selectedSegmentIndex = 0
tableView.tableHeaderView?.addSubview(segmentedControl)
segmentedControl.snp.makeConstraints { make in
make.centerY.equalToSuperview()
make.leading.trailing.equalTo(view.layoutMarginsGuide)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.prefersLargeTitles = true
tableView.indexPathsForSelectedRows?.forEach { tableView.deselectRow(at: $0, animated: animated) }
updateRightBarButtonItem()
if topics.count == 0 && !topicsIsLoaded || !networkErrorView.isHidden { fetchData() }
}
@objc
private func fetchData() {
if activityIndicatorView.isAnimating { tableView.refreshControl?.endRefreshing() }
if isRefreshing { return }
isRefreshing = true
let limit = 50
AF.request(
baseURL.appendingPathComponent("topics").appendingPathExtension("json"),
parameters: [
"type": ["last_actived", "recent", "popular", "excellent"][segmentedControl.selectedSegmentIndex],
"node_id": node?.id ?? [],
"limit": limit,
"offset": tableView.refreshControl?.isRefreshing ?? false ? 0 : topics.count,
]
)
.responseJSON { response in
if self.tableView.refreshControl?.isRefreshing ?? false {
self.topics = []
self.topicsIsLoaded = false
}
if 200..<300 ~= response.response?.statusCode ?? 0 {
let topics = (try? [Topic](json: response.value ?? [])) ?? []
self.topics += topics
self.topicsIsLoaded = topics.count < limit
self.noContentView.isHidden = self.topics.count > 0
} else {
self.networkErrorView.isHidden = false
}
self.tableView.reloadData()
self.isRefreshing = false
}
}
private func didSetRefreshing() {
if isRefreshing {
networkErrorView.isHidden = true
noContentView.isHidden = true
segmentedControl.isEnabled = false
if tableView.refreshControl?.isRefreshing ?? false { return }
activityIndicatorView.startAnimating()
} else {
segmentedControl.isEnabled = true
tableView.refreshControl?.endRefreshing()
activityIndicatorView.stopAnimating()
}
}
@objc
internal func refetchData() {
topics = []
topicsIsLoaded = false
tableView.reloadData()
fetchData()
}
private func didSetNode(_ oldValue: Node?) {
if node?.id == oldValue?.id { return }
title = node?.name ?? Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String
refetchData()
}
@objc
private func showNodes(_ barButtonItem: UIBarButtonItem) {
if isRefreshing { return }
let navigationController = UINavigationController(rootViewController: NodesController())
navigationController.modalPresentationStyle = .popover
navigationController.popoverPresentationController?.barButtonItem = barButtonItem
present(navigationController, animated: true)
}
@objc
private func newTopic(_ barButtonItem: UIBarButtonItem) {
let composeController = ComposeController()
composeController.topic = Topic()
composeController.topic?.nodeId = node?.id
composeController.topic?.nodeName = node?.name
let navigationController = UINavigationController(rootViewController: composeController)
navigationController.modalPresentationStyle = .popover
navigationController.popoverPresentationController?.barButtonItem = barButtonItem
present(navigationController, animated: true)
}
@objc
private func showAccount() {
navigationController?.pushViewController(AccountController(), animated: true)
}
@objc
internal func signIn(_ barButtonItem: UIBarButtonItem? = nil) {
showHUD()
SecRequestSharedWebCredential(nil, nil) { credentials, error in
DispatchQueue.main.async {
self.hideHUD()
guard let credentials = credentials, error == nil, CFArrayGetCount(credentials) > 0 else { self.showSignIn(barButtonItem); return }
let credential = unsafeBitCast(CFArrayGetValueAtIndex(credentials, 0), to: CFDictionary.self)
let account = unsafeBitCast(CFDictionaryGetValue(credential, Unmanaged.passUnretained(kSecAttrAccount).toOpaque()), to: CFString.self) as String
let password = unsafeBitCast(CFDictionaryGetValue(credential, Unmanaged.passUnretained(kSecSharedPassword).toOpaque()), to: CFString.self) as String
self.signInAs(username: account, password: password)
}
}
}
private func signInAs(username: String, password: String) {
showHUD()
AF.request(
baseURL.appendingPathComponent("sessions").appendingPathExtension("json"),
method: .post,
parameters: [
"username": username,
"password": password,
]
)
.responseJSON { response in
switch response.response?.statusCode ?? 0 {
case 200..<300:
User.current = try? User(json: response.value ?? [:])
self.updateRightBarButtonItem()
self.refetchData()
default:
self.showSignIn()
}
self.hideHUD()
}
}
internal func updateRightBarButtonItem() {
if User.current == nil {
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "person.crop.circle"), style: .plain, target: self, action: #selector(signIn))
} else {
let imageView = UIImageView()
imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showAccount)))
imageView.backgroundColor = .secondarySystemBackground
imageView.clipsToBounds = true
imageView.isUserInteractionEnabled = true
imageView.layer.cornerRadius = 14
imageView.setImage(withURL: User.current?.avatarURL)
imageView.snp.makeConstraints { $0.size.equalTo(28) }
navigationItem.rightBarButtonItem = UIBarButtonItem(customView: imageView)
}
}
internal func removeTopic(_ topic: Topic?) {
guard let row = topics.firstIndex(where: { $0.id == topic?.id }) else { return }
topics.remove(at: row)
let indexPath = IndexPath(row: row, section: 0)
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
extension TopicsController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return topics.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TopicsCell.description(), for: indexPath) as? TopicsCell ?? .init()
cell.topic = topics[indexPath.row]
return cell
}
}
extension TopicsController: UITableViewDelegate {
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if !topicsIsLoaded && indexPath.row == topics.count - 1 { fetchData() }
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let topicController = TopicController()
topicController.topic = topics[indexPath.row]
navigationController?.pushViewController(topicController, animated: true)
}
}
| mit | a081de543bb016cf7c3e7a62bb2f8b53 | 39.11284 | 169 | 0.649336 | 5.474774 | false | false | false | false |
nayzak/Swift-MVVM | Swift MVVM/App/TwoWayBindingPageModel.swift | 1 | 953 | //
// TwoWayBindingPageModel.swift
//
// Created by NayZaK on 26.02.15.
// Copyright (c) 2015 Amur.net. All rights reserved.
//
import Foundation
final class TwoWayBindingPageModel: PageModel {
let somethingEnabled = Dynamic<Bool>(true)
let userName = Dynamic<String>("Initial")
let accuracy = Dynamic<Float>(0.7)
override init() {
super.init()
title.value = "Two way bindings"
navBarAppearance = NavBarAppearanses.Blue
}
//MARK: Commands
lazy var changeSomethingEnabled: Command<()> = Command {
[weak self] v,s in s
self?.somethingEnabled.value = !self!.somethingEnabled.value
}
lazy var changeUserName: Command<()> = Command (
enabled: self.somethingEnabled,
command: {
[weak self] v,s in s
self?.userName.value = "\(rand())"
})
lazy var changeAccuracy: Command<()> = Command {
[weak self] v,s in s
self?.accuracy.value = Float(arc4random()) / Float(UINT32_MAX)
}
} | mit | 566731d423982ee8334729184cfcdbfe | 22.268293 | 66 | 0.663169 | 3.569288 | false | false | false | false |
KrishMunot/swift | test/SILOptimizer/specialize_unconditional_checked_cast.swift | 2 | 16707 | // RUN: %target-swift-frontend -Xllvm -sil-disable-pass="Function Signature Optimization" -emit-sil -o - -O %s | FileCheck %s
//////////////////
// Declarations //
//////////////////
public class C {}
public class D : C {}
public class E {}
var b : UInt8 = 0
var c = C()
var d = D()
var e = E()
var f : UInt64 = 0
var o : AnyObject = c
////////////////////////////
// Archetype To Archetype //
////////////////////////////
@inline(never)
public func ArchetypeToArchetype<T1, T2>(t t: T1, t2: T2) -> T2 {
return t as! T2
}
ArchetypeToArchetype(t: b, t2: b)
ArchetypeToArchetype(t: c, t2: c)
ArchetypeToArchetype(t: b, t2: c)
ArchetypeToArchetype(t: c, t2: b)
ArchetypeToArchetype(t: c, t2: d)
ArchetypeToArchetype(t: d, t2: c)
ArchetypeToArchetype(t: c, t2: e)
ArchetypeToArchetype(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_S____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, UInt8) -> UInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_S0____TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK-NOT: unconditional_checked_cast_addr
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast_addr
// y -> x where x is not a class but y is.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_Vs5UInt8___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1D___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $C
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK: unconditional_checked_cast_addr take_always C in [[STACK]] : $*C to D in
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D_CS_1C___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: upcast {{%[0-9]+}} : $D to $C
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C_CS_1E___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// x -> y where x and y are unrelated non classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8_Vs6UInt64___TF37specialize_unconditional_checked_cast20ArchetypeToArchetype{{.*}} : $@convention(thin) (UInt8, UInt64) -> UInt64 {
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
// CHECK: builtin "int_trap"
// CHECK-NOT: unconditional_checked_cast archetype_to_archetype
///////////////////////////
// Archetype To Concrete //
///////////////////////////
@inline(never)
public func ArchetypeToConcreteConvertUInt8<T>(t t: T) -> UInt8 {
return t as! UInt8
}
ArchetypeToConcreteConvertUInt8(t: b)
ArchetypeToConcreteConvertUInt8(t: c)
ArchetypeToConcreteConvertUInt8(t: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8{{.*}} : $@convention(thin) (UInt8) -> UInt8 {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where y is a class but x is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ArchetypeToConcreteConvertUInt8
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@owned C) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are classes and x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC{{.*}} : $@convention(thin) (@owned D) -> @owned C {
// CHECK: bb0
// CHECK-NEXT: debug_value %0
// CHECK: [[UC:%[0-9]+]] = upcast %0
// CHECK-NEXT: return [[UC]]
// x -> y where x,y are classes, but x is unrelated to y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertC
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ArchetypeToConcreteConvertC<T>(t t: T) -> C {
return t as! C
}
ArchetypeToConcreteConvertC(t: c)
ArchetypeToConcreteConvertC(t: b)
ArchetypeToConcreteConvertC(t: d)
ArchetypeToConcreteConvertC(t: e)
@inline(never)
public func ArchetypeToConcreteConvertD<T>(t t: T) -> D {
return t as! D
}
ArchetypeToConcreteConvertD(t: c)
// x -> y where x,y are classes and x is a sub class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertD{{.*}} : $@convention(thin) (@owned C) -> @owned D {
// CHECK: bb0(%0 : $C):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func ArchetypeToConcreteConvertE<T>(t t: T) -> E {
return t as! E
}
ArchetypeToConcreteConvertE(t: c)
// x -> y where x,y are classes, but y is unrelated to x. The idea is
// to make sure that the fact that y is concrete does not affect the
// result.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ArchetypeToConcreteConvertE
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
///////////////////////////
// Concrete to Archetype //
///////////////////////////
@inline(never)
public func ConcreteToArchetypeConvertUInt8<T>(t t: UInt8, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertUInt8(t: b, t2: b)
ConcreteToArchetypeConvertUInt8(t: b, t2: c)
ConcreteToArchetypeConvertUInt8(t: b, t2: f)
// x -> x where x is not a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, UInt8) -> UInt8 {
// CHECK: bb0(%0 : $UInt8, %1 : $UInt8):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: return %0
// x -> y where x is not a class but y is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, @owned C) -> @owned C {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x,y are different non class types.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs6UInt64___TF37specialize_unconditional_checked_cast31ConcreteToArchetypeConvertUInt8{{.*}} : $@convention(thin) (UInt8, UInt64) -> UInt64 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertC<T>(t t: C, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertC(t: c, t2: c)
ConcreteToArchetypeConvertC(t: c, t2: b)
ConcreteToArchetypeConvertC(t: c, t2: d)
ConcreteToArchetypeConvertC(t: c, t2: e)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
// x -> y where x is a class but y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0(%0 : $C, %1 : $D):
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $C
// CHECK-DAG: store %0 to [[STACK_C]]
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always C in [[STACK_C]] : $*C to D in [[STACK_D]] : $*D
// CHECK-DAG: strong_release %1
// CHECK-DAG: strong_release %0
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
// x -> y where x and y are unrelated classes.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1E___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertC{{.*}} : $@convention(thin) (@owned C, @owned E) -> @owned E {
// CHECK: bb0(%0 : $C, %1 : $E):
// CHECK-NEXT: builtin "int_trap"
// CHECK-NEXT: unreachable
// CHECK-NEXT: }
@inline(never)
public func ConcreteToArchetypeConvertD<T>(t t: D, t2: T) -> T {
return t as! T
}
ConcreteToArchetypeConvertD(t: d, t2: c)
// x -> y where x is a subclass of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast27ConcreteToArchetypeConvertD{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK: bb0(%0 : $D, %1 : $C):
// CHECK-DAG: [[UC:%[0-9]+]] = upcast %0
// CHECK-DAG: strong_release %1
// CHECK: return [[UC]]
////////////////////////
// Super To Archetype //
////////////////////////
@inline(never)
public func SuperToArchetypeC<T>(c c : C, t : T) -> T {
return c as! T
}
SuperToArchetypeC(c: c, t: c)
SuperToArchetypeC(c: c, t: d)
SuperToArchetypeC(c: c, t: b)
// x -> x where x is a class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, @owned C) -> @owned C {
// CHECK: bb0(%0 : $C, %1 : $C):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, @owned D) -> @owned D {
// CHECK: bb0
// CHECK: unconditional_checked_cast_addr take_always C in
// x -> y where x is a class and y is not.
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast17SuperToArchetypeC{{.*}} : $@convention(thin) (@owned C, UInt8) -> UInt8 {
// CHECK: bb0
// CHECK: builtin "int_trap"
// CHECK: unreachable
// CHECK-NEXT: }
@inline(never)
public func SuperToArchetypeD<T>(d d : D, t : T) -> T {
return d as! T
}
SuperToArchetypeD(d: d, t: c)
SuperToArchetypeD(d: d, t: d)
// *NOTE* The frontend is smart enough to turn this into an upcast. When this
// test is converted to SIL, this should be fixed appropriately.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@owned D, @owned C) -> @owned C {
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK: upcast
// CHECK-NOT: unconditional_checked_cast super_to_archetype
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1D___TF37specialize_unconditional_checked_cast17SuperToArchetypeD{{.*}} : $@convention(thin) (@owned D, @owned D) -> @owned D {
// CHECK: bb0(%0 : $D, %1 : $D):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
@inline(never)
public func ExistentialToArchetype<T>(o o : AnyObject, t : T) -> T {
return o as! T
}
// AnyObject -> Class.
// CHECK-LABEL: sil shared [noinline] @_TTSg5C37specialize_unconditional_checked_cast1C___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, @owned C) -> @owned C {
// CHECK: unconditional_checked_cast_addr take_always AnyObject in {{%.*}} : $*AnyObject to C
// AnyObject -> Non Class (should always fail)
// CHECK-LABEL: sil shared [noinline] @_TTSg5Vs5UInt8___TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, UInt8) -> UInt8 {
// CHECK: builtin "int_trap"()
// CHECK: unreachable
// CHECK-NEXT: }
// AnyObject -> AnyObject
// CHECK-LABEL: sil shared [noinline] @_TTSg5Ps9AnyObject____TF37specialize_unconditional_checked_cast22ExistentialToArchetype{{.*}} : $@convention(thin) (@owned AnyObject, @owned AnyObject) -> @owned AnyObject {
// CHECK: bb0(%0 : $AnyObject, %1 : $AnyObject):
// CHECK: strong_release %1
// CHECK-NEXT: return %0
ExistentialToArchetype(o: o, t: c)
ExistentialToArchetype(o: o, t: b)
ExistentialToArchetype(o: o, t: o)
// Ensure that a downcast from an Optional source is not promoted to a
// value cast. We could do the promotion, but the optimizer would need
// to insert the Optional unwrapping logic before the cast.
//
// CHECK-LABEL: sil shared [noinline] @_TTSg5GSqC37specialize_unconditional_checked_cast1C__CS_1D___TF37specialize_unconditional_checked_cast15genericDownCastu0_rFTxMq__q_ : $@convention(thin) (@owned Optional<C>, @thick D.Type) -> @owned D {
// CHECK: bb0(%0 : $Optional<C>, %1 : $@thick D.Type):
// CHECK-DAG: [[STACK_D:%[0-9]+]] = alloc_stack $D
// CHECK-DAG: [[STACK_C:%[0-9]+]] = alloc_stack $Optional<C>
// CHECK-DAG: store %0 to [[STACK_C]]
// TODO: This should be optimized to an unconditional_checked_cast without the need of alloc_stack: rdar://problem/24775038
// CHECK-DAG: unconditional_checked_cast_addr take_always Optional<C> in [[STACK_C]] : $*Optional<C> to D in [[STACK_D]] : $*D
// CHECK-DAG: [[LOAD:%[0-9]+]] = load [[STACK_D]]
// CHECK: return [[LOAD]]
@inline(never)
public func genericDownCast<T, U>(_ a: T, _ : U.Type) -> U {
return a as! U
}
public func callGenericDownCast(_ c: C?) -> D {
return genericDownCast(c, D.self)
}
| apache-2.0 | 307f68d6dbb3ee9aa75551bc007ca2dd | 42.850394 | 242 | 0.694799 | 3.368347 | false | false | false | false |
habr/ChatTaskAPI | IQKeyboardManager/Demo/Swift_Demo/ViewController/TextFieldViewController.swift | 3 | 4925 | //
// TextFieldViewController.swift
// IQKeyboard
//
// Created by Iftekhar on 23/09/14.
// Copyright (c) 2014 Iftekhar. All rights reserved.
//
import Foundation
import UIKit
class TextFieldViewController: UIViewController {
private var returnKeyHandler : IQKeyboardReturnKeyHandler!
@IBOutlet private var dropDownTextField : IQDropDownTextField!
@IBOutlet private var buttonPush : UIButton!
@IBOutlet private var buttonPresent : UIButton!
@IBOutlet private var barButtonDisable : UIBarButtonItem!
@IBAction func disableKeyboardManager (barButton : UIBarButtonItem!) {
if (IQKeyboardManager.sharedManager().enable == true) {
IQKeyboardManager.sharedManager().enable = false
} else {
IQKeyboardManager.sharedManager().enable = true
}
refreshUI()
}
func previousAction(sender : UITextField) {
print("PreviousAction")
}
func nextAction(sender : UITextField) {
print("nextAction")
}
func doneAction(sender : UITextField) {
print("doneAction")
}
override func viewDidLoad() {
super.viewDidLoad()
dropDownTextField.setCustomPreviousTarget(self, selector: Selector("previousAction:"))
dropDownTextField.setCustomNextTarget(self, selector: Selector("nextAction:"))
dropDownTextField.setCustomDoneTarget(self, selector: Selector("doneAction:"))
returnKeyHandler = IQKeyboardReturnKeyHandler(controller: self)
returnKeyHandler.lastTextFieldReturnKeyType = UIReturnKeyType.Done
var itemLists = [NSString]()
itemLists.append("Zero Line Of Code")
itemLists.append("No More UIScrollView")
itemLists.append("No More Subclasses")
itemLists.append("No More Manual Work")
itemLists.append("No More #imports")
itemLists.append("Device Orientation support")
itemLists.append("UITextField Category for Keyboard")
itemLists.append("Enable/Desable Keyboard Manager")
itemLists.append("Customize InputView support")
itemLists.append("IQTextView for placeholder support")
itemLists.append("Automanage keyboard toolbar")
itemLists.append("Can set keyboard and textFiled distance")
itemLists.append("Can resign on touching outside")
itemLists.append("Auto adjust textView's height")
itemLists.append("Adopt tintColor from textField")
itemLists.append("Customize keyboardAppearance")
itemLists.append("Play sound on next/prev/done")
dropDownTextField.itemList = itemLists
returnKeyHandler = IQKeyboardReturnKeyHandler(controller: self)
}
override func viewWillAppear(animated : Bool) {
super.viewWillAppear(animated)
if (self.presentingViewController != nil)
{
buttonPush.hidden = true
buttonPresent.setTitle("Dismiss", forState:UIControlState.Normal)
}
refreshUI()
}
override func viewWillDisappear(animated : Bool) {
super.viewWillDisappear(animated)
IQKeyboardManager.sharedManager().shouldToolbarUsesTextFieldTintColor = false
}
func refreshUI() {
if (IQKeyboardManager.sharedManager().enable == true) {
barButtonDisable.title = "Disable"
} else {
barButtonDisable.title = "Enable"
}
}
@IBAction func presentClicked (sender: AnyObject!) {
if self.presentingViewController == nil {
let controller: UIViewController = (storyboard?.instantiateViewControllerWithIdentifier("TextFieldViewController"))!
let navController : UINavigationController = UINavigationController(rootViewController: controller)
navController.navigationBar.tintColor = self.navigationController?.navigationBar.tintColor
navController.navigationBar.barTintColor = self.navigationController?.navigationBar.barTintColor
navController.navigationBar.titleTextAttributes = self.navigationController?.navigationBar.titleTextAttributes
// navController.modalTransitionStyle = Int(arc4random()%4)
// TransitionStylePartialCurl can only be presented by FullScreen style.
// if (navController.modalTransitionStyle == UIModalTransitionStyle.PartialCurl) {
// navController.modalPresentationStyle = UIModalPresentationStyle.FullScreen
// } else {
// navController.modalPresentationStyle = UIModalPresentationStyle.PageSheet
// }
presentViewController(navController, animated: true, completion: nil)
} else {
dismissViewControllerAnimated(true, completion: nil)
}
}
override func shouldAutorotate() -> Bool {
return true
}
}
| mit | d43254ec7ae6ccecdc8c33b182a6d178 | 36.310606 | 128 | 0.672081 | 5.760234 | false | false | false | false |
liuguya/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/model/CBRecommendModel.swift | 1 | 4054 | //
// CBRecommendModel.swift
// TestKitchen
//
// Created by 阳阳 on 16/8/16.
// Copyright © 2016年 liuguyang. All rights reserved.
//
import UIKit
import SwiftyJSON
class CBRecommendModel: NSObject {
var code:NSNumber?
var msg:Bool?
var version:String?
var timestamp:NSNumber?
var data:CBRecommendDataModel?
//解析
class func parseModel(data:NSData)->CBRecommendModel{
let model = CBRecommendModel()
let jsonData = JSON(data:data)
model.code = jsonData["code"].number
model.msg = jsonData["msg"].bool
model.version = jsonData["version"].string
model.timestamp = jsonData["timestamp"].number
let dataDict = jsonData["data"]
model.data = CBRecommendDataModel.parseModel(dataDict)
return model
}
}
class CBRecommendDataModel:NSObject{
var banner:Array<CBRecommendBannerModel>?
var widgetList:Array<CBRecommendWidgetListModel>?
class func parseModel(jsonData:JSON)->CBRecommendDataModel{
let model = CBRecommendDataModel()
let bannerArray = jsonData["banner"]
var bArray = Array<CBRecommendBannerModel>()
for (_,subjson) in bannerArray{
//subjson装换成CBRecommendBannerModel
let bannerModel = CBRecommendBannerModel.parseModel(subjson)
bArray.append(bannerModel)
}
model.banner = bArray
let listArray = jsonData["widgetList"]
var wlArray = Array<CBRecommendWidgetListModel>()
for (_,subjson) in listArray{
let widModel = CBRecommendWidgetListModel.parseModel(subjson)
wlArray.append(widModel)
}
model.widgetList = wlArray
return model
}
}
class CBRecommendBannerModel: NSObject {
var banner_id:NSNumber?
var banner_title:String?
var banner_picture:String?
var banner_link:String?
var is_link:NSNumber?
var refer_key:String?
var type_id:NSNumber?
class func parseModel(jsonData:JSON)->CBRecommendBannerModel{
let model = CBRecommendBannerModel()
model.banner_id = jsonData["banner_id"].number
model.banner_title = jsonData["banner_title"].string
model.banner_picture = jsonData["banner_picture"].string
model.banner_link = jsonData["banner_link"].string
model.is_link = jsonData["is_link"].number
model.refer_key = jsonData["refer_key"].string
model.type_id = jsonData["type_id"].number
return model
}
}
class CBRecommendWidgetListModel:NSObject{
var widget_id:NSNumber?
var widget_type:NSNumber?
var title:String?
var title_link:String?
var desc:String?
var widget_data:Array<CGRecommendWidgetDataModel>?
class func parseModel(jsonData:JSON)->CBRecommendWidgetListModel{
let model = CBRecommendWidgetListModel()
model.widget_id = jsonData["widget_id"].number
model.widget_type = jsonData["widget_type"].number
model.title = jsonData["title"].string
model.title_link = jsonData["title_link"].string
model.desc = jsonData["desc"].string
let dataArray = jsonData["widget_data"]
var wdArray = Array<CGRecommendWidgetDataModel>()
for (_,subjson) in dataArray{
let widgetModel = CGRecommendWidgetDataModel.parseModel(subjson)
wdArray.append(widgetModel)
}
model.widget_data = wdArray
return model
}
}
class CGRecommendWidgetDataModel: NSObject {
var id:NSNumber?
var type:String?
var content:String?
var link:String?
class func parseModel(jsonData:JSON)->CGRecommendWidgetDataModel{
let modle = CGRecommendWidgetDataModel()
modle.id = jsonData["id"].number
modle.type = jsonData["type"].string
modle.content = jsonData["content"].string
modle.link = jsonData["link"].string
return modle
}
}
| mit | 5072e191cc9bff3626d039c595bdc8bd | 28.683824 | 77 | 0.64107 | 4.500557 | false | false | false | false |
cpmpercussion/microjam | UIButtonExtensions.swift | 1 | 4615 | //
// UIButtonExtensions.swift
// microjam
//
// Created by Charles Martin on 10/11/18.
// Copyright © 2018 Charles Martin. All rights reserved.
//
import UIKit
/// Constant for the maximum glow opacity for record pulse animations.
let maximumGlowOpacity: Float = 0.9
/// UIButton Animation Extensions
extension UIButton{
func setupGlowShadow(withColour colour: UIColor) {
self.layer.shadowOffset = .zero
self.layer.shadowColor = colour.cgColor
self.layer.shadowRadius = 20
self.layer.shadowOpacity = maximumGlowOpacity
// recEnableButton.layer.shadowPath = UIBezierPath(rect: recEnableButton.bounds).cgPath
let glowWidth = self.bounds.height
let glowOffset = 0.5 * (self.bounds.width - glowWidth)
self.layer.shadowPath = UIBezierPath(ovalIn: CGRect(x: glowOffset,
y:0,
width: glowWidth,
height: glowWidth)).cgPath
}
func pulseGlow(withColour glowColour: UIColor, andTint tintColour: UIColor) {
setupGlowShadow(withColour: glowColour)
// Tint Color Animation
self.tintColor = ButtonColors.recordDisabled
UIView.animate(withDuration: 0.25, delay: 0.0, options: [.curveLinear, .repeat, .autoreverse], animations: {self.tintColor = ButtonColors.record}, completion: nil)
// Shadow animation
let animation = CABasicAnimation(keyPath: "shadowOpacity")
animation.fromValue = 0.05
animation.toValue = maximumGlowOpacity
animation.duration = 0.25
animation.repeatCount = 100000
animation.autoreverses = true
self.layer.add(animation, forKey: animation.keyPath)
self.layer.shadowOpacity = 0.05
}
func pulseGlow() {
pulseGlow(withColour: ButtonColors.recordGlow, andTint: ButtonColors.record)
}
func deactivateGlowing(withDeactivatedColour deactivatedColour: UIColor) {
self.layer.removeAllAnimations()
self.imageView?.layer.removeAllAnimations()
self.layer.shadowOpacity = 0.0
self.tintColor = deactivatedColour
}
func deactivateGlowing() {
deactivateGlowing(withDeactivatedColour: ButtonColors.recordDisabled)
}
func solidGlow(withColour glowColour: UIColor, andTint tintColour: UIColor) {
self.layer.removeAllAnimations()
self.imageView?.layer.removeAllAnimations()
setupGlowShadow(withColour: glowColour)
self.layer.shadowOpacity = maximumGlowOpacity
self.tintColor = tintColour
}
func solidGlow() {
solidGlow(withColour: ButtonColors.recordGlow, andTint: ButtonColors.record)
}
}
/// Shake animation for a UIButton
extension UIButton {
/// Shakes the button a little bit.
func shake() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.y")
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = 1.0
animation.values = [-10.0, 10.0, -5.0, 5.0, -2.5, 2.5, -1, 1, 0.0 ]
layer.add(animation, forKey: "shake")
}
func stopBopping() {
layer.removeAnimation(forKey: "bop")
}
func startBopping() {
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
animation.duration = 0.2
animation.values = [-2.5,2.5,0]
animation.repeatCount = 100
layer.add(animation, forKey: "bop")
}
func startSwirling() {
let animationX = CAKeyframeAnimation(keyPath: "transform.translation.x")
animationX.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animationX.duration = 0.2
animationX.values = [0,-2.5,2.5,0]
animationX.repeatCount = 100
let animationY = CAKeyframeAnimation(keyPath: "transform.translation.y")
animationY.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
animationY.duration = 0.2
animationY.values = [-2.5,0,0,2.5]
animationY.repeatCount = 100
layer.add(animationX, forKey: "swirl_x")
layer.add(animationY, forKey: "swirl_y")
}
func stopSwirling() {
layer.removeAnimation(forKey: "swirl_x")
layer.removeAnimation(forKey: "swirl_y")
}
}
| mit | c27c73490475bdd68102b68522235337 | 37.45 | 171 | 0.648678 | 4.563798 | false | false | false | false |
slash-hq/slash | Sources/main.swift | 1 | 920 | //
// slash
//
// Copyright © 2016 slash Corp. All rights reserved.
//
import Foundation
setlocale(LC_CTYPE,"UTF-8")
let device = try TerminalDevice()
CrashReporter.watch(usingDevice: device)
var token: String!
if CommandLine.arguments.count > 1 {
token = CommandLine.arguments[1]
} else {
device.flush(TerminalCanvas()
.clean()
.cursor(1, 1)
.text(String(format: R.string.authHelpMessage, SlackOAuth2.address)).buffer)
let slackAuthenticator = SlackOAuth2(clientId: "2296647491.109731100693", clientSecret: "db81eea6c974916693ab746775dbc096", permissions: ["client"])
token = try slackAuthenticator.authenticate()
device.flush(TerminalCanvas().clean().buffer)
}
let application = try Application(usingDevice: device, authenticatedBy: token)
signal(SIGWINCH) { _ in
application.notifyTerminalSizeHasChanged()
}
application.run()
| apache-2.0 | e846162a0f3a2de905d5391ce2051772 | 20.880952 | 152 | 0.700762 | 3.676 | false | false | false | false |
jandro-es/Evergreen | Evergreen/src/Extensions/NSDate+ISO8601.swift | 1 | 2713 | //
// NSDate+ISO8601.swift
// Evergreen
//
// Created by Alejandro Barros Cuetos on 01/02/2016.
// Copyright © 2016 Alejandro Barros Cuetos. 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 HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
public extension NSDate {
/**
Creates an NSDate object from a ISO8601 string
- parameter iso8601: The ISO8601 String
- returns: The created object or nil if failure
*/
convenience init?(iso8601: String) {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let date = dateFormatter.dateFromString(iso8601) {
self.init(timeInterval:0, sinceDate:date)
} else {
self.init()
}
}
/**
Transforms a NSDate object into a ISO8601 formated string
- returns: The string representing the ISO8601 date
*/
public func ISO8601() -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return dateFormatter.stringFromDate(self).stringByAppendingString("Z")
}
} | apache-2.0 | 3518074e9f59369a60372f18c5879bb5 | 38.318841 | 82 | 0.70059 | 4.659794 | false | false | false | false |
happyjake/FileBrowser | FileBrowser/FileListViewController.swift | 1 | 4721 | //
// FileListViewController.swift
// FileBrowser
//
// Created by Roy Marmelstein on 12/02/2016.
// Copyright © 2016 Roy Marmelstein. All rights reserved.
//
import Foundation
class FileListViewController: UIViewController {
// TableView
@IBOutlet weak var tableView: UITableView!
let collation = UILocalizedIndexedCollation.current()
/// Data
var didSelectFile: ((FBFile) -> ())?
var files = [FBFile]()
var initialPath: URL?
let parser = FileParser.sharedInstance
let previewManager = PreviewManager()
var sections: [[FBFile]] = []
// Search controller
var filteredFiles = [FBFile]()
let searchController: UISearchController = {
let searchController = UISearchController(searchResultsController: nil)
searchController.searchBar.searchBarStyle = .minimal
searchController.searchBar.backgroundColor = UIColor.white
searchController.dimsBackgroundDuringPresentation = false
return searchController
}()
//MARK: Lifecycle
convenience init (initialPath: URL) {
self.init(nibName: "FileBrowser", bundle: Bundle(for: FileListViewController.self))
self.edgesForExtendedLayout = UIRectEdge()
// Set initial path
self.initialPath = initialPath
self.title = initialPath.lastPathComponent
// Set search controller delegates
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.delegate = self
// Add dismiss button
self.navigationItem.rightBarButtonItems = [
UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(FileListViewController.dismiss(button:))),
UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(FileListViewController.share(button:))),
]
}
deinit{
if #available(iOS 9.0, *) {
searchController.loadViewIfNeeded()
} else {
searchController.loadView()
}
}
//MARK: UIViewController
override func viewDidLoad() {
// Prepare data
if let initialPath = initialPath {
files = parser.filesForDirectory(initialPath)
indexFiles()
}
// Set search bar
tableView.tableHeaderView = searchController.searchBar
// Register for 3D touch
self.registerFor3DTouch()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Scroll to hide search bar
self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.size.height)
// Make sure navigation bar is visible
self.navigationController?.isNavigationBarHidden = false
}
@objc func dismiss(button: UIBarButtonItem = UIBarButtonItem()) {
self.dismiss(animated: true, completion: nil)
}
@objc func share(button: UIBarButtonItem = UIBarButtonItem()) {
guard let path = self.initialPath else {
return
}
let activityViewController = UIActivityViewController(activityItems: [path], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
if let pop = activityViewController.popoverPresentationController,let v = self.view {
pop.sourceView = v
pop.sourceRect = v.bounds
}
}
//MARK: Data
func indexFiles() {
let selector: Selector = #selector(getter: UIPrinter.displayName)
sections = Array(repeating: [], count: collation.sectionTitles.count)
if let sortedObjects = collation.sortedArray(from: files, collationStringSelector: selector) as? [FBFile]{
for object in sortedObjects {
let sectionNumber = collation.section(for: object, collationStringSelector: selector)
sections[sectionNumber].append(object)
}
}
}
func fileForIndexPath(_ indexPath: IndexPath) -> FBFile {
var file: FBFile
if searchController.isActive {
file = filteredFiles[(indexPath as NSIndexPath).row]
}
else {
file = sections[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
}
return file
}
func filterContentForSearchText(_ searchText: String) {
filteredFiles = files.filter({ (file: FBFile) -> Bool in
return file.displayName.lowercased().contains(searchText.lowercased())
})
tableView.reloadData()
}
}
| mit | b11a049e98780b5143020faf372049b8 | 32.475177 | 132 | 0.637924 | 5.494761 | false | false | false | false |
MichMich/HomeSensor | HomeSensor/Sensor.swift | 1 | 1527 | //
// Sensor.swift
// HomeSensor
//
// Created by Michael Teeuw on 04/12/15.
// Copyright © 2015 Michael Teeuw. All rights reserved.
//
import Foundation
class Sensor {
var name: String
var identifier: String
var state:Bool = false {
didSet {
delegate?.sensorStateUpdate(self, state: state)
}
}
var timestamp:NSDate? {
didSet {
delegate?.sensorStateUpdate(self, state: state)
}
}
var publishNotificationSubscriptionChange = false
var notificationSubscription:NotificationType = .None {
didSet {
if notificationSubscription != oldValue {
delegate?.sensorNotificationSubscriptionChanged(self, notificationType: notificationSubscription)
}
}
}
var delegate:SensorDelegateProtocol?
init(name: String, identifier:String) {
self.name = name
self.identifier = identifier
}
func receivedNewValue(value:String) {
if let boolValue = value.toBool() {
state = boolValue
}
}
func receivedNewTimestamp(timeString:String) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
timestamp = dateFormatter.dateFromString(timeString)
}
}
protocol SensorDelegateProtocol {
func sensorStateUpdate(sensor:Sensor, state:Bool)
func sensorNotificationSubscriptionChanged(sensor:Sensor, notificationType:NotificationType)
}
extension String {
func toBool() -> Bool? {
switch self.lowercaseString {
case "true", "yes", "on", "1":
return true
case "false", "no", "off", "0":
return false
default:
return nil
}
}
} | apache-2.0 | d414a1f7c974b74b88ba143ab9ab8a6e | 20.507042 | 101 | 0.720183 | 3.548837 | false | false | false | false |
testpress/ios-app | ios-app/UI/ContentExamAttemptsTableViewController.swift | 1 | 10216 | //
// ContentExamAttemptsTableViewController.swift
// ios-app
//
// Copyright © 2017 Testpress. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import RealmSwift
class ContentExamAttemptsTableViewController: UITableViewController {
var activityIndicator: UIActivityIndicatorView! // Progress bar
var emptyView: EmptyView!
var content: Content!
var exam: Exam!
var attempts: [ContentAttempt] = []
var pausedAttempts: [ContentAttempt] = []
override func viewDidLoad() {
emptyView = EmptyView.getInstance(parentView: view)
tableView.tableFooterView = UIView(frame: .zero)
if content != nil && exam == nil {
exam = content.exam
}
UIUtils.setTableViewSeperatorInset(tableView, size: 15)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if (attempts.isEmpty) {
loadAttemptsWithProgress(url: content.getAttemptsUrl())
}
tableView.reloadData()
}
func loadAttemptsWithProgress(url: String) {
tableView.tableFooterView = UIView(frame: .zero)
activityIndicator = UIUtils.initActivityIndicator(parentView: view)
activityIndicator.startAnimating()
loadAttempts(url: url)
}
func loadAttempts(url: String) {
TPApiClient.getListItems(
endpointProvider: TPEndpointProvider(.loadAttempts, url: url),
completion: {
testpressResponse, error in
if let error = error {
debugPrint(error.message ?? "No error")
debugPrint(error.kind)
var retryButtonText: String?
var retryHandler: (() -> Void)?
if error.kind == .network {
retryButtonText = Strings.TRY_AGAIN
retryHandler = {
self.emptyView.hide()
self.loadAttemptsWithProgress(url: url)
}
}
if self.activityIndicator.isAnimating {
self.activityIndicator.stopAnimating()
}
let (image, title, description) = error.getDisplayInfo()
self.emptyView.show(image: image, title: title, description: description,
retryButtonText: retryButtonText,
retryHandler: retryHandler)
return
}
self.attempts.append(contentsOf: testpressResponse!.results)
if !(testpressResponse!.next.isEmpty) {
self.loadAttempts(url: testpressResponse!.next)
} else {
try! Realm().write {
self.content.attemptsCount = self.attempts.count
}
self.displayAttemptsList()
}
}, type: ContentAttempt.self)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return attempts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
if attempts.count <= indexPath.row {
// Needed to prevent index out of bound execption when dismiss view controller while
// table view is scrolling
return UITableViewCell()
}
let contentAttempt = attempts[indexPath.row]
var cellIdentifier: String
if contentAttempt.assessment.state == Constants.STATE_RUNNING {
cellIdentifier = Constants.PAUSED_ATTEMPT_TABLE_VIEW_CELL
} else {
cellIdentifier = Constants.COMPLETED_ATTEMPT_TABLE_VIEW_CELL
}
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath)
as! AttemptsTableViewCell
cell.initCell(contentAttempt: contentAttempt, parentViewController: self)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let contentAttempt = attempts[indexPath.row]
if contentAttempt.assessment.state == Constants.STATE_RUNNING {
if (content.getContentType() == .Quiz) {
self.loadQuestions(contentAttempt: contentAttempt)
}
showStartExamScreen(contentAttempt: contentAttempt)
} else {
showTestReport(contentAttempt: contentAttempt)
}
}
func loadQuestions(contentAttempt: ContentAttempt) {
let storyboard = UIStoryboard(name: Constants.TEST_ENGINE, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.QUIZ_EXAM_VIEW_CONTROLLER) as! QuizExamViewController
viewController.contentAttempt = contentAttempt
viewController.exam = self.exam
present(viewController, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableCell(withIdentifier: "AttemptsListHeader")
as! AttemptsListHeader
header.initCell()
return header
}
func getFooter() -> UIView? {
// Clear existing paused attempts if exist
pausedAttempts.removeAll()
for attempt: ContentAttempt in attempts {
if attempt.assessment.state == Constants.STATE_RUNNING {
pausedAttempts.append(attempt);
}
}
if canAttemptExam() && content.getContentType() != .Quiz {
let cell = tableView.dequeueReusableCell(withIdentifier: "ContentAttemptFooterCell")
as! ContentAttemptFooterCell
cell.initCell(parentViewController: self)
return cell
}
return UIView(frame: .zero)
}
private func displayAttemptsList() {
tableView.reloadData()
tableView.tableFooterView = getFooter()
if (activityIndicator?.isAnimating)! {
activityIndicator?.stopAnimating()
}
}
private func canAttemptExam() -> Bool {
// User can't retake an exam if retake disabled or max retake attemted or web only exam or
// exam start date is future. If paused attempt exist, can resume it.
if (exam.attemptsCount == 0 || pausedAttempts.count != 0 ||
((exam.allowRetake) && (attempts.count <= exam.maxRetakes || exam.maxRetakes < 0))) {
if (exam.deviceAccessControl == "web") {
return false;
} else {
return exam.hasStarted()
}
}
return false;
}
func showStartExamScreen(contentAttempt: ContentAttempt? = nil) {
let storyboard = UIStoryboard(name: Constants.TEST_ENGINE, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.START_EXAM_SCREEN_VIEW_CONTROLLER) as! StartExamScreenViewController
viewController.content = content
if contentAttempt != nil {
viewController.contentAttempt = contentAttempt
}
showDetailViewController(viewController, sender: self)
}
func showTestReport(contentAttempt: ContentAttempt) {
let storyboard = UIStoryboard(name: Constants.EXAM_REVIEW_STORYBOARD, bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier:
Constants.TEST_REPORT_VIEW_CONTROLLER) as! TestReportViewController
viewController.exam = self.exam!
viewController.attempt = contentAttempt.assessment
showDetailViewController(viewController, sender: self)
}
override func viewDidLayoutSubviews() {
activityIndicator?.frame = view.frame
}
}
class ContentAttemptFooterCell: UITableViewCell {
@IBOutlet weak var startButton: UIButton!
var parentViewController: ContentExamAttemptsTableViewController!
func initCell(parentViewController: ContentExamAttemptsTableViewController) {
self.parentViewController = parentViewController
if (parentViewController.pausedAttempts.isEmpty) {
startButton.setTitle("RETAKE", for: .normal)
} else {
startButton.setTitle("RESUME", for: .normal)
}
UIUtils.setButtonDropShadow(startButton)
}
@IBAction func onClickStartButton(_ sender: UIButton) {
parentViewController
.showStartExamScreen(contentAttempt: parentViewController.pausedAttempts.last)
}
}
| mit | c218657437b3fa44cc73b4ded25b843b | 38.902344 | 100 | 0.620069 | 5.416225 | false | false | false | false |
wuleijun/Zeus | Zeus/Views/BorderTextField.swift | 1 | 2199 | //
// BorderTextField.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/12.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
@IBDesignable
class BorderTextField: UITextField {
@IBInspectable var lineColor: UIColor = UIColor.zeusBorderColor()
@IBInspectable var lineWidth: CGFloat = 1 / UIScreen.mainScreen().scale
@IBInspectable var enabledTopLine: Bool = true
@IBInspectable var enabledLeftLine: Bool = false
@IBInspectable var enabledBottomLine: Bool = true
@IBInspectable var enabledRightLine: Bool = false
@IBInspectable var leftTextInset: CGFloat = 20
@IBInspectable var rightTextInset: CGFloat = 20
override func drawRect(rect: CGRect) {
super.drawRect(rect)
lineColor.setStroke()
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, lineWidth)
if enabledTopLine {
CGContextMoveToPoint(context, 0, 0)
CGContextAddLineToPoint(context, CGRectGetWidth(rect), 0)
CGContextStrokePath(context)
}
if enabledLeftLine {
let y = CGRectGetHeight(rect)
CGContextMoveToPoint(context, 0, 0)
CGContextAddLineToPoint(context, 0, y)
CGContextStrokePath(context)
}
if enabledBottomLine {
let y = CGRectGetHeight(rect)
CGContextMoveToPoint(context, 0, y)
CGContextAddLineToPoint(context, CGRectGetWidth(rect), y)
CGContextStrokePath(context)
}
if enabledRightLine {
let x = CGRectGetWidth(rect)
let y = CGRectGetHeight(rect)
CGContextMoveToPoint(context, x, 0)
CGContextAddLineToPoint(context, x, y)
CGContextStrokePath(context)
}
}
override func textRectForBounds(bounds: CGRect) -> CGRect {
return CGRect(x: leftTextInset, y: 0, width: bounds.width - leftTextInset - rightTextInset, height: bounds.height)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return textRectForBounds(bounds)
}
} | mit | 39f68cf6c9f4b9eb7cdc0057b1410ce4 | 30.3 | 122 | 0.630594 | 5.22673 | false | false | false | false |
naokits/my-programming-marathon | TrySwift/ryswift-chris-eidhof-table-view-controllers-swift/TrySwift/TrySwift/AppDelegate.swift | 1 | 4367 | //
// AppDelegate.swift
// TrySwift
//
// Created by Naoki Tsutsui on 9/8/16.
// Copyright © 2016 Naoki Tsutsui. All rights reserved.
//
import UIKit
struct Person {
let name: String
let city: String
}
let people = [
Person(name: "Chris", city: "Berlin"),
Person(name: "Natash", city: "Tokyo"),
Person(name: "Ayaka", city: "San Francisco"),
Person(name: "Ash", city: "New York")
]
let pokedex = ["Pikachu", "Snorlax", "Delphox"]
struct UndoHistory<Item> {
let initialValue: [Item]
var history: [[Item]] = []
init(_ initialValue: [Item]) {
self.initialValue = initialValue
}
var currentValue: [Item] {
get { return history.last ?? initialValue }
set { history.append(newValue) }
}
var canUndo: Bool {
return !history.isEmpty
}
mutating func undo() {
history.popLast()
}
}
struct TableViewConfiguration<Item> {
var items: [Item]
var style: UITableViewStyle
var cellStyle: UITableViewCellStyle
var editable: Bool
var configureCell: (UITableViewCell, Item) -> ()
}
final class MyTableViewController<Item>: UITableViewController {
var history: UndoHistory<Item> {
didSet {
tableView.reloadData()
navigationItem.rightBarButtonItem = history.canUndo ? UIBarButtonItem(barButtonSystemItem: .Undo, target: self, action: #selector(MyTableViewController.undo(_:))) : nil
}
}
var items: [Item] {
get { return history.currentValue }
set { history.currentValue = newValue }
}
let cellStyle: UITableViewCellStyle
let configureCell: (cell: UITableViewCell, item: Item) -> ()
init(configuration: TableViewConfiguration<Item>) {
self.history = UndoHistory(configuration.items)
self.cellStyle = configuration.cellStyle
self.configureCell = configuration.configureCell
super.init(style: configuration.style)
if configuration.editable {
navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: #selector(MyTableViewController.edit(_:)))
}
}
func edit(sender: AnyObject) {
self.tableView.editing = !self.tableView.editing
}
func undo(sender: AnyObject) {
history.undo()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: cellStyle, reuseIdentifier: nil)
let item = items[indexPath.row]
configureCell(cell: cell, item: item)
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
guard editingStyle == .Delete else { return }
items.removeAtIndex(indexPath.row)
}
}
let config = TableViewConfiguration(items: people, style: .Plain, cellStyle: .Subtitle, editable: true) { cell, item in
cell.textLabel?.text = item.name
cell.detailTextLabel?.text = item.city
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
var myConfig = config
myConfig.style = .Grouped
let tableVC = MyTableViewController(configuration: myConfig)
tableVC.title = "People"
let navigationController = UINavigationController(rootViewController: tableVC)
window?.rootViewController = navigationController
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
| mit | 40aad9014242f51ccfc8e4e15244c4de | 28.5 | 180 | 0.666285 | 4.961364 | false | true | false | false |
taoalpha/XMate | appcode/X-Mates/PostViewController.swift | 1 | 7536 | //
// PostViewController.swift
// X-Mates
//
// Created by Jiangyu Mao on 4/13/16.
// Copyright © 2016 CloudGroup. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import CoreLocation
class PostViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var postTable: UITableView!
@IBOutlet weak var matchTable: UITableView!
@IBOutlet weak var matchLabel: UILabel!
@IBOutlet weak var cancelButton: UIBarButtonItem!
private let fields = ["Date", "Start Time", "End Time", "Categories"]
private let catagoryList = ["Basketball", "Football", "Gym", "Swimming", "Running", "Vollyball"]
private let scheduleURL = "http://192.168.99.100:4000/schedule/"
private let messageURL = "http://192.168.99.100:4000/message/"
private var appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
private var catagory = "Basketball"
private var startTime : NSTimeInterval = 0.0
private var endTime : NSTimeInterval = 0.0
private var date = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.appDelegate.xmate.matches.removeAll()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == postTable
{
return self.fields.count
}
else
{
return self.appDelegate.xmate.matches.count
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if tableView == postTable
{
let cell = tableView.dequeueReusableCellWithIdentifier("fields", forIndexPath: indexPath)
cell.textLabel?.text = fields[indexPath.row]
return cell
}
else
{
let cell = tableView.dequeueReusableCellWithIdentifier("userinfo", forIndexPath: indexPath) as! MatchTableViewCell
cell.userLabel.text = self.appDelegate.xmate.matches[indexPath.row]["username"] as? String
cell.inviteButton.tag = indexPath.row
cell.inviteButton.addTarget(self, action: #selector(PostViewController.inviteUser(_:)), forControlEvents: .TouchUpInside)
return cell
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if tableView == self.postTable
{
let index = indexPath.row
let cell = tableView.cellForRowAtIndexPath(indexPath)!
switch index
{
case 0:
datePicker(cell, mode: "Date")
break
case 1:
datePicker(cell, mode: "Start Time")
break
case 2:
datePicker(cell, mode: "End Time")
break
case 3:
catagoryPicker(cell)
break
default:
break
}
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.catagoryList.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.catagoryList[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
print("Your favorite console is \(self.catagoryList[row])")
self.catagory = self.catagoryList[row]
}
func datePicker(cell: UITableViewCell, mode: String) {
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let datePicker = UIDatePicker(frame: CGRectMake(25, 0, 305, 200))
let formatter = NSDateFormatter()
datePicker.date = NSDate()
if mode == "Date"
{
datePicker.datePickerMode = UIDatePickerMode.Date
formatter.dateStyle = .MediumStyle
}
else if mode == "Start Time" || mode == "End Time"
{
datePicker.datePickerMode = UIDatePickerMode.Time
formatter.dateFormat = "hh:mm a"
}
let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = formatter.stringFromDate(datePicker.date)
if mode == "Start Time"
{
self.startTime = datePicker.date.timeIntervalSince1970
}
else if mode == "End Time"
{
self.endTime = datePicker.date.timeIntervalSince1970
}
else if mode == "Date"
{
self.date = formatter.stringFromDate(datePicker.date)
}
})
alertController.addAction(done)
alertController.view.addSubview(datePicker)
self.presentViewController(alertController, animated: true, completion: nil)
}
func catagoryPicker(cell: UITableViewCell) {
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
let catagoryPicker = UIPickerView(frame: CGRectMake(25, 0, 305, 200))
catagoryPicker.dataSource = self
catagoryPicker.delegate = self
let done = UIAlertAction(title: "Done", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
cell.detailTextLabel?.text = self.catagory
})
alertController.addAction(done)
alertController.view.addSubview(catagoryPicker)
self.presentViewController(alertController, animated: true, completion: nil)
}
@IBAction func cancelPost(sender: UIBarButtonItem) {
self.performSegueWithIdentifier("cancelPost", sender: self)
}
@IBAction func postExercise(sender: UIBarButtonItem) {
if self.endTime < self.startTime
{
let alertController = UIAlertController(title: "Invalid Post", message: "End Time must later than Start Time", preferredStyle: UIAlertControllerStyle.Alert)
let done = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(done)
self.presentViewController(alertController, animated: true, completion: nil)
}
else
{
self.appDelegate.xmate.schedule["creator"] = self.appDelegate.xmate.user["_id"]
self.appDelegate.xmate.schedule["start_time"] = self.startTime
self.appDelegate.xmate.schedule["end_time"] = self.endTime
self.appDelegate.xmate.schedule["type"] = self.catagory
self.appDelegate.xmate.schedule["date"] = self.date
// create post
self.appDelegate.xmate.post(self.scheduleURL, mode: "schedule")
// find all matches for the post
let data = ["pid":self.appDelegate.xmate.schedule["_id"]!, "uid":self.appDelegate.xmate.user["_id"]!, "start_time":self.startTime, "end_time":self.endTime, "type":self.catagory, "action":"match"]
self.appDelegate.xmate.search(self.scheduleURL, data: data)
self.postTable.userInteractionEnabled = false
self.matchTable.reloadData()
self.matchLabel.hidden = false
self.matchTable.hidden = false
}
}
@IBAction func inviteUser(sender: UIButton) {
let alertController = UIAlertController(title: "Confirm Invitation", message: "", preferredStyle: UIAlertControllerStyle.Alert)
let confirm = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default, handler: {(action) -> Void in
let row = sender.tag
let rid = self.appDelegate.xmate.matches[row]["_id"] as! String
let pid = self.appDelegate.xmate.schedule["_id"] as! String
self.appDelegate.xmate.post(self.messageURL, mode: "invite", pid: pid, rid: rid)
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: nil)
alertController.addAction(cancel)
alertController.addAction(confirm)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | 1f81046d32b6da9faf4ab619aa4074bd | 32.193833 | 198 | 0.730723 | 3.880021 | false | false | false | false |
mathewa6/Practise | PathShare.playground/Contents.swift | 1 | 2449 | import UIKit
import PlaygroundSupport
import MapKit
let vc: GPXViewController = GPXViewController()
PlaygroundPage.current.liveView = vc
let points = vc.testCoordinates
let overlay = DXLPointsOverlay(withLocations: points)
let drend = DXLPointsRenderer(overlay: overlay)
let mapv = vc.mapView
var plotPoints: [CGPoint] = []
func viewmage() {
let rect = CGRect(x: 0, y: 0, width: 512, height: 512)
let view = UIView(frame: rect)
for point in points {
let x = mapv?.convert(point, toPointTo: view)
plotPoints.append(x!)
}
}
func drawmage() -> UIImage {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512,
height: 512))
let image = renderer.image { (context: UIGraphicsImageRendererContext) in
let ctx: CGContext = context.cgContext
ctx.setFillColor(UIColor.red.cgColor)
for location in plotPoints {
let rect = CGRect(x: location.x, y: location.y, width: 3.0, height: 3.0)
ctx.setLineWidth(3.0)
ctx.addEllipse(in: rect)
ctx.fillEllipse(in: rect)
}
}
return image
}
func drawRect() -> UIImage {
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 512,
height: 512))
let image = renderer.image { (context: UIGraphicsImageRendererContext) in
let ctx: CGContext = context.cgContext
ctx.setFillColor(UIColor.red.cgColor)
for location in points {
let color: CGColor = UIColor.cyan.cgColor
let point: CGPoint = location.cgPoint(usingOverlayRenderer: drend)
let radius: CGFloat = 5.4
let dimensions: CGFloat = radius * pow(1/8, -1)
let origin: CGPoint = CGPoint(x: point.x - dimensions, y: point.y - dimensions)
let rect = CGRect(origin: origin, size: CGSize(width: 2 * dimensions,
height: 2 * dimensions))
ctx.setLineWidth(dimensions)
ctx.setStrokeColor(color)
ctx.setFillColor(color)
ctx.addEllipse(in: rect)
ctx.strokeEllipse(in: rect)
ctx.fillEllipse(in: rect)
}
}
return image
}
| mit | 3f1f7437d4a97a645fec13ebe7153406 | 30 | 91 | 0.555737 | 4.700576 | false | false | false | false |
griotspeak/PathMath | Sources/PathMath/Rendering.swift | 1 | 5797 | //
// Rendering.swift
// PathMath
//
// Created by TJ Usiyan on 12/26/15.
// Copyright © 2015 Buttons and Lights LLC. All rights reserved.
//
import QuartzCore
public protocol _CALayerBackedType {
mutating func backingLayer() -> CALayer?
}
/* TODO: appease the gods 2016-01-07 */
// public protocol RenderDrawingType {
// /* TODO: abstract over the context type 2016-01-07 */
// static func renderDrawing(size: CGSize, drawingHandler: (CGContext, CGSize) -> Bool) -> Self?
// }
//
// extension _CALayerBackedType {
// public mutating func renderLayerContents<Output : RenderDrawingType>() -> Output? {
// guard let containerLayer = backingLayer() else { return nil }
// return Output.renderDrawing(containerLayer.bounds.size) { (context, size) in
// containerLayer.renderInContext(context)
// return true
// }
// }
// }
#if os(OSX)
import AppKit
extension CALayer {
@nonobjc public func renderLayerContents() -> NSBitmapImageRep? {
guard let containerLayer = backingLayer() else { return nil }
return NSBitmapImageRep.renderDrawing(containerLayer.bounds.size) { context, size in
containerLayer.render(in: context)
return true
}
}
}
extension CALayer {
@nonobjc public func renderLayerContents() -> NSImage? {
guard let containerLayer = backingLayer() else { return nil }
return NSImage.renderDrawing(containerLayer.bounds.size) { context, size in
containerLayer.render(in: context)
return true
}
}
}
extension NSView {
@nonobjc public func renderLayerContents() -> NSBitmapImageRep? {
guard let containerLayer = backingLayer() else { return nil }
return NSBitmapImageRep.renderDrawing(containerLayer.bounds.size) { context, size in
containerLayer.render(in: context)
return true
}
}
}
extension NSView {
@nonobjc public func renderLayerContents() -> NSImage? {
guard let containerLayer = backingLayer() else { return nil }
return NSImage.renderDrawing(containerLayer.bounds.size) { context, size in
containerLayer.render(in: context)
return true
}
}
}
extension NSBitmapImageRep {
@nonobjc public static func renderDrawing(_ size: CGSize, drawingHandler: (CGContext, CGSize) -> Bool) -> Self? {
guard let convertedBounds = NSScreen.main?.convertRectToBacking(NSRect(origin: CGPoint.zero, size: size)).integral,
let intermediateImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(convertedBounds.width), pixelsHigh: Int(convertedBounds.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.calibratedRGB, bitmapFormat: NSBitmapImageRep.Format.alphaFirst, bytesPerRow: 0, bitsPerPixel: 0),
let imageRep = intermediateImageRep.retagging(with: .sRGB)
else { return nil }
imageRep.size = size
guard let bitmapContext = NSGraphicsContext(bitmapImageRep: imageRep) else { return nil }
NSGraphicsContext.saveGraphicsState()
defer { NSGraphicsContext.restoreGraphicsState() }
NSGraphicsContext.current = bitmapContext
let quartzContext = bitmapContext.cgContext
guard drawingHandler(quartzContext, size) else { return nil }
/* TODO: This seems wasteful… find something better? 2016-01-07 */
return imageRep.cgImage.map { self.init(cgImage: $0) }
}
}
extension NSImage {
@nonobjc public static func renderDrawing(_ size: CGSize, drawingHandler: @escaping (CGContext, CGSize) -> Bool) -> Self? {
self.init(size: size, flipped: false) { frame in
guard let context = NSGraphicsContext.current else { return false }
let quartzContext = context.cgContext
return drawingHandler(quartzContext, frame.size)
}
}
}
#endif
#if os(iOS)
import UIKit
extension CALayer {
@nonobjc public func renderLayerContents() -> UIImage? {
guard let containerLayer = backingLayer() else { return nil }
return UIImage.renderDrawing(containerLayer.bounds.size) { context, size in
containerLayer.render(in: context)
}
}
}
extension UIView {
@nonobjc public func renderLayerContents() -> UIImage? {
guard let containerLayer = backingLayer() else { return nil }
return UIImage.renderDrawing(containerLayer.bounds.size) { context, size in
containerLayer.render(in: context)
}
}
}
extension UIImage {
@nonobjc public static func renderDrawing(_ size: CGSize, drawingHandler: (CGContext, CGSize) -> Void) -> UIImage? {
let rect = CGRect(origin: CGPoint.zero, size: size)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.setFillColor(UIColor.clear.cgColor)
context.fill(rect)
drawingHandler(context, size)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image
// guard let imageData = UIImagePNGRepresentation(image) else { return nil }
//
// /* TODO: This seems wasteful… find something better? 2016-01-07 */
// return self.init(data: imageData)
}
}
#endif
| mit | c43d77eebd373ab0bd6ee0c0ee6d6781 | 37.872483 | 368 | 0.628798 | 4.971674 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/View/Common/BFPlaceHolderView.swift | 1 | 5124 | //
// BFPlaceHolderView.swift
// BeeFun
//
// Created by WengHengcong on 2018/6/2.
// Copyright © 2018年 JungleSong. All rights reserved.
//
import UIKit
protocol BFPlaceHolderViewDelegate: class {
func didAction(place: BFPlaceHolderView)
}
/// 占位视图
class BFPlaceHolderView: UIView {
/// 提示字符串
var tip: String?
/// 提示图
var image: String?
/// 操作按钮标题
var actionTitle: String?
/// 要执行的动作
weak var placeHolderActionDelegate: BFPlaceHolderViewDelegate?
private var tipLabel = UILabel()
private var tipImageView = UIImageView()
private var actionButton = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: CGRect.zero)
bfphv_custom()
}
convenience init(tip: String?, image: String?, actionTitle: String?) {
self.init(frame: CGRect.zero, tip: tip, image: image, actionTitle: actionTitle)
}
convenience init(frame: CGRect, tip: String?, image: String?, actionTitle: String?) {
self.init(frame: frame)
self.tip = tip
self.image = image
self.actionTitle = actionTitle
// windowLevel = .greatestFiniteMagnitude
bfphv_custom()
}
private func bfphv_custom() {
backgroundColor = UIColor.white
addSubview(tipImageView)
tipLabel.font = UIFont.bfSystemFont(ofSize: 19.0)
tipLabel.numberOfLines = 0
tipLabel.textAlignment = .center
tipLabel.textColor = UIColor.iOS11Gray
addSubview(tipLabel)
actionButton.addBorderAround(UIColor.bfRedColor, radius: 2.0, width: 1.0)
actionButton.setTitleColor(UIColor.bfRedColor, for: .normal)
actionButton.setTitleColor(UIColor.bfRedColor, for: .highlighted)
actionButton.titleLabel?.textAlignment = .center
actionButton.titleLabel?.font = UIFont.bfSystemFont(ofSize: 18.0)
actionButton.addTarget(self, action: #selector(buttonAction), for: UIControlEvents.touchUpInside)
addSubview(actionButton)
fillDataToUI()
}
@objc func buttonAction() {
print("reload action tapped")
DispatchQueue.main.async {
self.placeHolderActionDelegate?.didAction(place: self)
}
}
// MARK: - 数据
/// 刷新数据到页面
func fillDataToUI() {
if let imageName = image, let uiimageObj = UIImage(named: imageName) {
tipImageView.image = uiimageObj
}
if let tipString = tip {
tipLabel.text = tipString
}
if let buttonTitle = actionTitle {
actionButton.setTitle(buttonTitle, for: .normal)
}
setNeedsDisplay()
}
/// 重新布局
override func layoutSubviews() {
assert(tipImageView.image != nil)
let uiimageObj = tipImageView.image!
let imageW: CGFloat = uiimageObj.size.width
let imageX: CGFloat = (self.width-imageW)/2
let imageH: CGFloat = uiimageObj.size.height
tipImageView.frame = CGRect(x: imageX, y: 100, w: imageW, h: imageH)
let imageToLabelMargin: CGFloat = 13
let tipLabelX: CGFloat = 40
let tipLabelW = self.width-2*tipLabelX
let tipLabelH = BFGlobalHelper.heightWithConstrainedWidth(tipLabel.text ?? "", width: tipLabelW, font: tipLabel.font)
let labelToButtonMargin: CGFloat = 15
let btnH: CGFloat = 40
let btnW: CGFloat = BFGlobalHelper.widthWithConstrainedHeight(actionButton.currentTitle ?? "", height: btnH, font: actionButton.titleLabel!.font) + 20
let btnX = (self.width-btnW)/2
let allH = imageH + imageToLabelMargin + tipLabelH + labelToButtonMargin + btnH
let allY = (self.height-allH)/2-20
tipImageView.frame = CGRect(x: imageX, y: allY, w: imageW, h: imageH)
let tipLabelY = tipImageView.bottom + imageToLabelMargin
tipLabel.frame = CGRect(x: tipLabelX, y: tipLabelY, w: tipLabelW, h: tipLabelH)
let btnY: CGFloat = tipLabel.bottom + labelToButtonMargin
actionButton.frame = CGRect(x: btnX, y: btnY, w: btnW, h: btnH)
}
// MARK: - 重绘页面
func refresh() {
setNeedsDisplay()
}
func refresh(tip: String?) {
refresh(tip: tip, image: nil, actionTitle: nil)
}
func refresh(image: String?) {
refresh(tip: nil, image: image, actionTitle: nil)
}
func refresh(actionTitle: String?) {
refresh(tip: nil, image: nil, actionTitle: actionTitle)
}
func refresh(tip: String?, image: String?, actionTitle: String?) {
if tip != nil {
self.tip = tip
}
if image != nil {
self.image = image
}
if actionTitle != nil {
self.actionTitle = actionTitle
}
fillDataToUI()
}
}
| mit | 327f2750bc41f8c39d6f784ab5abf77c | 29.72561 | 158 | 0.6154 | 4.358997 | false | false | false | false |
camdenfullmer/UnsplashSwift | Source/CollectionsRoutes.swift | 1 | 6377 | // CollectionsRoutes.swift
//
// Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
public class CollectionsRoutes {
let client : UnsplashClient
public init(client: UnsplashClient) {
self.client = client
}
public func findCollections(page: UInt32?=nil, perPage: UInt32?=nil) -> UnsplashRequest<CollectionsResult.Serializer> {
var params = [String : AnyObject]()
if let page = page {
params["page"] = NSNumber(unsignedInt: page)
}
if let perPage = perPage {
params["per_page"] = NSNumber(unsignedInt: perPage)
}
return UnsplashRequest(client: self.client, route: "/collections", auth: false, params: params, responseSerializer: CollectionsResult.Serializer())
}
public func findCuratedCollections(page: UInt32?=nil, perPage: UInt32?=nil) -> UnsplashRequest<CollectionsResult.Serializer> {
var params = [String : AnyObject]()
if let page = page {
params["page"] = NSNumber(unsignedInt: page)
}
if let perPage = perPage {
params["per_page"] = NSNumber(unsignedInt: perPage)
}
return UnsplashRequest(client: self.client, route: "/collections/curated", auth: false, params: params, responseSerializer: CollectionsResult.Serializer())
}
public func findCollection(collectionId: UInt32) -> UnsplashRequest<Collection.Serializer> {
let params = ["id" : NSNumber(unsignedInt: collectionId)]
return UnsplashRequest(client: self.client, route: "/collections/\(collectionId)", auth: false, params: params, responseSerializer: Collection.Serializer())
}
public func findCuratedCollection(collectionId: UInt32) -> UnsplashRequest<Collection.Serializer> {
let params = ["id" : NSNumber(unsignedInt: collectionId)]
return UnsplashRequest(client: self.client, route: "/collections/curatd/\(collectionId)", auth: false, params: params, responseSerializer: Collection.Serializer())
}
public func photosForCollection(collectionId: UInt32) -> UnsplashRequest<PhotosResult.Serializer> {
let params = ["id" : NSNumber(unsignedInt: collectionId)]
return UnsplashRequest(client: self.client, route: "/collections/\(collectionId)/photos", auth: false, params: params, responseSerializer: PhotosResult.Serializer())
}
public func photosForCuratedCollection(collectionId: UInt32) -> UnsplashRequest<PhotosResult.Serializer> {
let params = ["id" : NSNumber(unsignedInt: collectionId)]
return UnsplashRequest(client: self.client, route: "/collections/curated/\(collectionId)/photos", auth: false, params: params, responseSerializer: PhotosResult.Serializer())
}
public func createCollection(title: String, description: String?=nil, isPrivate: Bool=false ) -> UnsplashRequest<Collection.Serializer> {
var params : [String : AnyObject] = ["title" : title]
if let d = description {
params["description"] = d
}
if isPrivate {
params["private"] = "true"
}
return UnsplashRequest(client: self.client, method: .POST, route: "/collections", auth: true, params: params, responseSerializer: Collection.Serializer())
}
public func updateCollection(collectionId: UInt32, title: String?=nil, description: String?=nil, isPrivate: Bool=false) -> UnsplashRequest<Collection.Serializer> {
var params : [String : AnyObject] = ["id" : NSNumber(unsignedInt: collectionId)]
if let t = title {
params["title"] = t
}
if let d = description {
params["description"] = d
}
if isPrivate {
params["private"] = "true"
}
return UnsplashRequest(client: self.client, method: .PUT, route: "/collections/\(collectionId)", auth: true, params: params, responseSerializer: Collection.Serializer())
}
public func deleteCollection(collectionId: UInt32) -> UnsplashRequest<DeleteResultSerializer> {
let params = ["id" : NSNumber(unsignedInt: collectionId)]
return UnsplashRequest(client: self.client, method: .DELETE, route: "/collections/\(collectionId)", auth: true, params: params, responseSerializer: DeleteResultSerializer())
}
public func addPhotoToCollection(collectionId: UInt32, photoId: String) -> UnsplashRequest<PhotoCollectionResult.Serializer> {
let params = [
"collection_id" : NSNumber(unsignedInt: collectionId),
"photo_id" : photoId
]
return UnsplashRequest(client: self.client, method: .POST, route: "/collections/\(collectionId)/add", auth: true, params: params, responseSerializer: PhotoCollectionResult.Serializer())
}
public func removePhotoToCollection(collectionId: UInt32, photoId: UInt32) -> UnsplashRequest<DeleteResultSerializer> {
let params = [
"collection_id" : NSNumber(unsignedInt: collectionId),
"photo_id" : NSNumber(unsignedInt: photoId)
]
return UnsplashRequest(client: self.client, method: .DELETE, route: "/collections/\(collectionId)/remove", auth: true, params: params, responseSerializer: DeleteResultSerializer())
}
}
| mit | 2bc76d9ac7bd15cba827e23c27fea3d3 | 51.270492 | 193 | 0.689196 | 4.709749 | false | false | false | false |
varun-naharia/VNOfficeHourPicker | VNOfficeHourPicker/Utilities/Extention+Extra.swift | 2 | 12506 | //
// UINavigationController+Extra.swift
// OfficeHourPicker
//
// Created by Varun Naharia on 06/03/17.
// Copyright © 2017 Varun Naharia. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension Date {
var millisecondsSince1970:Double {
return Double((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
init?(jsonDate: String) {
let prefix = "/Date("
let suffix = ")/"
// Check for correct format:
guard jsonDate.hasPrefix(prefix) && jsonDate.hasSuffix(suffix) else { return nil }
// Extract the number as a string:
let from = jsonDate.index(jsonDate.startIndex, offsetBy: prefix.characters.count)
let to = jsonDate.index(jsonDate.endIndex, offsetBy: -suffix.characters.count)
// Convert milliseconds to double
guard let milliSeconds = Double(jsonDate[from ..< to]) else { return nil }
// Create NSDate with this UNIX timestamp
self.init(timeIntervalSince1970: milliSeconds/1000.0)
}
}
import MapKit
fileprivate let MERCATOR_OFFSET: Double = 268435456
fileprivate let MERCATOR_RADIUS: Double = 85445659.44705395
extension MKMapView {
func getZoomLevel() -> Double {
let reg = self.region
let span = reg.span
let centerCoordinate = reg.center
// Get the left and right most lonitudes
let leftLongitude = centerCoordinate.longitude - (span.longitudeDelta / 2)
let rightLongitude = centerCoordinate.longitude + (span.longitudeDelta / 2)
let mapSizeInPixels = self.bounds.size
// Get the left and right side of the screen in fully zoomed-in pixels
let leftPixel = self.longitudeToPixelSpaceX(longitude: leftLongitude)
let rightPixel = self.longitudeToPixelSpaceX(longitude: rightLongitude)
let pixelDelta = abs(rightPixel - leftPixel)
let zoomScale = Double(mapSizeInPixels.width) / pixelDelta
let zoomExponent = log2(zoomScale)
let zoomLevel = zoomExponent + 20
return zoomLevel
}
func setCenter(coordinate: CLLocationCoordinate2D, zoomLevel: Int, animated: Bool) {
let zoom = min(zoomLevel, 28)
let span = self.coordinateSpan(centerCoordinate: coordinate, zoomLevel: zoom)
let region = MKCoordinateRegion(center: coordinate, span: span)
self.setRegion(region, animated: true)
}
// MARK: - Private func
private func coordinateSpan(centerCoordinate: CLLocationCoordinate2D, zoomLevel: Int) -> MKCoordinateSpan {
// Convert center coordiate to pixel space
let centerPixelX = self.longitudeToPixelSpaceX(longitude: centerCoordinate.longitude)
let centerPixelY = self.latitudeToPixelSpaceY(latitude: centerCoordinate.latitude)
// Determine the scale value from the zoom level
let zoomExponent = 20 - zoomLevel
let zoomScale = NSDecimalNumber(decimal: pow(2, zoomExponent)).doubleValue
// Scale the map’s size in pixel space
let mapSizeInPixels = self.bounds.size
let scaledMapWidth = Double(mapSizeInPixels.width) * zoomScale
let scaledMapHeight = Double(mapSizeInPixels.height) * zoomScale
// Figure out the position of the top-left pixel
let topLeftPixelX = centerPixelX - (scaledMapWidth / 2)
let topLeftPixelY = centerPixelY - (scaledMapHeight / 2)
// Find delta between left and right longitudes
let minLng: CLLocationDegrees = self.pixelSpaceXToLongitude(pixelX: topLeftPixelX)
let maxLng: CLLocationDegrees = self.pixelSpaceXToLongitude(pixelX: topLeftPixelX + scaledMapWidth)
let longitudeDelta: CLLocationDegrees = maxLng - minLng
// Find delta between top and bottom latitudes
let minLat: CLLocationDegrees = self.pixelSpaceYToLatitude(pixelY: topLeftPixelY)
let maxLat: CLLocationDegrees = self.pixelSpaceYToLatitude(pixelY: topLeftPixelY + scaledMapHeight)
let latitudeDelta: CLLocationDegrees = -1 * (maxLat - minLat)
return MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta)
}
private func longitudeToPixelSpaceX(longitude: Double) -> Double {
return round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * .pi / 180.0)
}
private func latitudeToPixelSpaceY(latitude: Double) -> Double {
if latitude == 90.0 {
return 0
} else if latitude == -90.0 {
return MERCATOR_OFFSET * 2
} else {
return round(MERCATOR_OFFSET - MERCATOR_RADIUS * Double(logf((1 + sinf(Float(latitude * .pi) / 180.0)) / (1 - sinf(Float(latitude * .pi) / 180.0))) / 2.0))
}
}
private func pixelSpaceXToLongitude(pixelX: Double) -> Double {
return ((round(pixelX) - MERCATOR_OFFSET) / MERCATOR_RADIUS) * 180.0 / .pi
}
private func pixelSpaceYToLatitude(pixelY: Double) -> Double {
return (.pi / 2.0 - 2.0 * atan(exp((round(pixelY) - MERCATOR_OFFSET) / MERCATOR_RADIUS))) * 180.0 / .pi
}
}
extension String {
func characterAtIndex(index: Int) -> Character? {
var cur = 0
for char in self.characters {
if cur == index {
return char
}
cur += 1
}
return nil
}
func verifyUrl () -> Bool {
if let url = URL(string: self) {
return UIApplication.shared.canOpenURL(url)
}
return false
}
func hasHttp()->Bool{
if(self.hasPrefix("http") || self.hasPrefix("https")){
return true
}
return false
}
func isValidEmail() -> Bool {
// print("validate calendar: \(testStr)")
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
}
extension MKMapView
{
func removeAllOverlay(){
for overlay:MKOverlay in self.overlays {
self.remove(overlay)
}
}
}
extension UIApplication {
class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = controller as? UINavigationController {
return topViewController(controller: navigationController.visibleViewController)
}
if let tabController = controller as? UITabBarController {
if let selected = tabController.selectedViewController {
return topViewController(controller: selected)
}
}
if let presented = controller?.presentedViewController {
return topViewController(controller: presented)
}
return controller
}
}
public extension UIWindow {
func captureWindow() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.frame.size, self.isOpaque, UIScreen.main.scale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
public extension UIView {
func capture() -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.frame.size, self.isOpaque, UIScreen.main.scale)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
extension Array {
mutating func delete(element: Int) {
self = self.filter() { $0 as! Int != element }
}
func jsonString() -> String {
let jsonData = try! JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions.prettyPrinted)
var JSONString:String!
//Convert back to string. Usually only do this for debugging
if let strJson = String(data: jsonData, encoding: String.Encoding.utf8) {
print(strJson)
JSONString = strJson
}
return JSONString
}
}
extension UILabel {
func isTruncated() -> Bool {
if let string = self.text {
let size: CGSize = (string as NSString).boundingRect(
with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: self.font],
context: nil).size
return (size.height > self.bounds.size.height)
}
return false
}
}
extension UIResponder {
func getParentViewController() -> UIViewController? {
if self.next is UIViewController {
return self.next as? UIViewController
} else {
if self.next != nil {
return (self.next!).getParentViewController()
}
else {return nil}
}
}
}
extension UITextField {
func isTruncated() -> Bool {
if let string = self.text {
let size: CGSize = (string as NSString).boundingRect(
with: CGSize(width: self.frame.size.width, height: CGFloat.greatestFiniteMagnitude),
options: NSStringDrawingOptions.usesLineFragmentOrigin,
attributes: [NSFontAttributeName: self.font!],
context: nil).size
return (size.height > self.bounds.size.height)
}
return false
}
}
extension UIToolbar {
func ToolbarPiker(selector : Selector) -> UIToolbar {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.black
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: selector)
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
toolBar.setItems([ spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
return toolBar
}
func addDoneButton(_ closure: @escaping ()->()) -> UIToolbar {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.black
toolBar.sizeToFit()
let sleeve = ClosureSleeve(closure)
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: sleeve, action: #selector(ClosureSleeve.invoke))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
toolBar.setItems([ spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
objc_setAssociatedObject(toolBar, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return toolBar
}
}
class ClosureSleeve {
let closure: ()->()
init (_ closure: @escaping ()->()) {
self.closure = closure
}
@objc func invoke () {
closure()
}
}
extension UIControl {
func add(for controlEvents: UIControlEvents, _ closure: @escaping ()->()) {
let sleeve = ClosureSleeve(closure)
addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents)
objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
| mit | 1d8a26d3349e0450260ee9b56ec14360 | 32.25266 | 167 | 0.628169 | 4.916634 | false | false | false | false |
BasThomas/MacOSX | RGBWell/RGBWell/MainWindowController.swift | 1 | 1550 | //
// MainWindowController.swift
// RGBWell
//
// Created by Bas Broek on 29/04/15.
// Copyright (c) 2015 Bas Broek. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController
{
@IBOutlet weak var rSlider: NSSlider!
@IBOutlet weak var gSlider: NSSlider!
@IBOutlet weak var bSlider: NSSlider!
@IBOutlet weak var colorWell: NSColorWell!
var r = 0.0
var g = 0.0
var b = 0.0
let a = 1.0
override func windowDidLoad() {
super.windowDidLoad()
self.rSlider.doubleValue = self.r
self.gSlider.doubleValue = self.g
self.bSlider.doubleValue = self.b
self.updateColor()
}
override var windowNibName: String?
{
return "MainWindowController"
}
func updateColor()
{
let newColor = NSColor(calibratedRed: CGFloat(self.r),
green: CGFloat(self.g),
blue: CGFloat(self.b),
alpha: CGFloat(self.a))
self.colorWell.color = newColor
}
@IBAction func adjustRed(sender: AnyObject)
{
self.r = sender.doubleValue
self.updateColor()
}
@IBAction func adjustGreen(sender: AnyObject)
{
self.g = sender.doubleValue
self.updateColor()
}
@IBAction func adjustBlue(sender: AnyObject)
{
self.b = sender.doubleValue
self.updateColor()
}
} | mit | 35d77206a9ce783b1c2cc679cedf9e24 | 21.808824 | 62 | 0.548387 | 4.545455 | false | false | false | false |
narner/AudioKit | AudioKit/Common/Internals/AKNodeRecorder.swift | 1 | 5655 | //
// AKAudioNodeRecorder.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Tweaked by Laurent Veliscek
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
/// Simple audio recorder class
@objc open class AKNodeRecorder: NSObject {
// MARK: - Properties
// The node we record from
fileprivate var node: AKNode?
// The file to record to
fileprivate var internalAudioFile: AKAudioFile
/// True if we are recording.
@objc public private(set) dynamic var isRecording = false
/// An optional duration for the recording to auto-stop when reached
open var durationToRecord: Double = 0
/// Duration of recording
open var recordedDuration: Double {
return internalAudioFile.duration
}
/// Used for fixing recordings being truncated
fileprivate var recordBufferDuration: Double = 16_384 / AKSettings.sampleRate
/// return the AKAudioFile for reading
open var audioFile: AKAudioFile? {
do {
return try AKAudioFile(forReading: internalAudioFile.url)
} catch let error as NSError {
AKLog("Cannot create internal audio file for reading")
AKLog("Error: \(error.localizedDescription)")
return nil
}
}
// MARK: - Initialization
/// Initialize the node recorder
///
/// Recording buffer size is defaulted to be AKSettings.bufferLength
/// You can set a different value by setting an AKSettings.recordingBufferLength
///
/// - Parameters:
/// - node: Node to record from
/// - file: Audio file to record to
///
@objc public init(node: AKNode? = AudioKit.output,
file: AKAudioFile? = nil) throws {
// AVAudioSession buffer setup
guard let existingFile = file else {
// We create a record file in temp directory
do {
internalAudioFile = try AKAudioFile()
} catch let error as NSError {
AKLog("AKNodeRecorder Error: Cannot create an empty audio file")
throw error
}
self.node = node
return
}
do {
// We initialize AKAudioFile for writing (and check that we can write to)
internalAudioFile = try AKAudioFile(forWriting: existingFile.url,
settings: existingFile.processingFormat.settings)
} catch let error as NSError {
AKLog("AKNodeRecorder Error: cannot write to \(existingFile.fileNamePlusExtension)")
throw error
}
self.node = node
}
// MARK: - Methods
/// Start recording
@objc open func record() throws {
if isRecording == true {
AKLog("AKNodeRecorder Warning: already recording")
return
}
guard let node = node else {
AKLog("AKNodeRecorder Error: input node is not available")
return
}
let recordingBufferLength: AVAudioFrameCount = AKSettings.recordingBufferLength.samplesCount
isRecording = true
AKLog("AKNodeRecorder: recording")
node.avAudioNode.installTap(
onBus: 0,
bufferSize: recordingBufferLength,
format: internalAudioFile.processingFormat) { [weak self] (buffer: AVAudioPCMBuffer!, _) -> Void in
do {
self!.recordBufferDuration = Double(buffer.frameLength) / AKSettings.sampleRate
try self!.internalAudioFile.write(from: buffer)
//AKLog("AKNodeRecorder writing (file duration: \(self!.internalAudioFile.duration) seconds)")
// allow an optional timed stop
if self!.durationToRecord != 0 && self!.internalAudioFile.duration >= self!.durationToRecord {
self!.stop()
}
} catch let error as NSError {
AKLog("Write failed: error -> \(error.localizedDescription)")
}
}
}
/// Stop recording
@objc open func stop() {
if isRecording == false {
AKLog("AKNodeRecorder Warning: Cannot stop recording, already stopped")
return
}
isRecording = false
if AKSettings.fixTruncatedRecordings {
// delay before stopping so the recording is not truncated.
let delay = UInt32(recordBufferDuration * 1_000_000)
usleep(delay)
}
node?.avAudioNode.removeTap(onBus: 0)
}
/// Reset the AKAudioFile to clear previous recordings
open func reset() throws {
// Stop recording
if isRecording == true {
stop()
}
// Delete the physical recording file
let fileManager = FileManager.default
let settings = internalAudioFile.processingFormat.settings
let url = internalAudioFile.url
do {
if let path = audioFile?.url.path {
try fileManager.removeItem(atPath: path)
}
} catch let error as NSError {
AKLog("Error: Can't delete: \(audioFile?.fileNamePlusExtension ?? "nil") \(error.localizedDescription)")
}
// Creates a blank new file
do {
internalAudioFile = try AKAudioFile(forWriting: url, settings: settings)
AKLog("AKNodeRecorder: file has been cleared")
} catch let error as NSError {
AKLog("Error: Can't record to: \(internalAudioFile.fileNamePlusExtension)")
throw error
}
}
}
| mit | 17c6a20494a73a269c3cf22452a929c9 | 31.494253 | 116 | 0.593739 | 5.395038 | false | false | false | false |
iosdevelopershq/code-challenges | CodeChallenge/Challenges/TwoSum/Entries/Mosab.swift | 1 | 871 | //
// Mosab.swift
// CodeChallenge
//
// Created by Ryan Arana on 11/1/15.
// Copyright © 2015 iosdevelopers. All rights reserved.
//
import Foundation
let mosabTwoSumEntry = CodeChallengeEntry<TwoSumChallenge>(name: "Mosab") { input in
var numbers = input.numbers
var dictionary : [Int : Int] = [:] //Dictionary to hold numbers and indices
for (index, number) in numbers.enumerated() {
dictionary[number] = index
}
return findIndices(&dictionary, numbers: &numbers, target: input.target)
}
private func findIndices(_ map : inout [Int:Int], numbers : inout [Int], target : Int) -> (Int, Int)?
{
for (index, number) in numbers.enumerated()
{
if let index2 = map[abs(number - target)]
{
return (index + 1, index2 + 1) //offset by 1 so we're not 0 based
}
}
return nil
}
| mit | 8d215319220b311a7bcbd6475ec51c52 | 25.363636 | 101 | 0.621839 | 3.670886 | false | false | false | false |
cotkjaer/Silverback | Silverback/UIApplication.swift | 1 | 4605 | //
// UIApplication.swift
// Silverback
//
// Created by Christian Otkjær on 16/11/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
import UIKit
public extension UIApplication
{
public class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController?
{
if let nav = base as? UINavigationController
{
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController
{
if let selected = tab.selectedViewController
{
return topViewController(selected)
}
}
if let presented = base?.presentedViewController
{
return topViewController(presented)
}
return base
}
}
//MARK: - visibleViewControllers
extension UIViewController
{
public func viewControllersWithVisibleViews() -> [UIViewController]
{
if let presented = presentedViewController
{
// Assume that a modally presented viewControllers view covers this ones completely
return presented.viewControllersWithVisibleViews()
}
if isViewLoadedAndAddedToWindow()
{
let childViewControllersWithVisibleViews = childViewControllers.filter({ (childViewController) -> Bool in
if childViewController.isViewLoadedAndAddedToWindow()
{
return view.bounds.intersects(view.convertRect(childViewController.view.bounds, fromView: childViewController.view))
}
return false
})
// Assume that all the childViewControllers views combined do not cover this ones completely
return [self] + childViewControllersWithVisibleViews.flatMap{ $0.viewControllersWithVisibleViews() }
}
return []
}
public func isViewLoadedAndAddedToWindow() -> Bool
{
if isViewLoaded()
{
if view.window != nil
{
return true
}
}
return false
}
public var visibleViewControllers : [UIViewController] { return presentedViewController?.visibleViewControllers ?? [self] + childViewControllers.flatMap({ $0.visibleViewControllers }) }
}
//MARK: - UINavigationController
extension UINavigationController
{
override public var visibleViewControllers : [UIViewController] { return visibleViewController?.visibleViewControllers ?? super.visibleViewControllers }
}
//MARK: - UITabBarController
extension UITabBarController
{
override public var visibleViewControllers : [UIViewController] { return selectedViewController?.visibleViewControllers ?? super.visibleViewControllers }
}
//MARK: - UISplitViewController
extension UISplitViewController
{
override public var visibleViewControllers : [UIViewController]
{
if collapsed
{
return viewControllers.first?.visibleViewControllers ?? super.visibleViewControllers
}
switch displayMode
{
case .AllVisible, .PrimaryOverlay, .Automatic:
return viewControllers.flatMap { $0.visibleViewControllers }
case .PrimaryHidden:
return viewControllers.last?.visibleViewControllers ?? super.visibleViewControllers
}
}
}
extension UIApplication
{
/// returns: the viewcontrollers currently displyed for this application
public var visibleViewControllers : [UIViewController] { return keyWindow?.rootViewController?.visibleViewControllers ?? [] }
// public class func visibleViewControllers(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> [UIViewController]
// {
// if let navigationController = base as? UINavigationController
// {
// return visibleViewControllers(navigationController.visibleViewController)
// }
//
// if let tabBarController = base as? UITabBarController
// {
// if let selected = tabBarController.selectedViewController
// {
// return visibleViewControllers(selected)
// }
// }
// if let presented = base?.presentedViewController {
// return topViewController(base: presented)
// }
// return base
// }
} | mit | 77ffe49061fa23815c68494f441608b3 | 30.312925 | 189 | 0.631465 | 6.111554 | false | false | false | false |
milseman/swift | stdlib/public/core/OptionSet.swift | 8 | 14981 | //===--- OptionSet.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that presents a mathematical set interface to a bit set.
///
/// You use the `OptionSet` protocol to represent bitset types, where
/// individual bits represent members of a set. Adopting this protocol in
/// your custom types lets you perform set-related operations such as
/// membership tests, unions, and intersections on those types. What's more,
/// when implemented using specific criteria, adoption of this protocol
/// requires no extra work on your part.
///
/// When creating an option set, include a `rawValue` property in your type
/// declaration. The `rawValue` property must be of a type that conforms to
/// the `FixedWidthInteger` protocol, such as `Int` or `UInt8`. Next, create
/// unique options as static properties of your custom type using unique
/// powers of two (1, 2, 4, 8, 16, and so forth) for each individual
/// property's raw value so that each property can be represented by a single
/// bit of the type's raw value.
///
/// For example, consider a custom type called `ShippingOptions` that is an
/// option set of the possible ways to ship a customer's purchase.
/// `ShippingOptions` includes a `rawValue` property of type `Int` that stores
/// the bit mask of available shipping options. The static members `nextDay`,
/// `secondDay`, `priority`, and `standard` are unique, individual options.
///
/// struct ShippingOptions: OptionSet {
/// let rawValue: Int
///
/// static let nextDay = ShippingOptions(rawValue: 1 << 0)
/// static let secondDay = ShippingOptions(rawValue: 1 << 1)
/// static let priority = ShippingOptions(rawValue: 1 << 2)
/// static let standard = ShippingOptions(rawValue: 1 << 3)
///
/// static let express: ShippingOptions = [.nextDay, .secondDay]
/// static let all: ShippingOptions = [.express, .priority, .standard]
/// }
///
/// Declare additional preconfigured option set values as static properties
/// initialized with an array literal containing other option values. In the
/// example, because the `express` static property is assigned an array
/// literal with the `nextDay` and `secondDay` options, it will contain those
/// two elements.
///
/// Using an Option Set Type
/// ========================
///
/// When you need to create an instance of an option set, assign one of the
/// type's static members to your variable or constant. Alternatively, to
/// create an option set instance with multiple members, assign an array
/// literal with multiple static members of the option set. To create an empty
/// instance, assign an empty array literal to your variable.
///
/// let singleOption: ShippingOptions = .priority
/// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]
/// let noOptions: ShippingOptions = []
///
/// Use set-related operations to check for membership and to add or remove
/// members from an instance of your custom option set type. The following
/// example shows how you can determine free shipping options based on a
/// customer's purchase price:
///
/// let purchasePrice = 87.55
///
/// var freeOptions: ShippingOptions = []
/// if purchasePrice > 50 {
/// freeOptions.insert(.priority)
/// }
///
/// if freeOptions.contains(.priority) {
/// print("You've earned free priority shipping!")
/// } else {
/// print("Add more to your cart for free priority shipping!")
/// }
/// // Prints "You've earned free priority shipping!"
public protocol OptionSet : SetAlgebra, RawRepresentable {
// We can't constrain the associated Element type to be the same as
// Self, but we can do almost as well with a default and a
// constrained extension
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
associatedtype Element = Self
// FIXME: This initializer should just be the failable init from
// RawRepresentable. Unfortunately, current language limitations
// that prevent non-failable initializers from forwarding to
// failable ones would prevent us from generating the non-failing
// default (zero-argument) initializer. Since OptionSet's main
// purpose is to create convenient conformances to SetAlgebra,
// we opt for a non-failable initializer.
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
init(rawValue: RawValue)
}
/// `OptionSet` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet {
/// Returns a new option set of the elements contained in this set, in the
/// given set, or in both.
///
/// This example uses the `union(_:)` method to add two more shipping options
/// to the default set.
///
/// let defaultShipping = ShippingOptions.standard
/// let memberShipping = defaultShipping.union([.secondDay, .priority])
/// print(memberShipping.contains(.priority))
/// // Prints "true"
///
/// - Parameter other: An option set.
/// - Returns: A new option set made up of the elements contained in this
/// set, in `other`, or in both.
public func union(_ other: Self) -> Self {
var r: Self = Self(rawValue: self.rawValue)
r.formUnion(other)
return r
}
/// Returns a new option set with only the elements contained in both this
/// set and the given set.
///
/// This example uses the `intersection(_:)` method to limit the available
/// shipping options to what can be used with a PO Box destination.
///
/// // Can only ship standard or priority to PO Boxes
/// let poboxShipping: ShippingOptions = [.standard, .priority]
/// let memberShipping: ShippingOptions =
/// [.standard, .priority, .secondDay]
///
/// let availableOptions = memberShipping.intersection(poboxShipping)
/// print(availableOptions.contains(.priority))
/// // Prints "true"
/// print(availableOptions.contains(.secondDay))
/// // Prints "false"
///
/// - Parameter other: An option set.
/// - Returns: A new option set with only the elements contained in both this
/// set and `other`.
public func intersection(_ other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.formIntersection(other)
return r
}
/// Returns a new option set with the elements contained in this set or in
/// the given set, but not in both.
///
/// - Parameter other: An option set.
/// - Returns: A new option set with only the elements contained in either
/// this set or `other`, but not in both.
public func symmetricDifference(_ other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.formSymmetricDifference(other)
return r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `Element == Self`, which is the default.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where Element == Self {
/// Returns a Boolean value that indicates whether a given element is a
/// member of the option set.
///
/// This example uses the `contains(_:)` method to check whether next-day
/// shipping is in the `availableOptions` instance.
///
/// let availableOptions = ShippingOptions.express
/// if availableOptions.contains(.nextDay) {
/// print("Next day shipping available")
/// }
/// // Prints "Next day shipping available"
///
/// - Parameter member: The element to look for in the option set.
/// - Returns: `true` if the option set contains `member`; otherwise,
/// `false`.
public func contains(_ member: Self) -> Bool {
return self.isSuperset(of: member)
}
/// Adds the given element to the option set if it is not already a member.
///
/// In the following example, the `.secondDay` shipping option is added to
/// the `freeOptions` option set if `purchasePrice` is greater than 50.0. For
/// the `ShippingOptions` declaration, see the `OptionSet` protocol
/// discussion.
///
/// let purchasePrice = 87.55
///
/// var freeOptions: ShippingOptions = [.standard, .priority]
/// if purchasePrice > 50 {
/// freeOptions.insert(.secondDay)
/// }
/// print(freeOptions.contains(.secondDay))
/// // Prints "true"
///
/// - Parameter newMember: The element to insert.
/// - Returns: `(true, newMember)` if `newMember` was not contained in
/// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is
/// the member of the set equal to `newMember`.
@discardableResult
public mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element) {
let oldMember = self.intersection(newMember)
let shouldInsert = oldMember != newMember
let result = (
inserted: shouldInsert,
memberAfterInsert: shouldInsert ? newMember : oldMember)
if shouldInsert {
self.formUnion(newMember)
}
return result
}
/// Removes the given element and all elements subsumed by it.
///
/// In the following example, the `.priority` shipping option is removed from
/// the `options` option set. Attempting to remove the same shipping option
/// a second time results in `nil`, because `options` no longer contains
/// `.priority` as a member.
///
/// var options: ShippingOptions = [.secondDay, .priority]
/// let priorityOption = options.remove(.priority)
/// print(priorityOption == .priority)
/// // Prints "true"
///
/// print(options.remove(.priority))
/// // Prints "nil"
///
/// In the next example, the `.express` element is passed to `remove(_:)`.
/// Although `.express` is not a member of `options`, `.express` subsumes
/// the remaining `.secondDay` element of the option set. Therefore,
/// `options` is emptied and the intersection between `.express` and
/// `options` is returned.
///
/// let expressOption = options.remove(.express)
/// print(expressOption == .express)
/// // Prints "false"
/// print(expressOption == .secondDay)
/// // Prints "true"
///
/// - Parameter member: The element of the set to remove.
/// - Returns: The intersection of `[member]` and the set, if the
/// intersection was nonempty; otherwise, `nil`.
@discardableResult
public mutating func remove(_ member: Element) -> Element? {
let r = isSuperset(of: member) ? Optional(member) : nil
self.subtract(member)
return r
}
/// Inserts the given element into the set.
///
/// If `newMember` is not contained in the set but subsumes current members
/// of the set, the subsumed members are returned.
///
/// var options: ShippingOptions = [.secondDay, .priority]
/// let replaced = options.update(with: .express)
/// print(replaced == .secondDay)
/// // Prints "true"
///
/// - Returns: The intersection of `[newMember]` and the set if the
/// intersection was nonempty; otherwise, `nil`.
@discardableResult
public mutating func update(with newMember: Element) -> Element? {
let r = self.intersection(newMember)
self.formUnion(newMember)
return r.isEmpty ? nil : r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `RawValue` conforms to `FixedWidthInteger`,
/// which is the usual case. Each distinct bit of an option set's
/// `.rawValue` corresponds to a disjoint value of the `OptionSet`.
///
/// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s
/// - `intersection` is implemented as a bitwise "and" (`&`) of
/// `rawValue`s
/// - `symmetricDifference` is implemented as a bitwise "exclusive or"
/// (`^`) of `rawValue`s
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where RawValue : FixedWidthInteger {
/// Creates an empty option set.
///
/// This initializer creates an option set with a raw value of zero.
public init() {
self.init(rawValue: 0)
}
/// Inserts the elements of another set into this option set.
///
/// This method is implemented as a `|` (bitwise OR) operation on the
/// two sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formUnion(_ other: Self) {
self = Self(rawValue: self.rawValue | other.rawValue)
}
/// Removes all elements of this option set that are not
/// also present in the given set.
///
/// This method is implemented as a `&` (bitwise AND) operation on the
/// two sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formIntersection(_ other: Self) {
self = Self(rawValue: self.rawValue & other.rawValue)
}
/// Replaces this set with a new set containing all elements
/// contained in either this set or the given set, but not in both.
///
/// This method is implemented as a `^` (bitwise XOR) operation on the two
/// sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formSymmetricDifference(_ other: Self) {
self = Self(rawValue: self.rawValue ^ other.rawValue)
}
}
@available(*, unavailable, renamed: "OptionSet")
public typealias OptionSetType = OptionSet
| apache-2.0 | 8ba2f616e2ee5e78f0ceabd5107130a6 | 40.156593 | 80 | 0.665109 | 4.398415 | false | false | false | false |
VladimirDinic/WDSideMenu | WDSideMenu/WDSideMenu/WDViewController/WDViewController.swift | 1 | 3206 | //
// WDViewController.swift
// Dictionary
//
// Created by Vladimir Dinic on 2/16/17.
// Copyright © 2017 Vladimir Dinic. All rights reserved.
//
import UIKit
public class Constants: NSObject {
static let SCREEN_WIDTH:CGFloat = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT:CGFloat = UIScreen.main.bounds.size.height
static let IS_IPAD:Bool = UIDevice.current.userInterfaceIdiom == .pad
}
@objc public protocol WDSideMenuDelegate{
@objc optional func sideViewDidShow()
@objc optional func sideViewDidHide()
}
enum SideMenuSide {
case LeftMenu
case RightMenu
}
enum SideMenuRelativePosition {
case StickedToMainView
case AboveMainView
case BelowMainView
}
public enum SideMenuType
{
case LeftMenuStickedToMainView
case LeftMenuAboveMainView
case LeftMenuBelowMainView
case RightMenuStickedToMainView
case RightMenuAboveMainView
case RightMenuBelowMainView
}
open class WDViewController: UIViewController, UIGestureRecognizerDelegate {
var panningSideMenuInProgress:Bool = false
var mainViewIsTapped:Bool = false
var panGestureRecognizer: UIPanGestureRecognizer?
var tapGestureRecognizer: UITapGestureRecognizer?
var edgeScreenGestureRecognizer: UIScreenEdgePanGestureRecognizer?
var sideMenuVisible:Bool = false
var originX = 0.0
var originY = 0.0
var originalSideHorizontalConstraint = 0.0
var originalSideVerticalConstraint = 0.0
var mainContentViewController:UIViewController?
var sideViewController:UIViewController?
var sideView:UIView?
var mainView:UIView?
var sideMenuHorizontalOffset: NSLayoutConstraint!
var sideMenuVerticalOffset: NSLayoutConstraint!
var menuSide:SideMenuSide = .LeftMenu
var sideMenuRelativePosition:SideMenuRelativePosition = .StickedToMainView
var animationInProgress = false
open var addShadowToTopView:Bool = true
open var sideMenuType:SideMenuType = .LeftMenuStickedToMainView
open var panGestureEnabled:Bool = true
open var sizeMenuWidth:CGFloat = Constants.SCREEN_WIDTH * 0.67
open var mainContentDelegate:WDSideMenuDelegate! = nil
open var sideMenuDelegate:WDSideMenuDelegate! = nil
open var resizeMainContentView:Bool = false
open var scaleFactor:CGFloat = 1.0
open var sideViewHasFullWidth: Bool = false
override open func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.setParameters()
self.setupContent()
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let sideViewDefined = self.sideView
{
sideViewDefined.isHidden = false
}
}
open func setupParameters()
{
}
open func getMainViewController() -> UIViewController?
{
return nil
}
open func getSideMenuViewController() -> UIViewController?
{
return nil
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 8ff2dbbdaa251ffa70b559c527a0d5b5 | 27.873874 | 78 | 0.715757 | 5.023511 | false | false | false | false |
DarrenKong/firefox-ios | Sync/StorageClient.swift | 2 | 32104 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Alamofire
import Shared
import Account
import XCGLogger
import Deferred
import SwiftyJSON
private let log = Logger.syncLogger
// Not an error that indicates a server problem, but merely an
// error that encloses a StorageResponse.
open class StorageResponseError<T>: MaybeErrorType, SyncPingFailureFormattable {
open let response: StorageResponse<T>
open var failureReasonName: SyncPingFailureReasonName {
return .httpError
}
public init(_ response: StorageResponse<T>) {
self.response = response
}
open var description: String {
return "Error."
}
}
open class RequestError: MaybeErrorType, SyncPingFailureFormattable {
open var failureReasonName: SyncPingFailureReasonName {
return .httpError
}
open var description: String {
return "Request error."
}
}
open class BadRequestError<T>: StorageResponseError<T> {
open let request: URLRequest?
public init(request: URLRequest?, response: StorageResponse<T>) {
self.request = request
super.init(response)
}
override open var description: String {
return "Bad request."
}
}
open class ServerError<T>: StorageResponseError<T> {
override open var description: String {
return "Server error."
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
open class NotFound<T>: StorageResponseError<T> {
override open var description: String {
return "Not found. (\(T.self))"
}
override public init(_ response: StorageResponse<T>) {
super.init(response)
}
}
open class RecordParseError: MaybeErrorType, SyncPingFailureFormattable {
open var description: String {
return "Failed to parse record."
}
open var failureReasonName: SyncPingFailureReasonName {
return .otherError
}
}
open class MalformedMetaGlobalError: MaybeErrorType, SyncPingFailureFormattable {
open var description: String {
return "Supplied meta/global for upload did not serialize to valid JSON."
}
open var failureReasonName: SyncPingFailureReasonName {
return .otherError
}
}
open class RecordTooLargeError: MaybeErrorType, SyncPingFailureFormattable {
open let guid: GUID
open let size: ByteCount
open var failureReasonName: SyncPingFailureReasonName {
return .otherError
}
public init(size: ByteCount, guid: GUID) {
self.size = size
self.guid = guid
}
open var description: String {
return "Record \(self.guid) too large: \(size) bytes."
}
}
/**
* Raised when the storage client is refusing to make a request due to a known
* server backoff.
* If you want to bypass this, remove the backoff from the BackoffStorage that
* the storage client is using.
*/
open class ServerInBackoffError: MaybeErrorType, SyncPingFailureFormattable {
fileprivate let until: Timestamp
open var failureReasonName: SyncPingFailureReasonName {
return .otherError
}
open var description: String {
let formatter = DateFormatter()
formatter.dateStyle = .short
formatter.timeStyle = .medium
let s = formatter.string(from: Date.fromTimestamp(self.until))
return "Server in backoff until \(s)."
}
public init(until: Timestamp) {
self.until = until
}
}
// Returns milliseconds. Handles decimals.
private func optionalSecondsHeader(_ input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
if let timestamp = decimalSecondsStringToTimestamp(val) {
return timestamp
}
}
if let seconds: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(seconds * 1000)
}
if let seconds: NSNumber = input as? NSNumber {
// Who knows.
return seconds.uint64Value * 1000
}
return nil
}
private func optionalIntegerHeader(_ input: AnyObject?) -> Int64? {
if input == nil {
return nil
}
if let val = input as? String {
return Scanner(string: val).scanLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Int64(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.int64Value
}
return nil
}
private func optionalUIntegerHeader(_ input: AnyObject?) -> Timestamp? {
if input == nil {
return nil
}
if let val = input as? String {
return Scanner(string: val).scanUnsignedLongLong()
}
if let val: Double = input as? Double {
// Oh for a BigDecimal library.
return Timestamp(val)
}
if let val: NSNumber = input as? NSNumber {
// Who knows.
return val.uint64Value
}
return nil
}
public enum SortOption: String {
case NewestFirst = "newest"
case OldestFirst = "oldest"
case Index = "index"
}
public struct ResponseMetadata {
public let status: Int
public let alert: String?
public let nextOffset: String?
public let records: UInt64?
public let quotaRemaining: Int64?
public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request.
public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp.
public let backoffMilliseconds: UInt64?
public let retryAfterMilliseconds: UInt64?
public init(response: HTTPURLResponse) {
self.init(status: response.statusCode, headers: response.allHeaderFields)
}
init(status: Int, headers: [AnyHashable: Any]) {
self.status = status
alert = headers["X-Weave-Alert"] as? String
nextOffset = headers["X-Weave-Next-Offset"] as? String
records = optionalUIntegerHeader(headers["X-Weave-Records"] as AnyObject?)
quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"] as AnyObject?)
timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"] as AnyObject?) ?? 0
lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"] as AnyObject?)
backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"] as AnyObject?) ??
optionalSecondsHeader(headers["X-Backoff"] as AnyObject?)
retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"] as AnyObject?)
}
}
public struct StorageResponse<T> {
public let value: T
public let metadata: ResponseMetadata
init(value: T, metadata: ResponseMetadata) {
self.value = value
self.metadata = metadata
}
init(value: T, response: HTTPURLResponse) {
self.value = value
self.metadata = ResponseMetadata(response: response)
}
}
public typealias BatchToken = String
public typealias ByteCount = Int
public struct POSTResult {
public let success: [GUID]
public let failed: [GUID: String]
public let batchToken: BatchToken?
public init(success: [GUID], failed: [GUID: String], batchToken: BatchToken? = nil) {
self.success = success
self.failed = failed
self.batchToken = batchToken
}
public static func fromJSON(_ json: JSON) -> POSTResult? {
if json.isError() {
return nil
}
let batchToken = json["batch"].string
if let s = json["success"].array,
let f = json["failed"].dictionary {
var failed = false
let stringOrFail: (JSON) -> String = { $0.string ?? { failed = true; return "" }() }
// That's the basic structure. Now let's transform the contents.
let successGUIDs = s.map(stringOrFail)
if failed {
return nil
}
let failedGUIDs = mapValues(f, f: stringOrFail)
if failed {
return nil
}
return POSTResult(success: successGUIDs, failed: failedGUIDs, batchToken: batchToken)
}
return nil
}
}
public typealias Authorizer = (URLRequest) -> URLRequest
// TODO: don't be so naïve. Use a combination of uptime and wall clock time.
public protocol BackoffStorage {
var serverBackoffUntilLocalTimestamp: Timestamp? { get set }
func clearServerBackoff()
func isInBackoff(_ now: Timestamp) -> Timestamp? // Returns 'until' for convenience.
}
// Don't forget to batch downloads.
open class Sync15StorageClient {
fileprivate let authorizer: Authorizer
fileprivate let serverURI: URL
open static let maxRecordSizeBytes: Int = 262_140 // A shade under 256KB.
open static let maxPayloadSizeBytes: Int = 1_000_000 // A shade under 1MB.
open static let maxPayloadItemCount: Int = 100 // Bug 1250747 will raise this.
var backoff: BackoffStorage
let workQueue: DispatchQueue
let resultQueue: DispatchQueue
public init(token: TokenServerToken, workQueue: DispatchQueue, resultQueue: DispatchQueue, backoff: BackoffStorage) {
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
// This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain.
// We want the serverURI to *not* have a trailing slash: to efficiently wipe a user's storage, we delete
// the user root (like /1.5/1234567) and not an "empty collection" (like /1.5/1234567/); the storage
// server treats the first like a DROP table and the latter like a DELETE *, and the former is more
// efficient than the latter.
self.serverURI = URL(string: token.api_endpoint.hasSuffix("/")
? token.api_endpoint.substring(to: token.api_endpoint.index(before: token.api_endpoint.endIndex))
: token.api_endpoint)!
self.authorizer = {
(r: URLRequest) -> URLRequest in
var req = r
let helper = HawkHelper(id: token.id, key: token.key.data(using: .utf8, allowLossyConversion: false)!)
req.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization")
return req
}
}
public init(serverURI: URL, authorizer: @escaping Authorizer, workQueue: DispatchQueue, resultQueue: DispatchQueue, backoff: BackoffStorage) {
self.serverURI = serverURI
self.authorizer = authorizer
self.workQueue = workQueue
self.resultQueue = resultQueue
self.backoff = backoff
}
func updateBackoffFromResponse<T>(_ response: StorageResponse<T>) {
// N.B., we would not have made this request if a backoff were set, so
// we can safely avoid doing the write if there's no backoff in the
// response.
// This logic will have to change if we ever invalidate that assumption.
if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds {
log.info("Backing off for \(ms)ms.")
self.backoff.serverBackoffUntilLocalTimestamp = ms + Date.now()
}
}
func errorWrap<T, U>(_ deferred: Deferred<Maybe<T>>, handler: @escaping (DataResponse<U>) -> Void) -> (DataResponse<U>) -> Void {
return { response in
log.verbose("Response is \(response.response ??? "nil").")
/**
* Returns true if handled.
*/
func failFromResponse(_ HTTPResponse: HTTPURLResponse?) -> Bool {
guard let HTTPResponse = HTTPResponse else {
// TODO: better error.
log.error("No response")
let result = Maybe<T>(failure: RecordParseError())
deferred.fill(result)
return true
}
log.debug("Status code: \(HTTPResponse.statusCode).")
let storageResponse = StorageResponse(value: HTTPResponse, metadata: ResponseMetadata(response: HTTPResponse))
self.updateBackoffFromResponse(storageResponse)
if HTTPResponse.statusCode >= 500 {
log.debug("ServerError.")
let result = Maybe<T>(failure: ServerError(storageResponse))
deferred.fill(result)
return true
}
if HTTPResponse.statusCode == 404 {
log.debug("NotFound<\(T.self)>.")
let result = Maybe<T>(failure: NotFound(storageResponse))
deferred.fill(result)
return true
}
if HTTPResponse.statusCode >= 400 {
log.debug("BadRequestError.")
let result = Maybe<T>(failure: BadRequestError(request: response.request, response: storageResponse))
deferred.fill(result)
return true
}
return false
}
// Check for an error from the request processor.
if response.result.isFailure {
log.error("Response: \(response.response?.statusCode ?? 0). Got error \(response.result.error ??? "nil").")
// If we got one, we don't want to hit the response nil case above and
// return a RecordParseError, because a RequestError is more fitting.
if let response = response.response {
if failFromResponse(response) {
log.error("This was a failure response. Filled specific error type.")
return
}
}
log.error("Filling generic RequestError.")
deferred.fill(Maybe<T>(failure: RequestError()))
return
}
if failFromResponse(response.response) {
return
}
handler(response)
}
}
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.syncUserAgent
let configuration = URLSessionConfiguration.ephemeral
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = ua
configuration.httpAdditionalHeaders = defaultHeaders
return SessionManager(configuration: configuration)
}()
func requestGET(_ url: URL) -> DataRequest {
var req = URLRequest(url: url as URL)
req.httpMethod = URLRequest.Method.get.rawValue
req.setValue("application/json", forHTTPHeaderField: "Accept")
let authorized: URLRequest = self.authorizer(req)
return alamofire.request(authorized)
.validate(contentType: ["application/json"])
}
func requestDELETE(_ url: URL) -> DataRequest {
var req = URLRequest(url: url as URL)
req.httpMethod = URLRequest.Method.delete.rawValue
req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete")
let authorized: URLRequest = self.authorizer(req)
return alamofire.request(authorized)
}
func requestWrite(_ url: URL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request {
var req = URLRequest(url: url as URL)
req.httpMethod = method
req.setValue(contentType, forHTTPHeaderField: "Content-Type")
if let ifUnmodifiedSince = ifUnmodifiedSince {
req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since")
}
req.httpBody = body.data(using: .utf8)!
let authorized: URLRequest = self.authorizer(req)
return alamofire.request(authorized)
}
func requestPUT(_ url: URL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: URLRequest.Method.put.rawValue, body: body.stringValue()!, contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(_ url: URL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestWrite(url, method: URLRequest.Method.post.rawValue, body: body.stringValue()!, contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(_ url: URL, body: [String], ifUnmodifiedSince: Timestamp?) -> Request {
let content = body.joined(separator: "\n")
return self.requestWrite(url, method: URLRequest.Method.post.rawValue, body: content, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince)
}
func requestPOST(_ url: URL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request {
return self.requestPOST(url, body: body.map { $0.stringValue()! }, ifUnmodifiedSince: ifUnmodifiedSince)
}
/**
* Returns true and fills the provided Deferred if our state shows that we're in backoff.
* Returns false otherwise.
*/
fileprivate func checkBackoff<T>(_ deferred: Deferred<Maybe<T>>) -> Bool {
if let until = self.backoff.isInBackoff(Date.now()) {
deferred.fill(Maybe<T>(failure: ServerInBackoffError(until: until)))
return true
}
return false
}
fileprivate func doOp<T>(_ op: (URL) -> DataRequest, path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
// Special case "": we want /1.5/1234567 and not /1.5/1234567/. See note about trailing slashes above.
let url: URL
if path == "" {
url = self.serverURI // No trailing slash.
} else {
url = self.serverURI.appendingPathComponent(path)
}
let req = op(url)
let handler = self.errorWrap(deferred) { (response: DataResponse<JSON>) in
if let json: JSON = response.result.value {
if let v = f(json) {
let storageResponse = StorageResponse<T>(value: v, response: response.response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
_ = req.responseParsedJSON(true, completionHandler: handler)
return deferred
}
// Sync storage responds with a plain timestamp to a PUT, not with a JSON body.
fileprivate func putResource<T>(_ path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: @escaping (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let url = self.serverURI.appendingPathComponent(path)
return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser)
}
fileprivate func putResource<T>(_ URL: Foundation.URL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: @escaping (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue)
if self.checkBackoff(deferred) {
return deferred
}
let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince) as! DataRequest
let handler = self.errorWrap(deferred) { (response: DataResponse<String>) in
if let data = response.result.value {
if let v = parser(data) {
let storageResponse = StorageResponse<T>(value: v, response: response.response!)
deferred.fill(Maybe(success: storageResponse))
} else {
deferred.fill(Maybe(failure: RecordParseError()))
}
return
}
deferred.fill(Maybe(failure: RecordParseError()))
}
req.responseString(completionHandler: handler)
return deferred
}
fileprivate func getResource<T>(_ path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestGET, path: path, f: f)
}
fileprivate func deleteResource<T>(_ path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> {
return doOp(self.requestDELETE, path: path, f: f)
}
func wipeStorage() -> Deferred<Maybe<StorageResponse<JSON>>> {
// In Sync 1.5 it's preferred that we delete the root, not /storage.
return deleteResource("", f: { $0 })
}
func getInfoCollections() -> Deferred<Maybe<StorageResponse<InfoCollections>>> {
return getResource("info/collections", f: InfoCollections.fromJSON)
}
func getMetaGlobal() -> Deferred<Maybe<StorageResponse<MetaGlobal>>> {
return getResource("storage/meta/global") { json in
// We have an envelope. Parse the meta/global record embedded in the 'payload' string.
let envelope = EnvelopeJSON(json)
if envelope.isValid() {
return MetaGlobal.fromJSON(JSON(parseJSON: envelope.payload))
}
return nil
}
}
func getCryptoKeys(_ syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Record<KeysPayload>>>> {
let syncKey = Keys(defaultBundle: syncKeyBundle)
let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0.json })
let encrypter = syncKey.encrypter("keys", encoder: encoder)
let client = self.clientForCollection("crypto", encrypter: encrypter)
return client.get("keys")
}
func uploadMetaGlobal(_ metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
let payload = metaGlobal.asPayload()
if payload.json.isError() {
return Deferred(value: Maybe(failure: MalformedMetaGlobalError()))
}
let record: JSON = JSON(object: ["payload": payload.json.stringValue() ?? JSON.null as Any, "id": "global"])
return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
// The crypto/keys record is a special snowflake: it is encrypted with the Sync key bundle. All other records are
// encrypted with the bulk key bundle (including possibly a per-collection bulk key) stored in crypto/keys.
func uploadCryptoKeys(_ keys: Keys, withSyncKeyBundle syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
let syncKey = Keys(defaultBundle: syncKeyBundle)
let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0.json })
let encrypter = syncKey.encrypter("keys", encoder: encoder)
let client = self.clientForCollection("crypto", encrypter: encrypter)
let record = Record(id: "keys", payload: keys.asPayload())
return client.put(record, ifUnmodifiedSince: ifUnmodifiedSince)
}
// It would be convenient to have the storage client manage Keys, but of course we need to use a different set of
// keys to fetch crypto/keys itself. See uploadCryptoKeys.
func clientForCollection<T>(_ collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> {
let storage = self.serverURI.appendingPathComponent("storage", isDirectory: true)
return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter)
}
}
private let DefaultInfoConfiguration = InfoConfiguration(maxRequestBytes: 1_048_576,
maxPostRecords: 100,
maxPostBytes: 1_048_576,
maxTotalRecords: 10_000,
maxTotalBytes: 104_857_600)
/**
* We'd love to nest this in the overall storage client, but Swift
* forbids the nesting of a generic class inside another class.
*/
open class Sync15CollectionClient<T: CleartextPayloadJSON> {
fileprivate let client: Sync15StorageClient
fileprivate let encrypter: RecordEncrypter<T>
fileprivate let collectionURI: URL
fileprivate let collectionQueue = DispatchQueue(label: "com.mozilla.sync.collectionclient", attributes: [])
fileprivate let infoConfig = DefaultInfoConfiguration
public init(client: Sync15StorageClient, serverURI: URL, collection: String, encrypter: RecordEncrypter<T>) {
self.client = client
self.encrypter = encrypter
self.collectionURI = serverURI.appendingPathComponent(collection, isDirectory: false)
}
var maxBatchPostRecords: Int {
get {
return infoConfig.maxPostRecords
}
}
fileprivate func uriForRecord(_ guid: String) -> URL {
return self.collectionURI.appendingPathComponent(guid)
}
open func newBatch(ifUnmodifiedSince: Timestamp? = nil, onCollectionUploaded: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) -> Sync15BatchClient<T> {
return Sync15BatchClient(config: infoConfig,
ifUnmodifiedSince: ifUnmodifiedSince,
serializeRecord: self.serializeRecord,
uploader: self.post,
onCollectionUploaded: onCollectionUploaded)
}
// Exposed so we can batch by size.
open func serializeRecord(_ record: Record<T>) -> String? {
return self.encrypter.serializer(record)?.stringValue()
}
open func post(_ lines: [String], ifUnmodifiedSince: Timestamp?, queryParams: [URLQueryItem]? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> {
let deferred = Deferred<Maybe<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let requestURI: URL
if let queryParams = queryParams {
requestURI = self.collectionURI.withQueryParams(queryParams)
} else {
requestURI = self.collectionURI
}
let req = client.requestPOST(requestURI, body: lines, ifUnmodifiedSince: ifUnmodifiedSince) as! DataRequest
_ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in
if let json: JSON = response.result.value,
let result = POSTResult.fromJSON(json) {
let storageResponse = StorageResponse(value: result, response: response.response!)
deferred.fill(Maybe(success: storageResponse))
return
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
open func post(_ records: [Record<T>], ifUnmodifiedSince: Timestamp?, queryParams: [URLQueryItem]? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> {
// TODO: charset
// TODO: if any of these fail, we should do _something_. Right now we just ignore them.
let lines = optFilter(records.map(self.serializeRecord))
return self.post(lines, ifUnmodifiedSince: ifUnmodifiedSince, queryParams: queryParams)
}
open func put(_ record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> {
if let body = self.encrypter.serializer(record) {
return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp)
}
return deferMaybe(RecordParseError())
}
open func get(_ guid: String) -> Deferred<Maybe<StorageResponse<Record<T>>>> {
let deferred = Deferred<Maybe<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue)
if self.client.checkBackoff(deferred) {
return deferred
}
let req = client.requestGET(uriForRecord(guid))
_ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in
if let json: JSON = response.result.value {
let envelope = EnvelopeJSON(json)
let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
if let record = record {
let storageResponse = StorageResponse(value: record, response: response.response!)
deferred.fill(Maybe(success: storageResponse))
return
}
} else {
log.warning("Couldn't parse JSON response.")
}
deferred.fill(Maybe(failure: RecordParseError()))
})
return deferred
}
/**
* Unlike every other Sync client, we use the application/json format for fetching
* multiple requests. The others use application/newlines. We don't want to write
* another Serializer, and we're loading everything into memory anyway.
*
* It is the caller's responsibility to check whether the returned payloads are invalid.
*
* Only non-JSON and malformed envelopes will be dropped.
*/
open func getSince(_ since: Timestamp, sort: SortOption?=nil, limit: Int?=nil, offset: String?=nil) -> Deferred<Maybe<StorageResponse<[Record<T>]>>> {
let deferred = Deferred<Maybe<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue)
// Fills the Deferred for us.
if self.client.checkBackoff(deferred) {
return deferred
}
var params: [URLQueryItem] = [
URLQueryItem(name: "full", value: "1"),
URLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since)),
]
if let offset = offset {
params.append(URLQueryItem(name: "offset", value: offset))
}
if let limit = limit {
params.append(URLQueryItem(name: "limit", value: "\(limit)"))
}
if let sort = sort {
params.append(URLQueryItem(name: "sort", value: sort.rawValue))
}
log.debug("Issuing GET with newer = \(since), offset = \(offset ??? "nil"), sort = \(sort ??? "nil").")
let req = client.requestGET(self.collectionURI.withQueryParams(params))
_ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in
log.verbose("Response is \(response).")
guard let json: JSON = response.result.value else {
log.warning("Non-JSON response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
guard let arr = json.array else {
log.warning("Non-array response.")
deferred.fill(Maybe(failure: RecordParseError()))
return
}
func recordify(_ json: JSON) -> Record<T>? {
let envelope = EnvelopeJSON(json)
return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory)
}
let records = arr.flatMap(recordify)
let response = StorageResponse(value: records, response: response.response!)
deferred.fill(Maybe(success: response))
})
return deferred
}
}
| mpl-2.0 | 1d958c1de6de71d3171c1abba244c993 | 38.15 | 190 | 0.634645 | 4.864828 | false | false | false | false |
Evildime/ForceTranslatingView | ForceTranslatingView.swift | 1 | 1221 | import UIKit
class ForceTranslatingView: UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
updateViewForTouch(touches.first!)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
updateViewForTouch(touches.first!)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
layer.transform = CATransform3DIdentity
}
private func updateViewForTouch(touch: UITouch) {
let forcePercentage = touch.maximumPossibleForce > 0 ? touch.force / touch.maximumPossibleForce : 0.5
let forceWeight = 0.3 + (0.7 * forcePercentage)
let touchLocation = touch.locationInView(self)
let halfWidth = (bounds.width / 2)
let halfHeight = (bounds.height / 2)
let locationFromCenter = CGPointMake(touchLocation.x - halfWidth, touchLocation.y - halfHeight)
let x = (0.0002 * forceWeight * locationFromCenter.x / halfWidth)
let y = (0.0002 * forceWeight * locationFromCenter.y / halfHeight)
layer.transform = transform3DPerspective(x, y: y)
}
func transform3DPerspective(x: CGFloat, y: CGFloat) -> CATransform3D {
var transform = CATransform3DIdentity
transform.m14 = x
transform.m24 = y
return transform
}
}
| mit | 4fbe1e171df900892da0a1a5f6921283 | 30.307692 | 103 | 0.74611 | 3.644776 | false | false | false | false |
dealforest/Cichlid | Cichlid/Cleaner.swift | 1 | 2638 | //
// Cleaner.swift
// Cichlid
//
// Created by Toshihiro Morimoto on 2/29/16.
// Copyright © 2016 Toshihiro Morimoto. All rights reserved.
//
import Foundation
struct Cleaner {
static func clearDerivedDataForProject(_ projectName: String) -> Bool {
let prefix = prefixForDerivedDataRule(projectName)
let paths = derivedDataPaths(prefix)
return removeDirectoriesAtPaths(paths)
}
static func clearAllDerivedData() -> Bool {
let paths = derivedDataPaths()
return removeDirectoriesAtPaths(paths)
}
static func derivedDataPath(_ projectName: String) -> URL? {
let prefix = prefixForDerivedDataRule(projectName)
let paths = derivedDataPaths(prefix)
return paths.first
}
}
extension Cleaner {
fileprivate static func derivedDataPaths(_ prefix: String? = nil) -> [URL] {
var paths = [URL]()
if let derivedDataPath = XcodeHelpers.derivedDataPath() {
do {
let directories = try FileManager.default.contentsOfDirectory(atPath: derivedDataPath)
directories.forEach { directory in
let path = URL(fileURLWithPath: derivedDataPath).appendingPathComponent(directory)
if let prefix = prefix , directory.hasPrefix(prefix) {
paths.append(path)
}
else if prefix == nil {
paths.append(path)
}
}
}
catch {
print("Cichlid: Failed to fetching derived data directories: \(derivedDataPath)")
}
}
return paths
}
fileprivate static func removeDirectoriesAtPaths(_ paths: [URL]) -> Bool {
return paths.reduce(true) { $0 && removeDirectoryAtPath($1) }
}
fileprivate static func removeDirectoryAtPath(_ path: URL) -> Bool {
let fileManager = FileManager.default
do {
try fileManager.removeItem(at: path)
// retry once
if fileManager.fileExists(atPath: path.absoluteString) {
try fileManager.removeItem(at: path)
}
}
catch let error {
print("Cichlid: Failed to remove directory: \(path) -> \(error)")
}
return !FileManager.default.fileExists(atPath: path.absoluteString)
}
fileprivate static func prefixForDerivedDataRule(_ projectName: String) -> String {
let name = projectName.replacingOccurrences(of: " ", with: "_")
return "\(name)-"
}
}
| mit | 9d6bc94e74b2bac22f8751a6e9ffa101 | 31.555556 | 102 | 0.582101 | 5.051724 | false | false | false | false |
kostiakoval/WatchKit-Apps | 5- Shared-CoreData/Shared CoreData/MasterViewController.swift | 8 | 2997 | //
// MasterViewController.swift
// Shared CoreData
//
// Created by Konstantin Koval on 24/12/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
import UIKit
import CoreData
import SharedKit
class MasterViewController: UITableViewController {
var stack: Seru!
var objects: [Record]!
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
objects = DataManager.loadAll(self.stack.stack.mainMOC)
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
let r = DataManager.insertNewRecord(stack.stack.mainMOC)
stack.persist()
objects.insert(r, atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let object = objects[indexPath.row] as Record
(segue.destinationViewController as! DetailViewController).detailItem = object
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let object = objects[indexPath.row]
cell.textLabel!.text = object.timestamp.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let object = objects[indexPath.row]
stack.stack.mainMOC.deleteObject(object)
objects.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
}
| mit | 18a0bf94577180c1c8ed01e1d8dfea08 | 31.225806 | 155 | 0.729062 | 5.003339 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Core/Shared/ComposedOperation.swift | 2 | 1197 | //
// ComposedOperation.swift
// Operations
//
// Created by Daniel Thorpe on 28/08/2015.
// Copyright © 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
public class ComposedOperation<T: NSOperation>: Operation {
public let target: Operation
public var operation: T
public convenience init(_ composed: T) {
self.init(operation: composed)
}
init(operation composed: T) {
self.target = composed as? Operation ?? GroupOperation(operations: [composed])
self.operation = composed
super.init()
name = "Composed Operation"
target.name = target.name ?? "Composed <\(T.self)>"
target.addObserver(DidFinishObserver { [unowned self] _, errors in
self.finish(errors)
})
}
public override func cancel() {
target.cancel()
super.cancel()
}
public override func cancelWithErrors(errors: [ErrorType]) {
target.cancelWithError(OperationError.ParentOperationCancelledWithErrors(errors))
super.cancelWithErrors(errors)
}
public override func execute() {
target.log.severity = log.severity
produceOperation(target)
}
}
| gpl-3.0 | f7fd7f43e06e2f6e8f9ad9cad6e5c7e6 | 25.577778 | 89 | 0.649666 | 4.547529 | false | false | false | false |
kokoroe/kokoroe-sdk-ios | KokoroeSDKTests/KKRMasterRequestTests.swift | 1 | 10347 | //
// KKRGenericRequestTests.swift
// KokoroeSDK
//
// Created by Guillaume Mirambeau on 21/04/2016.
// Copyright © 2016 I know u will. All rights reserved.
//
//import Foundation
import XCTest
import ObjectMapper
@testable import KokoroeSDK
class KKRMasterRequestTests: KokoroeSDKTests {
// MARK: Constants
let testUserID = 9364
let testUserFirstname = "test"
let testUserLastname = "iOS"
let testUserAccessToken = "clZmGwYbiUih8PuF9lwGsR8Y6o7KpuY2HfIHhKnCELbpIA5SywlVwtfmL9f8VyKWF6l8LrD3MUt7dtBc1JIVQxvwgvrOMYuOs3Uf"
let testUserClientID = "08569a22-62dc-11e5-81d4-3776d5f4cf15"
let testUserClientSecret = "2c8e498cae78a3e9475d36bc50a087245d1a06a573bfa6638c366b87c8d5"//"bb051dad8ae598ecda0a47a0e941d58d52bb95afe8a7d4f696ab2bf8f3414acb"
let testUserTracker = "ef95f987-7917-4a04-8feb-be07093bf674"
let testUserEmail = "[email protected]"
let testUserPassword = "KKRiOSTests"
let testCourseID = 2410
let testAddressID = 274
let KKRStripeTestPublishableKey = "pk_test_tcpYspbwDx8Py6Upvv8xR5rx"
// MARK: Lifecycle
override func setUp() {
super.setUp()
self.configureLoggedInUser()
}
// Mark: Tests
func testDefaultHeadersForLoggedInUser() {
self.configureLoggedInUser()
let defaultHeaders = KKRMasterRequest.sharedInstance.defaultHeaders()
XCTAssertTrue(defaultHeaders.keys.count == 3)
XCTAssertTrue(defaultHeaders[KKRHeaderKeyAcceptLanguage] == NSLocale.preferredLanguages()[0])
XCTAssertTrue(defaultHeaders[KKRHeaderKeyTracker] == testUserTracker)
XCTAssertTrue(defaultHeaders[KKRHeaderKeyAuthorization] == (KKRTokenTypeBearer + " " + testUserAccessToken))
}
func testDefaultHeadersForLoggedOutUser() {
self.configureLoggedOutUser()
let defaultHeaders = KKRMasterRequest.sharedInstance.defaultHeaders()
XCTAssertTrue(defaultHeaders.keys.count == 3)
XCTAssertTrue(defaultHeaders[KKRHeaderKeyAcceptLanguage] == NSLocale.preferredLanguages()[0])
XCTAssertTrue(defaultHeaders[KKRHeaderKeyTracker] == testUserTracker)
XCTAssertTrue(defaultHeaders[KKRHeaderKeyAuthorization] == (KKRTokenTypeBasic + " " + testUserClientID.toBase64()))
}
func testConcatenateLoggedIn() {
self.configureLoggedInUser()
let defaultHeaders = KKRMasterRequest.sharedInstance.defaultHeaders()
let concatenateStringURL = KKRMasterRequest.sharedInstance.concatenate("https://api.kokoroe.org", parameters: defaultHeaders)
let expectedStringURL = "https://api.kokoroe.org?Accept-Language=fr-FR&Authorization=Bearer%20clZmGwYbiUih8PuF9lwGsR8Y6o7KpuY2HfIHhKnCELbpIA5SywlVwtfmL9f8VyKWF6l8LrD3MUt7dtBc1JIVQxvwgvrOMYuOs3Uf&X-Kokoroe-Tracker=ef95f987-7917-4a04-8feb-be07093bf674"
XCTAssertTrue(concatenateStringURL == expectedStringURL)
}
func testConcatenateLoggedOut() {
self.configureLoggedOutUser()
//let defaultHeaders = KKRMasterRequest.sharedInstance.defaultHeaders()
//let concatenateStringURL = KKRMasterRequest.sharedInstance.concatenate("https://api.kokoroe.org", parameters: defaultHeaders)
let parameters = ["a": "1", "c": "3", "b": "2"]
let concatenateStringURL = KKRMasterRequest.sharedInstance.concatenate("https://api.kokoroe.org", parameters: parameters)
let expectedStringURL = "https://api.kokoroe.org?a=1&b=2&c=3"
XCTAssertTrue(concatenateStringURL == expectedStringURL)
}
func testSignature() {
let path = "https://api.kokoroe.org/v1.0" + KKRCategoryPathPattern
let parameters = ["a": "1", "c": "3", "b": "2"]
let signature = KKRMasterRequest.sharedInstance.processSignature(fromPath: path, parameters: parameters, clientSecret: testUserClientSecret)
//let expectedSignature = "be3dbf4ea9b4c353f94bc659d8812066f1d68df00280074b6fc02565653ffa00"
let expectedSignature = "198e64eb3f12bc1989f2a1776675ae19cca2917260c8e593cc51c0865c705a76"
XCTAssertTrue(expectedSignature == signature)
}
func testGetRequest() {
let parameters = ["a": "1", "c": "3", "b": "2"]
let request = KKRMasterRequest.sharedInstance.request(.GET, KKRCategoryPathPattern, queryParameters: parameters)
let absoluteStringURL = "https://api.kokoroe.org/v1.0/categories?a=1&b=2&c=3"
//let signature = "c24fe540dada017af0f861d5002fbe07a0f8dda23c67cf54e8dd1241f3e3adde"
let signature = "4287dbc4dada7ff11e0a85636fb8cf5d760cc9f71ea4c0e7ad076f610ab512a6"
XCTAssertTrue(request.request?.URL?.absoluteString == absoluteStringURL)
XCTAssertTrue(request.request?.allHTTPHeaderFields![KKRHeaderKeySignature] == signature)
}
func testPostRequest() {
self.configureLoggedInUser()
let message = KKRMessageContentEntity.init(withCourseID: testCourseID, content: "Test post request iOS")
let parameters = ["a": "1", "c": "3", "b": "2"]
let request = KKRMasterRequest.sharedInstance.request(.POST, KKRThreadsPathPattern, queryParameters: parameters, bodyParameters: message.container)
let absoluteStringURL = "https://api.kokoroe.org/v1.0/threads?pretty=1"
//let signature = "cb58bd17d5f072d7afbe158566284ce851da0343e25fc2c79897edbcb67e7165"
let signature = "c3ce6e8d77e55192f5f361aece0ee1586b96da82950f9afb0b6c55c66df5cdf3"
XCTAssertTrue(request.request?.URL?.absoluteString == absoluteStringURL)
XCTAssertTrue(request.request?.allHTTPHeaderFields![KKRHeaderKeySignature] == signature)
}
// MARK: Configuration
func configureLoggedInUser() {
KKRMasterRequest.sharedInstance.accessToken = testUserAccessToken
KKRMasterRequest.sharedInstance.setupConfig(testUserClientID, clientSecret: testUserClientSecret, shouldSign: true, prettyMode: true, domain: "api.kokoroe.org", version: "/v1.0", tracker: testUserTracker, logger: KKRLogger())
}
func configureLoggedOutUser() {
KKRMasterRequest.sharedInstance.accessToken = nil
KKRMasterRequest.sharedInstance.setupConfig(testUserClientID, clientSecret: testUserClientSecret, shouldSign: true, prettyMode: true, domain: "api.kokoroe.org", version: "/v1.0", tracker: testUserTracker, logger: KKRLogger())
}
// MARK: Default objects
func userTest() -> KKRUserEntity {
let user = KKRUserEntity()
user.firstname = testUserFirstname
user.lastname = testUserLastname
user.email = testUserEmail
user.userID = testUserID
user.password = testUserPassword
return user
}
func addressTest() -> KKRAddressEntity {
let address = KKRAddressEntity()
address.addressID = testAddressID
address.street = "6 rue du sentier"
address.zipcode = "75002"
address.city = "Paris"
address.state = "Ile De France"
address.country = "FR"
return address
}
func courseTest() -> KKRCourseEntity {
let course = KKRCourseEntity()
course.courseID = testCourseID
course.price = 15
return course
}
// MARK: File reader
func string(fromFilename filename: String, type: String) -> String? {
let testBundle = NSBundle(forClass: self.dynamicType)
if let filePath = testBundle.pathForResource(filename, ofType: type) {
//if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) {
if let JSONData = NSData(contentsOfFile: filePath) {
return String(data: JSONData, encoding: NSUTF8StringEncoding)
}
}
return nil
/*
let testBundle = NSBundle(forClass: self.dynamicType)
if let filePath = testBundle.pathForResource("categories", ofType: "json") {
//if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) {
if let JSONData = NSData(contentsOfFile: filePath) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions())// as? Array
let categories = Mapper<KKRCategoryEntity>().mapArray(json)
Log.debug("\(categories)")
} catch {
print(error)
}
}
}
*/
}
// MARK: Mapper
func fileToArray<N: Mappable>(filename: String, type: String) -> [N] {
let dataAsString = string(fromFilename: filename, type: type)
return Mapper<N>().mapArray(dataAsString)!
}
func fileToObject<N: Mappable>(filename: String, type: String) -> N {
let dataAsString = string(fromFilename: filename, type: type)
return Mapper<N>().map(dataAsString)!
}
}
/*
internal class Request {
var request:String?
struct response{
static var data:NSHTTPURLResponse?
static var json:AnyObject?
static var error:NSError?
}
init (request:String){
self.request = request
}
/*
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
completionHandler(NSURLRequest(URL: NSURL(string:self.request!)!), Request.response.data, Request.response.json, Request.response.error)
return self
}*/
internal func responseArray(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
completionHandler(NSURLRequest(URL: NSURL(string:self.request!)!), Request.response.data, Request.response.json, Request.response.error)
return self
}
internal func responseObject(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
completionHandler(NSURLRequest(URL: NSURL(string:self.request!)!), Request.response.data, Request.response.json, Request.response.error)
return self
}
}
*/ | mit | 7f12c209c151400ded002d7c01f93dcc | 43.407725 | 258 | 0.687125 | 4.070024 | false | true | false | false |
toshiapp/toshi-ios-client | Tests/String+AdditionsTests.swift | 1 | 6548 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
@testable import Toshi
import XCTest
class StringAdditionsTests: XCTestCase {
func testEnteringAValidPrefixDoesntCreateAPossibleURL() {
XCTAssertNil("h".asPossibleURLString)
XCTAssertNil("ht".asPossibleURLString)
XCTAssertNil("htt".asPossibleURLString)
XCTAssertNil("http".asPossibleURLString)
XCTAssertNil("http:".asPossibleURLString)
XCTAssertNil("http:/".asPossibleURLString)
XCTAssertNil("http://".asPossibleURLString)
XCTAssertEqual("http://a".asPossibleURLString, "http://a")
XCTAssertNil("https".asPossibleURLString)
XCTAssertNil("https:".asPossibleURLString)
XCTAssertNil("https:/".asPossibleURLString)
XCTAssertNil("https://".asPossibleURLString)
XCTAssertEqual("https://a".asPossibleURLString, "https://a")
XCTAssertNil("f".asPossibleURLString)
XCTAssertNil("ft".asPossibleURLString)
XCTAssertNil("ftp".asPossibleURLString)
XCTAssertNil("ftp:".asPossibleURLString)
XCTAssertNil("ftp:/".asPossibleURLString)
XCTAssertNil("ftp://".asPossibleURLString)
XCTAssertEqual("ftp://a".asPossibleURLString, "ftp://a")
XCTAssertNil("fo".asPossibleURLString)
XCTAssertNil("foo".asPossibleURLString)
XCTAssertNil("foo:".asPossibleURLString)
XCTAssertNil("foo:/".asPossibleURLString)
XCTAssertNil("foo://".asPossibleURLString)
XCTAssertEqual("foo://a".asPossibleURLString, "foo://a")
}
func testAddingSomethingWithADotAndOneExtraCharacterCreatesPossibleURLString() {
XCTAssertNil("foo".asPossibleURLString)
XCTAssertNil("foo.".asPossibleURLString)
XCTAssertEqual("foo.b".asPossibleURLString, "http://foo.b")
}
func testNoCaseCorrectionInPossibleURLStrings() {
XCTAssertEqual("foo.bar".asPossibleURLString, "http://foo.bar")
XCTAssertEqual("Foo.bar".asPossibleURLString, "http://Foo.bar")
XCTAssertEqual("FOO.BAR".asPossibleURLString, "http://FOO.BAR")
}
func testDescribesValueLargerThanZero() {
XCTAssertTrue("1.00".isValidPaymentValue())
XCTAssertTrue("1,00".isValidPaymentValue())
XCTAssertTrue("0.10".isValidPaymentValue())
XCTAssertTrue("0,10".isValidPaymentValue())
XCTAssertFalse("0.00".isValidPaymentValue())
XCTAssertFalse("0,00".isValidPaymentValue())
XCTAssertFalse("-1.00".isValidPaymentValue())
XCTAssertFalse("-1,00".isValidPaymentValue())
XCTAssertFalse("hi".isValidPaymentValue())
}
func testSplittingStringIntoLines() {
let shortString = "foo"
let splitShort = shortString.toLines(count: 3)
XCTAssertEqual(splitShort, """
f
o
o
""")
let mediumString = "HelloThereEllen"
let evenSplitMedium = mediumString.toLines(count: 3)
XCTAssertEqual(evenSplitMedium, """
Hello
There
Ellen
""")
let unevenSplitMedium = mediumString.toLines(count: 2)
XCTAssertEqual(unevenSplitMedium, """
HelloThe
reEllen
""")
let unevenerSplitMedium = mediumString.toLines(count: 4)
XCTAssertEqual(unevenerSplitMedium, """
Hell
oThe
reEl
len
""")
let unevenSupersplitMedium = mediumString.toLines(count: 7)
XCTAssertEqual(unevenSupersplitMedium, """
He
ll
oT
he
re
El
len
""")
}
func testToChecksumEncodedAddress() {
XCTAssertEqual("0x52908400098527886e0f7030069857d2e4169ee7".toChecksumEncodedAddress(), "0x52908400098527886E0F7030069857D2E4169EE7")
XCTAssertEqual("0x8617e340b3d01fa5f11f306f4090fd50e238070d".toChecksumEncodedAddress(), "0x8617E340B3D01FA5F11F306F4090FD50E238070D")
XCTAssertEqual("0xdE709F2102306220921060314715629080e2Fb77".toChecksumEncodedAddress(), "0xde709f2102306220921060314715629080e2fb77")
XCTAssertEqual("0x27b1fdb04752bbc536007a920d24acb045561c26".toChecksumEncodedAddress(), "0x27b1fdb04752bbc536007a920d24acb045561c26")
XCTAssertEqual("0x5aaeb6053f3e94c9b9a09f33669435e7ef1Beaed".toChecksumEncodedAddress(), "0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed")
XCTAssertEqual("0xfb6916095ca1df60bb79ce92ce3ea74c37c5d359".toChecksumEncodedAddress(), "0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359")
XCTAssertEqual("0xdbf03b407c01e7cd3cbea99509d93f8dddc8c6fb".toChecksumEncodedAddress(), "0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB")
XCTAssertEqual("0xd1220a0cf47c7b9be7a2e6ba89f429762e7b9adb".toChecksumEncodedAddress(), "0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb")
XCTAssertNil("Abcd".toChecksumEncodedAddress())
}
func testToDisplayValueWithTokens() {
var decimals: Int = 18
var inputValue = "0x1fbc58a15fb36dfb9"
XCTAssertEqual(inputValue.toDisplayValue(with: decimals), "36.588802574655086521")
inputValue = "0x3a81a92faf"
decimals = 10
XCTAssertEqual(inputValue.toDisplayValue(with: decimals), "25.1283451823")
decimals = 30
XCTAssertEqual(inputValue.toDisplayValue(with: decimals), "0.000000000000000000251283451823")
decimals = 0
XCTAssertEqual(inputValue.toDisplayValue(with: decimals), "251283451823")
}
func testMiddleTruncation() {
let tooShort = "1234567890"
let tooShortAdjusted = tooShort.truncateMiddle()
XCTAssertEqual(tooShort, tooShortAdjusted)
let withShorterCharacters = tooShort.truncateMiddle(charactersOnEitherSide: 2)
XCTAssertEqual(withShorterCharacters, "12...90")
let longEnough = "12345678901"
let longEnoughAdjusted = longEnough.truncateMiddle()
XCTAssertEqual(longEnoughAdjusted, "12345...78901")
let longEnoughCustomTruncation = longEnough.truncateMiddle(truncationString: "HAI")
XCTAssertEqual(longEnoughCustomTruncation, "12345HAI78901")
}
}
| gpl-3.0 | c388718b42d910ef5b7f4e4efa60b83b | 38.684848 | 141 | 0.722205 | 3.865407 | false | true | false | false |
PJayRushton/stats | Stats/AdjustingScrollView.swift | 1 | 4118 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
@objc public protocol AdjustingScrollView {
var scrollViewToAdjust: UIScrollView? { get }
/// Function to implement in extension conforming to `AdjustingScrollView`
@objc func keyboardWillShow(_ notification: Notification)
/// Function to implement in extension conforming to `AdjustingScrollView`
@objc func keyboardDidShow(_ notification: Notification)
/// Function to implement in extension conforming to `AdjustingScrollView`
@objc func keyboardWillHide()
}
public extension AdjustingScrollView where Self: UIViewController {
/**
Call this function in `viewDidLoad` in order to observe keyboard notifications.
- Note: This function registers observers for `UIKeyboardDidShowNotification` and
`UIKeyboardWillHideNotification`
*/
public func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
/**
Call this function from `keyboardWillShow` in order to have the scroll view adjust
its content insets properly. The insets will be based on the height of the keyboard
as contained in the notification payload.
- parameter notification: The `NSNotification` that is delivered containing
information about the keyboard.
*/
public func keyboardWillAppear(_ notification: Notification, in viewController: UIViewController) {
handleKeyboardNotification(notification, viewController: viewController)
}
/**
Call this function from `keyboardDidShow` in order to have the scroll view adjust
its content insets properly. The insets will be based on the height of the keyboard
as contained in the notification payload.
- parameter notification: The `NSNotification` that is delivered containing
information about the keyboard.
*/
public func keyboardDidAppear(_ notification: Notification, in viewController: UIViewController) {
handleKeyboardNotification(notification, viewController: viewController)
}
/**
Call this function from `keyboardWillHide` in order to have the scroll view reset
its content insets back to `UIEdgeInsetsZero`.
*/
public func keyboardWillDisappear() {
let contentInset = UIEdgeInsets.zero
scrollViewToAdjust?.contentInset = contentInset
scrollViewToAdjust?.scrollIndicatorInsets = contentInset
}
}
private extension AdjustingScrollView {
func handleKeyboardNotification(_ notification: Notification, viewController: UIViewController) {
guard let userInfo = (notification as NSNotification).userInfo, let keyboardFrameValue = userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue, let scrollView = scrollViewToAdjust else { return }
let keyboardFrame = keyboardFrameValue.cgRectValue
let convertedScrollViewFrame = scrollView.convert(scrollView.frame, to: viewController.view)
let keyboardHeight = keyboardFrame.size.height
let adjustedKeyboardFrame = CGRect(x: keyboardFrame.origin.x, y: keyboardFrame.origin.y - keyboardHeight, width: keyboardFrame.size.width, height: keyboardHeight)
guard adjustedKeyboardFrame.intersects(convertedScrollViewFrame) else { return }
let heightAdjustment = convertedScrollViewFrame.origin.y + convertedScrollViewFrame.size.height - adjustedKeyboardFrame.origin.y
let contentInset = UIEdgeInsetsMake(0, 0, heightAdjustment, 0)
scrollView.contentInset = contentInset
scrollView.scrollIndicatorInsets = contentInset
}
}
| mit | 9a8c2dd11087f56d18d4a4526a386fdf | 46.534884 | 203 | 0.728963 | 5.630854 | false | false | false | false |
akpw/AKPFlowLayout | AKPFlowLayout/AKPFlowLayout.swift | 1 | 16358 | //
// AKPFlowLayout.swift
// SwiftNetworkImages
//
// Created by Arseniy on 18/5/16.
// Copyright © 2016 Arseniy Kuznetsov. All rights reserved.
//
import UIKit
/**
Global / Sticky / Stretchy Headers using UICollectionViewFlowLayout.
Works for iOS8 and above.
*/
public final class AKPFlowLayout: UICollectionViewFlowLayout {
/// Layout configuration options
public var layoutOptions: AKPLayoutConfigOptions = [.firstSectionIsGlobalHeader,
.firstSectionStretchable,
.sectionsPinToGlobalHeaderOrVisibleBounds]
/// For stretchy headers, allowis limiting amount of stretch
public var firsSectionMaximumStretchHeight = CGFloat.greatestFiniteMagnitude
// MARK: - Initialization
override public init() {
super.init()
// For iOS9, needs to ensure the impl does not interfere with `sectionHeadersPinToVisibleBounds`
// Seems to be no reasonable way yet to use Swift property observers with conditional compilation,
// so falling back to KVO
if #available(iOS 9.0, *) {
addObserver(self, forKeyPath: "sectionHeadersPinToVisibleBounds",
options: .new, context: &AKPFlowLayoutKVOContext)
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
if #available(iOS 9.0, *) {
removeObserver(self, forKeyPath: "sectionHeadersPinToVisibleBounds", context: &AKPFlowLayoutKVOContext)
}
}
// MARK: - 📐Custom Layout
/// - returns: AKPFlowLayoutAttributes class for handling layout attributes
override public class var layoutAttributesClass : AnyClass {
return AKPFlowLayoutAttributes.self
}
/// Returns layout attributes for specified rectangle, with added custom headers
override public func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard shouldDoCustomLayout else { return super.layoutAttributesForElements(in: rect) }
guard var layoutAttributes = super.layoutAttributesForElements(in: rect) as? [AKPFlowLayoutAttributes],
// calculate custom headers that should be confined in the rect
let customSectionHeadersIdxs = customSectionHeadersIdxs(rect) else { return nil }
// add the custom headers to the regular UICollectionViewFlowLayout layoutAttributes
for idx in customSectionHeadersIdxs {
let indexPath = IndexPath(item: 0, section: idx)
if let attributes = super.layoutAttributesForSupplementaryView(
ofKind: UICollectionElementKindSectionHeader,
at: indexPath) as? AKPFlowLayoutAttributes {
layoutAttributes.append(attributes)
}
}
// for section headers, need to adjust their attributes
for attributes in layoutAttributes where
attributes.representedElementKind == UICollectionElementKindSectionHeader {
(attributes.frame, attributes.zIndex) = adjustLayoutAttributes(forSectionAttributes: attributes)
}
return layoutAttributes
}
/// Adjusts layout attributes for the custom section headers
override public func layoutAttributesForSupplementaryView(ofKind elementKind: String,
at indexPath: IndexPath)
-> UICollectionViewLayoutAttributes? {
guard shouldDoCustomLayout else {
return super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) }
guard let sectionHeaderAttributes = super.layoutAttributesForSupplementaryView(
ofKind: elementKind,
at: indexPath)
as? AKPFlowLayoutAttributes else { return nil }
// Adjust section attributes
(sectionHeaderAttributes.frame, sectionHeaderAttributes.zIndex) =
adjustLayoutAttributes(forSectionAttributes: sectionHeaderAttributes)
return sectionHeaderAttributes
}
// MARK: - 🎳Invalidation
/// - returns: `true`, unless running on iOS9 with `sectionHeadersPinToVisibleBounds` set to `true`
override public func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
guard shouldDoCustomLayout else { return super.shouldInvalidateLayout(forBoundsChange: newBounds) }
return true
}
/// Custom invalidation
override public func invalidationContext(forBoundsChange newBounds: CGRect)
-> UICollectionViewLayoutInvalidationContext {
guard shouldDoCustomLayout,
let invalidationContext = super.invalidationContext(forBoundsChange: newBounds)
as? UICollectionViewFlowLayoutInvalidationContext,
let oldBounds = collectionView?.bounds
else { return super.invalidationContext(forBoundsChange: newBounds) }
// Size changes?
if oldBounds.size != newBounds.size {
// re-query the collection view delegate for metrics such as size information etc.
invalidationContext.invalidateFlowLayoutDelegateMetrics = true
}
// Origin changes?
if oldBounds.origin != newBounds.origin {
// find and invalidate sections that would fall into the new bounds
guard let sectionIdxPaths = sectionsHeadersIDxs(forRect: newBounds) else {return invalidationContext}
// then invalidate
let invalidatedIdxPaths = sectionIdxPaths.map { IndexPath(item: 0, section: $0) }
invalidationContext.invalidateSupplementaryElements(
ofKind: UICollectionElementKindSectionHeader, at: invalidatedIdxPaths )
}
return invalidationContext
}
fileprivate var previousStretchFactor = CGFloat(0)
}
// MARK: - 🕶Private Helpers
extension AKPFlowLayout {
fileprivate var shouldDoCustomLayout: Bool {
var requestForCustomLayout = layoutOptions.contains(.firstSectionIsGlobalHeader) ||
layoutOptions.contains(.firstSectionStretchable) ||
layoutOptions.contains(.sectionsPinToGlobalHeaderOrVisibleBounds)
// iOS9 supports sticky headers natively, so we should not
// interfere with the the built-in functionality
if #available(iOS 9.0, *) {
requestForCustomLayout = requestForCustomLayout && !sectionHeadersPinToVisibleBounds
}
return requestForCustomLayout
}
fileprivate func zIndexForSection(_ section: Int) -> Int {
return section > 0 ? 128 : 256
}
// Given a rect, calculates indexes of all confined section headers
// _including_ the custom headers
fileprivate func sectionsHeadersIDxs(forRect rect: CGRect) -> Set<Int>? {
guard let layoutAttributes = super.layoutAttributesForElements(in: rect)
as? [AKPFlowLayoutAttributes] else {return nil}
let sectionsShouldPin = layoutOptions.contains(.sectionsPinToGlobalHeaderOrVisibleBounds)
var headersIdxs = Set<Int>()
for attributes in layoutAttributes
where attributes.visibleSectionHeader(sectionsShouldPin) {
headersIdxs.insert((attributes.indexPath as NSIndexPath).section)
}
if layoutOptions.contains(.firstSectionIsGlobalHeader) {
headersIdxs.insert(0)
}
return headersIdxs
}
// Given a rect, calculates the indexes of confined custom section headers
// _excluding_ the regular headers handled by UICollectionViewFlowLayout
fileprivate func customSectionHeadersIdxs(_ rect: CGRect) -> Set<Int>? {
guard let layoutAttributes = super.layoutAttributesForElements(in: rect),
var sectionIdxs = sectionsHeadersIDxs(forRect: rect) else {return nil}
// remove the sections that should already be taken care of by UICollectionViewFlowLayout
for attributes in layoutAttributes
where attributes.representedElementKind == UICollectionElementKindSectionHeader {
sectionIdxs.remove((attributes.indexPath as NSIndexPath).section)
}
return sectionIdxs
}
// Adjusts layout attributes of section headers
fileprivate func adjustLayoutAttributes(forSectionAttributes
sectionHeadersLayoutAttributes: AKPFlowLayoutAttributes)
-> (CGRect, Int) {
guard let collectionView = collectionView else { return (CGRect.zero, 0) }
let section = (sectionHeadersLayoutAttributes.indexPath as NSIndexPath).section
var sectionFrame = sectionHeadersLayoutAttributes.frame
// 1. Establish the section boundaries:
let (minY, maxY) = boundaryMetrics(forSectionAttributes: sectionHeadersLayoutAttributes)
// 2. Determine the height and insets of the first section,
// in case it's stretchable or serves as a global header
let (firstSectionHeight, firstSectionInsets) = firstSectionMetrics()
// 3. If within the above boundaries, the section should follow content offset
// (adjusting a few more things along the way)
var offset = collectionView.contentOffset.y + collectionView.contentInset.top
if (section > 0) {
// The global section
if layoutOptions.contains(.sectionsPinToGlobalHeaderOrVisibleBounds) {
if layoutOptions.contains(.firstSectionIsGlobalHeader) {
// A global header adjustment
offset += firstSectionHeight + firstSectionInsets.top
}
sectionFrame.origin.y = min(max(offset, minY), maxY)
}
} else {
if layoutOptions.contains(.firstSectionStretchable) && offset < 0 {
// Stretchy header
if firstSectionHeight - offset < firsSectionMaximumStretchHeight {
sectionFrame.size.height = firstSectionHeight - offset
sectionHeadersLayoutAttributes.stretchFactor = fabs(offset)
previousStretchFactor = sectionHeadersLayoutAttributes.stretchFactor
} else {
// need to limit the stretch
sectionFrame.size.height = firsSectionMaximumStretchHeight
sectionHeadersLayoutAttributes.stretchFactor = previousStretchFactor
}
sectionFrame.origin.y += offset + firstSectionInsets.top
} else if layoutOptions.contains(.firstSectionIsGlobalHeader) {
// Sticky header position needs to be relative to the global header
sectionFrame.origin.y += offset + firstSectionInsets.top
} else {
sectionFrame.origin.y = min(max(offset, minY), maxY)
}
}
return (sectionFrame, zIndexForSection(section))
}
fileprivate func boundaryMetrics(
forSectionAttributes sectionHeadersLayoutAttributes: UICollectionViewLayoutAttributes)
-> (CGFloat, CGFloat) {
// get attributes for first and last items in section
guard let collectionView = collectionView else { return (0, 0) }
let section = (sectionHeadersLayoutAttributes.indexPath as NSIndexPath).section
// Trying to use layoutAttributesForItemAtIndexPath for empty section would
// cause EXC_ARITHMETIC in simulator (division by zero items)
let lastInSectionIdx = collectionView.numberOfItems(inSection: section) - 1
if lastInSectionIdx < 0 { return (0, 0) }
guard let attributesForFirstItemInSection = layoutAttributesForItem(
at: IndexPath(item: 0, section: section)),
let attributesForLastItemInSection = layoutAttributesForItem(
at: IndexPath(item: lastInSectionIdx, section: section))
else {return (0, 0)}
let sectionFrame = sectionHeadersLayoutAttributes.frame
// Section Boundaries:
// The section should not be higher than the top of its first cell
let minY = attributesForFirstItemInSection.frame.minY - sectionFrame.height
// The section should not be lower than the bottom of its last cell
let maxY = attributesForLastItemInSection.frame.maxY - sectionFrame.height
return (minY, maxY)
}
fileprivate func firstSectionMetrics() -> (height: CGFloat, insets: UIEdgeInsets) {
guard let collectionView = collectionView else { return (0, UIEdgeInsets.zero) }
// height of the first section
var firstSectionHeight = headerReferenceSize.height
if let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout
, firstSectionHeight == 0 {
firstSectionHeight = delegate.collectionView!(collectionView,
layout: self,
referenceSizeForHeaderInSection: 0).height
}
// insets of the first section
var theSectionInset = sectionInset
if let delegate = collectionView.delegate as? UICollectionViewDelegateFlowLayout
, theSectionInset == UIEdgeInsets.zero {
theSectionInset = delegate.collectionView!(collectionView,
layout: self,
insetForSectionAt: 0)
}
return (firstSectionHeight, theSectionInset)
}
}
// MARK: - KVO check for `sectionHeadersPinToVisibleBounds`
extension AKPFlowLayout {
/// KVO check for `sectionHeadersPinToVisibleBounds`.
/// For iOS9, needs to ensure the impl does not interfere with `sectionHeadersPinToVisibleBounds`
override public func observeValue(forKeyPath keyPath: String?, of object: Any?,
change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &AKPFlowLayoutKVOContext {
if let newValue = change?[NSKeyValueChangeKey.newKey],
let boolValue = newValue as? Bool , boolValue {
print("AKPFlowLayout supports sticky headers by default, therefore " +
"the built-in functionality via sectionHeadersPinToVisibleBounds has been disabled")
if #available(iOS 9.0, *) { sectionHeadersPinToVisibleBounds = false }
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
private extension AKPFlowLayoutAttributes {
// Determines if element is a section, or is a cell in a section with custom header
func visibleSectionHeader(_ sectionsShouldPin: Bool) -> Bool {
let isHeader = representedElementKind == UICollectionElementKindSectionHeader
let isCellInPinnedSection = sectionsShouldPin && ( representedElementCategory == .cell )
return isCellInPinnedSection || isHeader
}
}
private var AKPFlowLayoutKVOContext = 0
| mit | 985470ed944036282c7d575e8bac3100 | 50.408805 | 122 | 0.615121 | 6.294956 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/Room/Views/BubbleCells/Encryption/RoomBubbleCellLayout.swift | 1 | 1435 | /*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
/// MXKRoomBubbleTableViewCell layout constants
@objcMembers
final class RoomBubbleCellLayout: NSObject {
// Reactions
static let reactionsViewTopMargin: CGFloat = 1.0
static let reactionsViewLeftMargin: CGFloat = 55.0
static let reactionsViewRightMargin: CGFloat = 15.0
// Read receipts
static let readReceiptsViewTopMargin: CGFloat = 5.0
static let readReceiptsViewRightMargin: CGFloat = 6.0
static let readReceiptsViewHeight: CGFloat = 12.0
static let readReceiptsViewWidth: CGFloat = 150.0
// Read marker
static let readMarkerViewHeight: CGFloat = 2.0
// Timestamp
static let timestampLabelHeight: CGFloat = 18.0
static let timestampLabelWidth: CGFloat = 39.0
// Others
static let encryptedContentLeftMargin: CGFloat = 15.0
}
| apache-2.0 | c53c96921fe0f76613ab94ec9e023c47 | 28.895833 | 73 | 0.730314 | 4.735974 | false | false | false | false |
gscalzo/PrettyWeather | PrettyWeather/WeatherHourlyForecastView.swift | 1 | 2675 | //
// WeatherHourlyForecastView.swift
// PrettyWeather
//
// Created by Giordano Scalzo on 03/02/2015.
// Copyright (c) 2015 Effective Code. All rights reserved.
//
import Foundation
import Cartography
class WeatherHourlyForecastView: UIView {
private var didSetupConstraints = false
private let scrollView = UIScrollView()
private var forecastCells = Array<WeatherHourForecastView>()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
style()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
if didSetupConstraints {
super.updateConstraints()
return
}
layoutView()
super.updateConstraints()
didSetupConstraints = true
}
}
// MARK: Setup
private extension WeatherHourlyForecastView{
func setup(){
for i in 0..<7 {
let cell = WeatherHourForecastView(frame: CGRectZero)
forecastCells.append(cell)
scrollView.addSubview(cell)
}
scrollView.showsHorizontalScrollIndicator = false
addSubview(scrollView)
}
}
// MARK: Layout
private extension WeatherHourlyForecastView{
func layoutView(){
layout(self) { view in
view.height == 100
}
layout(scrollView) { view in
view.top == view.superview!.top
view.bottom == view.superview!.bottom
view.left == view.superview!.left
view.right == view.superview!.right
}
layout(forecastCells.first!) { view in
view.left == view.superview!.left
}
layout(forecastCells.last!) { view in
view.right == view.superview!.right
}
for idx in 1..<forecastCells.count {
let previousCell = forecastCells[idx-1]
let cell = forecastCells[idx]
layout(previousCell, cell) { view, view2 in
view.right == view2.left + 5
}
}
for cell in forecastCells {
layout(cell) { view in
view.width == view.height
view.height == view.superview!.height
view.top == view.superview!.top
}
}
}
}
// MARK: Style
private extension WeatherHourlyForecastView{
func style(){
}
}
// MARK: Render
extension WeatherHourlyForecastView{
func render(weatherConditions: Array<WeatherCondition>){
for (idx, view) in enumerate(forecastCells) {
view.render(weatherConditions[idx])
}
}
}
| mit | 7601a998a70880b53474937f6bbd1161 | 25.485149 | 65 | 0.589159 | 4.768271 | false | false | false | false |
nathanfjohnson/NFJDemoWindow | NFJDemoWindow/Classes/NFJDemoWindow.swift | 1 | 4813 | /** Copyright (c) 2017 Nathan F Johnson <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
/// A subclass of UIWindow wich will show all the touches a user makes.
public class NFJDemoWindow: UIWindow {
/// The color of the touch incicators.
public var demoColor = #colorLiteral(red: 0.8745098039, green: 0.337254902, blue: 0.1450980392, alpha: 1)
/// The diameter of the circle.
public var circleDiamiter: CGFloat = 45
/// When true, the indicators will show, when false, NFJDemoWindow is just a normal UIWindow
public var activated = true {
didSet {
guard !activated else { return }
for touchIndicator in touchIndicators {
touchIndicator.view.removeFromSuperview()
}
touchIndicators.removeAll()
}
}
/// Here we hold onto all the touchIndicators
private var touchIndicators = [(touch: UITouch, view: UIView)]()
override open func sendEvent(_ event: UIEvent) {
super.sendEvent(event )
if activated && event.type == .touches, let allTouches = event.allTouches {
for touch in allTouches {
updateIndicators(withTouch: touch)
}
}
}
private func updateIndicators(withTouch touch: UITouch) {
switch touch.phase {
case .began:
addIndicatorView(forTouch: touch)
case .moved:
moveIndicatorViews(forTouch: touch)
case .stationary: break // we do nothing for stationary
default:
purgeIndicatorViews(withTouch: touch)
}
}
/// Add a new indicator view on the window at the touch's location.
private func addIndicatorView(forTouch touch: UITouch) {
let touchLocation = touch.location(in: self)
let view = UIView()
view.frame = CGRect(x: touchLocation.x - (circleDiamiter/2),
y: touchLocation.y - (circleDiamiter/2),
width: circleDiamiter,
height: circleDiamiter)
view.backgroundColor = demoColor.withAlphaComponent(0.75)
view.layer.cornerRadius = circleDiamiter/2
view.layer.zPosition = 1000
view.layer.borderColor = demoColor.cgColor
view.layer.borderWidth = 0
view.isUserInteractionEnabled = false
addSubview(view)
touchIndicators.append(touch: touch, view: view)
}
/// This will move the indicator associated with the touch to its new location.
private func moveIndicatorViews(forTouch touch: UITouch) {
for touchIndicator in touchIndicators where touchIndicator.touch == touch {
let touchLocation = touch.location(in: self)
touchIndicator.view.frame = CGRect(x: touchLocation.x - (circleDiamiter/2),
y: touchLocation.y - (circleDiamiter/2),
width: circleDiamiter,
height: circleDiamiter)
}
}
/// This will the indicator of the ended touch (with animation)
private func purgeIndicatorViews(withTouch touch: UITouch) {
var indicatorToDeleteIndex: Int?
for (index, touchIndicator) in touchIndicators.enumerated() where touchIndicator.touch == touch {
indicatorToDeleteIndex = index
touchIndicator.view.backgroundColor = UIColor.clear
UIView.animate(withDuration: 0.25,
delay: 0,
options: UIViewAnimationOptions.curveEaseOut,
animations: { () -> Void in
touchIndicator.view.transform = CGAffineTransform(scaleX: 2, y: 2)
touchIndicator.view.layer.borderWidth = 3
touchIndicator.view.alpha = 0
}, completion: { _ in
touchIndicator.view.removeFromSuperview()
})
}
if let indicatorToDeleteIndex = indicatorToDeleteIndex {
touchIndicators.remove(at: indicatorToDeleteIndex)
}
}
}
| mit | e1a1d0f86a69d60262a4633b76ad12e7 | 39.108333 | 119 | 0.68315 | 4.614573 | false | false | false | false |
michikono/swift-using-typealiases-as-generics-2 | swift-using-typealiases-as-generics-2.playground/Pages/a-typealias-as-a-return-type.xcplaygroundpage/Contents.swift | 1 | 1136 | //: A Typealias as a Return Type
//: ============================
//: [Previous](@previous)
//: You can safely ignore the following code block -- nothing has changed from previous examples
protocol Material {}
struct Wood: Material {}
struct Glass: Material {}
protocol HouseholdThing { }
protocol Furniture: HouseholdThing {
typealias M: Material
func mainMaterial() -> M
}
class Chair: Furniture {
func mainMaterial() -> Wood {
return Wood()
}
}
class Lamp: Furniture {
func mainMaterial() -> Glass {
return Glass()
}
}
//: New code changes
class Pet {}
class Inspector<P> {}
let inspector = Inspector<Pet>()
//: Changing `C: Chair` => `C: Furniture`
class FurnitureInspector<C: Furniture>: Inspector<Pet> {
//: Changing Wood => C.M
func getMaterials(thing: C) -> C.M {
return thing.mainMaterial()
}
}
//: These will now work since the return type of `thing.mainMaterial()` is the same as `C.M`
let inspector2 = FurnitureInspector()
inspector2.getMaterials(Chair())
let inspector3 = FurnitureInspector<Lamp>()
inspector3.getMaterials(Lamp())
//: [Next](@next)
| mit | defcac8d94a13ec4a83b8f883be2f45a | 20.433962 | 96 | 0.650528 | 3.652733 | false | false | false | false |
mleiv/IBIncludedStoryboard | IBIncludedStoryboardDemo/IBIncludedStoryboardDemo/nibs/nib/NibController.swift | 1 | 1440 | //
// NibController.swift
//
// Created by Emily Ivie on 4/11/15.
//
import UIKit
class NibController: UIViewController, IBIncludedSegueableController {
@IBOutlet weak var clickButton: UIButton!
@IBOutlet weak var clickButton2: UIButton!
var storedValue = "Unset"
override func awakeFromNib() {
super.awakeFromNib()
//no longer called, sorry!
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//yes, this works also!
}
@IBAction func clickedButton(sender: UIButton) {
storedValue = sender == clickButton ? "1" : "2"
// you can also set prepareAfterIBIncludedSegue here:
//let someValue = storedValue
//prepareAfterIBIncludedSegue = { (destination) in
// if let includedDestination = destination as? Nib2Controller {
// includedDestination.sentValue = storedValue
// }
//}
parentViewController?.performSegueWithIdentifier("Page 2 Segue", sender: sender)
}
lazy var prepareAfterIBIncludedSegue: PrepareAfterIBIncludedSegueType = { (destination) in
if let includedDestination = destination as? Nib2Controller {
includedDestination.sentValue = self.storedValue
return true
}
return false
}
} | mit | aff5c159f1700f57804f520f69c45423 | 26.711538 | 94 | 0.633333 | 5.198556 | false | false | false | false |
kevinlindkvist/lind | lind/UATerms.swift | 1 | 1317 | //
// UntypedArithmeticUATerms.swift
// lind
//
// Created by Kevin Lindkvist on 8/28/16.
// Copyright © 2016 lindkvist. All rights reserved.
//
public indirect enum UATerm {
case tmTrue
case tmFalse
case ifElse(IfElseUATerm)
case zero
case succ(UATerm)
case pred(UATerm)
case isZero(UATerm)
}
extension UATerm: Equatable {
}
public func ==(lhs: UATerm, rhs: UATerm) -> Bool {
switch (lhs, rhs) {
case (.tmTrue, .tmTrue):
return true
case (.tmFalse, .tmFalse):
return true
case (let .ifElse(left), let .ifElse(right)):
return left == right
case (.zero, .zero):
return true
case (let .succ(left), let .succ(right)):
return left == right
case (let .pred(left), let .pred(right)):
return left == right
case (let .isZero(left), let .isZero(right)):
return left == right
default:
return false
}
}
public struct IfElseUATerm {
let conditional: UATerm
let trueBranch: UATerm
let falseBranch: UATerm
var description: String {
return "if \n\t\(conditional)\nthen\n\t\(trueBranch)\nelse\n\t\(trueBranch)"
}
}
extension IfElseUATerm: Equatable {
}
public func ==(lhs: IfElseUATerm, rhs: IfElseUATerm) -> Bool {
return (lhs.conditional == rhs.conditional) && (lhs.trueBranch == rhs.trueBranch) && (lhs.falseBranch == rhs.falseBranch)
} | apache-2.0 | b44f81ae86935edd6a7513ebf0f6e35b | 21.706897 | 123 | 0.667933 | 3.089202 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Search/SearchViewController.swift | 1 | 4719 | ////
/// SearchViewController.swift
//
class SearchViewController: StreamableViewController {
override func trackerName() -> String? {
let searchFor: String
if isPostSearch {
searchFor = "Posts"
}
else {
searchFor = "Users"
}
return "Search for \(searchFor)"
}
override func trackerStreamInfo() -> (String, String?)? {
return ("search", nil)
}
var searchText: String?
var isPostSearch = true
var isRecentlyVisible = false
private var _mockScreen: SearchScreenProtocol?
var screen: SearchScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
override func loadView() {
let screen = SearchScreen()
screen.delegate = self
screen.showsFindFriends = currentUser != nil
view = screen
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if isRecentlyVisible {
isRecentlyVisible = false
screen.activateSearchField()
}
}
override func viewDidLoad() {
super.viewDidLoad()
let streamKind = StreamKind.simpleStream(endpoint: .searchForPosts(terms: ""), title: "")
streamViewController.streamKind = streamKind
screen.isGridView = streamKind.isGridView
streamViewController.isPullToRefreshEnabled = false
updateInsets()
isRecentlyVisible = true
}
func searchForPosts(_ terms: String) {
screen.searchFor(terms)
}
override func viewForStream() -> UIView {
return screen.viewForStream()
}
override func showNavBars(animated: Bool) {
super.showNavBars(animated: animated)
positionNavBar(
screen.navigationBar,
visible: true,
withConstraint: screen.navigationBarTopConstraint,
animated: animated
)
screen.showNavBars(animated: animated)
updateInsets()
}
override func hideNavBars(animated: Bool) {
super.hideNavBars(animated: animated)
positionNavBar(
screen.navigationBar,
visible: false,
withConstraint: screen.navigationBarTopConstraint,
animated: animated
)
screen.hideNavBars(animated: animated)
updateInsets()
}
private func updateInsets() {
updateInsets(navBar: screen.topInsetView)
}
}
extension SearchViewController: SearchScreenDelegate {
func searchCanceled() {
_ = navigationController?.popViewController(animated: true)
}
func searchFieldCleared() {
showNavBars(animated: false)
searchText = ""
streamViewController.removeAllCellItems()
streamViewController.loadingToken.cancelInitialPage()
}
func searchFieldChanged(_ text: String, isPostSearch: Bool) {
loadEndpoint(text, isPostSearch: isPostSearch)
}
func searchShouldReset() {
}
func toggleChanged(_ text: String, isPostSearch: Bool) {
searchShouldReset()
loadEndpoint(text, isPostSearch: isPostSearch, checkSearchText: false)
}
func gridListToggled(sender: UIButton) {
streamViewController.gridListToggled(sender)
}
func findFriendsTapped() {
let responder: InviteResponder? = findResponder()
responder?.onInviteFriends()
}
private func loadEndpoint(_ text: String, isPostSearch: Bool, checkSearchText: Bool = true) {
guard
text.count > 2, // just.. no (and the server doesn't guard against empty/short searches)
!checkSearchText || searchText != text // a search is already in progress for this text
else { return }
self.isPostSearch = isPostSearch
searchText = text
let endpoint = isPostSearch
? ElloAPI.searchForPosts(terms: text) : ElloAPI.searchForUsers(terms: text)
let streamKind = StreamKind.simpleStream(endpoint: endpoint, title: "")
streamViewController.streamKind = streamKind
streamViewController.removeAllCellItems()
streamViewController.showLoadingSpinner()
streamViewController.loadInitialPage()
trackSearch()
}
func trackSearch() {
guard let text = searchText else { return }
trackScreenAppeared()
if isPostSearch {
if text.hasPrefix("#") {
Tracker.shared.searchFor("hashtags", text)
}
else {
Tracker.shared.searchFor("posts", text)
}
}
else {
Tracker.shared.searchFor("users", text)
}
}
}
| mit | 91637e8a65e7a29a4b298d7bd723b05d | 27.257485 | 101 | 0.622378 | 5.134929 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.