repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
RocketChat/Rocket.Chat.iOS | Pods/MobilePlayer/MobilePlayer/Extensions/UIColor+Hex.swift | 1 | 1933 | //
// UIColor+Extension.swift
// MobilePlayer
//
// Created by Toygar Dündaralp on 27/05/15.
// Copyright (c) 2015 MovieLaLa. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(hex: String) {
var red = CGFloat(0)
var green = CGFloat(0)
var blue = CGFloat(0)
var alpha = CGFloat(1)
if hex.hasPrefix("#") {
let index = hex.index(hex.startIndex, offsetBy: 1)
let hex = String(hex[index...])
let scanner = Scanner(string: hex)
var hexValue = CUnsignedLongLong(0)
if scanner.scanHexInt64(&hexValue) {
switch (hex.count) {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
assert(false, "Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
} else {
assert(false, "Scan hex error")
}
} else {
assert(false, "Invalid RGB string, missing '#' as prefix")
}
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
}
| mit | 1ba637f52ff9cf8e5f274a2d8aa90d4f | 34.777778 | 107 | 0.534679 | 3.5 | false | false | false | false |
BelledonneCommunications/linphone-iphone | Classes/Swift/Conference/Views/ConferenceHistoryDetailsView.swift | 1 | 8096 | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-iphone
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Foundation
import linphonesw
@objc class ConferenceHistoryDetailsView: BackNextNavigationView, UICompositeViewDelegate, UITableViewDataSource {
let participantsListTableView = UITableView()
let organizerTableView = UITableView()
let conectionsListTableView = UITableView()
let participantsLabel = StyledLabel(VoipTheme.conference_scheduling_font, " "+VoipTexts.conference_schedule_participants_list)
let organiserLabel = StyledLabel(VoipTheme.conference_scheduling_font, " "+VoipTexts.conference_schedule_organizer)
let datePicker = StyledDatePicker(pickerMode: .date, readOnly:true)
let timePicker = StyledDatePicker(pickerMode: .time, readOnly:true)
var conferenceData : ScheduledConferenceData? {
didSet {
if let data = conferenceData {
super.titleLabel.text = data.subject.value!
self.participantsListTableView.reloadData()
self.participantsListTableView.removeConstraints().done()
self.participantsListTableView.matchParentSideBorders().alignUnder(view: participantsLabel,withMargin: self.form_margin).done()
self.participantsListTableView.height(Double(data.conferenceInfo.participants.count) * VoipParticipantCell.cell_height).alignParentBottom().done()
datePicker.liveValue = MutableLiveData(conferenceData!.rawDate)
timePicker.liveValue = MutableLiveData(conferenceData!.rawDate)
}
}
}
static let compositeDescription = UICompositeViewDescription(ConferenceHistoryDetailsView.self, statusBar: StatusBarView.self, tabBar: TabBarView.classForCoder(), sideMenu: SideMenuView.self, fullscreen: false, isLeftFragment: false,fragmentWith: HistoryListView.classForCoder())
static func compositeViewDescription() -> UICompositeViewDescription! { return compositeDescription }
func compositeViewDescription() -> UICompositeViewDescription! { return type(of: self).compositeDescription }
override func viewDidLoad() {
super.viewDidLoad(
backAction: {
PhoneMainView.instance().popView(self.compositeViewDescription())
},nextAction: {
},
nextActionEnableCondition: MutableLiveData(false),
title:"")
super.nextButton.isHidden = true
super.backButton.isHidden = UIDevice.ipad()
let schedulingStack = UIStackView()
schedulingStack.axis = .vertical
contentView.addSubview(schedulingStack)
schedulingStack.alignParentTop(withMargin: 2*form_margin).matchParentSideBorders(insetedByDx: form_margin).done()
let scheduleForm = UIView()
schedulingStack.addArrangedSubview(scheduleForm)
scheduleForm.matchParentSideBorders().done()
// Left column (Date)
let leftColumn = UIView()
scheduleForm.addSubview(leftColumn)
leftColumn.matchParentWidthDividedBy(2.2).alignParentLeft(withMargin: form_margin).alignParentTop(withMargin: form_margin).done()
let dateLabel = StyledLabel(VoipTheme.conference_scheduling_font, VoipTexts.conference_schedule_date)
leftColumn.addSubview(dateLabel)
dateLabel.alignParentLeft().alignParentTop(withMargin: form_margin).done()
leftColumn.addSubview(datePicker)
datePicker.alignParentLeft().alignUnder(view: dateLabel,withMargin: form_margin).matchParentSideBorders().done()
leftColumn.wrapContentY().done()
// Right column (Time)
let rightColumn = UIView()
scheduleForm.addSubview(rightColumn)
rightColumn.matchParentWidthDividedBy(2.2).alignParentRight(withMargin: form_margin).alignParentTop().done()
let timeLabel = StyledLabel(VoipTheme.conference_scheduling_font, VoipTexts.conference_schedule_time)
rightColumn.addSubview(timeLabel)
timeLabel.alignParentLeft().alignParentTop(withMargin: form_margin).done()
rightColumn.addSubview(timePicker)
timePicker.alignParentLeft().alignUnder(view: timeLabel,withMargin: form_margin).matchParentSideBorders().done()
rightColumn.wrapContentY().done()
scheduleForm.wrapContentY().done()
// Organiser
organiserLabel.backgroundColor = VoipTheme.voipFormBackgroundColor.get()
contentView.addSubview(organiserLabel)
organiserLabel.matchParentSideBorders().height(form_input_height).alignUnder(view: schedulingStack,withMargin: form_margin*2).done()
organiserLabel.textAlignment = .left
contentView.addSubview(organizerTableView)
organizerTableView.isScrollEnabled = false
organizerTableView.dataSource = self
organizerTableView.register(VoipParticipantCell.self, forCellReuseIdentifier: "VoipParticipantCellSSchedule")
organizerTableView.allowsSelection = false
if #available(iOS 15.0, *) {
organizerTableView.allowsFocus = false
}
organizerTableView.separatorStyle = .singleLine
organizerTableView.separatorColor = VoipTheme.light_grey_color
organizerTableView.tag = 1;
organizerTableView.matchParentSideBorders().height(VoipParticipantCell.cell_height).alignUnder(view: organiserLabel,withMargin: form_margin).done()
// Participants
participantsLabel.backgroundColor = VoipTheme.voipFormBackgroundColor.get()
contentView.addSubview(participantsLabel)
participantsLabel.matchParentSideBorders().height(form_input_height).alignUnder(view: organizerTableView,withMargin: form_margin).done()
participantsLabel.textAlignment = .left
contentView.addSubview(participantsListTableView)
participantsListTableView.isScrollEnabled = false
participantsListTableView.dataSource = self
participantsListTableView.register(VoipParticipantCell.self, forCellReuseIdentifier: "VoipParticipantCellSSchedule")
participantsListTableView.allowsSelection = false
if #available(iOS 15.0, *) {
participantsListTableView.allowsFocus = false
}
participantsListTableView.separatorStyle = .singleLine
participantsListTableView.separatorColor = VoipTheme.light_grey_color
// Goto chat - v2
/*
let chatButton = FormButton(title: VoipTexts.conference_go_to_chat.uppercased(), backgroundStateColors: VoipTheme.primary_colors_background)
contentView.addSubview(chatButton)
chatButton.onClick {
//let chatRoom = ChatRoom()
//PhoneMainView.instance().go(to: chatRoom?.getCobject)
}
chatButton.centerX().alignParentBottom(withMargin: 3*self.form_margin).alignUnder(view: participantsListTableView,withMargin: 3*self.form_margin).done()
*/
}
// Objc - bridge, as can't access easily to the view model.
@objc func setCallLog(callLog:OpaquePointer) {
let log = CallLog.getSwiftObject(cObject: callLog)
if let conferenceInfo = log.conferenceInfo {
self.conferenceData = ScheduledConferenceData(conferenceInfo: conferenceInfo)
}
}
// TableView datasource delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let data = conferenceData else {
return 0
}
return tableView.tag == 1 ? 1 : data.conferenceInfo.participants.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:VoipParticipantCell = tableView.dequeueReusableCell(withIdentifier: "VoipParticipantCellSSchedule") as! VoipParticipantCell
guard let data = conferenceData else {
return cell
}
cell.selectionStyle = .none
cell.scheduleConfParticipantAddress = tableView.tag == 1 ? data.conferenceInfo.participants.filter {$0.weakEqual(address2: data.conferenceInfo.organizer!)}.first : data.conferenceInfo.participants[indexPath.row]
cell.limeBadge.isHidden = true
return cell
}
}
| gpl-3.0 | b2fcb02062bb8c931cce3607e7179fde | 41.835979 | 280 | 0.788167 | 4.115913 | false | false | false | false |
rnystrom/GitHawk | Classes/Systems/ScrollViewKeyboardAdjuster.swift | 1 | 2534 | //
// ScrollViewKeyboardAdjuster.swift
// Freetime
//
// Created by Ryan Nystrom on 11/7/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
final class ScrollViewKeyboardAdjuster {
private let scrollView: UIScrollView
private var originalContentInset: UIEdgeInsets = .zero
private weak var viewController: UIViewController?
private var keyboardIsShowing = false
init(scrollView: UIScrollView, viewController: UIViewController) {
self.scrollView = scrollView
self.viewController = viewController
let nc = NotificationCenter.default
nc.addObserver(
self,
selector: #selector(onKeyboardWillShow(notification:)),
name: .UIKeyboardWillShow,
object: nil
)
nc.addObserver(
self,
selector: #selector(onKeyboardWillHide(notification:)),
name: .UIKeyboardWillHide,
object: nil
)
}
// MARK: Notifications
@objc func onKeyboardWillShow(notification: NSNotification) {
guard !keyboardIsShowing,
let frame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect,
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval,
let viewController = self.viewController
else { return }
keyboardIsShowing = true
var inset = scrollView.contentInset
originalContentInset = inset
let converted = viewController.view.convert(frame, from: nil)
let intersection = converted.intersection(frame)
let bottomInset = intersection.height - viewController.view.safeAreaInsets.bottom
inset.bottom = bottomInset
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState], animations: {
self.scrollView.contentInset = inset
self.scrollView.scrollIndicatorInsets = inset
})
}
@objc func onKeyboardWillHide(notification: NSNotification) {
guard keyboardIsShowing,
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval
else { return }
keyboardIsShowing = false
UIView.animate(withDuration: duration, delay: 0, options: [.beginFromCurrentState], animations: {
self.scrollView.contentInset = self.originalContentInset
self.scrollView.scrollIndicatorInsets = self.originalContentInset
})
}
}
| mit | c1618faba765e15ccbe09bcc9952731a | 32.328947 | 107 | 0.672325 | 5.743764 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01309-resolvetypedecl.swift | 1 | 628 | // 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
protocol A {
typealias B
}
class C<D> {
init <A: A where A.B == D>(e: A.B) {
P {
}
struct d<f : e, g: e where g.h == f.h> {
}
class A {
class func a() -> String {
struct c {
static let d: String = {
}
}
}
func b<T>(t: s d<c>: NSO
| apache-2.0 | cdb6418327106d7fad501d0940cd668d | 24.12 | 79 | 0.673567 | 3.033816 | false | false | false | false |
ben-ng/swift | test/SILGen/dso_handle.swift | 7 | 1073 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
// CHECK: sil_global hidden_external [[DSO:@__dso_handle]] : $Builtin.RawPointer
// CHECK-LABEL: sil @main : $@convention(c)
// CHECK: bb0
// CHECK: [[DSOAddr:%[0-9]+]] = global_addr [[DSO]] : $*Builtin.RawPointer
// CHECK-NEXT: [[DSOPtr:%[0-9]+]] = address_to_pointer [[DSOAddr]] : $*Builtin.RawPointer to $Builtin.RawPointer
// CHECK-NEXT: [[DSOPtrStruct:[0-9]+]] = struct $UnsafeRawPointer ([[DSOPtr]] : $Builtin.RawPointer)
// CHECK-LABEL: sil hidden @_TIF10dso_handle14printDSOHandleFT3dsoSV_SVA_
// CHECK: [[DSOAddr:%[0-9]+]] = global_addr [[DSO]] : $*Builtin.RawPointer
// CHECK-NEXT: [[DSOPtr:%[0-9]+]] = address_to_pointer [[DSOAddr]] : $*Builtin.RawPointer to $Builtin.RawPointer
// CHECK-NEXT: [[DSOPtrStruct:%[0-9]+]] = struct $UnsafeRawPointer ([[DSOPtr]] : $Builtin.RawPointer)
// CHECK-NEXT: return [[DSOPtrStruct]] : $UnsafeRawPointer
func printDSOHandle(dso: UnsafeRawPointer = #dsohandle) -> UnsafeRawPointer {
print(dso)
return dso
}
_ = printDSOHandle()
| apache-2.0 | f0d5372aa0309093c29526b554ef7f16 | 45.652174 | 112 | 0.678472 | 3.212575 | false | false | false | false |
fleurdeswift/video-clip-annotation-editor | VideoClipAnnotationEditor/VideoClipLineEntryView.swift | 1 | 6530 | //
// VideoClipLineEntryView.swift
// VideoClipAnnotationEditor
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Foundation
import ExtraDataStructures
private func generateSelectionBlock(cornerRadius: CGFloat) -> (rect: NSRect) -> Bool {
let borderColor = NSColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1);
let lineColor = NSColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1);
return { (rect: NSRect) -> Bool in
var nrect = rect;
nrect.origin.x += 1;
nrect.origin.y += 1;
nrect.size.width -= 2;
nrect.size.height -= 2;
let bezierPath = NSBezierPath(roundedRect:nrect, radius:cornerRadius);
bezierPath.lineWidth = 2;
borderColor.set();
bezierPath.stroke();
let t = rect.height / 3;
let leftLine = NSBezierPath(rect: NSRect(x: rect.origin.x + 0.5, y: rect.origin.y + t + 4, width: 1, height: t))
lineColor.set();
leftLine.fill();
let rightLine = NSBezierPath(rect: NSRect(x: rect.maxX - 1.5, y: rect.origin.y + t + 4, width: 1, height: t))
rightLine.fill();
return true;
};
}
private func generateSelectionImage(cornerRadius: CGFloat) -> NSImage {
let image = NSImage(size: NSSize(width: 32, height: 80), flipped: true, drawingHandler: generateSelectionBlock(cornerRadius))
image.capInsets = NSEdgeInsetsMake(35, 14, 35, 14);
image.resizingMode = NSImageResizingMode.Tile;
return image;
}
private let selectionImage = generateSelectionImage(4);
public class VideoClipLineEntryView : NSView {
internal var entry: VideoClipLineEntry!;
// MARK: Current Time
internal var currentTime: NSTimeInterval? {
didSet {
if NSTimeInterval.equalsWithAccuracy(oldValue, currentTime, accuracy: 0.01) {
return;
}
if let t = currentTime {
if entry.time.contains(t) {
currentTimeX = entry.positionInView(t);
}
else {
currentTimeX = nil;
}
}
else {
currentTimeX = nil;
}
self.needsDisplay = true;
}
}
internal var currentTimeX: CGFloat?;
// MARK: Selection
internal var selection: TimeRange? {
didSet {
if let t = selection {
if entry.time.intersects(t) {
selectionX = entry.positionInViewUnclampled(t);
}
else {
selectionX = nil;
}
}
else {
selectionX = nil;
}
self.window?.invalidateCursorRectsForView(self);
self.needsDisplay = true;
}
}
internal var selectionX: NSRange?;
public override func resetCursorRects() {
if let selx = selectionX {
let b = self.bounds;
addCursorRect(NSRect(x: CGFloat(selx.location), y: 0, width: 4, height: b.size.height), cursor: NSCursor.resizeLeftCursor());
addCursorRect(NSRect(x: CGFloat(selx.end - 4), y: 0, width: 4, height: b.size.height), cursor: NSCursor.resizeRightCursor());
}
}
// MARK: Drawing
internal init(frame: NSRect, entry: VideoClipLineEntry) {
self.entry = entry;
super.init(frame: frame);
}
public required init?(coder: NSCoder) {
super.init(coder: coder);
}
public func previewCacheUpdated(time: NSTimeInterval) {
if entry.previews.count == 0 {
return;
}
if (time >= entry.previews[0].time) &&
(time <= entry.time.end) {
self.needsDisplay = true;
}
}
public override func drawRect(dirtyRect: NSRect) {
let rect = self.bounds;
switch (entry.edge) {
case .Complete:
NSBezierPath(roundedRect: rect, radius: 2.5).setClip();
break;
case .Partial:
break;
case .Start:
NSBezierPath(roundedLeftRect: rect, radius: 2.5).setClip();
break;
case .End:
NSBezierPath(roundedRightRect: rect, radius: 2.5).setClip();
break;
}
if let context = NSGraphicsContext.currentContext()?.CGContext, let cache = (self.superview as? VideoClipView)?.cache {
var rect = CGRect(x: 0, y: 0, width: entry.previewWidth, height: rect.size.height);
for preview in entry.previews {
rect.origin.x = preview.x;
if let image = cache.get(entry.clip, time: preview.time) {
CGContextDrawImage(context, rect, image);
}
else {
NSColor.blackColor().setFill();
NSRectFill(rect);
}
}
}
else {
NSColor.blackColor().setFill();
NSRectFill(rect);
}
// Current time
if let ctx = currentTimeX {
var skip = false;
if let superview = self.superview as? VideoClipView {
skip = superview.dragging;
}
if !skip {
NSColor.whiteColor().set();
NSRectFill(NSRect(x: ctx, y: 0, width: 1, height: rect.size.height))
}
}
// Selection
if let selx = selectionX {
selectionImage.drawInRect(NSRect(
x: CGFloat(selx.location),
y: rect.origin.y,
width: CGFloat(selx.length),
height: rect.size.height));
}
}
public func time(x: CGFloat) -> NSTimeInterval {
return entry.time(x);
}
public func position(t: NSTimeInterval) -> CGFloat {
return entry.positionInView(t);
}
internal func selectionHandle(x: CGFloat) -> VideoClipView.HitHandle {
if let selx = selectionX {
if between(x, CGFloat(selx.location), CGFloat(selx.location + 4)) {
return .Left;
}
else if between(x, CGFloat(selx.end - 4), CGFloat(selx.end)) {
return .Right;
}
}
return .None;
}
public override var acceptsFirstResponder: Bool {
get {
return true;
}
}
}
| mit | d63e50528fb18232e45d86c26f28645d | 29.082949 | 138 | 0.525276 | 4.465116 | false | false | false | false |
erduoniba/FDDUITableViewDemoSwift | FDDUITableViewDemoSwift/FDDBaseRepo/FDDPullToRefresher.swift | 1 | 4192 | //
// FDDPullToRefresher.swift
// PullToRefreshDemo
//
// Created by denglibing on 2017/3/13.
// Copyright © 2017年 Yalantis. All rights reserved.
// Demo: https://github.com/erduoniba/FDDUITableViewDemoSwift
//
import UIKit
import QuartzCore
import PullToRefresh
// 使用教程 https://yalantis.com/blog/how-we-built-customizable-pull-to-refresh-pull-to-cook-soup-animation/
public class FDDPullToRefresher: PullToRefresh {
convenience init(at position: Position) {
let refreshView = FDDPullToRefreshViewer(at: position)
let animator = FDDPullToRefreshAnimator(refreshView: refreshView)
self.init(refreshView: refreshView, animator: animator, height:refreshView.frame.size.height, position: position)
//springDamping的范围为0.0f到1.0f,数值越小「弹簧」的振动效果越明显
self.springDamping = 1
//initialSpringVelocity则表示初始的速度,数值越大一开始移动越快
self.initialSpringVelocity = 0
}
}
// MARK: 自定义的PullToRefreshView
public class FDDPullToRefreshViewer: UIView {
var fddIcon = UIImageView()
var fddCircle = UIImageView()
var fddState = UILabel()
var fddPostion = Position.top
convenience init(at position: Position) {
self.init(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
fddPostion = position
fddCircle.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
fddCircle.image = UIImage(named: "fdd_logo_refresh_circle", in: Bundle(for: FDDPullToRefreshViewer.self), compatibleWith: nil)
self.addSubview(fddCircle)
fddIcon.frame = CGRect(x: 0, y: 0, width: 15, height: 15)
fddIcon.image = UIImage(named: "fdd_logo_refresh", in: Bundle(for: FDDPullToRefreshViewer.self), compatibleWith: nil)
self.addSubview(fddIcon)
fddState.frame = CGRect(x: 0, y: 0, width: 100, height: 20)
fddState.text = "继续下拉刷新"
fddState.font = UIFont.systemFont(ofSize: 13)
fddState.textColor = UIColor(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0)
self.addSubview(fddState)
}
override public func layoutSubviews() {
super.layoutSubviews()
if fddPostion == .top {
fddIcon.center = CGPoint(x: self.frame.size.width / 2 - 42, y: self.frame.size.height / 2)
fddCircle.center = fddIcon.center
fddState.frame = CGRect(x: self.frame.size.width / 2 - 10, y: (self.frame.size.height - 20) / 2.0, width: 100, height: 20)
fddState.isHidden = false
}
else if fddPostion == .bottom {
fddIcon.center = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
fddCircle.center = fddIcon.center
fddState.isHidden = true
}
}
public func startAnimation() {
let rotationAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: Double.pi * 2)
rotationAnimation.duration = 1
rotationAnimation.isCumulative = false
rotationAnimation.repeatCount = MAXFLOAT
fddCircle.layer.add(rotationAnimation, forKey: "rotationAnimation")
fddState.text = "刷新中"
}
public func stopAnimation() {
fddCircle.layer.removeAllAnimations()
fddState.text = "继续下拉刷新"
}
}
// MARK: 自定义PullToRefreshView的动画(Animator)
public class FDDPullToRefreshAnimator: NSObject, RefreshViewAnimator {
private let refreshView: FDDPullToRefreshViewer
init(refreshView: FDDPullToRefreshViewer) {
self.refreshView = refreshView
}
// MARK: RefreshViewAnimator protocol
public func animate(_ state: State) {
switch state {
case .initial:
self.refreshView.stopAnimation()
break
//case .releasing(let progress):
case .releasing:
self.refreshView.stopAnimation()
break
case .loading:
self.refreshView.startAnimation()
break
case .finished:
self.refreshView.stopAnimation()
break
}
}
}
| mit | 6f1e5b798bcaf6c56da26c0685f0ce99 | 33.008403 | 134 | 0.6553 | 3.86533 | false | false | false | false |
naokits/my-programming-marathon | iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift | 60 | 2975 | //
// TakeUntil.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class TakeUntilSinkOther<ElementType, Other, O: ObserverType where O.E == ElementType>
: ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Parent = TakeUntilSink<ElementType, Other, O>
typealias E = Other
private let _parent: Parent
var _lock: NSRecursiveLock {
return _parent._lock
}
private let _subscription = SingleAssignmentDisposable()
init(parent: Parent) {
_parent = parent
#if TRACE_RESOURCES
AtomicIncrement(&resourceCount)
#endif
}
func on(event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next:
_parent.forwardOn(.Completed)
_parent.dispose()
case .Error(let e):
_parent.forwardOn(.Error(e))
_parent.dispose()
case .Completed:
_parent._open = true
_subscription.dispose()
}
}
#if TRACE_RESOURCES
deinit {
AtomicDecrement(&resourceCount)
}
#endif
}
class TakeUntilSink<ElementType, Other, O: ObserverType where O.E == ElementType>
: Sink<O>
, LockOwnerType
, ObserverType
, SynchronizedOnType {
typealias E = ElementType
typealias Parent = TakeUntil<E, Other>
private let _parent: Parent
let _lock = NSRecursiveLock()
// state
private var _open = false
init(parent: Parent, observer: O) {
_parent = parent
super.init(observer: observer)
}
func on(event: Event<E>) {
synchronizedOn(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next:
forwardOn(event)
case .Error:
forwardOn(event)
dispose()
case .Completed:
forwardOn(event)
dispose()
}
}
func run() -> Disposable {
let otherObserver = TakeUntilSinkOther(parent: self)
let otherSubscription = _parent._other.subscribe(otherObserver)
otherObserver._subscription.disposable = otherSubscription
let sourceSubscription = _parent._source.subscribe(self)
return StableCompositeDisposable.create(sourceSubscription, otherObserver._subscription)
}
}
class TakeUntil<Element, Other>: Producer<Element> {
private let _source: Observable<Element>
private let _other: Observable<Other>
init(source: Observable<Element>, other: Observable<Other>) {
_source = source
_other = other
}
override func run<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
let sink = TakeUntilSink(parent: self, observer: observer)
sink.disposable = sink.run()
return sink
}
} | mit | 402663c0bad1a395ddab47da737ab09f | 23.791667 | 96 | 0.6039 | 4.575385 | false | false | false | false |
yonasstephen/swift-of-airbnb | airbnb-main/airbnb-main/AirbnbMapItemCell.swift | 1 | 4031 | //
// AirbnbMapItemCell.swift
// airbnb-main
//
// Created by Yonas Stephen on 3/7/17.
// Copyright © 2017 Yonas Stephen. All rights reserved.
//
import UIKit
class AirbnbMapItemCell: BaseCollectionCell {
var home: AirbnbHome? {
didSet {
imageView.image = UIImage(named: home!.imageName)
priceLabel.text = "$\(home!.price)"
descriptionLabel.text = home?.homeDescription
reviewCountLabel.text = "\(home!.reviewCount) Reviews"
ratingView.rating = home!.rating
}
}
var homeDescription: String? {
didSet {
descriptionLabel.text = homeDescription
}
}
var imageView: UIImageView = {
let view = UIImageView()
view.translatesAutoresizingMaskIntoConstraints = false
view.contentMode = .scaleAspectFill
view.clipsToBounds = true
return view
}()
var priceLabel: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.font = UIFont.boldSystemFont(ofSize: 14)
view.textColor = UIColor.black
return view
}()
var descriptionLabel: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.font = UIFont.systemFont(ofSize: 14)
view.textColor = UIColor.gray
return view
}()
var ratingView: AirbnbReview = {
let view = AirbnbReview()
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
var reviewCountLabel: UILabel = {
let view = UILabel()
view.translatesAutoresizingMaskIntoConstraints = false
view.font = UIFont.boldSystemFont(ofSize: 10)
view.textColor = UIColor.darkGray
return view
}()
override func setupViews() {
addSubview(imageView)
imageView.topAnchor.constraint(equalTo: topAnchor, constant: 15).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 120).isActive = true
imageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true
imageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
addSubview(priceLabel)
priceLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 5).isActive = true
priceLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
priceLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true
priceLabel.widthAnchor.constraint(equalToConstant: 40).isActive = true
addSubview(descriptionLabel)
descriptionLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 5).isActive = true
descriptionLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
descriptionLabel.leftAnchor.constraint(equalTo: priceLabel.rightAnchor).isActive = true
descriptionLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
addSubview(ratingView)
ratingView.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0).isActive = true
ratingView.heightAnchor.constraint(equalToConstant: 20).isActive = true
ratingView.leftAnchor.constraint(equalTo: leftAnchor, constant: 15).isActive = true
ratingView.widthAnchor.constraint(equalToConstant: ratingView.starSize * CGFloat(ratingView.stars.count)).isActive = true
addSubview(reviewCountLabel)
reviewCountLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 0).isActive = true
reviewCountLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
reviewCountLabel.leftAnchor.constraint(equalTo: ratingView.rightAnchor, constant: 5).isActive = true
reviewCountLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true
}
}
| mit | a2bb119c35e2958dedf5c725d5a9afbc | 37.018868 | 129 | 0.671464 | 5.431267 | false | false | false | false |
wenghengcong/Coderpursue | BeeFun/BeeFun/Model/Other/ObjSettings.swift | 1 | 774 | //
// ObjSettings.swift
// BeeFun
//
// Created by wenghengcong on 16/1/19.
// Copyright © 2016年 JungleSong. All rights reserved.
//
import UIKit
class ObjSettings: NSObject {
var itemKey: String?
var itemName: String?
var itemValue: String?
var itemIcon: String?
var itemDisclosure: Bool?
override func setValue(_ value: Any?, forUndefinedKey key: String) {
return
}
override func setValuesForKeys(_ keyedValues: [String : Any]) {
itemKey = keyedValues["itemKey"] as? String
itemName = keyedValues["itemName"] as? String
itemValue = keyedValues["itemValue"] as? String
itemIcon = keyedValues["itemIcon"] as? String
itemDisclosure = keyedValues["itemDisclosure"] as? Bool
}
}
| mit | 62732af944967a0012664eb7b18566d2 | 23.09375 | 72 | 0.656291 | 4.167568 | false | false | false | false |
jacobwhite/firefox-ios | Storage/SQL/SQLiteBookmarksHelpers.swift | 5 | 2670 | /* 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
public func titleForSpecialGUID(_ guid: GUID) -> String? {
switch guid {
case BookmarkRoots.RootGUID:
return "<Root>"
case BookmarkRoots.MobileFolderGUID:
return BookmarksFolderTitleMobile
case BookmarkRoots.ToolbarFolderGUID:
return BookmarksFolderTitleToolbar
case BookmarkRoots.MenuFolderGUID:
return BookmarksFolderTitleMenu
case BookmarkRoots.UnfiledFolderGUID:
return BookmarksFolderTitleUnsorted
default:
return nil
}
}
class BookmarkURLTooLargeError: MaybeErrorType {
init() {
}
var description: String {
return "URL too long to bookmark."
}
}
extension String {
public func truncateToUTF8ByteCount(_ keep: Int) -> String {
let byteCount = self.lengthOfBytes(using: .utf8)
if byteCount <= keep {
return self
}
let toDrop = keep - byteCount
// If we drop this many characters from the string, we will drop at least this many bytes.
// That's aggressive, but that's OK for our purposes.
guard let endpoint = self.index(self.endIndex, offsetBy: toDrop, limitedBy: self.startIndex) else {
return ""
}
return String(self[..<endpoint])
}
}
extension SQLiteBookmarks: ShareToDestination {
public func addToMobileBookmarks(_ url: URL, title: String, favicon: Favicon?) -> Success {
if url.absoluteString.lengthOfBytes(using: .utf8) > AppConstants.DB_URL_LENGTH_MAX {
return deferMaybe(BookmarkURLTooLargeError())
}
let title = title.truncateToUTF8ByteCount(AppConstants.DB_TITLE_LENGTH_MAX)
return isBookmarked(String(describing: url), direction: Direction.local)
>>== { yes in
guard !yes else { return succeed() }
return self.insertBookmark(url, title: title, favicon: favicon,
intoFolder: BookmarkRoots.MobileFolderGUID,
withTitle: BookmarksFolderTitleMobile)
}
}
public func shareItem(_ item: ShareItem) -> Success {
// We parse here in anticipation of getting real URLs at some point.
if let url = item.url.asURL {
let title = item.title ?? url.absoluteString
return self.addToMobileBookmarks(url, title: title, favicon: item.favicon)
}
return succeed()
}
}
| mpl-2.0 | 7f14f2a7c0ddb94e1275cab40a475f53 | 34.6 | 107 | 0.640075 | 4.845735 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/SiteSegmentsService.swift | 1 | 2864 |
import Foundation
import WordPressKit
/// Abstracts the service to obtain site types
typealias SiteSegmentsServiceCompletion = (SiteSegmentsResult) -> Void
protocol SiteSegmentsService {
func siteSegments(completion: @escaping SiteSegmentsServiceCompletion)
}
// MARK: - SiteSegmentsService
final class SiteCreationSegmentsService: LocalCoreDataService, SiteSegmentsService {
// MARK: Properties
/// A facade for WPCOM services.
private let remoteService: WordPressComServiceRemote
// MARK: LocalCoreDataService
override init(managedObjectContext context: NSManagedObjectContext) {
let api: WordPressComRestApi
if let account = try? WPAccount.lookupDefaultWordPressComAccount(in: context) {
api = account.wordPressComRestV2Api
} else {
api = WordPressComRestApi.anonymousApi(userAgent: WPUserAgent.wordPress(), localeKey: WordPressComRestApi.LocaleKeyV2)
}
self.remoteService = WordPressComServiceRemote(wordPressComRestApi: api)
super.init(managedObjectContext: context)
}
// MARK: SiteSegmentsService
func siteSegments(completion: @escaping SiteSegmentsServiceCompletion) {
remoteService.retrieveSegments(completion: { result in
completion(result)
})
}
}
// MARK: - Mock
/// Mock implementation of the SeiteSegmentsService
final class MockSiteSegmentsService: SiteSegmentsService {
func siteSegments(completion: @escaping SiteSegmentsServiceCompletion) {
let result = SiteSegmentsResult.success(mockSiteTypes)
completion(result)
}
lazy var mockSiteTypes: [SiteSegment] = {
return [ shortSubtitle(identifier: 1),
longSubtitle(identifier: 2),
shortSubtitle(identifier: 3),
shortSubtitle(identifier: 4) ]
}()
var mockCount: Int {
return mockSiteTypes.count
}
private func shortSubtitle(identifier: Int64) -> SiteSegment {
return SiteSegment(identifier: identifier,
title: "Blogger",
subtitle: "Publish a collection of posts",
icon: URL(string: "https://s.w.org/style/images/about/WordPress-logotype-standard.png")!,
iconColor: "#FF0000",
mobile: true)
}
private func longSubtitle(identifier: Int64) -> SiteSegment {
return SiteSegment(identifier: identifier,
title: "Professional",
subtitle: "Showcase your portfolio, skills or work. Expand this to two rows",
icon: URL(string: "https://s.w.org/style/images/about/WordPress-logotype-standard.png")!,
iconColor: "#0000FF",
mobile: true)
}
}
| gpl-2.0 | 90516e102db2b22b0e3c066e4b0b75b9 | 32.694118 | 130 | 0.643855 | 5.078014 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/maximum-subarray.swift | 2 | 756 | /**
* https://leetcode.com/problems/maximum-subarray/
*
*
*/
class Solution {
/// - Complexity: O(n), n is the number of elements in the array.
///
/// - Description:
/// Here,
/// 1. sum is the maximum sum ending with element n, inclusive.
/// 2. compare the maxSum with current sum ending with element n.
/// 3. if sum is negtive, it will not be helpful for the maximum possible element ending with next element. Then, clear it to zero, 0.
///
///
func maxSubArray(_ nums: [Int]) -> Int {
var sum = 0
var maxSum = Int.min
for n in nums {
sum += n
maxSum = max(maxSum, sum)
sum = max(0, sum)
}
return maxSum
}
}
| mit | 490b1352a2d2e4f5dee8f9c3b905c0cd | 28.076923 | 142 | 0.53836 | 3.798995 | false | false | false | false |
IdeasOnCanvas/Callisto | Callisto/GitHubCommunicationController.swift | 1 | 7372 | //
// GitHubCommunicationController.swift
// clangParser
//
// Created by Patrick Kladek on 21.04.17.
// Copyright © 2017 Patrick Kladek. All rights reserved.
//
import Cocoa
class GitHubCommunicationController {
public let account: GithubAccess
public let repository: GithubRepository
fileprivate let baseUrl = URL(string: "https://api.github.com")
init(access: GithubAccess, repository: GithubRepository) {
self.account = access
self.repository = repository
}
func pullRequest(forBranch branch: String) throws -> [String: Any] {
let pullRequests = self.allPullRequests()
return try pullRequests.first { pullRequest -> Bool in
guard let pullRequestBranch = pullRequest[keyPath: "head.ref"] as? String else { throw GithubError.pullRequestNotAvailible }
return pullRequestBranch == branch
} ?? [:]
}
func branch(named name: String) -> Result<Branch, Error> {
do {
let dict: [String: Any]
try dict = self.pullRequest(forBranch: name)
guard let branchPath = dict["html_url"] as? String, let title = dict["title"] as? String else { throw GithubError.pullRequestNoURL }
let prNumber = dict["number"] as? Int
return .success(Branch(title: title, name: name, url: URL(string: branchPath), number: prNumber))
} catch {
LogError("Something happend when collecting information about Pull Requests")
return .failure(error)
}
}
func postComment(on branch: Branch, comment: Comment) -> Result<Void, Error> {
guard let url = self.makeCommentURL(for: branch) else { return .failure(StatusCodeError.noPullRequestURL) }
do {
var request = self.defaultRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try JSONEncoder().encode(comment)
let taskResult = try URLSession.shared.synchronousDataTask(with: request)
if taskResult.response?.statusCode != 201 {
LogError(taskResult.response.debugDescription)
throw StatusCodeError.noResponse
}
if taskResult.data == nil {
throw StatusCodeError.noData
}
return .success
} catch {
return .failure(error)
}
}
func fetchPreviousComments(on branch: Branch) -> Result<[Comment], Error> {
guard let url = self.makeCommentURL(for: branch) else { return .failure(StatusCodeError.noPullRequestURL) }
do {
let request = self.defaultRequest(url: url)
let taskResult = try URLSession.shared.synchronousDataTask(with: request)
if taskResult.response?.statusCode != 200 {
LogError(taskResult.response.debugDescription)
throw StatusCodeError.noResponse
}
guard let data = taskResult.data else { throw StatusCodeError.noData }
let comments = try JSONDecoder().decode([Comment].self, from: data)
return .success(comments)
} catch {
return .failure(error)
}
}
func deleteComment(comment: Comment) -> Result<Void, Error> {
guard let id = comment.id else { return .failure(StatusCodeError.noPullRequestURL )}
guard let url = self.makeDeleteCommentURL(for: id) else { return .failure(StatusCodeError.noPullRequestURL) }
do {
var request = self.defaultRequest(url: url)
request.httpMethod = "DELETE"
let taskResult = try URLSession.shared.synchronousDataTask(with: request)
if taskResult.response?.statusCode != 204 {
LogError(taskResult.response.debugDescription)
throw StatusCodeError.noResponse
}
return .success
} catch {
return .failure(error)
}
}
}
fileprivate extension GitHubCommunicationController {
func makeUrl(repository: GithubRepository) -> URL? {
guard let baseUrl = self.baseUrl else { return nil }
return baseUrl.appendingPathComponent("repos").appendingPathComponent(repository.organisation).appendingPathComponent(repository.repository)
}
func makeCommentURL(for branch: Branch) -> URL? {
guard let prNumber = branch.number else { return nil }
var url = self.baseUrl
url?.appendPathComponent("repos")
url?.appendPathComponent(self.repository.organisation.lowercased())
url?.appendPathComponent(self.repository.repository.lowercased())
url?.appendPathComponent("issues")
url?.appendPathComponent("\(prNumber)")
url?.appendPathComponent("comments")
return url
}
func makeDeleteCommentURL(for issue: Int) -> URL? {
var url = self.baseUrl
url?.appendPathComponent("repos")
url?.appendPathComponent(self.repository.organisation.lowercased())
url?.appendPathComponent(self.repository.repository.lowercased())
url?.appendPathComponent("issues")
url?.appendPathComponent("comments")
url?.appendPathComponent("\(issue)")
return url
}
}
enum StatusCodeError: Error {
case noResponse
case noData
case noPullRequestURL
var localizedDescription: String {
switch self {
case .noData:
return "Could not parse data from github"
case .noResponse:
return "Github did not respond to request"
case .noPullRequestURL:
return "Could not find Github PullRequest URL"
}
}
}
enum GithubError: Error {
case pullRequestNotAvailible
case pullRequestNoURL
}
extension GitHubCommunicationController {
func allPullRequests() -> [[String: Any]] {
guard let repositoryUrl = self.makeUrl(repository: self.repository) else { return [] }
let pullRequestUrl = repositoryUrl.appendingPathComponent("pulls")
do {
let taskResult = try URLSession.shared.synchronousDataTask(with: self.defaultRequest(url: pullRequestUrl))
if taskResult.response?.statusCode != 200 {
NSLog("Error by sending Message!")
NSLog("%@", taskResult.response ?? "<nil>")
throw StatusCodeError.noResponse
}
if let data = taskResult.data {
return try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]] ?? []
} else {
throw StatusCodeError.noData
}
} catch {
LogError(error.localizedDescription)
return []
}
}
func defaultRequest(url: URL) -> URLRequest {
var request = URLRequest(url: url)
request.addValue("application/vnd.github.antiope-preview+json", forHTTPHeaderField: "Accept")
request.setValue("token \(self.account.token)", forHTTPHeaderField: "Authorization")
return request
}
}
private extension Branch {
var withAPIHost: Branch? {
guard let url = url else { return nil }
var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
urlComponents?.host = "api.github.com"
return Branch(title: self.title, name: self.name, url: urlComponents?.url, number: nil)
}
}
| mit | 88d50747df8090d6ae7702a6c28f5b86 | 33.605634 | 148 | 0.632614 | 4.920561 | false | false | false | false |
psturm-swift/SwiftySignals | Sources/DiscardModifier.swift | 1 | 2198 | // Copyright (c) 2017 Patrick Sturm <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public final class DiscardModifier<T>: ModifierType {
public typealias MessageIn = T
public typealias MessageOut = T
private var _count: Int
fileprivate init(count: Int) {
self._count = count
}
public func process(message: MessageIn, notify: @escaping (MessageOut) -> Void) {
if _count > 0 {
_count -= 1
}
else {
notify(message)
}
}
}
public typealias DiscardObservable<O: ObservableType> = ModifierObservable<O, O.MessageOut>
public typealias DiscardEndPoint<O: ObservableType> = EndPoint<DiscardObservable<O>>
extension EndPoint {
public func discard(first n: Int) -> DiscardEndPoint<SourceObservable> {
let discardObservable = DiscardObservable(
source: self.observable,
modifier: DiscardModifier<SourceObservable.MessageOut>(count: n))
return DiscardEndPoint<SourceObservable>(
observable: discardObservable,
dispatchQueue: self.dispatchQueue)
}
}
| mit | f92eea52e39b4e7a90aa5d97ee7ad326 | 38.25 | 91 | 0.710191 | 4.637131 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornKit/Models/Movie.swift | 1 | 11004 |
import Foundation
import ObjectMapper
import MediaPlayer.MPMediaItem
/**
Struct for managing Movie objects.
**Important:** In the description of all the optional variables where it says another method must be called on **only** `MovieManager` to populate x, does not apply if the movie was loaded from Trakt. **However**, no torrent metadata will be retrieved when movies are loaded from Trakt. They will need to be retrieved by calling `getInfo:imdbId:completion` on `MovieManager`.
`TraktManager` has to be called regardless to fill up the special variables.
*/
public struct Movie: Media, Equatable {
/// Imdb id of the movie.
public let id: String
/// TMDB id of the movie. If movie is loaded from Trakt, this will not be `nil`. Otherwise it will be `nil` and `getTMDBId:forImdbId:completion:` will have to be called on `TraktManager`.
public var tmdbId: Int?
/// The slug of the movie. May be wrong as it is being computed from title and year instead of being pulled from apis.
public let slug: String
/// Title of the movie.
public let title: String
/// Release date of the movie.
public let year: String
/// Rating percentage for the movie.
public let rating: Double
/// The runtime of the movie rounded to the nearest minute.
public let runtime: Int
/// The summary of the movie. Will default to "No summary available.".localized if a summary is not provided by the api.
public let summary: String
/// The trailer url of the movie. Will be `nil` if a trailer is not provided by the api.
public var trailer: String?
/// The youtube code (part of the url after `?v=`) of the trailer. Will be `nil` if trailer url is `nil`.
public var trailerCode: String? {
if let trailer = trailer { return trailer.slice(from: "?v=", to: "") }
return nil
}
/// The certification type according to the Motion picture rating system.
public let certification: String
/// If fanart image is available, it is returned with size 650*366.
public var smallBackgroundImage: String? {
let amazonUrl = largeBackgroundImage?.isAmazonUrl ?? false
return largeBackgroundImage?.replacingOccurrences(of: amazonUrl ? "SX1920" : "original", with: amazonUrl ? "SX650" : "w500")
}
/// If fanart image is available, it is returned with size 1280*720.
public var mediumBackgroundImage: String? {
let amazonUrl = largeBackgroundImage?.isAmazonUrl ?? false
return largeBackgroundImage?.replacingOccurrences(of: amazonUrl ? "SX1920" : "original", with: amazonUrl ? "SX1280" : "w1280")
}
/// If fanart image is available, it is returned with size 1920*1080.
public var largeBackgroundImage: String?
/// If poster image is available, it is returned with size 450*300.
public var smallCoverImage: String? {
let amazonUrl = largeCoverImage?.isAmazonUrl ?? false
return largeCoverImage?.replacingOccurrences(of: amazonUrl ? "SX1000" : "w780", with: amazonUrl ? "SX300" : "w342")
}
/// If poster image is available, it is returned with size 975*650.
public var mediumCoverImage: String? {
let amazonUrl = largeCoverImage?.isAmazonUrl ?? false
return largeCoverImage?.replacingOccurrences(of: amazonUrl ? "SX1000" : "w780", with: amazonUrl ? "SX650" : "w500")
}
/// If poster image is available, it is returned with size 1500*1000
public var largeCoverImage: String?
/// Convenience variable. Boolean value indicating the watched status of the movie.
public var isWatched: Bool {
get {
return WatchedlistManager<Movie>.movie.isAdded(id)
} set (add) {
add ? WatchedlistManager<Movie>.movie.add(id) : WatchedlistManager<Movie>.movie.remove(id)
}
}
/// Convenience variable. Boolean value indicating whether or not the movie has been added the users watchlist.
public var isAddedToWatchlist: Bool {
get {
return WatchlistManager<Movie>.movie.isAdded(self)
} set (add) {
add ? WatchlistManager<Movie>.movie.add(self) : WatchlistManager<Movie>.movie.remove(self)
}
}
/// All the people that worked on the movie. Empty by default. Must be filled by calling `getPeople:forMediaOfType:id:completion` on `TraktManager`.
public var crew = [Crew]()
/// All the actors in the movie. Empty by default. Must be filled by calling `getPeople:forMediaOfType:id:completion` on `TraktManager`.
public var actors = [Actor]()
/// The related movies. Empty by default. Must be filled by calling `getRelated:media:completion` on `TraktManager`.
public var related = [Movie]()
/// The torrents for the movie. Will be empty by default if the movies were loaded from Trakt. Can be filled by calling `getInfo:imdbId:completion` on `MovieManager`.
public var torrents = [Torrent]()
/// The subtitles associated with the movie. Empty by default. Must be filled by calling `search:episode:imdbId:limit:completion:` on `SubtitlesManager`.
public var subtitles = Dictionary<String, [Subtitle]>()
/// The genres associated with the movie.
public var genres = [String]()
public init?(map: Map) {
do { self = try Movie(map) }
catch { return nil }
}
private init(_ map: Map) throws {
if map.context is TraktContext {
self.id = try map.value("ids.imdb")
self.year = try map.value("year", using: StringTransform())
self.rating = try map.value("rating")
self.summary = ((try? map.value("overview")) ?? "No summary available.".localized).removingHtmlEncoding
self.runtime = try map.value("runtime")
} else {
self.id = try map.value("imdb_id")
self.year = try map.value("year")
self.rating = try map.value("rating.percentage")
self.summary = ((try? map.value("synopsis")) ?? "No summary available.".localized).removingHtmlEncoding
self.largeCoverImage = try? map.value("images.poster"); self.largeCoverImage = self.largeCoverImage?.replacingOccurrences(of: "w500", with: "w780").replacingOccurrences(of: "SX300", with: "SX1000")
self.largeBackgroundImage = try? map.value("images.fanart"); self.largeBackgroundImage = self.largeBackgroundImage?.replacingOccurrences(of: "w500", with: "original").replacingOccurrences(of: "SX300", with: "SX1920")
self.runtime = try map.value("runtime", using: IntTransform())
}
let title: String? = (try map.value("title") as String).removingHtmlEncoding
self.title = title ?? ""
self.tmdbId = try? map.value("ids.tmdb")
self.slug = title?.slugged ?? ""
self.trailer = try? map.value("trailer"); trailer == "false" ? trailer = nil : ()
self.certification = try map.value("certification")
self.genres = (try? map.value("genres")) ?? [String]()
if let torrents = map["torrents.en"].currentValue as? [String: [String: Any]] {
for (quality, torrent) in torrents {
if var torrent = Mapper<Torrent>().map(JSONObject: torrent) , quality != "0" {
torrent.quality = quality
self.torrents.append(torrent)
}
}
}
torrents.sort(by: <)
}
public init(title: String = "Unknown".localized, id: String = "tt0000000", tmdbId: Int? = nil, slug: String = "unknown", summary: String = "No summary available.".localized, torrents: [Torrent] = [], subtitles: Dictionary<String, [Subtitle]> = [:], largeBackgroundImage: String? = nil, largeCoverImage: String? = nil) {
self.title = title
self.id = id
self.tmdbId = tmdbId
self.slug = slug
self.summary = summary
self.torrents = torrents
self.subtitles = subtitles
self.largeBackgroundImage = largeBackgroundImage
self.largeCoverImage = largeCoverImage
self.year = ""
self.certification = "Unrated"
self.rating = 0.0
self.runtime = 0
}
public mutating func mapping(map: Map) {
switch map.mappingType {
case .fromJSON:
if let movie = Movie(map: map) {
self = movie
}
case .toJSON:
id >>> map["imdb_id"]
tmdbId >>> map["ids.tmdb"]
year >>> map["year"]
rating >>> map["rating.percentage"]
summary >>> map["synopsis"]
largeCoverImage >>> map["images.poster"]
largeBackgroundImage >>> map["images.fanart"]
runtime >>> (map["runtime"], IntTransform())
title >>> map["title"]
trailer >>> map["trailer"]
certification >>> map["certification"]
genres >>> map["genres"]
}
}
public var mediaItemDictionary: [String: Any] {
return [MPMediaItemPropertyTitle: title,
MPMediaItemPropertyMediaType: NSNumber(value: MPMediaType.movie.rawValue),
MPMediaItemPropertyPersistentID: id,
MPMediaItemPropertyArtwork: smallCoverImage ?? "",
MPMediaItemPropertyBackgroundArtwork: smallBackgroundImage ?? "",
MPMediaItemPropertySummary: summary]
}
public init?(_ mediaItemDictionary: [String: Any]) {
guard
let rawValue = mediaItemDictionary[MPMediaItemPropertyMediaType] as? NSNumber,
let type = MPMediaType(rawValue: rawValue.uintValue) as MPMediaType?,
type == MPMediaType.movie,
let id = mediaItemDictionary[MPMediaItemPropertyPersistentID] as? String,
let title = mediaItemDictionary[MPMediaItemPropertyTitle] as? String,
let image = mediaItemDictionary[MPMediaItemPropertyArtwork] as? String,
let backgroundImage = mediaItemDictionary[MPMediaItemPropertyBackgroundArtwork] as? String,
let summary = mediaItemDictionary[MPMediaItemPropertySummary] as? String
else {
return nil
}
let largeBackgroundImage = backgroundImage.replacingOccurrences(of: backgroundImage.isAmazonUrl ? "SX300" : "w342", with: backgroundImage.isAmazonUrl ? "SX1000" : "w780")
let largeCoverImage = image.replacingOccurrences(of: image.isAmazonUrl ? "SX300" : "w342", with: image.isAmazonUrl ? "SX1000" : "w780")
self.init(title: title, id: id, slug: title.slugged, summary: summary, largeBackgroundImage: largeBackgroundImage, largeCoverImage: largeCoverImage)
}
}
// MARK: - Hashable
extension Movie: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id.hashValue)
}
}
// MARK: Equatable
public func ==(lhs: Movie, rhs: Movie) -> Bool {
return lhs.id == rhs.id
}
| gpl-3.0 | c87c514d61343380b5f42dde71231462 | 44.85 | 376 | 0.641221 | 4.47499 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | SwiftCodeFragments/CodeFragments/Tool.swift | 1 | 3853 | //
// Tool.swift
// swiftDemo1
//
// Created by xiaoming on 16/3/7.
// Copyright © 2016年 shandandan. All rights reserved.
//
import Foundation
import UIKit
//import CryptoSwift // md5加密
public class Tool {
/**
封装的UILabel 初始化
- parameter frame: 大小位置
- parameter textString: 文字
- parameter font: 字体
- parameter textColor: 字体颜色
- returns: UILabel
*/
public class func initALabel(frame:CGRect,textString:String,font:UIFont,textColor:UIColor) -> UILabel {
let aLabel = UILabel()
aLabel.frame = frame
aLabel.backgroundColor = UIColor.clear
aLabel.text = textString
aLabel.font = font
aLabel.textColor = textColor
// aLabel.sizeToFit()
return aLabel
}
/**
封装的UIButton 初始化
- parameter frame: 位置大小
- parameter titleString: 按钮标题
- parameter font: 字体
- parameter textColor: 标题颜色
- parameter bgImage: 按钮背景图片
- returns: UIButton
*/
public class func initAButton(frame:CGRect ,titleString:String, font:UIFont, textColor:UIColor, bgImage:UIImage?) -> UIButton {
let aButton = UIButton()
aButton.frame = frame
aButton.backgroundColor = UIColor.clear
aButton .setTitle(titleString, for: UIControlState.normal)
aButton .setTitleColor(textColor, for: UIControlState.normal)
aButton.titleLabel?.font = font
if bgImage != nil { // bgImage 必须是可选类型,否则警告
aButton .setBackgroundImage(bgImage, for: UIControlState.normal)
}
return aButton
}
/// 保存NSArray 数据到本地文件
public class func saveDataToFile(resultArray: NSArray! , fileName: String!) {
let jsonString : NSString = self.toJSONString(arr: resultArray)!
let jsonData :Data? = jsonString.data(using: UInt(String.Encoding.utf8.hashValue))
let file = fileName
let fileUrl = URL(fileURLWithPath: kPathTemp).appendingPathComponent(file!)
print("fileUrl = \(fileUrl)")
let data = NSMutableData()
data.setData(jsonData!)
if data.write(toFile: fileUrl.path, atomically: true) {
print("保存成功:\(fileUrl.path)")
} else {
print("保存失败:\(fileUrl.path)")
}
}
/// 从本地获取json数据
public class func getJsonFromFile(fileName: String) -> Any? {
let file = fileName
let fileUrl = URL(fileURLWithPath: kPathTemp).appendingPathComponent(file)
if let readData = NSData.init(contentsOfFile: fileUrl.path) {
let jsonValue = try? JSONSerialization.jsonObject(with: readData as Data, options: .allowFragments)
print("获取成功:\(fileUrl.path)")
return jsonValue
} else {
print("获取失败:\(fileUrl.path)")
return nil
}
}
/// 转换数组到JSONStirng
public class func toJSONString(arr: NSArray!) -> NSString? {
guard let data = try? JSONSerialization.data(withJSONObject: arr, options: .prettyPrinted),
// Notice the extra question mark here!
let strJson = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else {
//throws MyError.InvalidJSON
return nil
}
return strJson
}
/// 加密算法
public class func md5Action(origin: String!, _ salt: String?) -> String! {
var str : String! = origin
if let salt = salt {
str = origin + salt
}
// let resultString = str.md5()
// return resultString
return str
}
}
| mit | 8f1782f777f1e5374576f89f5bb2ac6e | 30.686957 | 131 | 0.597969 | 4.566416 | false | false | false | false |
superk589/CGSSGuide | DereGuide/Common/CloudKitSync/SyncCoordinator.swift | 2 | 11187 | //
// RemoteSync.swift
// DereGuide
//
// Created by Daniel Eggert on 22/05/2015.
// Copyright (c) 2015 objc.io. All rights reserved.
//
import UIKit
import CoreData
import CloudKit
public protocol CloudKitNotificationDrain {
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any])
}
private let RemoteTypeEnvKey = "CloudKitRemote"
/// This is the central class that coordinates synchronization with the remote backend.
///
/// This classs does not have any model specific knowledge. It relies on multiple `ChangeProcessor` instances to process changes or communicate with the remote. Change processors have model-specific knowledge.
///
/// The change processors (`ChangeProcessor`) each have 1 specific aspect of syncing as their role. In our case there are three: one for uploading moods, one for downloading moods, and one for removing moods.
///
/// The `SyncCoordinator` is mostly single-threaded by design. This allows for the code to be relatively simple. All sync code runs on the queue of the `syncContext`. Entry points that may run on another queue **must** switch onto that context's queue using `perform(_:)`.
///
/// Note that inside this class we use `perform(_:)` in lieu of `dispatch_async()` to make sure all work is done on the sync context's queue. Adding asynchronous work to a dispatch group makes it easier to test. We can easily wait for all code to be completed by waiting on that group.
///
/// This class uses the `SyncContextType` and `ApplicationActiveStateObserving` protocols.
public final class SyncCoordinator {
static let shared = SyncCoordinator(viewContext: CoreDataStack.default.viewContext, syncContext: CoreDataStack.default.syncContext)
internal typealias ApplicationDidBecomeActive = () -> ()
let viewContext: NSManagedObjectContext
let syncContext: NSManagedObjectContext
let syncGroup: DispatchGroup = DispatchGroup()
let membersRemote: MembersRemote
let unitsRemote: UnitsRemote
let favoriteCardsRemote: FavoriteCardsRemote
let favoriteCharasRemote: FavoriteCharasRemote
let favoriteSongsRemote: FavoriteSongsRemote
fileprivate var observerTokens: [NSObjectProtocol] = [] // < The tokens registered with NotificationCenter
let changeProcessors: [ChangeProcessor] // < The change processors for upload, download, etc.
var teardownFlag = atomic_flag()
private init(viewContext: NSManagedObjectContext, syncContext: NSManagedObjectContext) {
self.membersRemote = MembersRemote()
self.unitsRemote = UnitsRemote()
self.favoriteCardsRemote = FavoriteCardsRemote()
self.favoriteCharasRemote = FavoriteCharasRemote()
self.favoriteSongsRemote = FavoriteSongsRemote()
self.viewContext = viewContext
self.syncContext = syncContext
syncContext.name = "SyncCoordinator"
syncContext.mergePolicy = CloudKitMergePolicy(mode: .remote)
// Member in remote has a reference of .deleteSelf action, so Member doesn't need a remover
// local Unit need all of the 6 members to create, Member is created when Unit is downloaded by fetching in CloudKit using the CKReference on remote Member, so Member downloader only responsible for update remote changes
changeProcessors = [UnitUploader(remote: unitsRemote),
UnitDownloader(remote: unitsRemote),
MemberDownloader(remote: membersRemote),
UnitRemover(remote: unitsRemote),
MemberUploader(remote: membersRemote),
UnitModifier(remote: unitsRemote),
MemberModifier(remote: membersRemote),
FavoriteCardUploader(remote: favoriteCardsRemote),
FavoriteCardDownloader(remote: favoriteCardsRemote),
FavoriteCardRemover(remote: favoriteCardsRemote),
FavoriteCharaUploader(remote: favoriteCharasRemote),
FavoriteCharaDownloader(remote: favoriteCharasRemote),
FavoriteCharaRemover(remote: favoriteCharasRemote),
FavoriteSongUploader(remote: favoriteSongsRemote),
FavoriteSongDownloader(remote: favoriteSongsRemote),
FavoriteSongRemover(remote: favoriteSongsRemote)]
setup()
}
/// The `tearDown` method must be called in order to stop the sync coordinator.
public func tearDown() {
guard !atomic_flag_test_and_set(&teardownFlag) else { return }
perform {
self.removeAllObserverTokens()
}
}
deinit {
guard atomic_flag_test_and_set(&teardownFlag) else { fatalError("deinit called without tearDown() being called.") }
// We must not call tearDown() at this point, because we can not call async code from within deinit.
// We want to be able to call async code inside tearDown() to make sure things run on the right thread.
}
fileprivate func setup() {
self.perform {
// All these need to run on the same queue, since they're modifying `observerTokens`
self.unitsRemote.cloudKitContainer.fetchUserRecordID(completionHandler: { (userRecordID, error) in
self.viewContext.userID = userRecordID?.recordName
})
self.setupContexts()
self.setupChangeProcessors()
self.setupApplicationActiveNotifications()
}
}
}
extension SyncCoordinator: CloudKitNotificationDrain {
public func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
perform {
self.fetchNewRemoteData()
}
}
}
// MARK: - Context Owner -
extension SyncCoordinator : ContextOwner {
/// The sync coordinator holds onto tokens used to register with the NotificationCenter.
func addObserverToken(_ token: NSObjectProtocol) {
observerTokens.append(token)
}
func removeAllObserverTokens() {
observerTokens.removeAll()
}
func processChangedLocalObjects(_ objects: [NSManagedObject]) {
for cp in changeProcessors {
cp.processChangedLocalObjects(objects, in: self)
}
}
fileprivate func processChangedLocalObjects(_ objects: [NSManagedObject], using processor: ChangeProcessor) {
processor.processChangedLocalObjects(objects, in: self)
}
}
// MARK: - Context -
extension SyncCoordinator: ChangeProcessorContext {
/// This is the context that the sync coordinator, change processors, and other sync components do work on.
var managedObjectContext: NSManagedObjectContext {
return syncContext
}
/// This switches onto the sync context's queue. If we're already on it, it will simply run the block.
func perform(_ block: @escaping () -> ()) {
syncContext.perform(group: syncGroup, block: block)
}
func perform<A,B>(_ block: @escaping (A,B) -> ()) -> (A,B) -> () {
return { (a: A, b: B) -> () in
self.perform {
block(a, b)
}
}
}
func perform<A,B,C>(_ block: @escaping (A,B,C) -> ()) -> (A,B,C) -> () {
return { (a: A, b: B, c: C) -> () in
self.perform {
block(a, b, c)
}
}
}
func delayedSaveOrRollback() {
managedObjectContext.delayedSaveOrRollback(group: syncGroup)
}
}
// MARK: Setup
extension SyncCoordinator {
fileprivate func setupChangeProcessors() {
for cp in self.changeProcessors {
cp.setup(for: self)
}
}
}
// MARK: - Active & Background -
extension SyncCoordinator: ApplicationActiveStateObserving {
func applicationDidFinishLaunching() {
fetchRemoteDataForApplicationDidFinishLaunching()
}
func applicationDidBecomeActive() {
fetchLocallyTrackedObjects()
fetchRemoteDataForApplicationDidBecomeActive()
}
func applicationDidEnterBackground() {
syncContext.refreshAllObjects()
}
// fileprivate func fetchLocallyTrackedObjects() {
// self.perform {
// var objects: Set<NSManagedObject> = []
// for cp in self.changeProcessors {
// guard let entityAndPredicate = cp.entityAndPredicateForLocallyTrackedObjects(in: self) else { continue }
// let request = entityAndPredicate.fetchRequest
// request.returnsObjectsAsFaults = false
//
// let result = try! self.syncContext.fetch(request)
// objects.formUnion(result)
//
// }
// self.processChangedLocalObjects(Array(objects))
// }
// }
fileprivate func fetchLocallyTrackedObjects() {
self.perform {
// TODO: Could optimize this to only execute a single fetch request per entity.
for cp in self.changeProcessors {
guard let entityAndPredicate = cp.entityAndPredicateForLocallyTrackedObjects(in: self) else { continue }
let request = entityAndPredicate.fetchRequest
request.returnsObjectsAsFaults = false
let result = try! self.syncContext.fetch(request)
self.processChangedLocalObjects(result, using: cp)
}
}
}
}
// MARK: - Remote -
extension SyncCoordinator {
fileprivate func fetchRemoteDataForApplicationDidBecomeActive() {
self.fetchNewRemoteData()
}
fileprivate func fetchRemoteDataForApplicationDidFinishLaunching() {
self.fetchLatestRemoteData()
}
fileprivate func fetchLatestRemoteData() {
perform {
for changeProcessor in self.changeProcessors {
changeProcessor.fetchLatestRemoteRecords(in: self)
self.delayedSaveOrRollback()
}
}
}
fileprivate func fetchNewRemoteData() {
fetchNewRemoteData(using: unitsRemote)
fetchNewRemoteData(using: membersRemote)
fetchNewRemoteData(using: favoriteCardsRemote)
fetchNewRemoteData(using: favoriteCharasRemote)
}
fileprivate func fetchNewRemoteData<T: Remote>(using remote: T) {
remote.fetchNewRecords { (changes, callback) in
self.processRemoteChanges(changes) {
self.perform {
self.managedObjectContext.delayedSaveOrRollback(group: self.syncGroup) { success in
callback(success)
}
}
}
}
}
fileprivate func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], completion: @escaping () -> ()) {
self.changeProcessors.asyncForEach(completion: completion) { changeProcessor, innerCompletion in
perform {
changeProcessor.processRemoteChanges(changes, in: self, completion: innerCompletion)
}
}
}
}
| mit | ae52a369b5747251bf48fad1bcb5096c | 37.180887 | 285 | 0.650934 | 5.362895 | false | false | false | false |
shu223/iOS-9-Sampler | iOS9Sampler/SampleViewControllers/SpringViewController.swift | 2 | 3242 | //
// SpringViewController.swift
// iOS9Sampler
//
// Created by Shuichi Tsutsumi on 9/13/15.
// Copyright © 2015 Shuichi Tsutsumi. All rights reserved.
//
// Thanks to
// http://qiita.com/kaway/items/b9e85403a4d78c11f8df
import UIKit
class SpringViewController: UIViewController, CAAnimationDelegate {
@IBOutlet weak fileprivate var massSlider: UISlider!
@IBOutlet weak fileprivate var massLabel: UILabel!
@IBOutlet weak fileprivate var stiffnessSlider: UISlider!
@IBOutlet weak fileprivate var stiffnessLabel: UILabel!
@IBOutlet weak fileprivate var dampingSlider: UISlider!
@IBOutlet weak fileprivate var dampingLabel: UILabel!
@IBOutlet weak fileprivate var durationLabel: UILabel!
@IBOutlet weak fileprivate var animateBtn: UIButton!
@IBOutlet weak fileprivate var imageView: UIImageView!
fileprivate let animation = CASpringAnimation(keyPath: "position")
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
animation.initialVelocity = -5.0
animation.isRemovedOnCompletion = false
animation.fillMode = CAMediaTimingFillMode.forwards
animation.delegate = self
// update labels
massChanged(massSlider)
stiffnessChanged(stiffnessSlider)
dampingChanged(dampingSlider)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let fromPos = CGPoint(x: view.bounds.midX + 100, y: imageView.center.y)
let toPos = CGPoint(x: fromPos.x - 200, y: fromPos.y)
animation.fromValue = NSValue(cgPoint: fromPos)
animation.toValue = NSValue(cgPoint: toPos)
imageView.center = fromPos
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
fileprivate func updateDurationLabel() {
durationLabel.text = String(format: "settlingDuration:%.1f", animation.settlingDuration)
}
// =========================================================================
// MARK: - CAAnimation Delegate
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
animateBtn.isEnabled = true
}
// =========================================================================
// MARK: - Actions
@IBAction func massChanged(_ sender: UISlider) {
massLabel.text = String(format: "%.1f", sender.value)
animation.mass = CGFloat(sender.value)
updateDurationLabel()
}
@IBAction func stiffnessChanged(_ sender: UISlider) {
stiffnessLabel.text = String(format: "%.1f", sender.value)
animation.stiffness = CGFloat(sender.value)
updateDurationLabel()
}
@IBAction func dampingChanged(_ sender: UISlider) {
dampingLabel.text = String(format: "%.1f", sender.value)
animation.damping = CGFloat(sender.value)
updateDurationLabel()
}
@IBAction func animateBtnTapped(_ sender: UIButton) {
animateBtn.isEnabled = false
animation.duration = animation.settlingDuration
imageView.layer.add(animation, forKey: nil)
}
}
| mit | fdba1d0be3ecd47735bdde7263f56a6e | 31.737374 | 96 | 0.642703 | 4.888386 | false | false | false | false |
Driftt/drift-sdk-ios | Drift/Models/CurrentUser.swift | 2 | 1238 | //
// CurrentUser.swift
// Drift-SDK
//
// Created by Eoin O'Connell on 02/03/2020.
// Copyright © 2020 Drift. All rights reserved.
//
import Foundation
///Codable for caching
struct CurrentUser: Codable, UserDisplayable {
let userId: Int64?
let orgId: Int?
let email: String?
let name: String?
let externalId: String?
let avatarURL: String?
let bot: Bool = false
func getUserName() -> String{
return name ?? email ?? "No Name Set"
}
}
class CurrentUserDTO: Codable, DTO {
typealias DataObject = CurrentUser
var userId: Int64?
var orgId: Int?
var email: String?
var name: String?
var externalId: String?
var avatarURL: String?
enum CodingKeys: String, CodingKey {
case userId = "id"
case email = "email"
case orgId = "orgId"
case name = "name"
case externalId = "externalId"
case avatarURL = "avatarUrl"
}
func mapToObject() -> CurrentUser? {
return CurrentUser(userId: userId,
orgId: orgId,
email: email,
name: name,
externalId: externalId,
avatarURL: avatarURL)
}
}
| mit | c30dcc8f2bf556ebb9262de8f66bfd62 | 21.490909 | 48 | 0.571544 | 4.265517 | false | false | false | false |
IdeasOnCanvas/Ashton | Sources/Ashton/AshtonXMLParser.swift | 1 | 14562 | //
// XMLParser.swift
// Ashton
//
// Created by Michael Schwarz on 15.01.18.
// Copyright © 2018 Michael Schwarz. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
protocol AshtonXMLParserDelegate: AnyObject {
func didParseContent(_ parser: AshtonXMLParser, string: String)
func didOpenTag(_ parser: AshtonXMLParser, name: AshtonXMLParser.Tag, attributes: [NSAttributedString.Key: Any]?)
func didCloseTag(_ parser: AshtonXMLParser)
func didEncounterUnknownFont(_ parser: AshtonXMLParser, fontName: String)
}
extension AshtonXMLParserDelegate {
func didEncounterUnknownFont(_ parser: AshtonXMLParser, fontName: String) { }
}
/// Parses Ashton XML and returns parsed content and attributes
final class AshtonXMLParser {
enum Tag {
case p
case span
case strong
case em
case a
case ignored
}
enum AttributeKeys {
enum Style {
static let backgroundColor = "background-color"
static let color = "color"
static let textDecoration = "text-decoration"
static let font = "font"
static let textAlign = "text-align"
static let verticalAlign = "vertical-align"
enum Cocoa {
static let commonPrefix = "-cocoa-"
static let strikethroughColor = "strikethrough-color"
static let underlineColor = "underline-color"
static let baseOffset = "baseline-offset"
static let verticalAlign = "vertical-align"
static let fontPostScriptName = "font-postscriptname"
static let underline = "underline"
static let strikethrough = "strikethrough"
static let fontFeatures = "font-features"
}
}
}
typealias Hash = Int
static var styleAttributesCache: [Hash: [NSAttributedString.Key: Any]] = [:]
// MARK: - AshtonXMLParser
weak var delegate: AshtonXMLParserDelegate?
func parse(string: String) {
var parsedScalars = "".unicodeScalars
var iterator: String.UnicodeScalarView.Iterator = string.unicodeScalars.makeIterator()
func flushContent() {
guard parsedScalars.isEmpty == false else { return }
delegate?.didParseContent(self, string: String(parsedScalars))
parsedScalars = "".unicodeScalars
}
while let character = iterator.next() {
switch character {
case "<":
flushContent()
self.parseTag(&iterator)
case "&":
if let escapedChar = iterator.parseEscapedChar() {
parsedScalars.append(escapedChar)
} else {
parsedScalars.append(character)
}
default:
parsedScalars.append(character)
}
}
flushContent()
}
}
// MARK: - Private
private extension AshtonXMLParser {
// MARK: - Tag Parsing
func parseTag(_ iterator: inout String.UnicodeScalarView.Iterator) {
guard let nextCharacter = iterator.next(), nextCharacter != ">" else { return }
switch nextCharacter {
case "b":
if iterator.forwardIfEquals("r /") {
iterator.foward(untilAfter: ">")
self.delegate?.didParseContent(self, string: "\n")
} else {
self.finalizeOpening(of: .ignored, iterator: &iterator)
}
case "p":
self.finalizeOpening(of: .p, iterator: &iterator)
case "s":
let parsedTag: Tag
if iterator.forwardIfEquals("pan") {
parsedTag = .span
} else if iterator.forwardIfEquals("trong") {
parsedTag = .strong
} else {
parsedTag = .ignored
}
self.finalizeOpening(of: parsedTag, iterator: &iterator)
case "e":
let parsedTag: Tag = iterator.forwardIfEquals("m") ? .em : .ignored
self.finalizeOpening(of: parsedTag, iterator: &iterator)
case "a":
self.finalizeOpening(of: .a, iterator: &iterator)
case "/":
iterator.foward(untilAfter: ">")
self.delegate?.didCloseTag(self)
default:
self.finalizeOpening(of: .ignored, iterator: &iterator)
}
}
func finalizeOpening(of tag: Tag, iterator: inout String.UnicodeScalarView.Iterator) {
guard tag != .ignored else {
iterator.foward(untilAfter: ">")
self.delegate?.didOpenTag(self, name: .ignored, attributes: nil)
return
}
guard let nextChar = iterator.next() else { return }
switch nextChar {
case ">":
self.delegate?.didOpenTag(self, name: tag, attributes: nil)
case " ":
let attributes = self.parseAttributes(&iterator)
self.delegate?.didOpenTag(self, name: tag, attributes: attributes)
default:
iterator.foward(untilAfter: ">")
// it seems we parsed only a prefix and the actual tag is unknown
self.delegate?.didOpenTag(self, name: .ignored, attributes: nil)
}
}
// MARK: - Attribute Parsing
func parseAttributes(_ iterator: inout String.UnicodeScalarView.Iterator) -> [NSAttributedString.Key: Any]? {
var parsedAttributes: [NSAttributedString.Key: Any]? = nil
func addAttributes(_ attributes: [NSAttributedString.Key: Any]) {
if parsedAttributes == nil {
parsedAttributes = attributes
} else {
parsedAttributes?.merge(attributes) { return $1 }
}
}
while let nextChar = iterator.next(), nextChar != ">" {
switch nextChar {
case "s":
guard iterator.forwardAndCheckingIfEquals("tyle") else { break }
iterator.foward(untilAfter: "=")
addAttributes(self.parseStyles(&iterator))
case "h":
guard iterator.forwardAndCheckingIfEquals("ref") else { break }
iterator.foward(untilAfter: "=")
addAttributes(self.parseHREF(&iterator))
default:
break
}
}
return parsedAttributes
}
// MARK: - Style Parsing
func parseStyles(_ iterator: inout String.UnicodeScalarView.Iterator) -> [NSAttributedString.Key: Any] {
var attributes: [NSAttributedString.Key: Any] = [:]
var fontBuilder: FontBuilder?
func ensureFontBuilder() -> FontBuilder {
if let fontBuilder = fontBuilder {
return fontBuilder
}
let newFontBuilder = FontBuilder()
fontBuilder = newFontBuilder
return newFontBuilder
}
iterator.skipWhiteSpace()
guard let terminationCharacter = iterator.next(), terminationCharacter == "'" || terminationCharacter == "\"" else { return attributes }
let cacheKey = iterator.hash(until: terminationCharacter)
if let cachedAttributes = AshtonXMLParser.styleAttributesCache[cacheKey] {
iterator.foward(untilAfter: terminationCharacter)
return cachedAttributes
}
while let char = iterator.testNextCharacter(), char != terminationCharacter, char != ">" {
switch char {
case "b":
guard iterator.forwardIfEquals(AttributeKeys.Style.backgroundColor) else { break }
iterator.skipStyleAttributeIgnoredCharacters()
attributes[.backgroundColor] = iterator.parseColor()
case "c":
guard iterator.forwardIfEquals(AttributeKeys.Style.color) else { break }
iterator.skipStyleAttributeIgnoredCharacters()
attributes[.foregroundColor] = iterator.parseColor()
case "t":
if iterator.forwardIfEquals(AttributeKeys.Style.textAlign) {
iterator.skipStyleAttributeIgnoredCharacters()
guard let textAlignment = iterator.parseTextAlignment() else { break }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
attributes[.paragraphStyle] = paragraphStyle
} else if iterator.forwardIfEquals(AttributeKeys.Style.textDecoration) {
iterator.skipStyleAttributeIgnoredCharacters()
// we have to use a temporary iterator to ensure that we are not skipping attributes too far
var tempIterator = iterator
while let textDecoration = tempIterator.parseTextDecoration() {
attributes[textDecoration] = NSUnderlineStyle.single.rawValue
iterator = tempIterator
tempIterator.skipStyleAttributeIgnoredCharacters()
}
}
case "f":
guard iterator.forwardIfEquals(AttributeKeys.Style.font) else { break }
iterator.skipStyleAttributeIgnoredCharacters()
let fontAttributes = iterator.parseFontAttributes()
let fontBuilder = ensureFontBuilder()
fontBuilder.isBold = fontAttributes.isBold
fontBuilder.isItalic = fontAttributes.isItalic
fontBuilder.familyName = fontAttributes.family
fontBuilder.pointSize = fontAttributes.points
case "v":
guard iterator.forwardIfEquals(AttributeKeys.Style.verticalAlign) else { break }
iterator.skipStyleAttributeIgnoredCharacters()
guard attributes[.superscript] == nil else { break }
guard let alignment = iterator.parseVerticalAlignmentFromString() else { break }
attributes[.superscript] = alignment
case "-":
guard iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.commonPrefix) else { break }
guard let firstChar = iterator.testNextCharacter() else { break }
switch firstChar {
case "s":
if iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.strikethroughColor) {
iterator.skipStyleAttributeIgnoredCharacters()
attributes[.strikethroughColor] = iterator.parseColor()
} else if iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.strikethrough) {
iterator.skipStyleAttributeIgnoredCharacters()
guard let underlineStyle = iterator.parseUnderlineStyle() else { break }
attributes[.strikethroughStyle] = underlineStyle.rawValue
}
case "u":
if iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.underlineColor) {
iterator.skipStyleAttributeIgnoredCharacters()
attributes[.underlineColor] = iterator.parseColor()
} else if iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.underline) {
iterator.skipStyleAttributeIgnoredCharacters()
guard let underlineStyle = iterator.parseUnderlineStyle() else { break }
attributes[.underlineStyle] = underlineStyle.rawValue
}
case "b":
guard iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.baseOffset) else { break }
iterator.skipStyleAttributeIgnoredCharacters()
guard let baselineOffset = iterator.parseBaselineOffset() else { break }
attributes[.baselineOffset] = baselineOffset
case "v":
guard iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.verticalAlign) else { break }
iterator.skipStyleAttributeIgnoredCharacters()
guard let verticalAlignment = iterator.parseVerticalAlignment() else { break }
attributes[.superscript] = verticalAlignment
case "f":
if iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.fontPostScriptName) {
iterator.skipStyleAttributeIgnoredCharacters()
guard let postscriptName = iterator.parsePostscriptFontName() else { break }
let fontBuilder = ensureFontBuilder()
fontBuilder.postScriptName = postscriptName
} else if iterator.forwardIfEquals(AttributeKeys.Style.Cocoa.fontFeatures) {
iterator.skipStyleAttributeIgnoredCharacters()
let fontFeatures = iterator.parseFontFeatures()
guard fontFeatures.isEmpty == false else { break }
let fontBuilder = ensureFontBuilder()
fontBuilder.fontFeatures = fontFeatures
}
default:
break
}
default:
break
}
guard iterator.forwardUntilNextAttribute(terminationChar: terminationCharacter) else { break }
}
iterator.foward(untilAfter: terminationCharacter)
if let font = fontBuilder?.makeFont() {
attributes[.font] = font
// Core Text implicitly returns a fallback font if the the requested font descriptor
// does not lead to an exact match. We perform a simple heuristic to take note of such
// fallbacks and inform the delegate.
if let requestedFontName = fontBuilder?.fontName, font.fontName != requestedFontName {
self.delegate?.didEncounterUnknownFont(self, fontName: requestedFontName)
}
}
AshtonXMLParser.styleAttributesCache[cacheKey] = attributes
return attributes
}
// MARK: - href-Parsing
func parseHREF(_ iterator: inout String.UnicodeScalarView.Iterator) -> [NSAttributedString.Key: Any] {
iterator.skipStyleAttributeIgnoredCharacters()
guard let url = iterator.parseURL() else { return [:] }
return [.link: url]
}
}
| mit | 9d4e511968bae98fba324ca6d8b113c2 | 39.559889 | 144 | 0.584369 | 5.551277 | false | false | false | false |
0Mooshroom/Learning-Swift | 2_基本运算符.playground/Contents.swift | 1 | 972 | //: Playground - noun: a place where people can play
// 运算符
import UIKit
//: 合并空值运算符
// 如果 a 有值则解包,没有则是nil
let a: String? = nil
a != nil ? a!: a
a ?? a
// 栗子🌰
let defaultColorName = "red"
var userDefaultColorName: String?
var colorNameToUse = userDefaultColorName ?? defaultColorName
userDefaultColorName = "green"
colorNameToUse = userDefaultColorName ?? defaultColorName
//: 区间运算符
// 闭区间运算符
for index in 1...5 {
print("index: \(index)")
}
// 半开区间
let names = ["M", "o", "o", "s", "h", "r", "o", "o", "m"]
let count = names.count
for index in 0..<count {
print("Person \(index + 1) is called \(names[index])")
}
// 单侧区间
/*
for name in names[2...] {
print(name)
}
for name in names[...2] {
print(name)
}
for name in names[..<2] {
print(name)
}
let range = ...5
range.contains(7) // false
range.contains(4) // true
range.contains(-1) // true
*/
| mit | ecf79ca2374ebffdf92e88b4b7f613aa | 15.054545 | 61 | 0.616082 | 2.983108 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Network/Sources/NetworkKit/General/Request/RequestBuilder.swift | 1 | 8380 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Foundation
import ToolKit
public struct RequestBuilderQueryParameters {
public var publisher: AnyPublisher<[URLQueryItem]?, Never>
public init<P: Publisher>(_ publisher: P) where P.Output == [URLQueryItem]?, P.Failure == Never {
self.publisher = publisher.eraseToAnyPublisher()
}
}
public class RequestBuilder {
public enum Error: Swift.Error {
case buildingRequest
}
private var defaultComponents: URLComponents {
var urlComponents = URLComponents()
urlComponents.scheme = networkConfig.apiScheme
urlComponents.host = networkConfig.apiHost
urlComponents.path = RequestBuilder.path(from: networkConfig.pathComponents)
return urlComponents
}
private let networkConfig: Network.Config
private let decoder: NetworkResponseDecoderAPI
private let headers: HTTPHeaders
private var queryParameters: [URLQueryItem]?
private var subscription: AnyCancellable?
public init(
config: Network.Config = resolve(),
decoder: NetworkResponseDecoderAPI = NetworkResponseDecoder(),
headers: HTTPHeaders = [:],
queryParameters: RequestBuilderQueryParameters = .init(Just(nil))
) {
networkConfig = config
self.decoder = decoder
self.headers = headers
if BuildFlag.isInternal {
subscription = queryParameters.publisher.sink { [weak self] parameters in
self?.queryParameters = parameters
}
}
}
// MARK: - GET
public func get(
path components: [String] = [],
parameters: [URLQueryItem]? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
get(
path: RequestBuilder.path(from: components),
parameters: parameters,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
public func get(
path: String,
parameters: [URLQueryItem]? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
buildRequest(
method: .get,
path: path,
parameters: parameters,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
// MARK: - PUT
public func put(
path components: [String] = [],
parameters: [URLQueryItem]? = nil,
body: Data? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
put(
path: RequestBuilder.path(from: components),
parameters: parameters,
body: body,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
public func put(
path: String,
parameters: [URLQueryItem]? = nil,
body: Data? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
buildRequest(
method: .put,
path: path,
parameters: parameters,
body: body,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
// MARK: - POST
public func post(
path components: [String] = [],
parameters: [URLQueryItem]? = nil,
body: Data? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
post(
path: RequestBuilder.path(from: components),
parameters: parameters,
body: body,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
public func post(
path: String,
parameters: [URLQueryItem]? = nil,
body: Data? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
buildRequest(
method: .post,
path: path,
parameters: parameters,
body: body,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
// MARK: - Delete
public func delete(
path components: [String] = [],
parameters: [URLQueryItem]? = nil,
body: Data? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI? = nil,
recordErrors: Bool = false
) -> NetworkRequest? {
buildRequest(
method: .delete,
path: RequestBuilder.path(from: components),
parameters: parameters,
body: body,
headers: headers,
authenticated: authenticated,
contentType: contentType,
decoder: decoder,
recordErrors: recordErrors
)
}
// MARK: - Utilities
public static func body(from parameters: [URLQueryItem]) -> Data? {
var components = URLComponents()
components.queryItems = parameters
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
return components.percentEncodedQuery?.data(using: .utf8)
}
// MARK: - Private methods
private static func path(from components: [String] = []) -> String {
components.reduce(into: "") { path, component in
path += "/\(component)"
}
}
private func buildRequest(
method: NetworkRequest.NetworkMethod,
path: String,
parameters: [URLQueryItem]? = nil,
body: Data? = nil,
headers: HTTPHeaders = [:],
authenticated: Bool = false,
contentType: NetworkRequest.ContentType = .json,
decoder: NetworkResponseDecoderAPI?,
recordErrors: Bool = false
) -> NetworkRequest? {
guard let url = buildURL(path: path, parameters: parameters) else {
return nil
}
return NetworkRequest(
endpoint: url,
method: method,
body: body,
headers: self.headers.merging(headers),
authenticated: authenticated,
contentType: contentType,
decoder: decoder ?? self.decoder,
recordErrors: recordErrors
)
}
private func buildURL(path: String, parameters: [URLQueryItem]? = nil) -> URL? {
var components = defaultComponents
components.path += path
if let parameters = parameters {
components.queryItems = parameters
}
if let parameters = queryParameters {
components.queryItems = components.queryItems.map { $0 + parameters } ?? parameters
}
return components.url
}
}
| lgpl-3.0 | 9478e52b780c119e49af4d080c560356 | 30.033333 | 115 | 0.584437 | 5.364277 | false | false | false | false |
KasunApplications/susi_iOS | Susi/Controllers/SettingsController/SettingsViewController.swift | 1 | 2701 | //
// SettingsViewController.swift
// Susi
//
// Created by Chashmeet Singh on 2017-03-15.
// Copyright © 2017 FOSSAsia. All rights reserved.
//
import UIKit
import Material
import Localize_Swift
class SettingsViewController: UITableViewController {
let availableLanguages = Localize.availableLanguages()
var actionSheet: UIAlertController!
// Get directory
let dirPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
lazy var backButton: IconButton = {
let button = IconButton()
button.image = Icon.arrowBack
button.tintColor = .white
button.addTarget(self, action: #selector(dismissView), for: .touchUpInside)
return button
}()
// Image Picker Controller
var imagePicker = UIImagePickerController()
override func viewDidLoad() {
super.viewDidLoad()
setupTitle()
setupTheme()
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel?.textColor = UIColor.hexStringToUIColor(hex: "#009688")
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = indexPath.section
let row = indexPath.row
if section == 3 {
if row == 0 {
presentTrainingController()
} else if row == 1 {
deleteVoiceModel()
}
} else if section == 4 {
if row == 2 {
presentResetPasswordController()
} else if row == 3 {
logoutUser()
}
}
else if section == 5 {
if row == 0 {
changeLanguage()
}
}
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let user = UserDefaults.standard.dictionary(forKey: ControllerConstants.UserDefaultsKeys.user)
if indexPath.section == 5 && indexPath.row == 2 && user == nil {
cell.isHidden = true
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let user = UserDefaults.standard.dictionary(forKey: ControllerConstants.UserDefaultsKeys.user)
if indexPath.section == 5 && indexPath.row == 2 && user == nil {
return 0
} else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
}
| apache-2.0 | 4606ee752615d8bac2de30ff102794e4 | 31.142857 | 121 | 0.62037 | 5.222437 | false | false | false | false |
evgenyneu/JsonSwiftson | JsonSwiftsonAppDemo/Utils/TickTock.swift | 1 | 746 |
//
// Measures elapsed time
//
// Usage:
//
// let tick = TickTock()
// ... code to measure execution time for
// tick.formattedWithMs()
//
// Output: [TOCK] 10.2 ms
//
import Foundation
class TickTock {
var startTime:Date
init() {
startTime = Date()
}
func measure() -> Double {
return Double(Int(-startTime.timeIntervalSinceNow * 10000)) / 10
}
func formatted() -> String {
let elapsedMs = measure()
return String(format: "%.1f", elapsedMs)
}
func formattedWithMs(_ message: String? = nil) -> String {
let outputPrefix = message ?? "[TOCK]"
return "\(outputPrefix) \(formatted()) ms"
}
func output(_ message: String? = nil) {
print(formattedWithMs(message))
}
}
| mit | ef3fc1b075f7ac50f63f457acfb785ea | 17.65 | 68 | 0.600536 | 3.586538 | false | false | false | false |
huonw/swift | test/SILGen/witnesses_class.swift | 2 | 4832 |
// RUN: %target-swift-emit-silgen -module-name witnesses_class -enable-sil-ownership %s | %FileCheck %s
protocol Fooable: class {
func foo()
static func bar()
init()
}
class Foo: Fooable {
func foo() { }
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW
// CHECK-NOT: function_ref
// CHECK: class_method
class func bar() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FZTW
// CHECK-NOT: function_ref
// CHECK: class_method
required init() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class3FooCAA7FooableA2aDP{{[_0-9a-zA-Z]*}}fCTW
// CHECK-NOT: function_ref
// CHECK: class_method
}
// CHECK-LABEL: sil hidden @$S15witnesses_class3genyyxAA7FooableRzlF
// CHECK: bb0([[SELF:%.*]] : @guaranteed $T)
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = witness_method $T
// CHECK: apply [[METHOD]]<T>([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: return
func gen<T: Fooable>(_ foo: T) {
foo.foo()
}
// CHECK-LABEL: sil hidden @$S15witnesses_class2exyyAA7Fooable_pF
// CHECK: bb0([[SELF:%[0-0]+]] : @guaranteed $Fooable):
// CHECK: [[SELF_PROJ:%.*]] = open_existential_ref [[SELF]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Fooable]],
// CHECK-NOT: copy_value [[SELF_PROJ]] : $
// CHECK: apply [[METHOD]]<[[OPENED]]>([[SELF_PROJ]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: return
func ex(_ foo: Fooable) {
foo.foo()
}
// Default implementations in a protocol extension
protocol HasDefaults {
associatedtype T = Self
func hasDefault()
func hasDefaultTakesT(_: T)
func hasDefaultGeneric<U : Fooable>(_: U)
func hasDefaultGenericTakesT<U : Fooable>(_: T, _: U)
}
extension HasDefaults {
func hasDefault() {}
func hasDefaultTakesT(_: T) {}
func hasDefaultGeneric<U : Fooable>(_: U) {}
func hasDefaultGenericTakesT<U : Fooable>(_: T, _: U) {}
}
protocol Barable {}
class UsesDefaults<X : Barable> : HasDefaults {}
// Covariant Self:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyqd__GAA03HasD0A2aEP10hasDefaultyyFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable> (@in_guaranteed τ_0_0) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE10hasDefaultyyF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<τ_0_0>(
// CHECK: return
// Invariant Self, since type signature contains an associated type:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP16hasDefaultTakesTyy1TQzFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable> (@in_guaranteed UsesDefaults<τ_0_0>, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE16hasDefaultTakesTyy1TQzF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults> (@in_guaranteed τ_0_0.T, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<UsesDefaults<τ_0_0>>(
// CHECK: return
// Covariant Self:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyqd__GAA03HasD0A2aEP17hasDefaultGenericyyqd__AA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0><τ_1_0 where τ_0_0 : UsesDefaults<τ_1_0>, τ_1_0 : Barable><τ_2_0 where τ_2_0 : Fooable> (@guaranteed τ_2_0, @in_guaranteed τ_0_0) -> () {
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE17hasDefaultGenericyyqd__AA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_2_0>(
// CHECK: return
// Invariant Self, since type signature contains an associated type:
// CHECK-LABEL: sil private [transparent] [thunk] @$S15witnesses_class12UsesDefaultsCyxGAA03HasD0A2aEP23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lFTW : $@convention(witness_method: HasDefaults) <τ_0_0 where τ_0_0 : Barable><τ_1_0 where τ_1_0 : Fooable> (@in_guaranteed UsesDefaults<τ_0_0>, @guaranteed τ_1_0, @in_guaranteed UsesDefaults<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @$S15witnesses_class11HasDefaultsPAAE23hasDefaultGenericTakesTyy1TQz_qd__tAA7FooableRd__lF : $@convention(method) <τ_0_0 where τ_0_0 : HasDefaults><τ_1_0 where τ_1_0 : Fooable> (@in_guaranteed τ_0_0.T, @guaranteed τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[FN]]<UsesDefaults<τ_0_0>, τ_1_0>(
// CHECK: return
| apache-2.0 | 8d75d4c0dd3aec6af226ad042e7d5f4e | 44.961538 | 358 | 0.669038 | 3.126226 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Components/StringConverter.swift | 1 | 5198 | //
// Xcore
// Copyright © 2019 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
public struct StringConverter {
private let string: String
public init?(_ value: String?) {
guard let value = value else {
return nil
}
self.string = value
}
public init<T: LosslessStringConvertible>(_ value: T) {
self.string = value.description
}
public init?<T>(_ value: T) {
if let value = value as? LosslessStringConvertible {
self.string = value.description
return
}
// Captures NSString
if let value = value as? String {
self.string = value
return
}
if let value = value as? NSNumber {
self.string = value.stringValue
return
}
if let value = value as? Date {
self.string = value.timeIntervalSinceReferenceDate.description
return
}
if let value = value as? URL {
self.string = value.absoluteString
return
}
if let value = (value as? NSURL)?.absoluteString {
self.string = value
return
}
if let value = value as? Data, let dataString = String(data: value, encoding: .utf8) {
self.string = dataString
return
}
return nil
}
private var url: URL? {
URL(string: string)
}
private var json: Any? {
guard !string.isBlank else {
return nil
}
return JSONHelpers.decode(string)
}
private var nsNumber: NSNumber? {
let formatter = NumberFormatter().apply {
$0.numberStyle = .decimal
}
return formatter.number(from: string)
}
}
extension StringConverter {
public func get<T>(_ type: T.Type = T.self) -> T? {
switch T.self {
case is String.Type, is Optional<String>.Type:
return string as? T
case is Bool.Type, is Optional<Bool>.Type:
return Bool(string) as? T
case is Double.Type, is Optional<Double>.Type:
return Double(string) as? T
case is Float.Type, is Optional<Float>.Type:
return Float(string) as? T
case is Int.Type, is Optional<Int>.Type:
return Int(string) as? T
case is URL.Type, is Optional<URL>.Type:
return url as? T
case is NSNumber.Type, is Optional<NSNumber>.Type:
return nsNumber as? T
case is NSString.Type, is Optional<NSString>.Type:
return string as? T
case is Data.Type, is Optional<Data>.Type:
return string.data(using: .utf8) as? T
case is URL.Type, is Optional<URL>.Type:
return URL(string: string) as? T
case is NSURL.Type, is Optional<NSURL>.Type:
return NSURL(string: string) as? T
case is Date.Type, is Optional<Date>.Type:
if let double = Double(string) {
return Date(timeIntervalSinceReferenceDate: double) as? T
}
return nil
default:
return json as? T
}
}
public func get<T>() -> T? where T: RawRepresentable, T.RawValue == String {
T(rawValue: string)
}
}
// MARK: - JSONDecoder
extension StringConverter {
/// Returns a value of the type you specify, decoded from an object.
///
/// - Parameters:
/// - type: The type of the value to decode from the string.
/// - decoder: The decoder used to decode the data. If set to `nil`, it uses
/// ``JSONDecoder`` with `convertFromSnakeCase` key decoding strategy.
/// - Returns: A value of the specified type, if the decoder can parse the data.
public func get<T>(_ type: T.Type = T.self, decoder: JSONDecoder? = nil) -> T? where T: Decodable {
guard let data = string.data(using: .utf8) else {
return nil
}
return Self.get(type, from: data, decoder: decoder)
}
/// Returns a value of the type you specify, decoded from an object.
///
/// - Parameters:
/// - type: The type of the value to decode from the string.
/// - decoder: The decoder used to decode the data. If set to `nil`, it uses
/// ``JSONDecoder`` with `convertFromSnakeCase` key decoding strategy.
/// - Returns: A value of the specified type, if the decoder can parse the data.
static func get<T>(_ type: T.Type = T.self, from data: Data, decoder: JSONDecoder? = nil) -> T? where T: Decodable {
let decoder = decoder ?? JSONDecoder().apply {
$0.keyDecodingStrategy = .convertFromSnakeCase
}
do {
return try decoder.decode(T.self, from: data)
} catch {
#if DEBUG
if AppInfo.isDebuggerAttached {
print("Failed to decode \(type):")
print("---")
dump(error)
print("---")
}
#endif
return nil
}
}
}
| mit | f7dff18b1bd6f741436bcb5c1626f636 | 29.751479 | 120 | 0.54416 | 4.546807 | false | false | false | false |
mattiasjahnke/arduino-projects | matrix-painter/iOS/PixelDrawer/Carthage/Checkouts/flow/Flow/UIView+Signal.swift | 1 | 2894 | //
// UIView+Signal.swift
// Flow
//
// Created by Måns Bernhardt on 2017-11-07.
// Copyright © 2017 iZettle. All rights reserved.
//
#if canImport(UIKit)
import UIKit
public extension UIView {
var windowSignal: ReadSignal<UIWindow?> {
return signal(for: \.windowCallbacker).readable(capturing: self.window)
}
var hasWindowSignal: ReadSignal<Bool> {
return windowSignal.map { $0 != nil }
}
var didMoveToWindowSignal: Signal<()> {
return hasWindowSignal.filter { $0 }.toVoid()
}
var didMoveFromWindowSignal: Signal<()> {
return hasWindowSignal.filter { !$0 }.toVoid()
}
var traitCollectionSignal: ReadSignal<UITraitCollection> {
return signal(for: \.traitCollectionCallbacker).readable(capturing: self.traitCollection)
}
var didLayoutSignal: Signal<()> {
return signal(for: \.didLayoutCallbacker)
}
}
private extension UIView {
func signal<T>(for keyPath: KeyPath<CallbackerView, Callbacker<T>>) -> Signal<T> {
return Signal { c in
let view = (self.viewWithTag(987892442) as? CallbackerView) ?? {
let v = CallbackerView(frame: self.bounds)
v.autoresizingMask = [.flexibleWidth, .flexibleHeight] // trick so layoutsubViews is called when the view is resized
v.tag = 987892442
v.backgroundColor = .clear
v.isUserInteractionEnabled = false
self.insertSubview(v, at: 0)
v.setNeedsLayout()
return v
}()
view.refCount += 1
let bag = DisposeBag()
bag += {
view.refCount -= 1
if view.refCount == 0 {
view.removeFromSuperview()
}
}
bag += view[keyPath: keyPath].addCallback(c)
return bag
}
}
}
private class CallbackerView: UIView {
let windowCallbacker = Callbacker<UIWindow?>()
let traitCollectionCallbacker = Callbacker<UITraitCollection>()
let didLayoutCallbacker = Callbacker<()>()
var refCount = 0
override fileprivate func didMoveToWindow() {
super.didMoveToWindow()
windowCallbacker.callAll(with: window)
}
fileprivate override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
traitCollectionCallbacker.callAll(with: traitCollection)
}
override fileprivate func layoutSubviews() {
super.layoutSubviews()
didLayoutCallbacker.callAll()
}
// Tap through
fileprivate override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return false
}
}
#endif
| mit | 27986ce60880893341c2543e4ee38454 | 28.212121 | 132 | 0.596819 | 4.901695 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue | iOS/Venue/Models/Ad.swift | 1 | 1111 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
import CoreData
/// Class to represent an Ad object
class Ad: NSObject {
let id: Int
let name: String
let details: String
let thumbnailUrl: String
override init() {
id = 0
name = ""
details = ""
thumbnailUrl = ""
super.init()
}
convenience init(managedAd: NSManagedObject) {
guard let id = managedAd.valueForKey("id") as? Int, let name = managedAd.valueForKey("name") as? String, let details = managedAd.valueForKey("details") as? String, let thumbnailUrl = managedAd.valueForKey("thumbnail_url") as? String else {
self.init()
return
}
self.init(id: id,name: name,details: details,thumbnailUrl: thumbnailUrl)
}
internal init(id: Int, name: String, details: String, thumbnailUrl: String) {
self.id = id
self.name = name
self.details = details
self.thumbnailUrl = thumbnailUrl
super.init()
}
} | epl-1.0 | fff78bfc4bb85e6cc2c71ddb7a9f1191 | 26.097561 | 247 | 0.607207 | 4.475806 | false | false | false | false |
m4rr/MosCoding | EasyBrowser/EasyBrowser/ViewController.swift | 1 | 1700 | //
// ViewController.swift
// EasyBrowser
//
// Created by Marat S. on 12/11/2016.
// Copyright © 2016 m4rr. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func openPageInSafari(_ sender: Any) {
// open moscoding.ru
// безопасное расркытие контейнера `NSURL?`
// if let адресСайта = URL(string: "http://moscoding.ru") {
// UIApplication.shared
// .open(адресСайта, options: [:], completionHandler: nil)
// }
// let опасноРаскрытыйАдрес = NSURL(string: "https://moscoding.ru!@#$%^&*(")!
}
@IBAction func openPage(_ sender: Any) {
// безопасное расркытие контейнера `NSURL?`
if let адресСайта = URL(string: "https://yandex.ru") {
let urlReq = URLRequest(url: адресСайта)
webView.loadRequest(urlReq)
}
}
@IBAction func backButtonDidTap(_ sender: Any) {
// нажатие кнопки "назад"
webView.goBack()
}
}
extension ViewController: UIWebViewDelegate {
func webViewDidStartLoad(_ webView: UIWebView) {
// сменить фон экрана на зеленый
self.view.backgroundColor = .green
}
func webViewDidFinishLoad(_ webView: UIWebView) {
// сменить фон экрана на белый
view.backgroundColor = .white
}
}
| mit | aa7b76705d1e2af5e99a30ea92c46a68 | 18.675325 | 80 | 0.662706 | 3.412162 | false | false | false | false |
silence0201/Swift-Study | Swifter/12FuncDispatch.playground/Contents.swift | 1 | 649 | //: Playground - noun: a place where people can play
import Foundation
class MyClass {
func method(number: Int) -> Int {
return number + 1
}
}
let object = MyClass()
let result = object.method(number: 1)
// result = 2
let f = MyClass.method
let object1 = MyClass()
let result1 = f(object)(1)
class MyClass1 {
func method(number: Int) -> Int {
return number + 1
}
class func method(number: Int) -> Int {
return number
}
}
let f1 = MyClass1.method
// class func method 的版本
let f2: (Int) -> Int = MyClass1.method
// 和 f1 相同
let f3: (MyClass1) -> (Int) -> Int = MyClass1.method
| mit | 715fd4ef87fc5b8bba33f99c1c779845 | 16.216216 | 52 | 0.613815 | 3.266667 | false | false | false | false |
liuweicode/LinkimFoundation | Example/LinkimFoundation/AppDelegate.swift | 1 | 4221 | //
// AppDelegate.swift
// LinkimFoundation
//
// Created by liuwei on 06/30/2016.
// Copyright (c) 2016 liuwei. All rights reserved.
//
import UIKit
import CoreGraphics
import LinkimFoundation
import IQKeyboardManagerSwift
import PKHUD
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var reachability: Reachability?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
IQKeyboardManager.sharedManager().enable = true
self.window = UIWindow(frame:UIScreen.mainScreen().bounds)
// let mainController = MainViewController()
// let navigationController = UINavigationController(rootViewController: mainController)
// self.window?.rootViewController = navigationController
let tabBarController = TabBarController()
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
// 监听网络连接状态
self.startInternetConnectionMonitoring()
return true
}
func startInternetConnectionMonitoring()
{
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(reachabilityChanged(_:)),name: ReachabilityChangedNotification,object: reachability)
do{
try reachability?.startNotifier()
}catch{
print("could not start reachability notifier")
}
}
// 网络状态通知
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
if reachability.isReachableViaWiFi() {
#if DEBUG
print("DEBUG WiFi网络")
#endif
#if INHOUSE
print("INHOUSE WiFi网络")
#endif
} else {
print("手机网络")
}
} else {
#if DEBUG
print("DEBUG 没有网络")
#endif
#if INHOUSE
print("INHOUSE 没有网络")
#endif
}
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 9d6001e050b8587da342f2ac6dd5e059 | 34.87069 | 285 | 0.648161 | 5.978448 | false | false | false | false |
sdkshredder/SocialMe | SocialMe/SocialMe/SettingsTVC.swift | 1 | 31682 | //
// SettingsTVC.swift
// SocialMe
//
// Created by Mariam Ghanbari on 5/17/15.
// Copyright (c) 2015 new. All rights reserved.
//
import UIKit
import Parse
class SettingsTVC: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate {
@IBOutlet weak var relationshipSegments: UISegmentedControl!
var homeButtons = [UIButton]()
var schoolButtons = [UIButton]()
var occButtons = [UIButton]()
var aboutButtons = [UIButton]()
var center = NSNotificationCenter.defaultCenter()
@IBOutlet weak var lowerAge: UIPickerView!
@IBOutlet weak var upperAge: UIPickerView!
@IBOutlet weak var distanceValue: UILabel!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var segment: UISegmentedControl!
@IBOutlet weak var keyword: UITextField!
@IBOutlet weak var keySeg: UISegmentedControl!
@IBOutlet weak var keyCell: UIView!
@IBOutlet var keyTVC: UITableViewCell!
@IBOutlet var noContentLabel: UILabel!
@IBOutlet var distanceSwitch: UIButton!
var distanceEnabled = true
var pickerData = [18]
var purple = UIColor(red: 59.0/255.0, green: 45.0/255.0, blue: 128.0/255.0, alpha: 1)
@IBAction func valueDidChange(sender: UISlider) {
let distance = Int(sender.value)
distanceValue.text = "\(distance) ft"
}
@IBAction func relatOptionChanged(sender: UISegmentedControl) {
var aAlpha = 1
var bAlpha = 1
var cAlpha = 1
if sender.selectedSegmentIndex == 0 {
bAlpha = 0
cAlpha = 0
} else if sender.selectedSegmentIndex == 1 {
aAlpha = 0
cAlpha = 0
} else {
aAlpha = 0
bAlpha = 0
}
}
@IBAction func controlSwitch(sender: UISegmentedControl) {
var aAlpha = 1
var bAlpha = 1
var cAlpha = 1
if sender.selectedSegmentIndex == 0 {
bAlpha = 0
cAlpha = 0
} else if sender.selectedSegmentIndex == 1 {
aAlpha = 0
cAlpha = 0
} else {
aAlpha = 0
bAlpha = 0
}
UIView.animateWithDuration(0.2, animations: {
for button in self.homeButtons {
button.alpha = CGFloat(aAlpha)
}
for button in self.schoolButtons {
button.alpha = CGFloat(bAlpha)
}
for button in self.occButtons {
button.alpha = CGFloat(cAlpha)
}
})
}
/*
func capFirstLetter(name: String) -> String {
if (name.isEmpty) {
return name
}
var capLet = name.substringWithRange(Range<String.Index>(start: name.startIndex , end: advance(name.startIndex, 1))) as NSString
capLet = capLet.uppercaseString
let needle: Character = " "
if let idx = find(name, needle){
let pos = distance(name,stateIndex, idx)
var rest = capFirstLetter(
} else {
var rest = name.substringFromIndex(advance(name.startIndex, 1)) as NSString
return (capLet as String) + (rest as String)
}*/
func deleteKey(sender: UIButton) {
print("Deleting key")
print(sender.titleLabel!.text!)
let user = PFUser.currentUser()
let toRemove = sender.titleLabel!.text! as String
let type = keySeg.titleForSegmentAtIndex(keySeg.selectedSegmentIndex)!
let keywordQuery = PFQuery(className: "KeywordFilter")
keywordQuery.whereKey("username", equalTo: user!.username!)
var objectArr = keywordQuery.findObjects() as! [PFObject]
if objectArr.count > 0 { // Username exists in keyword filters
let keyObj = objectArr[0]
sender.removeFromSuperview()
switch type {
case "Hometown":
if let filter = keyObj["homeFilter"] as? NSMutableArray {
if filter.containsObject(toRemove){
filter.removeObject(toRemove)
keyObj["homeFilter"] = filter
keyObj.save()
}
}
var index = 0
for button in self.homeButtons {
if button.titleLabel!.text == toRemove {
self.homeButtons.removeAtIndex(index)
}
index += 1
}
case "School":
if let filter = keyObj["schoolFilter"] as? NSMutableArray {
if filter.containsObject(toRemove){
filter.removeObject(toRemove)
keyObj["schoolFilter"] = filter
keyObj.save()
}
}
var index = 0
for button in self.schoolButtons {
if button.titleLabel!.text == toRemove {
self.schoolButtons.removeAtIndex(index)
}
index += 1
}
case "Occupation":
if let filter = keyObj["occFilter"] as? NSMutableArray {
if filter.containsObject(toRemove){
filter.removeObject(toRemove)
keyObj["occFilter"] = filter
keyObj.save()
}
}
var index = 0
for button in self.occButtons {
if button.titleLabel!.text == toRemove {
self.occButtons.removeAtIndex(index)
}
index += 1
}
case "About":
if let filter = keyObj["aboutFilter"] as? NSMutableArray {
if filter.containsObject(toRemove){
filter.removeObject(toRemove)
keyObj["aboutFilter"] = filter
keyObj.save()
}
}
var index = 0
for button in self.aboutButtons {
if button.titleLabel!.text == toRemove {
self.aboutButtons.removeAtIndex(index)
}
index += 1
}
default:
print("Error determining keyword filter type")
}
}
}
@IBAction func loadKeys(sender: UISegmentedControl) {
let user = PFUser.currentUser()
if let type = self.keySeg.titleForSegmentAtIndex(self.keySeg.selectedSegmentIndex) {
let keywordQuery = PFQuery(className: "KeywordFilter")
keywordQuery.whereKey("username", equalTo: user!.username!)
var objectArr = keywordQuery.findObjects() as! [PFObject]
if objectArr.count > 0 { // Username exists in keyword filters
let keyObj = objectArr[0]
for v in self.keyCell.subviews {
if v is UIButton {
v.removeFromSuperview()
}
}
switch type {
case "Hometown":
if let filter = keyObj["homeFilter"] as? NSMutableArray {
self.noContentLabel.hidden = true
self.homeButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
if self.homeButtons.count == 0 {
self.noContentLabel.hidden = false
}
} else {
self.noContentLabel.hidden = false
}
case "School":
if let filter = keyObj["schoolFilter"] as? NSMutableArray {
self.noContentLabel.hidden = true
self.schoolButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
if self.schoolButtons.count == 0 {
self.noContentLabel.hidden = false
}
} else {
self.noContentLabel.hidden = false
}
case "Occupation":
if let filter = keyObj["occFilter"] as? NSMutableArray {
self.noContentLabel.hidden = true
self.occButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
if self.occButtons.count == 0 {
self.noContentLabel.hidden = false
}
} else {
self.noContentLabel.hidden = false
}
case "About":
if let filter = keyObj["aboutFilter"] as? NSMutableArray {
self.noContentLabel.hidden = true
self.aboutButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
if self.aboutButtons.count == 0 {
self.noContentLabel.hidden = false
}
} else {
self.noContentLabel.hidden = false
}
default:
print("Error determining keyword filter type")
}
} else {
self.noContentLabel.hidden = false
}
}
}
func makeButton(order: Double, label: NSString) -> UIButton{
print("creatingbutton")
print(label)
let button = UIButton(type: UIButtonType.System)
var posX = Double(noContentLabel.frame.origin.x)
//let buttonWidth = (Double(self.keyCell.frame.size.width) / 3.0) - 20.0
let buttonWidth = 100.0
print(self.keyCell.frame.size.width)
if order == 0.0 {
noContentLabel.hidden = true
} else {
posX += order * (buttonWidth + 10)
}
button.frame = CGRectMake(CGFloat(posX), noContentLabel.frame.origin.y, CGFloat(buttonWidth), 30)
//button.backgroundColor = UIColor.greenColor()
button.setTitle(label as String, forState: UIControlState.Normal)
button.titleLabel?.numberOfLines = 1
button.titleLabel?.adjustsFontSizeToFitWidth = true
//button.addTarget(self, action: "deleteKey:", forControlEvents: UIControlEvents.TouchDragExit)
button.addTarget(self, action: #selector(SettingsTVC.deleteKey(_:)), forControlEvents: UIControlEvents.TouchUpInside)
return button
}
func addButton(input: String, type: String) {
let color = UIColor(red: 57.0/255.0, green: 29.0/255.0, blue: 130.0/255.0, alpha: 1)
switch type {
case "Hometown":
if homeButtons.count <= 3 {
let button = makeButton(Double(self.homeButtons.count), label: input)
button.tintColor = color
button.layer.borderColor = color.CGColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 4
self.homeButtons.append(button)
self.keyCell.addSubview(button)
}
case "School":
if schoolButtons.count <= 3 {
let button = makeButton(Double(self.schoolButtons.count), label: input)
button.tintColor = color
button.layer.borderColor = color.CGColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 4
self.schoolButtons.append(button)
self.keyCell.addSubview(button)
}
case "Occupation":
if occButtons.count <= 3 {
let button = makeButton(Double(self.occButtons.count), label: input)
button.tintColor = color
button.layer.borderColor = color.CGColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 4
self.occButtons.append(button)
self.keyCell.addSubview(button)
}
case "About":
if occButtons.count <= 3 {
let button = makeButton(Double(self.aboutButtons.count), label: input)
button.tintColor = color
button.layer.borderColor = color.CGColor
button.layer.borderWidth = 1
button.layer.cornerRadius = 4
self.aboutButtons.append(button)
self.keyCell.addSubview(button)
}
default:
print("no match")
}
tableView.reloadData()
}
/*
@IBAction func distanceSwitched(sender: UIButton) {
let title = sender.titleForState(.Normal)?.lowercaseString
var hello = String()
var color = UIColor()
var tColor = UIColor()
distanceEnabled = !distanceEnabled
var info = [String : Bool]()
info["value"] = distanceEnabled
center.postNotificationName("distanceNote", object: nil, userInfo: info)
if title == "disabled" {
hello = "Enabled"
color = UIColor.whiteColor()
tColor = purple
} else {
hello = "Disabled"
color = purple
tColor = UIColor.whiteColor()
// sender.setTitle("Disabled", forState: .Normal)
}
UIView.animateWithDuration(0.2, animations: {
sender.setTitle(hello, forState: .Normal)
sender.backgroundColor = color
sender.setTitleColor(tColor, forState: .Normal)
})
}*/
@IBAction func addKey(sender: UITextField) {
let input = sender.text
let type = self.keySeg.titleForSegmentAtIndex(self.keySeg.selectedSegmentIndex)!
if input != "" {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let user = PFUser.currentUser()
let query = PFQuery(className: "KeywordFilter")
query.whereKey("username", equalTo: user!.username!)
var objectArr = query.findObjects() as! [PFObject]
if objectArr.count > 0 { // Username in list
let keyObj = objectArr[0]
switch type {
case "Hometown":
if let filter = keyObj["homeFilter"] as? NSMutableArray { // Has already filtered by hometown
if !filter.containsObject(input!) && filter.count < 3 { // keyword not already in list
print("Number filters:")
print(filter.count)
// (get_ma, <#block: dispatch_block_t##() -> Void#>
dispatch_async(dispatch_get_main_queue(), {
self.addButton(input!, type: type)
})
filter.addObject(input!)
keyObj["homeFilter"] = filter
keyObj.save()
} else if filter.count >= 3 {
let alert = UIAlertView(title: "Keyword Limit Reached", message: "Delete a keyword before adding a new one", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
} else { // Has not previously filtered by hometown, create new array
let basic = NSMutableArray()
basic.addObject(input!)
keyObj["homeFilter"] = basic
keyObj.save()
}
/*
var button = self.makeButton(Double(self.homeButtons.count), label: sender.text)
self.homeButtons.append(button)
self.keyCell.addSubview(button)
*/
//self.homeButtons.append(self.makeButton(Double(self.homeButtons.count), label: sender.text))
case "School":
if let filter = keyObj["schoolFilter"] as? NSMutableArray { // Has already filtered by school
if !filter.containsObject(input!) && filter.count < 3 {
dispatch_async(dispatch_get_main_queue(), {
self.addButton(input!, type: type)
})
filter.addObject(input!)
keyObj["schoolFilter"] = filter
keyObj.save()
} else if filter.count >= 3 {
let alert = UIAlertView(title: "Keyword Limit Reached", message: "Delete a keyword before adding a new one", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
} else {
let basic = NSMutableArray()
basic.addObject(input!)
keyObj["schoolFilter"] = basic
keyObj.save()
}
//self.schoolButtons.append(self.makeButton(Double(self.schoolButtons.count), label: sender.text))
case "Occupation":
if let filter = keyObj["occFilter"] as? NSMutableArray { // Has already filttered by occupation
if !filter.containsObject(input!) && filter.count < 3 {
dispatch_async(dispatch_get_main_queue(), {
self.addButton(input!, type: type)
})
filter.addObject(input!)
keyObj["occFilter"] = filter
keyObj.save()
} else if filter.count >= 3 {
let alert = UIAlertView(title: "Keyword Limit Reached", message: "Delete a keyword before adding a new one", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
} else {
let basic = NSMutableArray()
basic.addObject(input!)
keyObj["occFilter"] = basic
keyObj.save()
}
//self.occButtons.append(self.makeButton(Double(self.occButtons.count), label: sender.text))
case "About":
if let filter = keyObj["aboutFilter"] as? NSMutableArray { // Has already filttered by occupation
if !filter.containsObject(input!) && filter.count < 3 {
self.addButton(input!, type: type)
filter.addObject(input!)
keyObj["aboutFilter"] = filter
keyObj.save()
} else if filter.count >= 3 {
let alert = UIAlertView(title: "Keyword Limit Reached", message: "Delete a keyword before adding a new one", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
} else {
let basic = NSMutableArray()
basic.addObject(input!)
keyObj["aboutFilter"] = basic
keyObj.save()
}
default:
print("No match" )
}
} else { // Username not in list, create new row and add filter
let newKey = PFObject(className: "KeywordFilter")
newKey["username"] = user?.username
let basic = NSMutableArray()
basic.addObject(input!)
switch type {
case "Hometown":
newKey["homeFilter"] = basic
case "School":
newKey["schoolFilter"] = basic
case "Occupation":
newKey["occFilter"] = basic
default:
print("No match")
}
newKey.save()
}
}
sender.text = ""
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
let a = pickerData[row]
return String(stringInterpolationSegment: a)
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
func initData(){
for index in 19...50 {
pickerData.append(index)
}
}
func handleSave(){
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
var change = 0
let user = PFUser.currentUser()
if Int(self.slider.value) != user?.objectForKey("distanceFilter") as! Int{
user!.setObject(Int(self.slider.value), forKey:"distanceFilter")
change = 1
}
if Int(self.lowerAge.selectedRowInComponent(0)) + 18 != user?.objectForKey("lowerAgeFilter") as! Int{
user!.setObject(Int(self.lowerAge.selectedRowInComponent(0)) + 18, forKey:"lowerAgeFilter")
change = 1
}
if Int(self.upperAge.selectedRowInComponent(0)) + 18 != user?.objectForKey("upperAgeFilter") as! Int{
user!.setObject(Int(self.upperAge.selectedRowInComponent(0)) + 18, forKey:"upperAgeFilter")
change = 1
}
if self.segment.titleForSegmentAtIndex(self.segment.selectedSegmentIndex) != user?.objectForKey("genderFilter") as? String{
user!.setObject(self.segment.titleForSegmentAtIndex(self.segment.selectedSegmentIndex)!, forKey:"genderFilter")
change = 1
}
if self.relationshipSegments.titleForSegmentAtIndex(self.relationshipSegments.selectedSegmentIndex) != user?.objectForKey("relationshipGoal") as? String {
user!.setObject(self.relationshipSegments.titleForSegmentAtIndex(self.relationshipSegments.selectedSegmentIndex)!, forKey: "relationshipGoal")
change = 1
}
if change == 1 {
user?.save()
}
}
}
func back(sender: UIBarButtonItem) {
if self.lowerAge.selectedRowInComponent(0) > self.upperAge.selectedRowInComponent(0){
let alert = UIAlertView(title: "Invalid Age Range", message: "Lower age cannot be greater than Upper age", delegate: nil, cancelButtonTitle: "OK")
alert.show()
} else {
navigationController?.popViewControllerAnimated(true)
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
keyword.resignFirstResponder()
keyword.endEditing(true)
return true
}
func setupDistanceSwitch() {
/*
distanceSwitch.layer.cornerRadius = 4
distanceSwitch.layer.borderColor = UIColor.purpleColor().CGColor
distanceSwitch.layer.borderWidth = 1
distanceSwitch.clipsToBounds = true
*/
}
override func viewDidLoad() {
super.viewDidLoad()
setupDistanceSwitch()
let backButton = UIBarButtonItem(barButtonSystemItem: .Save, target: self, action: #selector(SettingsTVC.back(_:)))
navigationItem.leftBarButtonItem = backButton
navigationItem.title = "Filters"
initData()
let user = PFUser.currentUser()
let distance = user?.objectForKey("distanceFilter") as! Int
slider.value = Float(distance)
distanceValue.text = "\(distance) ft"
//lookingForPicker.selectRow((user?.objectForKey("lookingForStatus") as! Int), inComponent: 0, animated: true )
lowerAge.delegate = self
lowerAge.dataSource = self
lowerAge.selectRow((user?.objectForKey("lowerAgeFilter") as! Int) - 18, inComponent: 0, animated: true)
upperAge.delegate = self
upperAge.dataSource = self
upperAge.selectRow((user?.objectForKey("upperAgeFilter") as! Int) - 18, inComponent: 0, animated: true)
let gender = user?.objectForKey("genderFilter") as! String
switch gender {
case "Male":
segment.selectedSegmentIndex = 0
case "Female":
segment.selectedSegmentIndex = 1
default:
segment.selectedSegmentIndex = 2
}
if let relationshipGoal = user?.objectForKey("relationshipGoal") as? String {
switch relationshipGoal {
case "Business":
relationshipSegments.selectedSegmentIndex = 1
case "Romantic":
relationshipSegments.selectedSegmentIndex = 2
case "Social":
relationshipSegments.selectedSegmentIndex = 0
default:
relationshipSegments.selectedSegmentIndex = 3
}
} else {
relationshipSegments.selectedSegmentIndex = 3
}
keyword.delegate = self
if keySeg.selectedSegmentIndex == -1 {
keySeg.selectedSegmentIndex = 0
}
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
if let type = self.keySeg.titleForSegmentAtIndex(self.keySeg.selectedSegmentIndex) {
let keywordQuery = PFQuery(className: "KeywordFilter")
keywordQuery.whereKey("username", equalTo: user!.username!)
var objectArr = keywordQuery.findObjects() as! [PFObject]
if objectArr.count > 0 { // Username exists in keyword filters
let keyObj = objectArr[0]
for v in self.keyCell.subviews {
if v is UIButton {
v.removeFromSuperview()
}
}
switch type {
case "Hometown":
if let filter = keyObj["homeFilter"] as? NSMutableArray {
if self.homeButtons.count <= 0 {
self.noContentLabel.hidden = false
} else {
self.noContentLabel.hidden = true
}
self.homeButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
} else {
self.noContentLabel.hidden = false
}
case "School":
if let filter = keyObj["schoolFilter"] as? NSMutableArray {
if self.schoolButtons.count <= 0 {
self.noContentLabel.hidden = false
} else {
self.noContentLabel.hidden = true
}
self.schoolButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
} else {
self.noContentLabel.hidden = false
}
case "Occupation":
if let filter = keyObj["occFilter"] as? NSMutableArray {
if self.occButtons.count <= 0 {
self.noContentLabel.hidden = false
} else {
self.noContentLabel.hidden = true
}
self.occButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
} else {
self.noContentLabel.hidden = false
}
case "About":
if let filter = keyObj["aboutFilter"] as? NSMutableArray {
if self.aboutButtons.count <= 0 {
self.noContentLabel.hidden = false
} else {
self.noContentLabel.hidden = true
}
self.aboutButtons.removeAll(keepCapacity: false)
for keyword in filter {
self.addButton(keyword as! String, type: type)
}
} else {
self.noContentLabel.hidden = false
}
default:
print("Error determining keyword filter type")
}
} else {
self.noContentLabel.hidden = false
}
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
handleSave()
}
}
| mit | 04cfa92b190556fc74d8230759393df4 | 40.092088 | 184 | 0.479484 | 5.734299 | false | false | false | false |
wutongyu008/PictureSelector | PictureSelector/Extension/UIButton+Extension.swift | 1 | 2428 | //
// PictureSelectorViewController.swift
// PictureSelector
//
// Created by 裘明 on 15/9/20.
// Copyright © 2015年 裘明. All rights reserved.
//
import UIKit
extension UIButton {
/// 便利构造函数
///
/// - parameter imageName: 图像名称
/// - parameter backImageName: 背景图像名称
///
/// - returns: UIButton
/// - 备注:如果图像名称使用 "" 会抱错误 CUICatalog: Invalid asset name supplied:
convenience init(imageName: String, backImageName: String?) {
self.init()
setImage(UIImage(named: imageName), forState: .Normal)
setImage(UIImage(named: imageName + "_highlighted"), forState: .Highlighted)
if let backImageName = backImageName {
setBackgroundImage(UIImage(named: backImageName), forState: .Normal)
setBackgroundImage(UIImage(named: backImageName + "_highlighted"), forState: .Highlighted)
}
// 会根据背景图片的大小调整尺寸
sizeToFit()
}
/// 便利构造函数
///
/// - parameter title: title
/// - parameter color: color
/// - parameter backImageName: 背景图像
///
/// - returns: UIButton
convenience init(title: String, color: UIColor, backImageName: String) {
self.init()
setTitle(title, forState: .Normal)
setTitleColor(color, forState: .Normal)
setBackgroundImage(UIImage(named: backImageName), forState: .Normal)
sizeToFit()
}
/// 便利构造函数
///
/// - parameter title: title
/// - parameter color: color
/// - parameter fontSize: 字体大小
/// - parameter imageName: 图像名称
/// - parameter backColor: 背景颜色(默认为nil)
///
/// - returns: UIButton
convenience init(title: String, fontSize: CGFloat, color: UIColor, imageName: String?, backColor: UIColor? = nil) {
self.init()
setTitle(title, forState: .Normal)
setTitleColor(color, forState: .Normal)
if let imageName = imageName {
setImage(UIImage(named: imageName), forState: .Normal)
}
// 设置背景颜色
backgroundColor = backColor
titleLabel?.font = UIFont.systemFontOfSize(fontSize)
sizeToFit()
}
}
| apache-2.0 | be058eef3bd3731544bb9db298d603c3 | 27.468354 | 119 | 0.577145 | 4.646694 | false | false | false | false |
vyo/sprig | Sources/Level.swift | 1 | 145 | public enum Level: Int {
case TRACE = 10
case DEBUG = 20
case INFO = 30
case WARN = 40
case ERROR = 50
case FATAL = 60
}
| mit | dda2028b8a1031bc8f0e693353d006b3 | 17.125 | 24 | 0.565517 | 3.625 | false | false | false | false |
AwwApps/Open-Beacon-Credentials | BeaconLookup.swift | 1 | 5619 | //
// BeaconLookup.swift
//
//
// Created by Bernd Plontsch on 29/08/14.
// Copyright (c) 2014 Bernd Plontsch. All rights reserved.
//
import UIKit
import CoreLocation
public class BeaconLookup: NSObject {
public class func lookUpForCredentials(beaconUUID:NSString,beaconMajorID:Int,beaconMinorID:Int)->NSString {
var region:CLBeaconRegion
let uuid:NSUUID = NSUUID(UUIDString: beaconUUID)!
region = CLBeaconRegion(proximityUUID: uuid, major: CLBeaconMajorValue(beaconMajorID), minor: CLBeaconMinorValue(beaconMinorID), identifier: beaconUUID)
let lookedUpString:NSString = lookUpForCLBeacon(region).string as NSString!
return lookedUpString
}
public class func lookUpSpotForCredentials(beaconUUID:NSString,beaconMajorID:Int,beaconMinorID:Int)->NSString {
var region:CLBeaconRegion
let uuid:NSUUID = NSUUID(UUIDString: beaconUUID)!
region = CLBeaconRegion(proximityUUID: uuid, major: CLBeaconMajorValue(beaconMajorID), minor: CLBeaconMinorValue(beaconMinorID), identifier: beaconUUID)
var lookedUpString:NSString? = lookUpForCLBeacon(region).spot
if lookedUpString != nil {
return lookedUpString!
} else {
return "Beacon"
}
}
public class func lookUpForCLBeacon(beacon:CLBeaconRegion)->(room:NSString?, spot:NSString?, string:NSString) {
let lookUpMajor:NSString = beacon.major.stringValue;
let lookUpMinor:NSString = beacon.minor.stringValue;
let lookUpUUID:NSString = beacon.proximityUUID.UUIDString;
let beaconDictionary:NSDictionary = openBeaconCredentialsDictionary()
let UUIDDictionary:NSDictionary = beaconDictionary.objectForKey("UUID") as NSDictionary
let majorIDDictionary:NSDictionary = (beaconDictionary.objectForKey("Major") as NSDictionary).objectForKey("ID") as NSDictionary
let minorIDDictionary:NSDictionary = (beaconDictionary.objectForKey("Minor") as NSDictionary).objectForKey("ID") as NSDictionary
//BEACON NAME
var beaconName:NSString?
if UUIDDictionary.valueForKey(lookUpUUID) != nil {
beaconName = UUIDDictionary.valueForKey(lookUpUUID) as? NSString
} else {
beaconName = "Beacon"
}
//ROOM
var beaconRoom:NSString? = majorIDDictionary.valueForKey(lookUpMajor) as? NSString
if beaconRoom == nil {
var beaconRoomRange:NSString? = lookUpRange(lookUpMajor.integerValue, rangeDictionary: (beaconDictionary.objectForKey("Major") as NSDictionary).objectForKey("Range") as NSDictionary)
if beaconRoomRange != nil {
beaconRoom = beaconRoomRange
}
}
//SPOT
var beaconSpot:NSString? = minorIDDictionary.valueForKey(lookUpMinor) as? NSString
if beaconSpot == nil {
var beaconSpotRange:NSString? = lookUpRange(lookUpMinor.integerValue, rangeDictionary: (beaconDictionary.objectForKey("Minor") as NSDictionary).objectForKey("Range") as NSDictionary)
if beaconSpotRange != nil {
beaconSpot = beaconSpotRange
}
}
//LABEL
var label:NSString = "Beacon"
if (beaconSpot != nil && beaconRoom != nil) {
label = NSString(format: "%@ %@", beaconSpot!,beaconRoom!)
} else {
if (beaconSpot == nil && beaconRoom != nil) {
label = beaconRoom!
}
if (beaconSpot != nil && beaconRoom == nil) {
label = beaconSpot!
}
if beaconSpot == nil && beaconRoom == nil && beaconName != nil {
label = beaconName!
}
}
return (beaconRoom,beaconSpot,label)
}
public class func lookUpRange(identifier:Int, rangeDictionary:NSDictionary)->NSString? {
var lookedUpString:NSString?
rangeDictionary.enumerateKeysAndObjectsUsingBlock { (key, object, stop) -> Void in
let from:Int? = Int(object.valueForKey("from") as NSNumber)
let to:Int? = Int(object.valueForKey("to") as NSNumber)
if from != nil && to != nil {
if identifier > from && identifier < to {
lookedUpString = key as? NSString
stop.memory = true
}
}
}
return lookedUpString
}
public class func openBeaconCredentialsDictionary()->NSDictionary {
let path:NSString = NSBundle(forClass: BeaconLookup.self).pathForResource("OpenBeaconCredentials", ofType: "plist")!
let openBeaconCredentialsDictionary:NSDictionary = NSDictionary(contentsOfFile: path)!
return openBeaconCredentialsDictionary
}
public class func lookUpNameForUUID(uuidString:NSString)->NSString {
let beacons:NSDictionary = openBeaconCredentialsDictionary().objectForKey("UUID") as NSDictionary
let name:NSString? = beacons.objectForKey(uuidString) as? NSString
if name != nil {
return name!
}
return "Beacon"
}
public class func allBeacons()->NSArray {
let beacons:NSDictionary = openBeaconCredentialsDictionary().objectForKey("UUID") as NSDictionary
var allBeacons:NSMutableArray = NSMutableArray()
beacons.enumerateKeysAndObjectsUsingBlock { (item, count, stop) -> Void in
if item != nil {
allBeacons.addObject(item as NSString)
}
}
return allBeacons
}
}
| mit | 8ea4bbc778ef43572e1da5876b631616 | 41.24812 | 194 | 0.640861 | 5.008021 | false | false | false | false |
fragginAJ/projectEuler | projectEuler2.playground/Contents.swift | 1 | 1335 | //: Playground - noun: a place where people can play
import UIKit
/*
Fibonacci sequence:
F(n) = F(n-1) + F(n-2)
Performing the houskeeping at the end of each loop is an easy way to get the wrong answer to this problem. Think the sequence through.
*/
//
// Helper Functions
//
func numberIsEven(number: Int) -> Bool {
return (number % 2) == 0
}
//
// Brute Force
//
func bruteForceFibonacciSumWithinLimit(limit: Int) {
var fibonacciOne = 1
var fibonacciTwo = 1
var fibonacciResult = 0
var sum = 0
repeat {
if (numberIsEven(fibonacciResult)) {
sum += fibonacciResult
}
fibonacciResult = fibonacciOne + fibonacciTwo
fibonacciTwo = fibonacciOne
fibonacciOne = fibonacciResult
} while (fibonacciResult < limit)
print(sum)
}
bruteForceFibonacciSumWithinLimit(4000000)
//
// Optimized to work with only even numbers
// http://www.mathblog.dk/project-euler-problem-2/
//
func optimallyFindFibonacciSumWithinLimit(limit: Int) {
var fibonacciOne = 2
var fibonacciTwo = 0
var fibonacciResult = 2
var sum = 0
repeat {
if (numberIsEven(fibonacciResult)) {
sum += fibonacciResult
}
fibonacciResult = 4 * fibonacciOne + fibonacciTwo
fibonacciTwo = fibonacciOne
fibonacciOne = fibonacciResult
} while (fibonacciResult < limit)
print(sum)
}
optimallyFindFibonacciSumWithinLimit(4000000) | mit | 2c1ea1379e429adff1eb1c95b1ccb319 | 19.242424 | 135 | 0.723596 | 3.345865 | false | false | false | false |
czechboy0/XcodeServerSDK | XcodeServerSDKTests/XcodeServerTests.swift | 1 | 4723 | //
// XcodeServerTests.swift
// XcodeServerSDKTests
//
// Created by Honza Dvorsky on 11/06/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import XCTest
@testable import XcodeServerSDK
class XcodeServerTests: XCTestCase {
var server: XcodeServer!
override func setUp() {
super.setUp()
do {
let config = try XcodeServerConfig(
host: "https://127.0.0.1",
user: "ICanCreateBots",
password: "superSecr3t")
self.server = XcodeServerFactory.server(config)
} catch {
XCTFail("Failed to initialize the server configuration: \(error)")
}
}
func testServerCreation() {
XCTAssertNotNil(self.server)
}
// MARK: Creadentials tests
func testCredentials() {
let user = server.credential?.user
let pass = server.credential?.password
XCTAssertEqual(user!, "ICanCreateBots")
XCTAssertEqual(pass!, "superSecr3t")
}
func testNoUserCredentials() {
let noUserConfig = try! XcodeServerConfig(host: "https://127.0.0.1")
let server = XcodeServerFactory.server(noUserConfig)
XCTAssertNil(server.credential)
}
func DEV_testLiveUpdates() {
let exp = self.expectationWithDescription("Network")
let stopHandler = self.server.startListeningForLiveUpdates({ (messages: [LiveUpdateMessage]) -> () in
print(messages)
})
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5000 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue(), { () -> Void in
print("stopping")
stopHandler()
exp.fulfill()
})
self.waitForExpectationsWithTimeout(1000) { (_) -> Void in
stopHandler()
}
}
func DEV_testLive_GetBots() {
let exp = self.expectationWithDescription("Network")
self.server.getBots { (bots, error) in
exp.fulfill()
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func DEV_testLive_FetchAndRecordBot() {
let exp = self.expectationWithDescription("Network")
let server = self.getRecordingXcodeServer("test_bot")
server.getBots { (bots, error) in
exp.fulfill()
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
func DEV_testLive_BotCreation() {
let exp = self.expectationWithDescription("wait")
let privateKey = self.stringAtPath("~/.ssh/id_rsa")
let publicKey = self.stringAtPath("~/.ssh/id_rsa.pub")
let blueprint = SourceControlBlueprint(branch: "swift-2", projectWCCIdentifier: "A36AEFA3F9FF1F738E92F0C497C14977DCE02B97", wCCName: "XcodeServerSDK", projectName: "XcodeServerSDK", projectURL: "[email protected]:czechboy0/XcodeServerSDK.git", projectPath: "XcodeServerSDK.xcworkspace", publicSSHKey: publicKey, privateSSHKey: privateKey, sshPassphrase: nil, certificateFingerprint: nil)
let scriptBody = "cd XcodeServerSDK; /usr/local/bin/carthage update --no-build"
let scriptTrigger = Trigger(config: TriggerConfig(phase: .Prebuild, kind: .RunScript, scriptBody: scriptBody, name: "Carthage", conditions: nil, emailConfiguration: nil)!)
let devices = [
"a85553a5b26a7c1a4998f3b237005ac7",
"a85553a5b26a7c1a4998f3b237004afd"
]
let deviceSpec = DeviceSpecification.iOS(.SelectedDevicesAndSimulators, deviceIdentifiers: devices)
let config = BotConfiguration(builtFromClean: BotConfiguration.CleaningPolicy.Once_a_Day, codeCoveragePreference: .UseSchemeSetting, buildConfiguration: .UseSchemeSetting, analyze: true, test: true, archive: true, exportsProductFromArchive: true, schemeName: "XcodeServerSDK - iOS", schedule: BotSchedule.commitBotSchedule(), triggers: [scriptTrigger], deviceSpecification: deviceSpec, sourceControlBlueprint: blueprint)
let bot = Bot(name: "TestBot From XcodeServerSDK", configuration: config)
self.server.createBot(bot) { (response) -> () in
print("")
switch response {
case .Success(let newBot):
self.server.postIntegration(newBot.id) { (integration, error) -> () in
print("")
exp.fulfill()
}
default: break
}
}
self.waitForExpectationsWithTimeout(1000, handler: nil)
}
}
| mit | aa8a708e052c61e515ec88b1e556c2b2 | 34.511278 | 428 | 0.616557 | 4.536984 | false | true | false | false |
Hypercubesoft/HCFramework | HCFramework/Extensions/HCAttributedString.swift | 1 | 1022 | //
// HCAttributedString.swift
//
// Created by Hypercube on 9/26/17.
// Copyright © 2017 Hypercube. All rights reserved.
//
import UIKit
// MARK: - NSAttributedString extension
extension NSAttributedString
{
/// Calculate height of attributed string for specific font, the width text occupies and specific number of line.
///
/// - Parameters:
/// - font: AttributedString Font
/// - width: The width that the AttributedString occupies
/// - lineNumber: number of lines for AttributedString
/// - Returns: Height of AttributedString
open func hcTextHeight(font:UIFont, width:CGFloat, lineNumber: Int) -> CGFloat
{
let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = lineNumber
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = font
label.attributedText = self
label.sizeToFit()
return label.frame.height
}
}
| mit | 63af2cd106f4f5f18784728fdb58fd4d | 31.935484 | 117 | 0.675808 | 4.6621 | false | false | false | false |
ja-mes/experiments | Old/MyApp/MyApp/AppDelegate.swift | 1 | 6082 | //
// AppDelegate.swift
// MyApp
//
// Created by James Brown on 7/31/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.example.MyApp" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MyApp", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| mit | 8a64aa136966446caac943cad290f0f3 | 53.783784 | 291 | 0.718961 | 5.909621 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Widgets/AutocompleteTextField.swift | 3 | 5870 | /* 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
/// Delegate for the text field events. Since AutocompleteTextField owns the UITextFieldDelegate,
/// callers must use this instead.
protocol AutocompleteTextFieldDelegate: class {
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didTextChange text: String)
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField)
func autocompleteTextFieldDidEndEditing(autocompleteTextField: AutocompleteTextField)
}
private struct AutocompleteTextFieldUX {
static let HighlightColor = UIColor(rgb: 0xccdded)
}
class AutocompleteTextField: UITextField, UITextFieldDelegate {
weak var autocompleteDelegate: AutocompleteTextFieldDelegate?
private var autocompleting = false
private var acceptingSuggestions = false
override init(frame: CGRect) {
super.init(frame: frame)
super.delegate = self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
super.delegate = self
}
private var enteredText: NSString = "" {
didSet {
autocompleteDelegate?.autocompleteTextField(self, didTextChange: enteredText as String)
}
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let text = textField.text as NSString
// If we're autocompleting, stretch the range to the end of the text.
let range = autocompleting ? NSMakeRange(range.location, text.length - range.location) : range
// Update the entered text if we're adding characters or we're not autocompleting.
// Otherwise, we're going to clear the autocompletion, which means the entered text shouldn't change.
if !string.isEmpty || !autocompleting {
enteredText = text.stringByReplacingCharactersInRange(range, withString: string)
}
// TODO: short-circuit if no previous match and text is longer.
// TODO: cache last autocomplete result to prevent unnecessary iterations.
if !string.isEmpty {
acceptingSuggestions = true
// Do the replacement. We'll asynchronously set the autocompletion suggestion if needed.
return true
}
if autocompleting {
// Characters are being deleted, so clear the autocompletion, but don't change the text.
clearAutocomplete()
return false
}
// Characters are being deleted, and there's no autocompletion active, so go on.
return true
}
func setAutocompleteSuggestion(suggestion: String?) {
// We're not accepting suggestions, so ignore.
if !acceptingSuggestions {
return
}
// If there's no suggestion, clear the existing autocompletion and bail.
if suggestion == nil {
clearAutocomplete()
return
}
// Create the attributed string with the autocompletion highlight.
let attributedString = NSMutableAttributedString(string: suggestion!)
attributedString.addAttribute(NSBackgroundColorAttributeName, value: AutocompleteTextFieldUX.HighlightColor, range: NSMakeRange(self.enteredText.length, count(suggestion!) - self.enteredText.length))
attributedText = attributedString
// Set the current position to the beginning of the highlighted text.
let position = positionFromPosition(beginningOfDocument, offset: self.enteredText.length)
selectedTextRange = textRangeFromPosition(position, toPosition: position)
// Enable autocompletion mode as long as there are still suggested characters remaining.
autocompleting = enteredText != suggestion
}
/// Finalize any highlighted text.
private func finishAutocomplete() {
if autocompleting {
enteredText = attributedText?.string ?? ""
clearAutocomplete()
}
}
/// Clear any highlighted text and turn off the autocompleting flag.
private func clearAutocomplete() {
if autocompleting {
attributedText = NSMutableAttributedString(string: enteredText as String)
acceptingSuggestions = false
autocompleting = false
// Set the current position to the end of the text.
selectedTextRange = textRangeFromPosition(endOfDocument, toPosition: endOfDocument)
}
}
override func caretRectForPosition(position: UITextPosition!) -> CGRect {
return autocompleting ? CGRectZero : super.caretRectForPosition(position)
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
finishAutocomplete()
super.touchesEnded(touches, withEvent: event)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
finishAutocomplete()
return autocompleteDelegate?.autocompleteTextFieldShouldReturn(self) ?? true
}
func textFieldDidBeginEditing(textField: UITextField) {
autocompleteDelegate?.autocompleteTextFieldDidBeginEditing(self)
}
func textFieldDidEndEditing(textField: UITextField) {
finishAutocomplete()
autocompleteDelegate?.autocompleteTextFieldDidEndEditing(self)
}
func textFieldShouldClear(textField: UITextField) -> Bool {
clearAutocomplete()
return autocompleteDelegate?.autocompleteTextFieldShouldClear(self) ?? true
}
} | mpl-2.0 | 78b87c418973e1e0a810d8d1f6caade6 | 39.212329 | 207 | 0.705622 | 5.726829 | false | false | false | false |
twtstudio/WePeiYang-iOS | WePeiYang/Read/Model/Librarian.swift | 1 | 12975 | //
// Librarian.swift
// WePeiYang
//
// Created by Allen X on 10/27/16.
// Copyright © 2016 Qin Yubo. All rights reserved.
//
class Librarian {
struct SearchResult {
let title: String
//优化,此时得到的一些信息,特别是 cover 的图片可以在详情页面复用
let coverURL: String
let author: String
let publisher: String
let year: String
let rating: Double
let bookID: Int
let ISBN: String
}
static let shared = Librarian()
// static var resultList = [SearchResult]()
// static var currentBook: Book? = nil
static func searchBook(withString str: String, and completion: [SearchResult] -> ()) {
User.sharedInstance.getToken {
token in
// log.word(token)/
let manager = AFHTTPSessionManager()
manager.requestSerializer.setValue("Bearer {\(token)}", forHTTPHeaderField: "Authorization")
var searchURL = ReadAPI.bookSearchURL + str
searchURL = searchURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
log.word(searchURL)/
// manager.GET(searchURL, parameters: nil, progress: { (_) in
// MsgDisplay.showLoading()
// }, success: { (task, responseObject) in
MsgDisplay.showLoading()
manager.GET(searchURL, parameters: nil, progress: nil, success: { (task, responseObject) in
// print(responseObject)
guard responseObject != nil else {
MsgDisplay.showErrorMsg("哎呀, 出错啦")
//log.word("fuck1")/
return
}
guard responseObject?.objectForKey("error_code") as? Int == -1 else {
guard let msg = responseObject?.objectForKey("message") as? String else {
MsgDisplay.showErrorMsg("未知错误1")
//log.word("fuck2")/
return
}
MsgDisplay.showErrorMsg(msg)
//log.word("fuck1\(msg)")/
return
}
guard let fooBooksResults = responseObject?.objectForKey("data") as? Array<NSDictionary> else {
completion([SearchResult]())
return
}
let foo = fooBooksResults.flatMap({ (dict: NSDictionary) -> SearchResult? in
guard let title = dict["title"] as? String,
//let coverURL = dict["cover"] as? String,
let author = dict["author"] as? String,
let publisher = dict["publisher"] as? String,
let year = dict["year"] as? String,
//let rating = dict["rating"] as? Double,
let bookID = dict["index"] as? String,
let ISBN = dict["isbn"] as? String
else {
MsgDisplay.showErrorMsg("未知错误2")
log.word("未知错误")/
return nil
}
var coverURL = "https://images-na.ssl-images-amazon.com/images/I/51w6QuPzCLL._SX319_BO1,204,203,200_.jpg"
if let foo = dict["cover"] as? String {
coverURL = foo
}
var rating: Double = 3.0
if let foo = dict["rating"] as? Double {
rating = foo
}
// FIXME: bookID到底是String还是Int
return SearchResult(title: title, coverURL: coverURL, author: author, publisher: publisher, year: year, rating: rating, bookID: Int(bookID)!, ISBN: ISBN)
})
MsgDisplay.dismiss()
completion(foo)
}) { (_, err) in
MsgDisplay.showErrorMsg("网络不好,请稍后重试")
log.any(err)/
}
}
}
static func getBookDetail(ofID id: String, and completion: Book -> ()) {
User.sharedInstance.getToken { token in
let manager = AFHTTPSessionManager()
//manager.responseSerializer.acceptableContentTypes = Set(arrayLiteral: "text/html")
log.word(token)/
manager.requestSerializer.setValue("Bearer {\(token)}", forHTTPHeaderField: "Authorization")
let bookDetailURL = ReadAPI.bookDetailURL + "\(id)?include=review,starreview,holding"
// log.word(bookDetailURL)/
manager.GET(bookDetailURL, parameters: nil, progress: { (_) in
MsgDisplay.showLoading()
}, success: { (task, responseObject) in
// print(responseObject)
MsgDisplay.dismiss()
guard responseObject != nil else {
MsgDisplay.showErrorMsg("哎呀,出错啦")
//log.word("fuck1")/
return
}
guard responseObject?.objectForKey("error_code") as? Int == -1 else {
guard let msg = responseObject?.objectForKey("message") as? String else {
MsgDisplay.showErrorMsg("未知错误")
return
}
MsgDisplay.showErrorMsg(msg)
return
}
// log.obj(responseObject!)/
guard let fooDetail = responseObject?.objectForKey("data") as? NSDictionary else {
MsgDisplay.showErrorMsg("服务器开小差啦")
log.word("Server Fault1")/
//log.word("fuck3")/
return
}
// log.obj(fooData)/
//
// guard let fooDetail = fooData["data"] as? NSDictionary else {
// MsgDisplay.showErrorMsg("服务器开小差啦")
// log.word("Server Fault2")/
// //log.word("fuck3")/
// return
// }
guard let id = fooDetail["id"] as? Int,
let title = fooDetail["title"] as? String,
let ISBN = fooDetail["isbn"] as? String,
let author = fooDetail["author"] as? String,
let publisher = fooDetail["publisher"] as? String,
let year = fooDetail["time"] as? String,
//let coverURL = fooDetail["cover_url"] as? String,
//let rating = fooDetail["rating"] as? Double,
//let index = fooDetail["index"] as? String,
let reviewData = fooDetail["review"] as? NSDictionary,
let starReviewData = fooDetail["starreview"] as? NSDictionary,
let summary = fooDetail["summary"] as? String,
let holdingStatusData = fooDetail["holding"] as? NSDictionary else {
MsgDisplay.showErrorMsg("未知错误2")
log.word("Unknown Error2")/
return
}
//Default cover
var coverURL = "https://images-na.ssl-images-amazon.com/images/I/51w6QuPzCLL._SX319_BO1,204,203,200_.jpg"
if let foo = fooDetail["cover_url"] as? String {
coverURL = foo
}
//Default rating
var rating = 3.0
if let foo = fooDetail["rating"] as? Double {
rating = foo
}
var fooHoldingStatus: [Book.Status] = []
if let holdingStatus = holdingStatusData["data"] as? Array<NSDictionary> {
// log.obj(holdingStatus)/
fooHoldingStatus = holdingStatus.flatMap({ (dict: NSDictionary) -> Book.Status? in
guard let id = dict["id"] as? Int,
let barcode = dict["barcode"] as? String,
let callno = dict["callno"] as? String,
let stateCode = dict["stateCode"] as? Int,
let state = dict["state"] as? String,
let statusInLibrary = dict["state"] as? String,
let libCode = dict["libCode"] as? String,
let localCode = dict["localCode"] as? String,
let dueTime = dict["indate"] as? String,
let library = dict["local"] as? String
else {
MsgDisplay.showErrorMsg("未知错误3")
log.word("Unknown Error3")/
return nil
}
//return nil
return Book.Status(id: id, barcode: barcode, callno: callno, stateCode: stateCode, statusInLibrary: statusInLibrary, libCode: libCode, localCode: localCode, dueTime: dueTime, library: library)
})
}
var fooReviews: [Review] = []
if let reviews = reviewData["data"] as? Array<NSDictionary> {
fooReviews = reviews.flatMap({ (dict: NSDictionary) -> Review? in
guard let reviewID = dict["review_id"] as? Int,
let bookID = dict["book_id"] as? Int,
let bookName = dict["title"] as? String,
let userName = dict["user_name"] as? String,
let avatarURL = dict["avatar"] as? String,
let rating = dict["score"] as? Double,
let like = dict["like_count"] as? Int,
let content = dict["content"] as? String,
let updateTime = dict["updated_at"] as? String,
//TODO: liked as Bool may fail
let liked = dict["liked"] as? Bool else {
MsgDisplay.showErrorMsg("未知错误")
log.word("Unknown Error5")/
return nil
}
log.word(content)/
return Review(reviewID: reviewID, bookID: bookID, bookName: bookName, userName: userName, avatarURL: avatarURL, rating: rating, like: like, content: content, updateTime: updateTime, liked: liked)
})
}
var fooStarReviews: [StarReview] = []
if let star_reviews = starReviewData["data"] as? Array<NSDictionary> {
fooStarReviews = star_reviews.flatMap({ (dict: NSDictionary) -> StarReview? in
guard let name = dict["name"] as? String,
let content = dict["content"] as? String else {
return nil
}
return StarReview(name: name, content: content)
})
}
// 评论按时间倒序
let reviewReversed: [Review] = fooReviews.reverse()
let foo = Book(id: id, title: title, ISBN: ISBN, author: author, publisher: publisher, year: year, coverURL: coverURL, rating: rating, summary: summary, status: fooHoldingStatus, reviews: reviewReversed, starReviews: fooStarReviews)
completion(foo)
}) { (_, err) in
MsgDisplay.showErrorMsg("网络不好,请稍后重试")
log.any("fucker")/
}
}
}
}
| mit | 7ab6d2c0f75dc11d8b23a6e77f703ffb | 48.403101 | 252 | 0.435117 | 5.58056 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Utility/NotificationManager.swift | 2 | 3505 | //
// NotificationManager.swift
// HSTracker
//
// Created by Istvan Fehervari on 17/04/2017.
// Copyright © 2017 Benjamin Michotte. All rights reserved.
//
import Foundation
enum NotificationType {
case gameStart, turnStart, opponentConcede, hsReplayPush(replayId: String), hsReplayUploadFailed(error: String)
}
class NotificationManager {
static func showNotification(type: NotificationType) {
switch type {
case .gameStart:
guard Settings.notifyGameStart else { return }
if CoreManager.isHearthstoneActive() { return }
show(title: NSLocalizedString("Hearthstone", comment: ""),
message: NSLocalizedString("Your game begins", comment: ""))
case .opponentConcede:
guard Settings.notifyOpponentConcede else { return }
if CoreManager.isHearthstoneActive() { return }
show(title: NSLocalizedString("Victory", comment: ""),
message: NSLocalizedString("Your opponent have conceded", comment: ""))
case .turnStart:
guard Settings.notifyTurnStart else { return }
if CoreManager.isHearthstoneActive() { return }
show(title: NSLocalizedString("Hearthstone", comment: ""),
message: NSLocalizedString("It's your turn to play", comment: ""))
case .hsReplayPush(let replayId):
guard Settings.showHSReplayPushNotification else { return }
show(title: NSLocalizedString("HSReplay", comment: ""),
message: NSLocalizedString("Your replay has been uploaded on HSReplay",
comment: "")) {
HSReplayManager.showReplay(replayId: replayId)
}
case .hsReplayUploadFailed(let error):
show(title: NSLocalizedString("HSReplay", comment: ""),
message: NSLocalizedString("Failed to upload replay: \(error)", comment: ""))
}
}
private static var notificationDelegate = NotificationDelegate()
private static func show(title: String, message: String, duration: Double? = 3,
action: (() -> Void)? = nil) {
if Settings.useToastNotification {
Toast.show(title: title, message: message, duration: duration, action: action)
} else {
let notification = NSUserNotification()
notification.title = title
notification.subtitle = ""
notification.informativeText = message
if action != nil {
notification.actionButtonTitle = NSLocalizedString("Show", comment: "")
notification.hasActionButton = true
notificationDelegate.action = action
NSUserNotificationCenter.default.delegate = notificationDelegate
}
notification.deliveryDate = Date()
NSUserNotificationCenter.default.scheduleNotification(notification)
}
}
private class NotificationDelegate: NSObject, NSUserNotificationCenterDelegate {
var action: (() -> Void)?
func userNotificationCenter(_ center: NSUserNotificationCenter,
didActivate notification: NSUserNotification) {
self.action?()
}
}
}
| mit | fd3fedff7658de494b063e2271a9a410 | 38.818182 | 115 | 0.581906 | 5.89899 | false | false | false | false |
apple/swift-nio | Sources/NIOPosix/LinuxCPUSet.swift | 1 | 3424 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if os(Linux) || os(Android)
import CNIOLinux
/// A set that contains CPU ids to use.
struct LinuxCPUSet {
/// The ids of all the cpus.
let cpuIds: Set<Int>
/// Create a new instance
///
/// - arguments:
/// - cpuIds: The `Set` of CPU ids. It must be non-empty and can not contain invalid ids.
init(cpuIds: Set<Int>) {
precondition(!cpuIds.isEmpty)
self.cpuIds = cpuIds
}
/// Create a new instance
///
/// - arguments:
/// - cpuId: The CPU id.
init(_ cpuId: Int) {
let ids: Set<Int> = [cpuId]
self.init(cpuIds: ids)
}
}
extension LinuxCPUSet: Equatable {}
/// Linux specific extension to `NIOThread`.
extension NIOThread {
/// Specify the thread-affinity of the `NIOThread` itself.
var affinity: LinuxCPUSet {
get {
var cpuset = cpu_set_t()
// Ensure the cpuset is empty (and so nothing is selected yet).
CNIOLinux_CPU_ZERO(&cpuset)
let res = self.withUnsafeThreadHandle { p in
CNIOLinux_pthread_getaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset)
}
precondition(res == 0, "pthread_getaffinity_np failed: \(res)")
let set = Set((CInt(0)..<CNIOLinux_CPU_SETSIZE()).lazy.filter { CNIOLinux_CPU_ISSET($0, &cpuset) != 0 }.map { Int($0) })
return LinuxCPUSet(cpuIds: set)
}
set(cpuSet) {
var cpuset = cpu_set_t()
// Ensure the cpuset is empty (and so nothing is selected yet).
CNIOLinux_CPU_ZERO(&cpuset)
// Mark the CPU we want to run on.
cpuSet.cpuIds.forEach { CNIOLinux_CPU_SET(CInt($0), &cpuset) }
let res = self.withUnsafeThreadHandle { p in
CNIOLinux_pthread_setaffinity_np(p, MemoryLayout.size(ofValue: cpuset), &cpuset)
}
precondition(res == 0, "pthread_setaffinity_np failed: \(res)")
}
}
}
extension MultiThreadedEventLoopGroup {
/// Create a new `MultiThreadedEventLoopGroup` that create as many `NIOThread`s as `pinnedCPUIds`. Each `NIOThread` will be pinned to the CPU with the id.
///
/// - arguments:
/// - pinnedCPUIds: The CPU ids to apply to the `NIOThread`s.
convenience init(pinnedCPUIds: [Int]) {
let initializers: [ThreadInitializer] = pinnedCPUIds.map { id in
// This will also take care of validation of the provided id.
let set = LinuxCPUSet(id)
return { t in
t.affinity = set
}
}
self.init(threadInitializers: initializers)
}
}
#endif
| apache-2.0 | f63656f6a806dd31122dfcfed7a1ce7e | 34.666667 | 162 | 0.524241 | 4.269327 | false | false | false | false |
alblue/swift | stdlib/public/core/StringProtocol.swift | 1 | 6696 | //===----------------------------------------------------------------------===//
//
// 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 can represent a string as a collection of characters.
///
/// Do not declare new conformances to `StringProtocol`. Only the `String` and
/// `Substring` types in the standard library are valid conforming types.
public protocol StringProtocol
: BidirectionalCollection,
TextOutputStream, TextOutputStreamable,
LosslessStringConvertible, ExpressibleByStringInterpolation,
Hashable, Comparable
where Iterator.Element == Character,
Index == String.Index,
SubSequence : StringProtocol,
StringInterpolation == DefaultStringInterpolation
{
associatedtype UTF8View : /*Bidirectional*/Collection
where UTF8View.Element == UInt8, // Unicode.UTF8.CodeUnit
UTF8View.Index == Index
associatedtype UTF16View : BidirectionalCollection
where UTF16View.Element == UInt16, // Unicode.UTF16.CodeUnit
UTF16View.Index == Index
associatedtype UnicodeScalarView : BidirectionalCollection
where UnicodeScalarView.Element == Unicode.Scalar,
UnicodeScalarView.Index == Index
associatedtype SubSequence = Substring
var utf8: UTF8View { get }
var utf16: UTF16View { get }
var unicodeScalars: UnicodeScalarView { get }
func hasPrefix(_ prefix: String) -> Bool
func hasSuffix(_ prefix: String) -> Bool
func lowercased() -> String
func uppercased() -> String
/// Creates a string from the given Unicode code units in the specified
/// encoding.
///
/// - Parameters:
/// - codeUnits: A collection of code units encoded in the encoding
/// specified in `sourceEncoding`.
/// - sourceEncoding: The encoding in which `codeUnits` should be
/// interpreted.
init<C: Collection, Encoding: Unicode.Encoding>(
decoding codeUnits: C, as sourceEncoding: Encoding.Type
)
where C.Iterator.Element == Encoding.CodeUnit
/// Creates a string from the null-terminated, UTF-8 encoded sequence of
/// bytes at the given pointer.
///
/// - Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous,
/// UTF-8 encoded bytes ending just before the first zero byte.
init(cString nullTerminatedUTF8: UnsafePointer<CChar>)
/// Creates a string from the null-terminated sequence of bytes at the given
/// pointer.
///
/// - Parameters:
/// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code
/// units in the encoding specified in `sourceEncoding`, ending just
/// before the first zero code unit.
/// - sourceEncoding: The encoding in which the code units should be
/// interpreted.
init<Encoding: Unicode.Encoding>(
decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,
as sourceEncoding: Encoding.Type)
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(encodedAs:_:)`. Do not store or return the
/// pointer for later use.
///
/// - Parameters:
/// - body: A closure with a pointer parameter that points to a
/// null-terminated sequence of code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(encodedAs:_:)` method. The pointer argument is valid
/// only for the duration of the method's execution.
/// - targetEncoding: The encoding in which the code units should be
/// interpreted.
/// - Returns: The return value, if any, of the `body` closure parameter.
func withCString<Result, Encoding: Unicode.Encoding>(
encodedAs targetEncoding: Encoding.Type,
_ body: (UnsafePointer<Encoding.CodeUnit>) throws -> Result
) rethrows -> Result
}
extension StringProtocol {
// TODO(String performance): Make a _SharedString for non-smol Substrings
//
// TODO(String performance): Provide a closure-based call with stack-allocated
// _SharedString for non-smol Substrings
//
public // @SPI(NSStringAPI.swift)
var _ephemeralString: String {
@_specialize(where Self == String)
@_specialize(where Self == Substring)
get { return String(self) }
}
@inlinable // Eliminate for String, Substring
internal var _gutsSlice: _StringGutsSlice {
@_specialize(where Self == String)
@_specialize(where Self == Substring)
@inline(__always) get {
if let str = self as? String {
return _StringGutsSlice(str._guts)
}
if let subStr = self as? Substring {
return _StringGutsSlice(subStr._wholeGuts, subStr._offsetRange)
}
return _StringGutsSlice(String(self)._guts)
}
}
@inlinable
internal var _offsetRange: Range<Int> {
@inline(__always) get {
let start = startIndex
let end = endIndex
_sanityCheck(start.transcodedOffset == 0 && end.transcodedOffset == 0)
return Range(uncheckedBounds: (start.encodedOffset, end.encodedOffset))
}
}
@inlinable
internal var _wholeGuts: _StringGuts {
@_specialize(where Self == String)
@_specialize(where Self == Substring)
@inline(__always) get {
if let str = self as? String {
return str._guts
}
if let subStr = self as? Substring {
return subStr._wholeGuts
}
return String(self)._guts
}
}
}
| apache-2.0 | c237bc3b2420e5f126fe2c81d9eb148b | 37.045455 | 80 | 0.675478 | 4.682517 | false | false | false | false |
Ben21hao/edx-app-ios-new | Source/EnrolledCoursesViewController.swift | 1 | 8489 | //
// EnrolledCoursesViewController.swift
// edX
//
// Created by Akiva Leffert on 12/21/15.
// Copyright © 2015 edX. All rights reserved.
//
import Foundation
var isActionTakenOnUpgradeSnackBar: Bool = false
class EnrolledCoursesViewController : OfflineSupportViewController, CoursesTableViewControllerDelegate, PullRefreshControllerDelegate, LoadStateViewReloadSupport {
typealias Environment = protocol<OEXAnalyticsProvider, OEXConfigProvider, DataManagerProvider, NetworkManagerProvider, ReachabilityProvider, OEXRouterProvider>
private let environment : Environment
private let tableController : CoursesTableViewController
private let loadController = LoadStateViewController()
private let refreshController = PullRefreshController()
private let insetsController = ContentInsetsController()
private let enrollmentFeed: Feed<[UserCourseEnrollment]?>
private let userPreferencesFeed: Feed<UserPreference?>
init(environment: Environment) {
self.tableController = CoursesTableViewController(environment: environment, context: .EnrollmentList)
self.enrollmentFeed = environment.dataManager.enrollmentManager.feed
self.userPreferencesFeed = environment.dataManager.userPreferenceManager.feed
self.environment = environment
super.init(env: environment)
self.titleViewLabel.text = Strings.myCourses
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.accessibilityIdentifier = "enrolled-courses-screen"
setviewConfig()
self.enrollmentFeed.refresh()
self.userPreferencesFeed.refresh()
let currentUser = OEXRouter.sharedRouter().environment.session.currentUser
if (currentUser != nil) {//登陆状态
refreshController.setupInScrollView(self.tableController.tableView)
refreshController.delegate = self
setupListener()
} else {
self.tableController.tableView.reloadData()
self.loadController.state = .Loaded
}
setupFooter()
setupObservers()
if !environment.reachability.isReachable() {
self.loadController.state = .Loaded
}
}
override func viewWillAppear(animated: Bool) {
environment.analytics.trackScreenWithName(OEXAnalyticsScreenMyCourses)
showVersionUpgradeSnackBarIfNecessary()
super.viewWillAppear(animated)
hideSnackBarForFullScreenError()
}
override func reloadViewData() {
refreshIfNecessary()
}
private func setupListener() {//数据
enrollmentFeed.output.listen(self) {[weak self] result in
if !(self?.enrollmentFeed.output.active ?? false) {
self?.refreshController.endRefreshing()
}
switch result {
case let .Success(enrollments):
if let enrollments = enrollments {
self?.tableController.courses = enrollments.flatMap { $0.course } ?? [] //flatMap去掉nil项的数组 -- 数据
self?.tableController.tableView.reloadData()
self?.loadController.state = .Loaded
} else {
self?.loadController.state = .Initial
}
case let .Failure(error):
self?.loadController.state = LoadState.failed(error)
if error.errorIsThisType(NSError.oex_outdatedVersionError()) {
self?.hideSnackBar()
}
}
}
}
private func setviewConfig() {
self.view.backgroundColor = OEXStyles.sharedStyles().baseColor5()
tableController.delegate = self
addChildViewController(tableController)
tableController.didMoveToParentViewController(self)
self.loadController.setupInController(self, contentView: tableController.view)
self.view.addSubview(tableController.view)
tableController.view.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
insetsController.setupInController(self, scrollView: tableController.tableView)
insetsController.addSource(self.refreshController)
// We visually separate each course card so we also need a little padding
// at the bottom to match
insetsController.addSource(
ConstantInsetsSource(insets: UIEdgeInsets(top: 0, left: 0, bottom: StandardVerticalMargin, right: 0), affectsScrollIndicators: false)
)
}
private func setupFooter() { //底部视图
if environment.config.courseEnrollmentConfig.isCourseDiscoveryEnabled() {
let footer = EnrolledCoursesFooterView()
footer.findCoursesAction = {[weak self] in
self?.environment.router?.showCourseCatalog(nil)
}
footer.sizeToFit()
self.tableController.tableView.tableFooterView = footer
} else {
tableController.tableView.tableFooterView = UIView()
}
}
private func enrollmentsEmptyState() {
if !environment.config.courseEnrollmentConfig.isCourseDiscoveryEnabled() {
let error = NSError.oex_errorWithCode(.Unknown, message: Strings.EnrollmentList.noEnrollment)
loadController.state = LoadState.failed(error, icon: Icon.UnknownError)
}
}
private func setupObservers() {
let config = environment.config
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: OEXExternalRegistrationWithExistingAccountNotification) { (notification, observer, _) -> Void in
let platform = config.platformName()
let service = notification.object as? String ?? ""
let message = Strings.externalRegistrationBecameLogin(platformName: platform, service: service)
observer.showOverlayMessage(message)
}
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: AppNewVersionAvailableNotification) { (notification, observer, _) -> Void in
observer.showVersionUpgradeSnackBarIfNecessary()
}
}
func refreshIfNecessary() {
if environment.reachability.isReachable() && !enrollmentFeed.output.active {
enrollmentFeed.refresh()
if loadController.state.isError {
loadController.state = .Initial
}
}
}
private func showVersionUpgradeSnackBarIfNecessary() {
if let _ = VersionUpgradeInfoController.sharedController.latestVersion {
var infoString = Strings.VersionUpgrade.newVersionAvailable
if let _ = VersionUpgradeInfoController.sharedController.lastSupportedDateString {
infoString = Strings.VersionUpgrade.deprecatedMessage
}
if !isActionTakenOnUpgradeSnackBar {
showVersionUpgradeSnackBar(infoString)
}
}
else {
hideSnackBar()
}
}
private func hideSnackBarForFullScreenError() {
if tableController.courses.count <= 0 {
hideSnackBar()
}
}
func coursesTableChoseCourse(course: OEXCourse) {
if let course_id = course.course_id {
self.environment.router?.showCourseWithID(course_id, fromController: self, animated: true)
}
else {
preconditionFailure("course without a course id")
}
}
func refreshControllerActivated(controller: PullRefreshController) {
self.enrollmentFeed.refresh()
self.userPreferencesFeed.refresh()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableController.tableView.autolayoutFooter()
}
//MARK:- LoadStateViewReloadSupport method
func loadStateViewReload() {
refreshIfNecessary()
}
}
// For testing use only
extension EnrolledCoursesViewController {
var t_loaded: Stream<()> {
return self.enrollmentFeed.output.map {_ in
return ()
}
}
}
| apache-2.0 | d78d516d70868bfb166884630ade1dae | 35.274678 | 169 | 0.638665 | 5.672483 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/ContactsUI/ZMAddressBookContact+LocalInvitation.swift | 1 | 2899 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSyncEngine
import MessageUI
class EmailInvitePresenter: NSObject, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {
static let sharedInstance: EmailInvitePresenter = EmailInvitePresenter()
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: .none)
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: .none)
}
}
extension ZMAddressBookContact {
static func canInviteLocallyWithEmail() -> Bool {
return MFMailComposeViewController.canSendMail()
}
func inviteLocallyWithEmail(_ email: String) {
let composeController = MFMailComposeViewController()
composeController.mailComposeDelegate = EmailInvitePresenter.sharedInstance
composeController.modalPresentationStyle = .formSheet
composeController.setMessageBody(invitationBody(), isHTML: false)
composeController.setToRecipients([email])
ZClientViewController.shared?.present(composeController, animated: true, completion: .none)
}
static func canInviteLocallyWithPhoneNumber() -> Bool {
return MFMessageComposeViewController.canSendText()
}
func inviteLocallyWithPhoneNumber(_ phoneNumber: String) {
let composeController = MFMessageComposeViewController()
composeController.messageComposeDelegate = EmailInvitePresenter.sharedInstance
composeController.modalPresentationStyle = .formSheet
composeController.body = invitationBody()
composeController.recipients = [phoneNumber]
ZClientViewController.shared?.present(composeController, animated: true, completion: .none)
}
private func invitationBody() -> String {
guard
let handle = SelfUser.provider?.selfUser.handle
else {
return "send_invitation_no_email.text".localized
}
return "send_invitation.text".localized(args: "@" + handle)
}
}
| gpl-3.0 | 81da5ee617c25e39518a2b7591b00e48 | 38.712329 | 133 | 0.742325 | 5.378479 | false | false | false | false |
sschiau/swift-package-manager | Sources/PackageGraph/PackageGraphLoader.swift | 1 | 21705 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
import SourceControl
import PackageLoading
import PackageModel
import Utility
struct UnusedDependencyDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: UnusedDependencyDiagnostic.self,
name: "org.swift.diags.unused-dependency",
defaultBehavior: .warning,
description: {
$0 <<< "dependency" <<< { "'\($0.dependencyName)'" } <<< "is not used by any target"
})
public let dependencyName: String
}
struct ProductRequiresHigherPlatformVersion: DiagnosticData {
static let id = DiagnosticID(
type: ProductRequiresHigherPlatformVersion.self,
name: "org.swift.diags.\(ProductRequiresHigherPlatformVersion.self)",
defaultBehavior: .error,
description: {
$0 <<< "the product" <<< { "'\($0.product)'" }
$0 <<< "requires minimum platform version" <<< { $0.platform.version!.versionString }
$0 <<< "for" <<< { $0.platform.platform.name } <<< "platform"
})
public let product: String
public let platform: SupportedPlatform
init(product: String, platform: SupportedPlatform) {
self.product = product
self.platform = platform
}
}
struct ProductHasNoSupportedPlatform: DiagnosticData {
static let id = DiagnosticID(
type: ProductHasNoSupportedPlatform.self,
name: "org.swift.diags.\(ProductHasNoSupportedPlatform.self)",
defaultBehavior: .error,
description: {
$0 <<< "the product" <<< { "'\($0.productDependency)'" }
$0 <<< "doesn't support any of the platform required by"
$0 <<< "the target" <<< { "'\($0.target)'" }
})
public let productDependency: String
public let target: String
init(product: String, target: String) {
self.productDependency = product
self.target = target
}
}
enum PackageGraphError: Swift.Error {
/// Indicates a non-root package with no targets.
case noModules(Package)
/// The package dependency declaration has cycle in it.
case cycleDetected((path: [Manifest], cycle: [Manifest]))
/// The product dependency not found.
case productDependencyNotFound(name: String, package: String?)
/// The product dependency was found but the package name did not match.
case productDependencyIncorrectPackage(name: String, package: String)
/// A product was found in multiple packages.
case duplicateProduct(product: String, packages: [String])
}
extension PackageGraphError: CustomStringConvertible {
public var description: String {
switch self {
case .noModules(let package):
return "package '\(package)' contains no targets"
case .cycleDetected(let cycle):
return "cyclic dependency declaration found: " +
(cycle.path + cycle.cycle).map({ $0.name }).joined(separator: " -> ") +
" -> " + cycle.cycle[0].name
case .productDependencyNotFound(let name, _):
return "product dependency '\(name)' not found"
case .productDependencyIncorrectPackage(let name, let package):
return "product dependency '\(name)' in package '\(package)' not found"
case .duplicateProduct(let product, let packages):
return "multiple products named '\(product)' in: \(packages.joined(separator: ", "))"
}
}
}
/// A helper class for loading a package graph.
public struct PackageGraphLoader {
/// Create a package loader.
public init() { }
/// Load the package graph for the given package path.
public func load(
root: PackageGraphRoot,
config: SwiftPMConfig = SwiftPMConfig(),
externalManifests: [Manifest],
diagnostics: DiagnosticsEngine,
fileSystem: FileSystem = localFileSystem,
shouldCreateMultipleTestProducts: Bool = false,
createREPLProduct: Bool = false
) -> PackageGraph {
// Create a map of the manifests, keyed by their identity.
//
// FIXME: For now, we have to compute the identity of dependencies from
// the URL but that shouldn't be needed after <rdar://problem/33693433>
// Ensure that identity and package name are the same once we have an
// API to specify identity in the manifest file
let manifestMapSequence = root.manifests.map({ ($0.name.lowercased(), $0) }) +
externalManifests.map({ (PackageReference.computeIdentity(packageURL: $0.url), $0) })
let manifestMap = Dictionary(uniqueKeysWithValues: manifestMapSequence)
let successors: (Manifest) -> [Manifest] = { manifest in
manifest.dependencies.compactMap({
let url = config.mirroredURL(forURL: $0.url)
return manifestMap[PackageReference.computeIdentity(packageURL: url)]
})
}
// Construct the root manifest and root dependencies set.
let rootManifestSet = Set(root.manifests)
let rootDependencies = Set(root.dependencies.compactMap({
manifestMap[PackageReference.computeIdentity(packageURL: $0.url)]
}))
let inputManifests = root.manifests + rootDependencies
// Collect the manifests for which we are going to build packages.
let allManifests: [Manifest]
// Detect cycles in manifest dependencies.
if let cycle = findCycle(inputManifests, successors: successors) {
diagnostics.emit(PackageGraphError.cycleDetected(cycle))
// Break the cycle so we can build a partial package graph.
allManifests = inputManifests.filter({ $0 != cycle.cycle[0] })
} else {
// Sort all manifests toplogically.
allManifests = try! topologicalSort(inputManifests, successors: successors)
}
// Create the packages.
var manifestToPackage: [Manifest: Package] = [:]
for manifest in allManifests {
let isRootPackage = rootManifestSet.contains(manifest)
// Derive the path to the package.
//
// FIXME: Lift this out of the manifest.
let packagePath = manifest.path.parentDirectory
// Create a package from the manifest and sources.
let builder = PackageBuilder(
manifest: manifest,
path: packagePath,
fileSystem: fileSystem,
diagnostics: diagnostics,
isRootPackage: isRootPackage,
shouldCreateMultipleTestProducts: shouldCreateMultipleTestProducts,
createREPLProduct: isRootPackage ? createREPLProduct : false
)
diagnostics.wrap(with: PackageLocation.Local(name: manifest.name, packagePath: packagePath), {
let package = try builder.construct()
manifestToPackage[manifest] = package
// Throw if any of the non-root package is empty.
if package.targets.isEmpty && !isRootPackage {
throw PackageGraphError.noModules(package)
}
})
}
// Resolve dependencies and create resolved packages.
let resolvedPackages = createResolvedPackages(
allManifests: allManifests,
config: config,
manifestToPackage: manifestToPackage,
rootManifestSet: rootManifestSet,
diagnostics: diagnostics
)
let rootPackages = resolvedPackages.filter({ rootManifestSet.contains($0.manifest) })
checkAllDependenciesAreUsed(rootPackages, diagnostics)
return PackageGraph(
rootPackages: rootPackages,
rootDependencies: resolvedPackages.filter({ rootDependencies.contains($0.manifest) })
)
}
}
private func checkAllDependenciesAreUsed(_ rootPackages: [ResolvedPackage], _ diagnostics: DiagnosticsEngine) {
for package in rootPackages {
// List all dependency products dependended on by the package targets.
let productDependencies: Set<ResolvedProduct> = Set(package.targets.flatMap({ target in
return target.dependencies.compactMap({ targetDependency in
switch targetDependency {
case .product(let product):
return product
case .target:
return nil
}
})
}))
for dependency in package.dependencies {
// We continue if the dependency contains executable products to make sure we don't
// warn on a valid use-case for a lone dependency: swift run dependency executables.
guard !dependency.products.contains(where: { $0.type == .executable }) else {
continue
}
// Skip this check if this dependency is a system module because system module packages
// have no products.
//
// FIXME: Do/should we print a warning if a dependency has no products?
if dependency.products.isEmpty && dependency.targets.filter({ $0.type == .systemModule }).count == 1 {
continue
}
let dependencyIsUsed = dependency.products.contains(where: productDependencies.contains)
if !dependencyIsUsed {
diagnostics.emit(data: UnusedDependencyDiagnostic(dependencyName: dependency.name))
}
}
}
}
/// Create resolved packages from the loaded packages.
private func createResolvedPackages(
allManifests: [Manifest],
config: SwiftPMConfig,
manifestToPackage: [Manifest: Package],
// FIXME: This shouldn't be needed once <rdar://problem/33693433> is fixed.
rootManifestSet: Set<Manifest>,
diagnostics: DiagnosticsEngine
) -> [ResolvedPackage] {
// Create package builder objects from the input manifests.
let packageBuilders: [ResolvedPackageBuilder] = allManifests.compactMap({
guard let package = manifestToPackage[$0] else {
return nil
}
return ResolvedPackageBuilder(package)
})
// Create a map of package builders keyed by the package identity.
let packageMap: [String: ResolvedPackageBuilder] = packageBuilders.spm_createDictionary({
// FIXME: This shouldn't be needed once <rdar://problem/33693433> is fixed.
let identity = rootManifestSet.contains($0.package.manifest) ? $0.package.name.lowercased() : PackageReference.computeIdentity(packageURL: $0.package.manifest.url)
return (identity, $0)
})
// In the first pass, we wire some basic things.
for packageBuilder in packageBuilders {
let package = packageBuilder.package
// Establish the manifest-declared package dependencies.
packageBuilder.dependencies = package.manifest.dependencies.compactMap({
let url = config.mirroredURL(forURL: $0.url)
return packageMap[PackageReference.computeIdentity(packageURL: url)]
})
// Create target builders for each target in the package.
let targetBuilders = package.targets.map({ ResolvedTargetBuilder(target: $0, diagnostics: diagnostics) })
packageBuilder.targets = targetBuilders
// Establish dependencies between the targets. A target can only depend on another target present in the same package.
let targetMap = targetBuilders.spm_createDictionary({ ($0.target, $0) })
for targetBuilder in targetBuilders {
targetBuilder.dependencies += targetBuilder.target.dependencies.map({ targetMap[$0]! })
}
// Create product builders for each product in the package. A product can only contain a target present in the same package.
packageBuilder.products = package.products.map({
ResolvedProductBuilder(product: $0, targets: $0.targets.map({ targetMap[$0]! }))
})
}
// Find duplicate products in the package graph.
let duplicateProducts = packageBuilders
.flatMap({ $0.products })
.map({ $0.product })
.spm_findDuplicateElements(by: \.name)
.map({ $0[0].name })
// Emit diagnostics for duplicate products.
for productName in duplicateProducts {
let packages = packageBuilders
.filter({ $0.products.contains(where: { $0.product.name == productName }) })
.map({ $0.package.name })
.sorted()
diagnostics.emit(PackageGraphError.duplicateProduct(product: productName, packages: packages))
}
// Remove the duplicate products from the builders.
for packageBuilder in packageBuilders {
packageBuilder.products = packageBuilder.products.filter({ !duplicateProducts.contains($0.product.name) })
}
// The set of all target names.
var allTargetNames = Set<String>()
// Track if multiple targets are found with the same name.
var foundDuplicateTarget = false
// Do another pass and establish product dependencies of each target.
for packageBuilder in packageBuilders {
let package = packageBuilder.package
// The diagnostics location for this package.
let diagnosticLocation = { PackageLocation.Local(name: package.name, packagePath: package.path) }
// Get all implicit system library dependencies in this package.
let implicitSystemTargetDeps = packageBuilder.dependencies
.flatMap({ $0.targets })
.filter({
if case let systemLibrary as SystemLibraryTarget = $0.target {
return systemLibrary.isImplicit
}
return false
})
// Get all the products from dependencies of this package.
let productDependencies = packageBuilder.dependencies
.flatMap({ $0.products })
.filter({ $0.product.type != .test })
let productDependencyMap = productDependencies.spm_createDictionary({ ($0.product.name, $0) })
// Establish dependencies in each target.
for targetBuilder in packageBuilder.targets {
// Record if we see a duplicate target.
foundDuplicateTarget = foundDuplicateTarget || !allTargetNames.insert(targetBuilder.target.name).inserted
// Directly add all the system module dependencies.
targetBuilder.dependencies += implicitSystemTargetDeps
// Establish product dependencies.
for productRef in targetBuilder.target.productDependencies {
// Find the product in this package's dependency products.
guard let product = productDependencyMap[productRef.name] else {
let error = PackageGraphError.productDependencyNotFound(name: productRef.name, package: productRef.package)
diagnostics.emit(error, location: diagnosticLocation())
continue
}
// If package name is mentioned, ensure it is valid.
if let packageName = productRef.package {
// Find the declared package and check that it contains
// the product we found above.
guard let dependencyPackage = packageMap[packageName.lowercased()], dependencyPackage.products.contains(product) else {
let error = PackageGraphError.productDependencyIncorrectPackage(
name: productRef.name, package: packageName)
diagnostics.emit(error, location: diagnosticLocation())
continue
}
}
targetBuilder.productDeps.append(product)
}
}
}
// If a target with similar name was encountered before, we emit a diagnostic.
if foundDuplicateTarget {
for targetName in allTargetNames.sorted() {
// Find the packages this target is present in.
let packageNames = packageBuilders
.filter({ $0.targets.contains(where: { $0.target.name == targetName }) })
.map({ $0.package.name })
.sorted()
if packageNames.count > 1 {
diagnostics.emit(ModuleError.duplicateModule(targetName, packageNames))
}
}
}
return packageBuilders.map({ $0.construct() })
}
/// A generic builder for `Resolved` models.
private class ResolvedBuilder<T>: ObjectIdentifierProtocol {
/// The constucted object, available after the first call to `constuct()`.
private var _constructedObject: T?
/// Construct the object with the accumulated data.
///
/// Note that once the object is constucted, future calls to
/// this method will return the same object.
final func construct() -> T {
if let constructedObject = _constructedObject {
return constructedObject
}
_constructedObject = constructImpl()
return _constructedObject!
}
/// The object construction implementation.
func constructImpl() -> T {
fatalError("Should be implemented by subclasses")
}
}
/// Builder for resolved product.
private final class ResolvedProductBuilder: ResolvedBuilder<ResolvedProduct> {
/// The product reference.
let product: Product
/// The target builders in the product.
let targets: [ResolvedTargetBuilder]
init(product: Product, targets: [ResolvedTargetBuilder]) {
self.product = product
self.targets = targets
}
override func constructImpl() -> ResolvedProduct {
return ResolvedProduct(
product: product,
targets: targets.map({ $0.construct() })
)
}
}
/// Builder for resolved target.
private final class ResolvedTargetBuilder: ResolvedBuilder<ResolvedTarget> {
/// The target reference.
let target: Target
/// The target dependencies of this target.
var dependencies: [ResolvedTargetBuilder] = []
/// The product dependencies of this target.
var productDeps: [ResolvedProductBuilder] = []
/// The diagnostics engine.
let diagnostics: DiagnosticsEngine
init(target: Target, diagnostics: DiagnosticsEngine) {
self.target = target
self.diagnostics = diagnostics
}
func validateProductDependency(_ product: ResolvedProduct) {
// Get the first target as supported platforms are on the top-level.
// This will need to become a bit complicated once we have target-level platform support.
let productTarget = product.underlyingProduct.targets[0]
/// Check if at least one of our platform is supported by this product dependency.
let atLeastOneTargetIsSupported = self.target.platforms.contains(where: { productTarget.supportsPlatform($0.platform) })
if !atLeastOneTargetIsSupported {
diagnostics.emit(data: ProductHasNoSupportedPlatform(product: product.name, target: target.name))
}
for targetPlatform in self.target.platforms {
// Ignore the compatibility check for platforms that we support but are unsupported by this product.
guard let productPlatform = productTarget.getSupportedPlatform(for: targetPlatform.platform) else {
continue
}
// For the supported platforms, check if the version requirement is satisfied.
//
// We're done if the supported platform doesn't have any version associated with it.
guard let targetVersion = targetPlatform.version, let productVersion = productPlatform.version else {
continue
}
// If the product's platform version is greater than ours, then it is incompatible.
if productVersion > targetVersion {
diagnostics.emit(data: ProductRequiresHigherPlatformVersion(product: product.name, platform: productPlatform))
}
}
}
override func constructImpl() -> ResolvedTarget {
var deps: [ResolvedTarget.Dependency] = []
for dependency in dependencies {
deps.append(.target(dependency.construct()))
}
for dependency in productDeps {
let product = dependency.construct()
// FIXME: Should we not add the dependency if validation fails?
validateProductDependency(product)
deps.append(.product(product))
}
return ResolvedTarget(
target: target,
dependencies: deps
)
}
}
/// Builder for resolved package.
private final class ResolvedPackageBuilder: ResolvedBuilder<ResolvedPackage> {
/// The package reference.
let package: Package
/// The targets in the package.
var targets: [ResolvedTargetBuilder] = []
/// The products in this package.
var products: [ResolvedProductBuilder] = []
/// The dependencies of this package.
var dependencies: [ResolvedPackageBuilder] = []
init(_ package: Package) {
self.package = package
}
override func constructImpl() -> ResolvedPackage {
return ResolvedPackage(
package: package,
dependencies: dependencies.map({ $0.construct() }),
targets: targets.map({ $0.construct() }),
products: products.map({ $0.construct() })
)
}
}
| apache-2.0 | 9776ec471093170b6da8d976dfc877d1 | 38.680073 | 171 | 0.639714 | 5.090291 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/KillmailAttackerCell.swift | 2 | 3902 | //
// KillmailAttackerCell.swift
// Neocom
//
// Created by Artem Shimanski on 11/14/18.
// Copyright © 2018 Artem Shimanski. All rights reserved.
//
import Foundation
import EVEAPI
import TreeController
class KillmailAttackerCell: RowCell {
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var subtitleLabel: UILabel?
@IBOutlet weak var iconView: UIImageView?
@IBOutlet weak var shipImageView: UIImageView?
@IBOutlet weak var shipLabel: UILabel?
@IBOutlet weak var weaponLabel: UILabel?
}
extension Prototype {
enum KillmailAttackerCell {
static let `default` = Prototype(nib: UINib(nibName: "KillmailAttackerCell", bundle: nil), reuseIdentifier: "KillmailAttackerCell")
static let npc = Prototype(nib: UINib(nibName: "KillmailAttackerNPCCell", bundle: nil), reuseIdentifier: "KillmailAttackerNPCCell")
}
}
extension Tree.Item {
class KillmailAttackerRow: Row<ESI.Killmails.Killmail.Attacker>, Routable {
override var prototype: Prototype? {
return character != nil ? Prototype.KillmailAttackerCell.default : Prototype.KillmailAttackerCell.npc
}
let character: Contact?
let corporation: Contact?
let alliance: Contact?
lazy var faction = content.factionID.flatMap{Services.sde.viewContext.chrFaction($0)}
lazy var shipType = content.shipTypeID.flatMap{Services.sde.viewContext.invType($0)}
lazy var weaponType = content.weaponTypeID.flatMap{Services.sde.viewContext.invType($0)}
var image: UIImage?
var route: Routing?
var api: API
init(_ content: ESI.Killmails.Killmail.Attacker, contacts: [Int64: Contact]?, api: API) {
character = content.characterID.flatMap{contacts?[Int64($0)]}
corporation = content.corporationID.flatMap{contacts?[Int64($0)]}
alliance = content.allianceID.flatMap{contacts?[Int64($0)]}
self.api = api
super.init(content)
}
override func configure(cell: UITableViewCell, treeController: TreeController?) {
super.configure(cell: cell, treeController: treeController)
guard let cell = cell as? KillmailAttackerCell else {return}
let title = character?.name ?? corporation?.name ?? alliance?.name ?? faction?.factionName
if content.finalBlow {
cell.titleLabel?.attributedText = (title ?? "") + " [\(NSLocalizedString("final blow", comment: ""))]" * [NSAttributedString.Key.foregroundColor: UIColor.caption]
}
else {
cell.titleLabel?.text = title
}
switch (corporation?.name, alliance?.name) {
case let (a?, b?):
cell.subtitleLabel?.text = "\(a) / \(b)"
case let (a?, nil):
cell.subtitleLabel?.text = a
case let (nil, b):
cell.subtitleLabel?.text = b
}
cell.accessoryType = route != nil ? .disclosureIndicator : .none
cell.shipLabel?.text = shipType?.typeName
cell.shipImageView?.image = shipType?.icon?.image?.image
if let weapon = weaponType?.typeName, character != nil {
cell.weaponLabel?.text = String(format: NSLocalizedString("%@ damage done with %@", comment: ""), UnitFormatter.localizedString(from: content.damageDone, unit: .none, style: .long), weapon)
}
else {
cell.weaponLabel?.text = String(format: NSLocalizedString("%@ damage done", comment: ""), UnitFormatter.localizedString(from: content.damageDone, unit: .none, style: .long))
}
if image == nil, let size = cell.iconView?.bounds.size {
if let contact = character ?? corporation ?? alliance {
api.image(contact: contact, dimension: Int(size.width), cachePolicy: .useProtocolCachePolicy).then(on: .main) { [weak self, weak treeController] result in
guard let strongSelf = self else {return}
strongSelf.image = result.value
treeController?.reloadRow(for: strongSelf, with: .none)
}.catch(on: .main) { [weak self] _ in
self?.image = UIImage()
}
}
else {
image = faction?.icon?.image?.image ?? UIImage()
}
}
cell.iconView?.image = image
}
}
}
| lgpl-2.1 | 2d57904db537a989746135679f675037 | 34.144144 | 193 | 0.703922 | 3.729446 | false | false | false | false |
caicai0/ios_demo | load/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift | 14 | 26028 | //
// UploadTests.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Alamofire
import Foundation
import XCTest
class UploadFileInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndFile() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(imageURL, to: urlString)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndFile() {
// Given
let urlString = "https://httpbin.org/"
let headers = ["Authorization": "123456"]
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(imageURL, to: urlString, method: .post, headers: headers)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndData() {
// Given
let urlString = "https://httpbin.org/"
// When
let request = Alamofire.upload(Data(), to: urlString)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndData() {
// Given
let urlString = "https://httpbin.org/"
let headers = ["Authorization": "123456"]
// When
let request = Alamofire.upload(Data(), to: urlString, headers: headers)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadStreamInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndStream() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
let imageStream = InputStream(url: imageURL)!
// When
let request = Alamofire.upload(imageStream, to: urlString)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndStream() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = url(forResource: "rainbow", withExtension: "jpg")
let headers = ["Authorization": "123456"]
let imageStream = InputStream(url: imageURL)!
// When
let request = Alamofire.upload(imageStream, to: urlString, headers: headers)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.url?.absoluteString, urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataTestCase: BaseTestCase {
func testUploadDataRequest() {
// Given
let urlString = "https://httpbin.org/post"
let data = "Lorem ipsum dolor sit amet".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "Upload request should succeed: \(urlString)")
var response: DefaultDataResponse?
// When
Alamofire.upload(data, to: urlString)
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNil(response?.error)
}
func testUploadDataRequestWithProgress() {
// Given
let urlString = "https://httpbin.org/post"
let data: Data = {
var text = ""
for _ in 1...3_000 {
text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
}
return text.data(using: .utf8, allowLossyConversion: false)!
}()
let expectation = self.expectation(description: "Bytes upload progress should be reported: \(urlString)")
var uploadProgressValues: [Double] = []
var downloadProgressValues: [Double] = []
var response: DefaultDataResponse?
// When
Alamofire.upload(data, to: urlString)
.uploadProgress { progress in
uploadProgressValues.append(progress.fractionCompleted)
}
.downloadProgress { progress in
downloadProgressValues.append(progress.fractionCompleted)
}
.response { resp in
response = resp
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0
for progress in uploadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousUploadProgress)
previousUploadProgress = progress
}
if let lastProgressValue = uploadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in uploadProgressValues should not be nil")
}
var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0
for progress in downloadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress)
previousDownloadProgress = progress
}
if let lastProgressValue = downloadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in downloadProgressValues should not be nil")
}
}
}
// MARK: -
class UploadMultipartFormDataTestCase: BaseTestCase {
// MARK: Tests
func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload_data".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var formData: MultipartFormData?
var response: DefaultDataResponse?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "upload_data")
formData = multipartFormData
},
to: urlString,
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.response { resp in
response = resp
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
if
let request = response?.request,
let multipartFormData = formData,
let contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType)
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
// Given
let urlString = "https://httpbin.org/post"
let frenchData = "français".data(using: .utf8, allowLossyConversion: false)!
let japaneseData = "日本語".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var response: DefaultDataResponse?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(frenchData, withName: "french")
multipartFormData.append(japaneseData, withName: "japanese")
},
to: urlString,
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.response { resp in
response = resp
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
}
func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
}
func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
// Given
let urlString = "https://httpbin.org/post"
let frenchData = "français".data(using: .utf8, allowLossyConversion: false)!
let japaneseData = "日本語".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: URL?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(frenchData, withName: "french")
multipartFormData.append(japaneseData, withName: "japanese")
},
to: urlString,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _ in
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNil(streamFileURL, "stream file URL should be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload data".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "upload_data")
formData = multipartFormData
},
to: urlString,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { resp in
request = resp.request
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
if
let request = request,
let multipartFormData = formData,
let contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
// Given
let urlString = "https://httpbin.org/post"
let frenchData = "français".data(using: .utf8, allowLossyConversion: false)!
let japaneseData = "日本語".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: URL?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(frenchData, withName: "french")
multipartFormData.append(japaneseData, withName: "japanese")
},
usingThreshold: 0,
to: urlString,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _ in
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
if let streamingFromDisk = streamingFromDisk, let streamFilePath = streamFileURL?.path {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
XCTAssertFalse(FileManager.default.fileExists(atPath: streamFilePath), "stream file path should not exist")
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload data".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(uploadData, withName: "upload_data")
formData = multipartFormData
},
usingThreshold: 0,
to: urlString,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { resp in
request = resp.request
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
}
if
let request = request,
let multipartFormData = formData,
let contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
#if os(macOS)
func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
// Given
let manager: SessionManager = {
let identifier = "org.alamofire.uploadtests.\(UUID().uuidString)"
let configuration = URLSessionConfiguration.background(withIdentifier: identifier)
return SessionManager(configuration: configuration, serverTrustPolicyManager: nil)
}()
let urlString = "https://httpbin.org/post"
let french = "français".data(using: .utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: .utf8, allowLossyConversion: false)!
let expectation = self.expectation(description: "multipart form data upload should succeed")
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: Error?
var streamingFromDisk: Bool?
// When
manager.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(french, withName: "french")
multipartFormData.append(japanese, withName: "japanese")
},
to: urlString,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { defaultResponse in
request = defaultResponse.request
response = defaultResponse.response
data = defaultResponse.data
error = defaultResponse.error
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
} else {
XCTFail("streaming from disk should not be nil")
}
}
#endif
// MARK: Combined Test Execution
private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
// Given
let urlString = "https://httpbin.org/post"
let loremData1: Data = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
}
return loremValues.joined(separator: " ").data(using: .utf8, allowLossyConversion: false)!
}()
let loremData2: Data = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
}
return loremValues.joined(separator: " ").data(using: .utf8, allowLossyConversion: false)!
}()
let expectation = self.expectation(description: "multipart form data upload should succeed")
var uploadProgressValues: [Double] = []
var downloadProgressValues: [Double] = []
var response: DefaultDataResponse?
// When
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(loremData1, withName: "lorem1")
multipartFormData.append(loremData2, withName: "lorem2")
},
usingThreshold: streamFromDisk ? 0 : 100_000_000,
to: urlString,
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload
.uploadProgress { progress in
uploadProgressValues.append(progress.fractionCompleted)
}
.downloadProgress { progress in
downloadProgressValues.append(progress.fractionCompleted)
}
.response { resp in
response = resp
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(timeout: timeout, handler: nil)
// Then
XCTAssertNotNil(response?.request)
XCTAssertNotNil(response?.response)
XCTAssertNotNil(response?.data)
XCTAssertNil(response?.error)
var previousUploadProgress: Double = uploadProgressValues.first ?? 0.0
for progress in uploadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousUploadProgress)
previousUploadProgress = progress
}
if let lastProgressValue = uploadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in uploadProgressValues should not be nil")
}
var previousDownloadProgress: Double = downloadProgressValues.first ?? 0.0
for progress in downloadProgressValues {
XCTAssertGreaterThanOrEqual(progress, previousDownloadProgress)
previousDownloadProgress = progress
}
if let lastProgressValue = downloadProgressValues.last {
XCTAssertEqual(lastProgressValue, 1.0)
} else {
XCTFail("last item in downloadProgressValues should not be nil")
}
}
}
| mit | 6919deacb1999e8bdd4b8bbf197da1d0 | 36.626628 | 119 | 0.614538 | 5.734451 | false | true | false | false |
KevinCoble/AIToolbox | Playgrounds/LinearRegression.playground/Contents.swift | 1 | 7126 | /*: Introduction
# Linear Regression
This playground shows how the basics of Linear Regression, and shows how to use the AIToolbox framework to generate test data, train a linear regression model, and plot the results
We start with the required import statements. If this was your own program, rather than a playground, you would also add an 'import AIToolbox' line.
*/
import Cocoa
import PlaygroundSupport
/*: Target Function
## Create a Target function
First we need some data. You can hard-code data points, or you can generate them from a function. This playground will generate them from a function and add noise to the data
Linear regression input data can be of any dimension. Since we want to plot the data, we will use a 1 dimensional input (and output) for now
We will use a linear regression model to generate the data. Set the 'targetOrder' to the maximum power of the polynomial.
*/
let targetOrder = 2 // Between 1 and 5
/*:
The target function is created with the input and output size. We will use a convenience initializer that takes the polynomial order and creates a linear function with no cross terms (y = A, y = A + Bx, y = A + Bx + Cx², etc.
*/
let target = LinearRegressionModel(inputSize: 1, outputSize: 1, polygonOrder: targetOrder)
/*:
Next we create some parameters (this is the target function. For the hypothesis function, we 'learn' these parameters)
Start with an array of reasonable values, and add some gaussian noise to make different curves for each run. Set the values as the parameters of the target function
*/
var targetParameters : [Double] = [10.0, 0.5, 0.25, -0.125, 0.0675, -0.038]
for index in 0...targetOrder {
targetParameters[index] += Gaussian.gaussianRandom(0.0, standardDeviation: targetParameters[index])
}
try target.setParameters(targetParameters)
targetParameters // Show target parameters to compare with hypothesis parameters later
/*: Data Set
## Create a Regression DataSet
Now that we have a target function, we need to get some data from it
DataSets in AIToolbox come in two types, Regression and Classification. Regression is where you get a value (or array of values if the output dimension is >1) for your inputs. Classification is when you get an integer 'class label' based on the inputs. Regression is used to do things like 'predict time till failure', while classification is used for tasks like 'is that tumor malignant or benign'
This is Linear Regression, so our data set will be the 'Regression type, with the same input and output dimensions as our target function.
*/
let data = DataSet(dataType: .regression, inputDimension: 1, outputDimension: 1)
/*:
We are going to use the target function to create points, and add noise
set numPoints to the number of points to create, and set the standard deviation of the gaussian noise
*/
let numPoints = 100 // Number of points to fit
let standardDeviation = 1.0 // Amount of noise in target line
/*:
The following code creates the points and adds them to the data set.
We are keeping the input data in the range of 0-10, but that could be changed if you wanted.
Note that the 'addDataPoint' function is preceded by a 'try' operator. Many AIToolbox routines can throw errors if dimensions don't match
*/
for index in 0..<numPoints {
let x = Double(index) * 10.0 / Double(numPoints)
let targetValue = try target.predictOne([x])
let y = targetValue[0] + Gaussian.gaussianRandom(0.0, standardDeviation: standardDeviation)
try data.addDataPoint(input: [x], output:[y])
}
/*: Hypothesis
## Create a Regression Hypothesis Model
The Hypothesis Model is the form of the function to 'learn' the parameters for. Linear regression cannot create a function from the data, you specify the function and linear regression finds the best parameters to match the data to that function
We will again use the convenience initializer to create a polygon model of a specific order. The polygon order does NOT have to match that of the target function/data. In fact, having a complicated hypothesis function with a small amount of data leads to 'overfitting'. Note that the input and output dimensions have to match our data.
*/
let hypothesisOrder = 2 // Polygon order for the model
let lr = LinearRegressionModel(inputSize: 1, outputSize: 1, polygonOrder: hypothesisOrder)
/*: Training
## 'Train' the model
All regressors in AIToolbox, linear or not, have a 'trainRegressor' function that takes a Regression data set. This function asks the hypothesis to find the best parameters for the data set passed in.
Note the 'try' again. Don't attempt to train a hypothesis with data of a different dimension.
*/
try lr.trainRegressor(data)
let parameters = try lr.getParameters()
/*: Plotting
## Create a Data Plot
AIToolbox includes a subclass of NSView that can be used to plot the data and the functions. We use one here to show the data
There are different types of plot objects that can be added. Data, functions, axis labels, and legends will be used here. Plot objects are drawn in the order added to the view.
Start with creating the view
*/
let dataView = MLView(frame: CGRect(x: 0, y: 0, width: 480, height: 320))
//: Create a symbol object for plotting the data set - a green circle
let dataPlotSymbol = MLPlotSymbol(color: NSColor.green, symbolShape: .circle, symbolSize: 7.0)
//: Create a regression data set plot item
let dataPlotItem = try MLViewRegressionDataSet(dataset: data, symbol: dataPlotSymbol)
//: Set that item as the source of the initial scale of plot items. Some plot items can be set to change the scale, but something needs to set the initial scale
dataView.setInitialScaleItem(dataPlotItem)
//: Add a set of labels first (so they are underneath any other drawing). Both X and Y axis labels
let axisLabels = MLViewAxisLabel(showX: true, showY: true)
dataView.addPlotItem(axisLabels)
//: Create a regression data line item for the target function, blue
let targetLine = MLViewRegressionLine(regressor: target, color: NSColor.blue)
dataView.addPlotItem(targetLine)
//: Create a regression data line item for the hypothes function, red
let hypothesisLine = MLViewRegressionLine(regressor: lr, color: NSColor.red)
dataView.addPlotItem(hypothesisLine)
//: Add the data plot item now (so the data points are on top of the lines - reorder if you want!)
dataView.addPlotItem(dataPlotItem)
//: Create a legend
let legend = MLViewLegend(location: .lowerRight, title: "Legend")
//: Add the target line to the legend
let targetLegend = MLLegendItem(label: "target", regressionLinePlotItem: targetLine)
legend.addItem(targetLegend)
//: Add the data set to the legend
let dataLegend = MLLegendItem(label: "data", dataSetPlotItem: dataPlotItem)
legend.addItem(dataLegend)
//: Add the hypothesis line to the legend
let lineLegend = MLLegendItem(label: "hypothesis", regressionLinePlotItem: hypothesisLine)
legend.addItem(lineLegend)
dataView.addPlotItem(legend)
//: Finally, set the view to be drawn by the playground
PlaygroundPage.current.liveView = dataView
| apache-2.0 | b59ef91797f52861f818b7633ad8ba2c | 52.977273 | 402 | 0.762947 | 4.132831 | false | false | false | false |
csnu17/My-Swift-learning | collection-data-structures-swift/DataStructures/SwiftArrayManipulator.swift | 1 | 3762 | //
// SwiftArrayManipulator.swift
// DataStructures
//
// Created by Ellen Shapiro on 8/3/14.
// Copyright (c) 2014 Ray Wenderlich Tutorial Team. All rights reserved.
//
import Foundation
open class SwiftArrayManipulator: ArrayManipulator {
fileprivate var intArray = [Int]()
open func arrayHasObjects() -> Bool {
if intArray.count == 0 {
return false
} else {
return true
}
}
open func setupWithObjectCount(_ count: Int) -> TimeInterval {
return Profiler.runClosureForTime() {
self.intArray = [Int]()
for i in 0 ..< count {
self.intArray.append(i)
}
}
}
fileprivate func nextElement() -> Int {
return intArray.count + 1
}
//MARK: Addition Tests
open func insertNewObjectAtBeginning() -> TimeInterval {
let next = nextElement()
let time = Profiler.runClosureForTime() {
self.intArray.insert(next, at: 0)
}
assert(intArray[0] == next, "First object was not changed!")
intArray.remove(at: 0)
assert(intArray[0] != next, "First object not back to original!")
return time
}
open func insertNewObjectInMiddle() -> TimeInterval {
let half = Float(intArray.count) / Float(2)
let middleIndex = Int(ceil(half))
let next = nextElement()
let time = Profiler.runClosureForTime() {
self.intArray.insert(next, at: middleIndex)
}
assert(intArray[middleIndex] == next, "Middle object didn't change!")
//Reset
self.intArray.remove(at: middleIndex)
assert(intArray[middleIndex] != next, "Middle object is not the same after removal!")
return time
}
open func addNewObjectAtEnd() -> TimeInterval {
let next = nextElement()
let time = Profiler.runClosureForTime() {
self.intArray.append(next)
}
//Remove the added string
self.intArray.removeLast()
return time
}
//MARK: Removal tests
func removeFirstObject() -> TimeInterval {
let originalFirst = intArray[0] as Int
let time = Profiler.runClosureForTime() {
self.intArray.remove(at: 0)
}
assert(intArray[0] != originalFirst, "First object didn't change!")
intArray.insert(originalFirst, at: 0)
assert(intArray[0] == originalFirst, "First object is not the same after removal!")
return time
}
func removeMiddleObject() -> TimeInterval {
let half = Float(intArray.count) / Float(2)
let middleIndex = Int(ceil(half))
let originalMiddle = intArray[middleIndex] as Int
let time = Profiler.runClosureForTime() {
self.intArray.remove(at: middleIndex)
}
assert(intArray[middleIndex] != originalMiddle, "Middle object didn't change!")
intArray.insert(originalMiddle, at: middleIndex)
assert(intArray[middleIndex] == originalMiddle, "Middle object is not the same after being added back!")
return time
}
func removeLastObject() -> TimeInterval {
intArray.append(nextElement())
return Profiler.runClosureForTime() {
self.intArray.removeLast()
}
}
//MARK: Lookup tests
func lookupByIndex() -> TimeInterval {
let elements = UInt32(intArray.count)
let randomIndex = Int(arc4random_uniform(elements))
let time = Profiler.runClosureForTime() {
self.intArray[randomIndex]
}
return time
}
func lookupByObject() -> TimeInterval {
//Add a known object at a random index.
let next = nextElement()
let elements = UInt32(intArray.count)
let randomIndex = Int(arc4random_uniform(elements))
intArray.insert(next, at: randomIndex)
let time = Profiler.runClosureForTime() {
let _ = self.intArray.index(of: next)//find(self.intArray, next)
}
return time
}
}
| mit | f5224a7633105c263716fa31be1db741 | 25.307692 | 108 | 0.650718 | 4.284738 | false | false | false | false |
ahoppen/swift | test/Parse/init_deinit.swift | 4 | 4433 | // RUN: %target-typecheck-verify-swift
struct FooStructConstructorA {
init // expected-error {{expected '('}}
}
struct FooStructConstructorB {
init() // expected-error {{initializer requires a body}}
}
struct FooStructConstructorC {
init {} // expected-error {{expected '('}}{{7-7=()}}
init<T> {} // expected-error {{expected '('}} {{10-10=()}}
init? { self.init() } // expected-error {{expected '('}} {{8-8=()}}
}
struct FooStructDeinitializerA {
deinit // expected-error {{expected '{' for deinitializer}}
deinit x // expected-error {{deinitializers cannot have a name}} {{10-12=}} expected-error {{expected '{' for deinitializer}}
deinit x() // expected-error {{deinitializers cannot have a name}} {{10-11=}} expected-error {{no parameter clause allowed on deinitializer}} {{11-13=}} expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerB {
deinit // expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerC {
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
class FooClassDeinitializerA {
deinit(a : Int) {} // expected-error{{no parameter clause allowed on deinitializer}}{{9-18=}}
}
class FooClassDeinitializerB {
deinit { }
}
class FooClassDeinitializerC {
deinit x (a : Int) {} // expected-error {{deinitializers cannot have a name}} {{10-12=}} expected-error{{no parameter clause allowed on deinitializer}}{{12-22=}}
}
init {} // expected-error {{initializers may only be declared within a type}} expected-error {{expected '('}} {{5-5=()}}
init() // expected-error {{initializers may only be declared within a type}}
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
deinit // expected-error {{expected '{' for deinitializer}}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
struct BarStruct {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
extension BarStruct {
init(x : Int) {}
// When/if we allow 'var' in extensions, then we should also allow dtors
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
enum BarUnion {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
extension BarUnion {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
class BarClass {
init() {}
deinit {}
}
extension BarClass {
convenience init(x : Int) { self.init() }
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
protocol BarProtocol {
init() {} // expected-error {{protocol initializers must not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
extension BarProtocol {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
func fooFunc() {
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
}
func barFunc() {
var x : () = { () -> () in
// expected-warning@-1 {{variable 'x' was never used; consider replacing with '_' or removing it}}
init() {} // expected-error {{initializers may only be declared within a type}}
return
} ()
var y : () = { () -> () in
// expected-warning@-1 {{variable 'y' was never used; consider replacing with '_' or removing it}}
deinit {} // expected-error {{deinitializers may only be declared within a class or actor}}
return
} ()
}
// SR-852
class Aaron {
init(x: Int) {}
convenience init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} {{24-24=self.}}
}
class Theodosia: Aaron {
init() {
init(x: 2) // expected-error {{missing 'super.' at initializer invocation}} {{5-5=super.}}
}
}
struct AaronStruct {
init(x: Int) {}
init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} {{12-12=self.}}
}
enum AaronEnum: Int {
case A = 1
init(x: Int) { init(rawValue: x)! } // expected-error {{missing 'self.' at initializer invocation}} {{18-18=self.}}
}
| apache-2.0 | 3059280b59711ca9fc5f4ccbd640838a | 32.330827 | 204 | 0.673584 | 3.982929 | false | false | false | false |
eduarenas80/MarvelClient | Source/RequestBuilders/CharacterRequestBuilder.swift | 2 | 3669 | //
// CharacterRequestBuilder.swift
// MarvelClient
//
// Copyright (c) 2016 Eduardo Arenas <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public class CharacterRequestBuilder: MarvelRequestBuilder {
private let entityTypeString = "characters"
public var name: String?
public var nameStartsWith: String?
public var comics: [Int]?
public var series: [Int]?
public var events: [Int]?
public var stories: [Int]?
public var orderBy: [CharacterOrder]?
init(keys: MarvelAPIKeys) {
super.init(entityType: self.entityTypeString, keys: keys)
}
public func fetch(completionHandler: Wrapper<Character> -> Void) {
super.fetchResults(completionHandler)
}
public func name(name: String) -> Self {
self.name = name
return self
}
public func nameStartsWith(nameStartsWith: String) -> Self {
self.nameStartsWith = nameStartsWith
return self
}
public func comics(comics: [Int]) -> Self {
self.comics = comics
return self
}
public func series(series: [Int]) -> Self {
self.series = series
return self
}
public func events(events: [Int]) -> Self {
self.events = events
return self
}
public func stories(stories: [Int]) -> Self {
self.stories = stories
return self
}
public func orderBy(orderBy: [CharacterOrder]) -> Self {
self.orderBy = orderBy
return self
}
override func buildQueryParameters() -> [String : AnyObject] {
var queryParameters = super.buildQueryParameters()
if let name = self.name {
queryParameters["name"] = name
}
if let nameStartsWith = self.nameStartsWith {
queryParameters["nameStartsWith"] = nameStartsWith
}
if let comics = self.comics {
queryParameters["comics"] = comics.joinDescriptionsWithSeparator(",")
}
if let series = self.series {
queryParameters["series"] = series.joinDescriptionsWithSeparator(",")
}
if let events = self.events {
queryParameters["events"] = events.joinDescriptionsWithSeparator(",")
}
if let stories = self.stories {
queryParameters["stories"] = stories.joinDescriptionsWithSeparator(",")
}
if let orderBy = self.orderBy {
queryParameters["orderBy"] = orderBy.joinDescriptionsWithSeparator(",")
}
return queryParameters
}
}
public enum CharacterOrder: String, CustomStringConvertible {
case Name = "name"
case Modified = "modified"
case NameDescending = "-name"
case ModifiedDescending = "-modified"
public var description: String {
return self.rawValue
}
}
| mit | bf4783225d9b60766fe237dee162e15e | 29.322314 | 81 | 0.69692 | 4.420482 | false | false | false | false |
tripleCC/GanHuoCode | GanHuo/Views/Category/TPCCategoryEditView.swift | 1 | 3065 | //
// TPCCategoryEditView.swift
// GanHuo
//
// Created by tripleCC on 16/3/16.
// Copyright © 2016年 tripleCC. All rights reserved.
//
import UIKit
let TPCCategoryStoreKey = "TPCCategoryStoreKey"
enum TPCCategoryEditType: Int {
case Select
case Edit
}
class TPCCategoryEditView: UIView {
let reuseIdentifier = "TPCCategoryEditViewCell"
var selectedAction: ((TPCCategoryEditView) -> Void)?
var categories = [String]() {
didSet {
tableView.reloadData()
}
}
var selectedCategory: String? {
didSet {
tableView.reloadData()
}
}
var type: TPCCategoryEditType = .Select {
didSet {
tableView.setEditing(type == .Edit, animated: true)
tableView.reloadData()
}
}
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.delegate = self
tableView.dataSource = self
tableView.registerNib(UINib(nibName: String(TPCCategoryEditViewCell.self), bundle: nil), forCellReuseIdentifier: reuseIdentifier)
tableView.separatorStyle = .None
tableView.tableFooterView = UIView()
}
}
static func editView() -> TPCCategoryEditView {
return NSBundle.mainBundle().loadNibNamed(String(TPCCategoryEditView.self), owner: nil, options: nil).first as! TPCCategoryEditView
}
}
extension TPCCategoryEditView: UITableViewDataSource {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TPCCategoryEditViewCell
cell.categoryLabel.text = categories[indexPath.row]
cell.type = type
cell.enable = categories[indexPath.row] == selectedCategory
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return type == .Edit
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
return .None
}
func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
let s = categories[sourceIndexPath.row]
categories.removeAtIndex(sourceIndexPath.row)
categories.insert(s, atIndex: destinationIndexPath.row)
}
}
extension TPCCategoryEditView: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if type == .Select {
selectedCategory = categories[indexPath.row]
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
selectedAction?(self)
}
}
} | mit | 88e73c5defff55e068001f9899623971 | 33.806818 | 141 | 0.682887 | 5.270224 | false | false | false | false |
jeanetienne/Bee | Bee/Tools/UIViewController+KeyboardManagement.swift | 1 | 2405 | //
// Bee
// Copyright © 2017 Jean-Étienne. All rights reserved.
//
import UIKit
extension UIViewController {
static func observeKeyboardWillShowNotification(completion: @escaping (Notification) -> ()) {
NotificationCenter.default.addObserver(forName: Notification.Name.UIKeyboardWillShow,
object: nil,
queue: nil,
using: completion)
}
static func observeKeyboardWillHideNotification(completion: @escaping (Notification) -> ()) {
NotificationCenter.default.addObserver(forName: Notification.Name.UIKeyboardWillHide,
object: nil,
queue: nil,
using: completion)
}
static func handleKeyboardWillShow(withNotification notification: Notification, onScrollView scrollView: UIScrollView) {
if let info = notification.userInfo {
let keyboardSizeDictionary = info[UIKeyboardFrameBeginUserInfoKey] as! NSValue
let keyboardSize = keyboardSizeDictionary.cgRectValue.size
let animationDurationNumber = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
let animationDuration = animationDurationNumber.doubleValue as TimeInterval
let animationOptionsNumber = info[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
let animationOptions = UIViewAnimationOptions(rawValue: animationOptionsNumber.uintValue)
var contentInset = UIEdgeInsets.zero
contentInset.bottom += keyboardSize.height
UIView.animate(withDuration: animationDuration,
delay: 0,
options: animationOptions,
animations: {
scrollView.contentInset = contentInset
scrollView.scrollIndicatorInsets = contentInset
},
completion: nil)
}
}
static func handleKeyboardWillHide(withNotification notification: Notification, onScrollView scrollView: UIScrollView) {
let contentInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
}
| mit | 35d515d8164bc5d38ce86ac870e725e0 | 44.339623 | 124 | 0.607158 | 7.259819 | false | false | false | false |
Sensoro/Beacon-Active-iOS | BeaconActive-Swift/BeaconActive-Swift/ViewController.swift | 1 | 2110 | //
// ViewController.swift
// BeaconActive-Swift
//
// Created by David Yang on 15/4/3.
// Copyright (c) 2015年 Sensoro. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var actionButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if SENLocationManager.sharedInstance.started == true{
actionButton.setTitle("结束监测", for: .normal);
}else{
actionButton.setTitle("启动监测", for: .normal);
}
}
override func viewDidAppear(_ animated: Bool) {
//UIApplication.sharedApplication().applicationIconBadgeNumber = 0;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//46D06053-9FAD-483B-B704-E576735CE1A3
@IBAction func startMonitor(_ sender: Any) {
if SENLocationManager.sharedInstance.started == false{
actionButton.setTitle("结束监测", for: .normal);
SENLocationManager.sharedInstance.startMonitor(relaunch: false);
}else{
actionButton.setTitle("启动监测", for: .normal);
SENLocationManager.sharedInstance.stopMonitor();
}
}
@IBAction func saveToAlbum(sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(image.image!,
self,#selector(image(image:didFinishSavingWithError:contextInfo:)),nil);
}
//
@objc func image(image : UIImage, didFinishSavingWithError error : NSError!, contextInfo info: UnsafeRawPointer) {
if error == nil {
let alert = UIAlertView(title: "提示", message: "保存成功", delegate: nil, cancelButtonTitle: "OK");
alert.show();
}else{
let alert = UIAlertView(title: "提示", message: "保存失败", delegate: nil, cancelButtonTitle: "OK");
alert.show();
}
}
}
| mit | 738e22581455929e9b41c1506da72c71 | 32.639344 | 118 | 0.630604 | 4.590604 | false | false | false | false |
huonw/swift | benchmark/single-source/BitCount.swift | 16 | 1282 | //===--- BitCount.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
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift bit count.
// and mask operator.
// rdar://problem/22151678
import Foundation
import TestsUtils
public let BitCount = BenchmarkInfo(
name: "BitCount",
runFunction: run_BitCount,
tags: [.validation, .algorithm])
func countBitSet(_ num: Int) -> Int {
let bits = MemoryLayout<Int>.size * 8
var cnt: Int = 0
var mask: Int = 1
for _ in 0...bits {
if num & mask != 0 {
cnt += 1
}
mask <<= 1
}
return cnt
}
@inline(never)
public func run_BitCount(_ N: Int) {
var sum = 0
for _ in 1...1000*N {
// Check some results.
sum = sum &+ countBitSet(getInt(1))
&+ countBitSet(getInt(2))
&+ countBitSet(getInt(2457))
}
CheckResults(sum == 8 * 1000 * N)
}
| apache-2.0 | 087b3e456ddf39a1504cfe964408878c | 26.276596 | 80 | 0.574103 | 4.122186 | false | false | false | false |
arevaloarboled/Moviles | Proyecto/iOS/Messages/Pods/Restofire/Sources/RequestEventuallyOperation.swift | 2 | 2150 | //
// RequestEventuallyOperation.swift
// Restofire
//
// Created by Rahul Katariya on 17/04/16.
// Copyright © 2016 AarKay. All rights reserved.
//
#if !os(watchOS)
import Foundation
import Alamofire
/// A `RequestOperation`, when added to an `NSOperationQueue` moitors the
/// network reachability and executes the `Requestable` when the network
/// is reachable.
///
/// - Note: Do not call `start()` directly instead add it to an `NSOperationQueue`
/// because calling `start()` will begin the execution of work regardless of network reachability
/// which is equivalant to `RequestOperation`.
public class RequestEventuallyOperation<R: Requestable>: RequestOperation<R> {
private let networkReachabilityManager = NetworkReachabilityManager()
override init(requestable: R, completionHandler: (Response<R.Model, NSError> -> Void)?) {
super.init(requestable: requestable, completionHandler: completionHandler)
self.ready = false
networkReachabilityManager?.listener = { status in
switch status {
case .Reachable(_):
if self.pause {
self.resume = true
} else {
self.ready = true
}
default:
if self.finished == false && self.executing == false {
self.ready = false
} else {
self.pause = true
}
}
}
networkReachabilityManager?.startListening()
}
override func handleErrorResponse(response: Response<R.Model, NSError>) {
if self.retryAttempts > 0 {
if response.result.error!.code == NSURLErrorNotConnectedToInternet {
self.pause = true
} else if self.requestable.retryErrorCodes.contains(response.result.error!.code) {
self.retryAttempts -= 1
self.performSelector(#selector(RequestOperation<R>.executeRequest), withObject: nil, afterDelay: self.requestable.retryInterval)
}
} else {
super.handleErrorResponse(response)
}
}
}
#endif
| mit | b57be4935dc2e4ae3c648837cc3f5a11 | 34.229508 | 144 | 0.616566 | 4.906393 | false | false | false | false |
J1aDong/GoodBooks | GoodBooks/pushBook_Cell.swift | 1 | 1768 | //
// pushBook_Cell.swift
// GoodBooks
//
// Created by J1aDong on 2017/2/2.
// Copyright © 2017年 J1aDong. All rights reserved.
//
import UIKit
import SWTableViewCell
class pushBook_Cell: SWTableViewCell {
var bookName:UILabel?
var editor:UILabel?
var more:UILabel?
var cover:UIImageView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
for view in self.contentView.subviews{
view.removeFromSuperview()
}
self.bookName = UILabel(frame: CGRect(x: 78, y: 8, width: 242, height: 25))
self.editor = UILabel(frame: CGRect(x: 78, y: 33, width: 242, height: 25))
self.more = UILabel(frame: CGRect(x: 78, y: 66, width: 242, height: 25))
self.bookName?.font = UIFont(name: MY_FONT, size: 15)
self.editor?.font = UIFont(name: MY_FONT, size: 15)
self.more?.font = UIFont(name: MY_FONT, size: 13)
self.more?.textColor = UIColor.gray
self.contentView.addSubview(self.bookName!)
self.contentView.addSubview(self.editor!)
self.contentView.addSubview(self.more!)
self.cover = UIImageView(frame: CGRect(x: 8, y: 9, width: 56, height: 70))
self.contentView.addSubview(self.cover!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | ec256744bdb62278f358b7e249e092d2 | 29.431034 | 83 | 0.627762 | 4.011364 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/Providers/API Providers/APICommentsRequester.swift | 1 | 6731 | //
// APICommentsRequester.swift
// Inbbbox
//
// Created by Patryk Kaczmarek on 16/02/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
import SwiftyJSON
/// Provides interface for dribbble comments update, delete and create API
class APICommentsRequester: Verifiable {
/**
Creates and posts comment for given shot with provided text.
- Warning: Posting comments requires authenticated user with AccountType *Team* or *Player*
- parameter shot: Shot which should be commented.
- parameter text: Text of comment.
- returns: Promise which resolves with created comment.
*/
func postCommentForShot(_ shot: ShotType, withText text: String) -> Promise<CommentType> {
AnalyticsManager.trackUserActionEvent(.comment)
let query = CreateCommentQuery(shot: shot, body: text)
return sendCommentQuery(query, verifyTextLength: text)
}
/**
Updates given comment for shot with provided text.
- Warning: Updating comments requires authenticated user with AccountType *Team* or *Player*.
User has to be owner of comment.
- parameter comment: Comment which should be updated.
- parameter shot: Shot which belongs to comment.
- parameter text: New body of comment.
- returns: Promise which resolves with updated comment.
*/
func updateComment(_ comment: CommentType, forShot shot: ShotType, withText text: String) -> Promise<CommentType> {
let query = UpdateCommentQuery(shot: shot, comment: comment, withBody: text)
return sendCommentQuery(query, verifyTextLength: text)
}
/**
Deletes given comment for provided shot.
- Warning: Deleting comments requires authenticated user with AccountType *Team* or *Player*.
User has to be owner of comment.
- parameter comment: Comment which should be deleted.
- parameter shot: Shot which belongs to comment.
- returns: Promise which resolves with Void.
*/
func deleteComment(_ comment: CommentType, forShot shot: ShotType) -> Promise<Void> {
return Promise<Void> { fulfill, reject in
let query = DeleteCommentQuery(shot: shot, comment: comment)
firstly {
sendCommentDeleteQuery(query)
}.then(execute: fulfill).catch(execute: reject)
}
}
/**
Likes given comment for provided shot.
- Warning: Liking comments requires authenticated user with the *write* scope.
- parameter comment: Comment which should be marked as liked.
- parameter shot: Shot which belongs to comment.
- returns: Promise which resolves with Void.
*/
func likeComment(_ comment: CommentType, forShot shot: ShotType) -> Promise<Void> {
return Promise<Void> { fulfill, reject in
let query = CommentLikeQuery(shot: shot, comment: comment)
firstly {
sendCommentLikeQuery(query)
}.then(execute: fulfill).catch(execute: reject)
}
}
/**
Unlikes given comment for provided shot.
- Warning: Unliking comments requires authenticated user with the *write* scope.
- parameter comment: Comment for which a like mark should be removed.
- parameter shot: Shot which belongs to comment.
- returns: Promise which resolves with Void.
*/
func unlikeComment(_ comment: CommentType, forShot shot: ShotType) -> Promise<Void> {
return Promise<Void> { fulfill, reject in
let query = CommentUnlikeQuery(shot: shot, comment: comment)
firstly {
sendCommentLikeQuery(query)
}.then(execute: fulfill).catch(execute: reject)
}
}
/**
Checks like status of comment for provided shot.
- parameter comment: Comment for check.
- parameter shot: Shot which belongs to comment.
- returns: Promise which resolves with Bool.
*/
func checkIfLikeComment(_ comment: CommentType, forShot shot: ShotType) -> Promise<Bool> {
return Promise<Bool> { fulfill, reject in
let query = CommentLikedQuery(shot: shot, comment: comment)
firstly {
sendCommentLikedQuery(query)
}.then { result in
fulfill(result)
}.catch(execute: reject)
}
}
}
private extension APICommentsRequester {
func sendCommentQuery(_ query: Query, verifyTextLength text: String) -> Promise<CommentType> {
return Promise<CommentType> { fulfill, reject in
firstly {
verifyTextLength(text, min: 1, max: UInt.max)
}.then {
self.sendCommentQuery(query)
}.then(execute: fulfill).catch(execute: reject)
}
}
func sendCommentQuery(_ query: Query) -> Promise<CommentType> {
return Promise<CommentType> { fulfill, reject in
firstly {
verifyAuthenticationStatus(true)
}.then {
self.verifyAccountType()
}.then {
Request(query: query).resume()
}.then { json -> Void in
guard let json = json else {
throw ResponseError.unexpectedResponse
}
fulfill(Comment.map(json))
}.catch(execute: reject)
}
}
func sendCommentDeleteQuery(_ query: Query) -> Promise<Void> {
return Promise<Void> { fulfill, reject in
firstly {
verifyAuthenticationStatus(true)
}.then {
self.verifyAccountType()
}.then {
Request(query: query).resume()
}.then { _ in fulfill() }.catch(execute: reject)
}
}
func sendCommentLikeQuery(_ query: Query) -> Promise<Void> {
return Promise<Void> { fulfill, reject in
firstly {
verifyAuthenticationStatus(true)
}.then {
Request(query: query).resume()
}.then { _ in fulfill() }.catch(execute: reject)
}
}
func sendCommentLikedQuery(_ query: Query) -> Promise<Bool> {
return Promise<Bool> { fulfill, reject in
firstly {
verifyAuthenticationStatus(true)
}.then {
Request(query: query).resume()
}.then { _ in
fulfill(true)
}.catch { error in
// According to API documentation, when response.code is 404,
// then comment is not liked by authenticated user.
(error as NSError).code == 404 ? fulfill(false) : reject(error)
}
}
}
}
| gpl-3.0 | 13d869b37b2525cc1965cb63637f45d5 | 31.200957 | 119 | 0.608172 | 4.776437 | false | false | false | false |
gu704823/DYTV | dytv/Pods/LeanCloud/Sources/Storage/CQLClient.swift | 5 | 3436 | //
// CQLClient.swift
// LeanCloud
//
// Created by Tang Tianyong on 5/30/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
/**
A type represents the result value of CQL execution.
*/
open class LCCQLValue {
let response: LCResponse
init(response: LCResponse) {
self.response = response
}
var results: [[String: AnyObject]] {
return (response.results as? [[String: AnyObject]]) ?? []
}
var className: String {
return (response["className"] as? String) ?? LCObject.objectClassName()
}
/**
Get objects for object query.
*/
open var objects: [LCObject] {
let results = self.results
let className = self.className
return results.map { dictionary in
ObjectProfiler.object(dictionary: dictionary, className: className)
}
}
/**
Get count value for count query.
*/
open var count: Int {
return response.count
}
}
/**
CQL client.
CQLClient allow you to use CQL (Cloud Query Language) to make CRUD for object.
*/
open class LCCQLClient {
static let endpoint = "cloudQuery"
/// The dispatch queue for asynchronous CQL execution task.
static let backgroundQueue = DispatchQueue(label: "LeanCloud.CQLClient", attributes: .concurrent)
/**
Asynchronize task into background queue.
- parameter task: The task to be performed.
- parameter completion: The completion closure to be called on main thread after task finished.
*/
static func asynchronize(_ task: @escaping () -> LCCQLResult, completion: @escaping (LCCQLResult) -> Void) {
Utility.asynchronize(task, backgroundQueue, completion)
}
/**
Assemble parameters for CQL execution.
- parameter cql: The CQL statement.
- parameter parameters: The parameters for placeholders in CQL statement.
- returns: The parameters for CQL execution.
*/
static func parameters(_ cql: String, parameters: LCArrayConvertible?) -> [String: AnyObject] {
var result = ["cql": cql]
if let parameters = parameters?.lcArray {
if !parameters.isEmpty {
result["pvalues"] = Utility.jsonString(parameters.lconValue!)
}
}
return result as [String : AnyObject]
}
/**
Execute CQL statement synchronously.
- parameter cql: The CQL statement to be executed.
- parameter parameters: The parameters for placeholders in CQL statement.
- returns: The result of CQL statement.
*/
open static func execute(_ cql: String, parameters: LCArrayConvertible? = nil) -> LCCQLResult {
let parameters = self.parameters(cql, parameters: parameters)
let response = RESTClient.request(.get, endpoint, parameters: parameters)
return LCCQLResult(response: response)
}
/**
Execute CQL statement asynchronously.
- parameter cql: The CQL statement to be executed.
- parameter parameters: The parameters for placeholders in CQL statement.
- parameter completion: The completion callback closure.
*/
open static func execute(_ cql: String, parameters: LCArrayConvertible? = nil, completion: @escaping (_ result: LCCQLResult) -> Void) {
asynchronize({ execute(cql, parameters: parameters) }) { result in
completion(result)
}
}
}
| mit | c466e72e9b3b8e5b32c15cd2f5a53e4d | 28.358974 | 139 | 0.644833 | 4.426546 | false | false | false | false |
younata/RSSClient | TethysKitSpecs/Helpers/ModelFactories.swift | 1 | 1017 | import TethysKit
func feedFactory(
title: String = "title",
url: URL = URL(string: "https://example.com/feed")!,
summary: String = "summary",
tags: [String] = [],
unreadCount: Int = 0,
image: Image? = nil
) -> Feed {
return Feed(
title: title,
url: url,
summary: summary,
tags: tags,
unreadCount: unreadCount,
image: image
)
}
func articleFactory(
title: String = "",
link: URL = URL(string: "https://example.com")!,
summary: String = "",
authors: [Author] = [],
identifier: String = "",
content: String = "",
read: Bool = false,
estimatedReadingTime: TimeInterval = 0,
published: Date = Date(),
updated: Date? = nil
) -> Article {
return Article(
title: title,
link: link,
summary: summary,
authors: authors,
identifier: identifier,
content: content,
read: read,
published: published,
updated: updated
)
}
| mit | cebeeb2d4bc1ed875e4f9a63953acc70 | 22.113636 | 56 | 0.544739 | 4.117409 | false | false | false | false |
banxi1988/BXModel | Pod/Classes/StaticTableViewDataSource.swift | 4 | 1612 | //
// StaticTableViewDataSource.swift
// Pods
//
// Created by Haizhen Lee on 15/12/1.
//
//
import Foundation
open class StaticTableViewDataSource:NSObject,UITableViewDataSource,BXDataSourceContainer{
open fileprivate(set) var cells:[UITableViewCell] = []
public typealias ItemType = UITableViewCell
open var section = 0
open var configureCellBlock:((UITableViewCell) -> Void)?
public init(cells:[UITableViewCell] = []){
self.cells = cells
}
open func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
open func cellAtIndexPath(_ indexPath:IndexPath) -> UITableViewCell{
return self.cells[(indexPath as NSIndexPath).row]
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.cells.count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = cellAtIndexPath(indexPath)
self.configureCellBlock?(cell)
return cell
}
open func append(_ cell:UITableViewCell){
if !cells.contains(cell){
self.cells.append(cell)
}
}
open func appendContentsOf(_ cells:[UITableViewCell]){
for cell in cells{
append(cell)
}
}
open func updateItems<S : Sequence>(_ items: S) where S.Iterator.Element == ItemType {
self.cells.removeAll()
self.cells.append(contentsOf: items)
}
open func appendItems<S : Sequence>(_ items: S) where S.Iterator.Element == ItemType {
self.cells.append(contentsOf: items)
}
open var numberOfItems:Int{ return cells.count }
}
| mit | 533a290bad602271831118ed0862aab4 | 23.8 | 102 | 0.692308 | 4.416438 | false | false | false | false |
alexandreblin/ios-car-dashboard | CarDash/GraphView.swift | 1 | 6287 | //
// GraphView.swift
// CarDash
//
// Created by Alexandre Blin on 14/01/2017.
// Copyright © 2017 Alexandre Blin. All rights reserved.
//
import UIKit
/// A view representing a curved line graph. It animates when a new value
/// is added by shifting the graph to the left.
class GraphView: UIView {
/// Maximum number of values to display on the graph at the same time
var maximumNumberOfValues: Int = 8 {
didSet {
values.removeAll()
for _ in 0..<maximumNumberOfValues {
values.append(0)
}
}
}
/// Maximum value on the y-axis
var maximumScale: CGFloat = 15
private static let translationAnimationKey = "translationAnimation"
private var values = [CGFloat]()
private var shapeLayer: CAShapeLayer!
private var maskLayer: CAShapeLayer!
private var gradientView: UIView!
private var gradientLayer: CAGradientLayer! // gradient under the curve
private var blackGradientLayer: CAGradientLayer! // black fading gradient at the end of graph
private var isAnimating = false
override func awakeFromNib() {
super.awakeFromNib()
clipsToBounds = true
// Setup gradient view
let gradientView = UIView(frame: bounds)
gradientView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = [
UIColor(colorLiteralRed: 0.84, green: 0.96, blue: 0.96, alpha: 0.75).cgColor,
UIColor.black.cgColor
]
gradientView.layer.addSublayer(gradientLayer)
self.addSubview(gradientView)
let maskLayer = CAShapeLayer()
maskLayer.lineWidth = 4.0
maskLayer.position = CGPoint.zero
gradientView.layer.mask = maskLayer
self.gradientView = gradientView
self.gradientLayer = gradientLayer
self.maskLayer = maskLayer
// Setup shape layer
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor(white: 0.7, alpha: 1.0).cgColor
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineWidth = 4.0
shapeLayer.position = CGPoint.zero
layer.addSublayer(shapeLayer)
self.shapeLayer = shapeLayer
let blackGradientLayer = CAGradientLayer()
blackGradientLayer.frame = CGRect(x: 0, y: 0, width: 30, height: bounds.height)
blackGradientLayer.colors = [
UIColor.clear.cgColor,
UIColor.black.cgColor
]
blackGradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
blackGradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)
layer.addSublayer(blackGradientLayer)
self.blackGradientLayer = blackGradientLayer
}
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = gradientView.bounds
blackGradientLayer.frame = CGRect(x: 0, y: 0, width: blackGradientLayer.frame.width, height: bounds.height)
}
private func bezierPathForValues(withClose close: Bool = false) -> CGPath {
precondition(values.count >= 2)
let path = UIBezierPath()
let padding: CGFloat = 3.0
let viewHeight = bounds.height - 2 * padding
let stepWidth = bounds.width / CGFloat(maximumNumberOfValues - 1)
let curveForce = stepWidth / 3.0
let lastFiveValues = values.suffix(5)
let scaleMultiplier = viewHeight / lastFiveValues.reduce(maximumScale, max)
var p1 = CGPoint(x: 0, y: viewHeight - padding - values[0] * scaleMultiplier)
var p2: CGPoint = CGPoint.zero
path.move(to: p1)
for i in 1..<values.count {
p2 = CGPoint(x: CGFloat(i) * stepWidth, y: viewHeight - padding - values[i] * scaleMultiplier)
path.addCurve(to: p2,
controlPoint1: CGPoint(x: p1.x + curveForce, y: p1.y),
controlPoint2: CGPoint(x: p2.x - curveForce, y: p2.y))
p1 = p2
}
if close {
path.addLine(to: CGPoint(x: p2.x, y: viewHeight))
path.addLine(to: CGPoint(x: 0, y: viewHeight))
path.close()
}
return path.cgPath
}
func add(value: CGFloat) {
if isAnimating {
return
}
isAnimating = true
values.append(value)
if values.count < 2 {
// No need to go further is we don't have more than 1 data point
return
}
CATransaction.begin()
CATransaction.setCompletionBlock {
if self.values.count > self.maximumNumberOfValues {
self.values.remove(at: 0)
self.shapeLayer.path = self.bezierPathForValues()
self.shapeLayer.removeAnimation(forKey: GraphView.translationAnimationKey)
self.maskLayer.path = self.bezierPathForValues(withClose: true)
self.maskLayer.removeAnimation(forKey: GraphView.translationAnimationKey)
}
self.isAnimating = false
}
let morphAnimation = CABasicAnimation(keyPath: "path")
morphAnimation.duration = 0.2
let path = bezierPathForValues()
morphAnimation.fromValue = shapeLayer.path
morphAnimation.toValue = path
shapeLayer.add(morphAnimation, forKey: nil)
if values.count > maximumNumberOfValues {
let translationAnimation = CABasicAnimation(keyPath: "transform.translation.x")
translationAnimation.duration = 0.2
translationAnimation.fromValue = 0
translationAnimation.toValue = -(bounds.width / CGFloat(maximumNumberOfValues - 1))
translationAnimation.isRemovedOnCompletion = false
translationAnimation.fillMode = kCAFillModeForwards
shapeLayer.add(translationAnimation, forKey: GraphView.translationAnimationKey)
maskLayer.add(translationAnimation, forKey: GraphView.translationAnimationKey)
}
CATransaction.commit()
shapeLayer.path = path
maskLayer.path = bezierPathForValues(withClose: true)
}
func fillWithLastValue() {
add(value: values.last ?? 0)
}
}
| mit | 90b88247d1bada84e47c00dfe929d033 | 30.747475 | 115 | 0.630608 | 4.820552 | false | false | false | false |
pkrawat1/TravelApp-ios | TravelApp/View/UserProfile/Following.swift | 1 | 5982 | //
// Following.swift
// TravelApp
//
// Created by Nitesh on 23/02/17.
// Copyright © 2017 Pankaj Rawat. All rights reserved.
//
import UIKit
class Following: BaseCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
let cellId = "CellId"
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let cv = UICollectionView(frame: CGRect.init(), collectionViewLayout: layout)
cv.backgroundColor = UIColor.appMainBGColor()
cv.translatesAutoresizingMaskIntoConstraints = false
cv.dataSource = self
cv.delegate = self
return cv
}()
override func setupViews() {
setupCollectionView()
}
private func setupCollectionView() {
addSubview(collectionView)
collectionView.register(FollowingCell.self, forCellWithReuseIdentifier: cellId)
collectionView.topAnchor.constraint(equalTo: topAnchor, constant: 100).isActive = true
collectionView.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
collectionView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -100).isActive = true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! FollowingCell
cell.backgroundColor = UIColor.white
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: frame.width, height: 60)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 5
}
}
class FollowingCell: BaseCell {
let userProfileImageView: CustomImageView = {
let ui = CustomImageView()
ui.image = UIImage(named: "")
ui.contentMode = .scaleAspectFill
ui.clipsToBounds = true
ui.layer.cornerRadius = 20
ui.layer.masksToBounds = true
ui.layer.borderWidth = 2
ui.layer.borderColor = UIColor.white.cgColor
ui.translatesAutoresizingMaskIntoConstraints = false
ui.backgroundColor = UIColor.red
return ui
}()
let userNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.numberOfLines = 1
label.font = label.font.withSize(15)
label.textColor = UIColor.black
label.backgroundColor = UIColor.green
return label
}()
let userFollowersLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = ""
label.numberOfLines = 1
label.font = label.font.withSize(15)
label.textColor = UIColor.black
label.backgroundColor = UIColor.green
return label
}()
let followerBtn: UIButton = {
let ub = UIButton(type: .system)
ub.setImage(UIImage(named: "like"), for: .normal)
ub.tintColor = UIColor.white
ub.translatesAutoresizingMaskIntoConstraints = false
ub.backgroundColor = UIColor.red
return ub
}()
override func setupViews() {
setupUserProfileImageView()
setupFollowerBtn()
setupUserNameLabel()
setUserFollowersLabel()
}
func setupUserProfileImageView() {
addSubview(userProfileImageView)
userProfileImageView.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
userProfileImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
userProfileImageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -4).isActive = true
// userProfileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
userProfileImageView.widthAnchor.constraint(equalToConstant: 50).isActive = true
}
func setupUserNameLabel() {
addSubview(userNameLabel)
userNameLabel.topAnchor.constraint(equalTo: userProfileImageView.topAnchor).isActive = true
userNameLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true
userNameLabel.rightAnchor.constraint(equalTo: followerBtn.leftAnchor , constant: -10).isActive = true
userNameLabel.heightAnchor.constraint(equalToConstant: 22).isActive = true
}
func setupFollowerBtn() {
addSubview(followerBtn)
followerBtn.topAnchor.constraint(equalTo: userProfileImageView.topAnchor).isActive = true
followerBtn.rightAnchor.constraint(equalTo: rightAnchor, constant: -5).isActive = true
followerBtn.bottomAnchor.constraint(equalTo: userProfileImageView.bottomAnchor).isActive = true
// followerBtn.heightAnchor.constraint(equalToConstant: 40).isActive = true
followerBtn.widthAnchor.constraint(equalToConstant: 50).isActive = true
}
func setUserFollowersLabel() {
addSubview(userFollowersLabel)
userFollowersLabel.bottomAnchor.constraint(equalTo: userProfileImageView.bottomAnchor).isActive = true
userFollowersLabel.heightAnchor.constraint(equalToConstant: 22).isActive = true
userFollowersLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true
userFollowersLabel.rightAnchor.constraint(equalTo: followerBtn.leftAnchor , constant: -10).isActive = true
}
}
| mit | 85684d064aff5ad1d5dd3312ff52645a | 38.348684 | 170 | 0.694365 | 5.553389 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Data/Implementations/Standard/LineScatterCandleRadarChartDataSet.swift | 13 | 1964 | //
// LineScatterCandleRadarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 29/7/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
public class LineScatterCandleRadarChartDataSet: BarLineScatterCandleBubbleChartDataSet, ILineScatterCandleRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn.
public var drawHorizontalHighlightIndicatorEnabled = true
/// Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn.
public var drawVerticalHighlightIndicatorEnabled = true
/// - returns: true if horizontal highlight indicator lines are enabled (drawn)
public var isHorizontalHighlightIndicatorEnabled: Bool { return drawHorizontalHighlightIndicatorEnabled }
/// - returns: true if vertical highlight indicator lines are enabled (drawn)
public var isVerticalHighlightIndicatorEnabled: Bool { return drawVerticalHighlightIndicatorEnabled }
/// Enables / disables both vertical and horizontal highlight-indicators.
/// :param: enabled
public func setDrawHighlightIndicators(enabled: Bool)
{
drawHorizontalHighlightIndicatorEnabled = enabled
drawVerticalHighlightIndicatorEnabled = enabled
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
let copy = super.copyWithZone(zone) as! LineScatterCandleRadarChartDataSet
copy.drawHorizontalHighlightIndicatorEnabled = drawHorizontalHighlightIndicatorEnabled
copy.drawVerticalHighlightIndicatorEnabled = drawVerticalHighlightIndicatorEnabled
return copy
}
}
| apache-2.0 | bbe2c2dcbb2dffd65f67644076f4fdfa | 36.056604 | 124 | 0.747963 | 5.933535 | false | false | false | false |
Eric217/-OnSale | 打折啦/打折啦/ELToolBar.swift | 1 | 2629 | //
// ELToolBar.swift
// 打折啦
//
// Created by Eric on 11/09/2017.
// Copyright © 2017 INGStudio. All rights reserved.
//
import Foundation
class ToolItemView0: BackView {
override init(frame: CGRect) {
super.init(frame: frame)
img.snp.updateConstraints { make in
make.width.height.equalTo(18)
}
txt.snp.updateConstraints { make in
make.width.equalTo(25)
make.height.equalTo(18)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ToolItemView: UIView {
var innerView: ToolItemView0!
override init(frame: CGRect) {
super.init(frame: frame)
innerView = ToolItemView0()
addSubview(innerView)
innerView.snp.makeConstraints { make in
make.width.equalTo(45)
make.height.equalTo(18)
make.center.equalTo(self)
}
}
func setup(_ aimg: UIImage, title: String) {
innerView.img.image = aimg
innerView.txt.text = title
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ELToolBar: UIView {
var button1: ToolItemView!
var button2: ToolItemView!
var button3: ToolItemView!
var button4: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
let effc = UIBlurEffect(style: .extraLight)
let effcView = UIVisualEffectView(effect: effc)
addSubview(effcView)
effcView.snp.makeConstraints { make in
make.center.size.equalTo(self)
}
let w = ScreenWidth*0.25
button1 = ToolItemView(frame: myRect(0, 0, w, 44))
addSubview(button1)
button1.setup(#imageLiteral(resourceName: "small"), title: "留言")
button2 = ToolItemView(frame: myRect(w, 0, w, 44))
addSubview(button2)
button2.setup(#imageLiteral(resourceName: "small"), title: "收藏")
button3 = ToolItemView(frame: myRect(w*2, 0, w, 44))
addSubview(button3)
button3.setup(#imageLiteral(resourceName: "small"), title: "咨询")
button4 = UIButton(frame: myRect(w*3, 0, w, 44))
addSubview(button4)
button4.backgroundColor = Config.themeColor
button4.setTitle("到这去", for: .normal)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 2f1904cba7b7cc2709cbb2d89ee1c1c2 | 24.281553 | 72 | 0.583717 | 4.03096 | false | false | false | false |
devlucky/Kakapo | Source/RouteMatcher.swift | 1 | 5360 | //
// RouteMatcher.swift
// Kakapo
//
// Created by Joan Romano on 31/03/16.
// Copyright © 2016 devlucky. All rights reserved.
//
import Foundation
/**
A tuple holding components and query parameters, check `matchRoute` for more details
*/
public typealias URLInfo = (components: [String : String], queryParameters: [URLQueryItem])
/**
Match a route and a requestURL. A route is composed by a baseURL and a path, together they should match the given requestURL.
To match a route the baseURL must be contained in the requestURL, the substring of the requestURL following the baseURL then is tested against the path to check if they match.
A baseURL can contain a scheme, and the requestURL must match the scheme; if it doesn't contain a scheme then the baseURL is a wildcard and will be matched by any subdomain or any scheme:
- base: `http://kakapo.com`, path: "any", requestURL: "http://kakapo.com/any" ✅
- base: `http://kakapo.com`, path: "any", requestURL: "https://kakapo.com/any" ❌ because it's **https**
- base: `kakapo.com`, path: "any", requestURL: "https://kakapo.com/any" ✅
- base: `kakapo.com`, path: "any", requestURL: "https://api.kakapo.com/any" ✅
A path can contain wildcard components prefixed with ":" (e.g. /users/:userid) that are used to build the component dictionary, the wildcard is then used as key and the respective component of the requestURL is used as value.
Any component that is not a wildcard have to be exactly the same in both the path and the request, otherwise the route won't match.
- `/users/:userid` and `/users/1234` ✅ -> `[userid: 1234]`
- `/comment/:commentid` and `/users/1234` ❌
QueryParameters are stripped from requestURL before the matching and used to fill `URLInfo.queryParamters`, anything after "?" won't affect the matching.
- parameter baseURL: The base url, can contain the scheme or not but must be contained in the `requestURL`, (e.g. http://kakapo.com/api) if the baseURL doesn't contain the scheme it's considered as a wildcard that match any scheme and subdomain, see the examples above.
- parameter path: The path of the request, can contain wildcards components prefixed with ":" (e.g. /users/:id/)
- parameter requestURL: The URL of the request (e.g. https://kakapo.com/api/users/1234)
- returns: A URL info object containing `components` and `queryParameters` or nil if `requestURL`doesn't match the route.
*/
func matchRoute(_ baseURL: String, path: String, requestURL: URL) -> URLInfo? {
// remove the baseURL and the params, if baseURL is not in the string the result will be nil
guard let relevantURL: String = {
let string = requestURL.absoluteString // http://kakapo.com/api/users/1234?a=b
let stringWithoutParams = string.substring(.to, string: "?") ?? string // http://kakapo.com/api/users/1234
return stringWithoutParams.substring(.from, string: baseURL) // `/api/users`
}() else { return nil }
let routePathComponents = path.split("/") // e.g. [users, :userid]
let requestPathComponents = relevantURL.split("/") // e.g. [users, 1234]
guard routePathComponents.count == requestPathComponents.count else {
// different components count means that the path can't match
return nil
}
var components: [String : String] = [:]
for (routeComponent, requestComponent) in zip(routePathComponents, requestPathComponents) {
// [users, users], [:userid, 1234]
// if they are not equal then it must be a key prefixed by ":" otherwise the route is not matched
if routeComponent == requestComponent {
continue // not a wildcard, no need to insert it in components
} else {
guard let firstChar = routeComponent.characters.first, firstChar == ":" else {
return nil // not equal nor a wildcard
}
}
let relevantKeyIndex = routeComponent.characters.index(after: routeComponent.characters.startIndex) // second position
let key = routeComponent.substring(from: relevantKeyIndex) // :key -> key
components[key] = requestComponent
}
// get the parameters [a:b]
let queryItems = URLComponents(url: requestURL, resolvingAgainstBaseURL: false)?.queryItems
return (components, queryItems ?? [])
}
private extension String {
func split(_ separator: Character) -> [String] {
return characters.split(separator: separator).map { String($0) }
}
enum SplitMode {
case from
case to
}
/**
Return the substring From/To a given string or nil if the string is not contained.
- **from**: return the substring following the given string (e.g. `kakapo.com/users`, `kakapo.com` -> `/users`)
- **to**: return the substring preceding the given string (e.g. `kakapo.com/users?a=b`, `?` -> `kakapo.com/users`)
*/
func substring(_ mode: SplitMode, string: String) -> String? {
guard !string.characters.isEmpty else {
return self
}
guard let range = range(of: string) else {
return nil
}
switch mode {
case .from:
return substring(from: range.upperBound)
case .to:
return substring(to: range.lowerBound)
}
}
}
| mit | 97261f0a3fc58e134dac6f216676e684 | 45.903509 | 273 | 0.668599 | 4.138545 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/ViewControllers/DebugUI/LogViewController.swift | 1 | 5150 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc
public class LogPickerViewController: OWSTableViewController {
let logDirUrl: URL
@objc
public init(logDirUrl: URL) {
self.logDirUrl = logDirUrl
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func viewDidLoad() {
super.viewDidLoad()
updateTableContents()
}
public func updateTableContents() {
let contents = OWSTableContents()
contents.addSection(buildPreferenceSection())
contents.addSection(buildLogsSection())
self.contents = contents
}
private func buildPreferenceSection() -> OWSTableSection {
let enableItem = OWSTableItem.switch(withText: "🚂 Play Sound When Errors Occur",
isOn: { OWSPreferences.isAudibleErrorLoggingEnabled() },
target: self,
selector: #selector(didToggleAudiblePreference(_:)))
return OWSTableSection(title: "Preferences", items: [enableItem])
}
private func buildLogsSection() -> OWSTableSection {
guard let directoryEnumerator = FileManager.default.enumerator(at: logDirUrl, includingPropertiesForKeys: nil) else {
owsFailDebug("logUrls was unexpectedly nil")
return OWSTableSection(title: "No Log URLs", items: [])
}
let logUrls: [URL] = directoryEnumerator.compactMap { $0 as? URL }
let sortedUrls = logUrls.sorted { (a, b) -> Bool in
return a.lastPathComponent > b.lastPathComponent
}
let logItems: [OWSTableItem] = sortedUrls.map { logUrl in
return OWSTableItem(
customCellBlock: { () -> UITableViewCell in
let cell = OWSTableItem.newCell()
guard let textLabel = cell.textLabel else {
owsFailDebug("textLabel was unexpectedly nil")
return cell
}
textLabel.lineBreakMode = .byTruncatingHead
textLabel.text = logUrl.lastPathComponent
return cell
},
actionBlock: { [weak self] in
guard let self = self else { return }
let logVC = LogViewController(logUrl: logUrl)
guard let navigationController = self.navigationController else {
owsFailDebug("navigationController was unexpectedly nil")
return
}
navigationController.pushViewController(logVC, animated: true)
}
)
}
return OWSTableSection(title: "View Logs", items: logItems)
}
@objc
func didToggleAudiblePreference(_ sender: UISwitch) {
OWSPreferences.setIsAudibleErrorLoggingEnabled(sender.isOn)
if sender.isOn {
ErrorLogger.playAlertSound()
}
}
}
@objc
public class LogViewController: UIViewController {
let logUrl: URL
@objc
public init(logUrl: URL) {
self.logUrl = logUrl
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let textView = UITextView()
override public func loadView() {
self.view = textView
loadLogText()
}
override public func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItems = [UIBarButtonItem(barButtonSystemItem: .action,
target: self,
action: #selector(didTapShare(_:))),
UIBarButtonItem(barButtonSystemItem: .trash,
target: self,
action: #selector(didTapTrash(_:)))]
}
func loadLogText() {
do {
// This is super crude, but:
// 1. generally we should haven't a ton of logged errors
// 2. this is a dev tool
let logData = try Data(contentsOf: logUrl)
// TODO most recent lines on top?
textView.text = String(data: logData, encoding: .utf8)
} catch {
textView.text = "Failed to load log data: \(error)"
}
}
@objc
func didTapTrash(_ sender: UIBarButtonItem) {
// truncate logUrl
do {
try NSData().write(to: logUrl)
loadLogText()
} catch {
owsFailDebug("error: \(error)")
}
}
@objc
func didTapShare(_ sender: UIBarButtonItem) {
let logText = textView.text ?? "Empty Log"
let vc = UIActivityViewController(activityItems: [logText], applicationActivities: [])
present(vc, animated: true)
}
}
| gpl-3.0 | 55b0f848db3ce99375c7dad2a9c30ba4 | 32.422078 | 125 | 0.546338 | 5.423604 | false | false | false | false |
sztoth/PodcastChapters | PodcastChapters/Utilities/Extensions/NSUserNotification.swift | 1 | 661 | //
// NSUserNotification.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 10. 12..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Foundation
extension NSUserNotification {
convenience init(appNotification: AppNotification) {
self.init()
identifier = appNotification.identifier
title = appNotification.title
informativeText = appNotification.description
hasActionButton = true
actionButtonTitle = appNotification.actionButtonTitle
otherButtonTitle = appNotification.otherButtonTitle
setValue(appNotification.image, forKey: "_identityImage")
}
}
| mit | ea19131805ac5c1324a992bdca1d3fa0 | 26.5 | 65 | 0.712121 | 5.19685 | false | false | false | false |
crossroadlabs/PathToRegex | Package.swift | 1 | 1303 | //===--- Package.swift ------------------------------------------------===//
//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//This file is part of PathToRegex.
//
//PathToRegex is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//PathToRegex is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with PathToRegex. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import PackageDescription
let package = Package(
name: "PathToRegex",
targets: [
Target(
name: "PathToRegex"
)
],
dependencies: [
.Package(url: "https://github.com/crossroadlabs/Regex.git", "1.0.0-alpha"),
.Package(url: "https://github.com/crossroadlabs/Boilerplate.git", majorVersion: 1, minor: 1),
],
exclude: ["Carthage"]
)
| gpl-3.0 | 1fcec348baff95efbf2c3aacf8e4ca8e | 35.194444 | 101 | 0.62241 | 4.286184 | false | false | false | false |
PANDA-Guide/PandaGuideApp | Carthage/Checkouts/SwiftTweaks/iOS Example/iOS Example/ExampleTweaks.swift | 1 | 3339 | //
// ExampleTweaks.swift
// iOS Example
//
// Created by Bryan Clark on 11/9/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import Foundation
import SwiftTweaks
public struct ExampleTweaks: TweakLibraryType {
public static let colorBackground = Tweak("General", "Colors", "Background", UIColor(white: 0.95, alpha: 1.0))
public static let colorTint = Tweak("General", "Colors", "Tint", UIColor.blue)
public static let colorButtonText = Tweak("General", "Colors", "Button Text", UIColor.white)
// Tweaks work *great* with numbers, you just need to tell the compiler
// what kind of number you're using (Int, CGFloat, or Double)
public static let fontSizeText1 = Tweak<CGFloat>("Text", "Font Sizes", "title", 30)
public static let fontSizeText2 = Tweak<CGFloat>("Text", "Font Sizes", "body", 15)
// If the tweak is for a number, you can optionally add default / min / max / stepSize options to restrict the values.
// Maybe you've got a number that must be non-negative, for example:
public static let horizontalMargins = Tweak<CGFloat>("General", "Layout", "H. Margins", defaultValue: 15, min: 0)
public static let verticalMargins = Tweak<CGFloat>("General", "Layout", "V. Margins", defaultValue: 10, min: 0)
public static let colorText1 = Tweak("Text", "Color", "text-1", UIColor(white: 0.05, alpha: 1.0))
public static let colorText2 = Tweak("Text", "Color", "text-2", UIColor(white: 0.15, alpha: 1.0))
// Tweaks are often used in combination with each other, so we have some templates available for ease-of-use:
public static let buttonAnimation = SpringAnimationTweakTemplate("Animation", "Button Animation", duration: 0.5) // Note: "duration" is optional, if you don't provide it, there's a sensible default!
/*
Seriously, SpringAnimationTweakTemplate is *THE BEST* - here's what the equivalent would be if you were to make that by hand:
public static let animationDuration = Tweak<Double>("Animation", "Button Animation", "Duration", defaultValue: 0.5, min: 0.0)
public static let animationDelay = Tweak<Double>("Animation", "Button Animation", "Delay", defaultValue: 0.0, min: 0.0, max: 1.0)
public static let animationDamping = Tweak<CGFloat>("Animation", "Button Animation", "Damping", defaultValue: 0.7, min: 0.0, max: 1.0)
public static let animationVelocity = Tweak<CGFloat>("Animation", "Button Animation", "Initial V.", 0.0)
*/
public static let featureFlagMainScreenHelperText = Tweak("Feature Flags", "Main Screen", "Show Body Text", true)
public static let defaultStore: TweakStore = {
let allTweaks: [TweakClusterType] = [
colorBackground,
colorTint,
colorButtonText,
horizontalMargins,
verticalMargins,
colorText1,
colorText2,
fontSizeText1,
fontSizeText2,
buttonAnimation,
featureFlagMainScreenHelperText
]
// Since SwiftTweaks is a dynamic library, you'll need to determine whether tweaks are enabled.
// Try using the DEBUG flag (add "-D DEBUG" to "Other Swift Flags" in your project's Build Settings).
// Below, we'll use TweakDebug.isActive, which is a shortcut to check the DEBUG flag.
return TweakStore(
tweaks: allTweaks,
storeName: "ExampleTweaks", // NOTE: You can omit the `storeName` parameter if you only have one TweakLibraryType in your application.
enabled: TweakDebug.isActive
)
}()
}
| gpl-3.0 | 1203f94ea6837bef5190244722aec36c | 44.108108 | 199 | 0.726183 | 3.729609 | false | false | false | false |
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART | bluefruitconnect/Platform/OSX/Controllers/MainWindowController.swift | 1 | 1371 | //
// MainWindowController.swift
// Bluefruit Connect
//
// Created by Antonio García on 28/09/15.
// Copyright © 2015 Adafruit. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController {
@IBOutlet weak var startScanItem: NSToolbarItem!
@IBOutlet weak var stopScanItem: NSToolbarItem!
override func windowDidLoad() {
super.windowDidLoad()
// Fix for Autosave window position
// http://stackoverflow.com/questions/25150223/nswindowcontroller-autosave-using-storyboard
self.windowFrameAutosaveName = "Main App Window"
updateScanItems()
}
override func validateToolbarItem(theItem: NSToolbarItem) -> Bool {
return theItem.enabled
}
@IBAction func onClickScan(sender: NSToolbarItem) {
let tag = sender.tag
DLog("onClickScan: \(tag)")
let bleManager = BleManager.sharedInstance
if (tag == 0) {
bleManager.startScan()
}
else if (tag == 1) {
bleManager.stopScan()
}
updateScanItems()
}
func updateScanItems() {
let bleManager = BleManager.sharedInstance
let isScanning = bleManager.isScanning
startScanItem.enabled = !isScanning
stopScanItem.enabled = isScanning
}
}
| mit | 002eaf5304bd9b4d41b32a15adc606d5 | 24.830189 | 99 | 0.621622 | 4.871886 | false | false | false | false |
WSDOT/wsdot-ios-app | wsdot/FacebookStore.swift | 2 | 2310 | //
// FacebookStore.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import Foundation
import Alamofire
import SwiftyJSON
class FacebookStore {
typealias FetchPostsCompletion = (_ data: [FacebookItem]?, _ error: Error?) -> ()
static func getPosts(_ completion: @escaping FetchPostsCompletion) {
AF.request("https://www.wsdot.wa.gov/news/socialroom/posts/facebook").validate().responseJSON { response in
switch response.result {
case .success:
if let value = response.data {
let json = JSON(value)
let posts = parsePostsJSON(json)
completion(posts, nil)
}
case .failure(let error):
print(error)
completion(nil, error)
}
}
}
fileprivate static func parsePostsJSON(_ json: JSON) ->[FacebookItem]{
var posts = [FacebookItem]()
for (_,postJson):(String, JSON) in json {
let post = FacebookItem()
post.id = postJson["id"].stringValue
post.message = postJson["message"].stringValue
.replacingOccurrences(of: "(https?:\\/\\/[-a-zA-Z0-9._~:\\/?#@!$&\'()*+,;=%]+)", with: "<a href=\"$1\">$1</a>", options: .regularExpression, range: nil)
post.createdAt = TimeUtils.postPubDateToNSDate(postJson["created_time"].stringValue, formatStr: "yyyy-MM-dd'T'HH:mm:ssZ", isUTC: true)
posts.append(post)
}
return posts
}
}
| gpl-3.0 | 59bba4769ddc96455a916ec887549474 | 35.09375 | 168 | 0.596104 | 4.391635 | false | false | false | false |
Tsiems/mobile-sensing-apps | AirDrummer/AIToolbox/DeepNetwork.swift | 1 | 20077 | //
// DeepNetwork.swift
// AIToolbox
//
// Created by Kevin Coble on 6/25/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
protocol DeepNetworkInputSource {
func getInputDataSize(_ inputID : String) -> DeepChannelSize?
func getValuesForID(_ inputID : String) -> [Float]
func getAllValues() -> [Float]
}
protocol DeepNetworkOutputDestination {
func getGradientForSource(_ sourceID : String) -> [Float]
}
public struct DeepNetworkInput : MLPersistence {
public let inputID : String
public private(set) var size : DeepChannelSize
var values : [Float]
public init(inputID: String, size: DeepChannelSize, values: [Float])
{
self.inputID = inputID
self.size = size
self.values = values
}
// Persistence assumes values are set later, and only ID and size need to be saved
public init?(fromDictionary: [String: AnyObject])
{
// Init for nil return (hopefully Swift 3 removes this need)
size = DeepChannelSize(dimensionCount: 0, dimensionValues: [])
values = []
// Get the id string
let id = fromDictionary["inputID"] as? NSString
if id == nil { return nil }
inputID = id! as String
// Get the number of dimension
let dimensionValue = fromDictionary["numDimension"] as? NSInteger
if dimensionValue == nil { return nil }
let numDimensions = dimensionValue!
// Get the dimensions values
let tempArray = getIntArray(fromDictionary, identifier: "dimensions")
if (tempArray == nil) { return nil }
let dimensions = tempArray!
size = DeepChannelSize(dimensionCount: numDimensions, dimensionValues: dimensions)
}
public func getPersistenceDictionary() -> [String: AnyObject]
{
var resultDictionary : [String: AnyObject] = [:]
// Set the identifier
resultDictionary["inputID"] = inputID as AnyObject?
// Set the number of dimension
resultDictionary["numDimension"] = size.numDimensions as AnyObject?
// Set the dimensions levels
resultDictionary["dimensions"] = size.dimensions as AnyObject?
return resultDictionary
}
}
/// Top-level class for a deep neural network definition
final public class DeepNetwork : DeepNetworkInputSource, DeepNetworkOutputDestination, MLPersistence
{
var inputs : [DeepNetworkInput] = []
var layers : [DeepLayer] = []
var validated = false
fileprivate var finalResultMin : Float = 0.0
fileprivate var finalResultMax : Float = 1.0
fileprivate var finalResults : [Float] = []
fileprivate var errorVector : [Float] = []
fileprivate var expectedClass : Int = 0
public init() {
}
public init?(fromDictionary: [String: AnyObject])
{
// Get the array of inputs
let inputArray = fromDictionary["inputs"] as? NSArray
if (inputArray == nil) { return nil }
for item in inputArray! {
let element = item as? [String: AnyObject]
if (element == nil) { return nil }
let input = DeepNetworkInput(fromDictionary: element!)
if (input == nil) { return nil }
inputs.append(input!)
}
// Get the array of layers
let layerArray = fromDictionary["layers"] as? NSArray
if (layerArray == nil) { return nil }
for item in layerArray! {
let element = item as? [String: AnyObject]
if (element == nil) { return nil }
let layer = DeepLayer(fromDictionary: element!)
if (layer == nil) { return nil }
layers.append(layer!)
}
}
/// Function to get the number of defined inputs
public var numInputs: Int {
get { return inputs.count }
}
/// Function to get the input for the specified index
public func getInput(atIndex: Int) -> DeepNetworkInput
{
return inputs[atIndex]
}
/// Function to add an input to the network
public func addInput(_ newInput: DeepNetworkInput)
{
inputs.append(newInput)
}
/// Function to remove an input from the network
public func removeInput(_ inputIndex: Int)
{
if (inputIndex >= 0 && inputIndex < inputs.count) {
inputs.remove(at: inputIndex)
}
validated = false
}
// Function to get the index from an input ID
public func getInputIndex(_ idString: String) -> Int?
{
for index in 0..<inputs.count {
if (inputs[index].inputID == idString) { return index }
}
return nil
}
/// Function to set the values for an input
public func setInputValues(_ forInput: String, values : [Float])
{
// Get the input to process
if let index = getInputIndex(forInput) {
inputs[index].values = values
}
}
/// Function to get the size of an input set
public func getInputDataSize(_ inputID : String) -> DeepChannelSize?
{
// Get the index
if let index = getInputIndex(inputID) {
return inputs[index].size
}
return nil
}
/// Function to get the number of defined layers
public var numLayers: Int {
get { return layers.count }
}
/// Function to get the layer for the specified index
public func getLayer(atIndex: Int) -> DeepLayer
{
return layers[atIndex]
}
/// Function to add a layer to the network
public func addLayer(_ newLayer: DeepLayer)
{
layers.append(newLayer)
validated = false
}
/// Function to remove a layer from the network
public func removeLayer(_ layerIndex: Int)
{
if (layerIndex >= 0 && layerIndex < layers.count) {
layers.remove(at: layerIndex)
validated = false
}
}
/// Function to add a channel to the network
public func addChannel(_ toLayer: Int, newChannel: DeepChannel)
{
if (toLayer >= 0 && toLayer < layers.count) {
layers[toLayer].addChannel(newChannel)
validated = false
}
}
/// Functions to remove a channel from the network
public func removeChannel(_ layer: Int, channelIndex: Int)
{
if (layer >= 0 && layer < layers.count) {
layers[layer].removeChannel(channelIndex)
validated = false
}
}
public func removeChannel(_ layer: Int, channelID: String)
{
if let index = layers[layer].getChannelIndex(channelID) {
removeChannel(layer, channelIndex: index)
}
}
/// Functions to add a network operator to the network
public func addNetworkOperator(_ toLayer: Int, channelIndex: Int, newOperator: DeepNetworkOperator)
{
if (toLayer >= 0 && toLayer < layers.count) {
layers[toLayer].addNetworkOperator(channelIndex, newOperator: newOperator)
validated = false
}
}
public func addNetworkOperator(_ toLayer: Int, channelID: String, newOperator: DeepNetworkOperator)
{
if (toLayer >= 0 && toLayer < layers.count) {
if let index = layers[toLayer].getChannelIndex(channelID) {
layers[toLayer].addNetworkOperator(index, newOperator: newOperator)
validated = false
}
}
}
/// Function to get the network operator at the specified index
public func getNetworkOperator(_ toLayer: Int, channelIndex: Int, operatorIndex: Int) ->DeepNetworkOperator?
{
if (toLayer >= 0 && toLayer < layers.count) {
return layers[toLayer].getNetworkOperator(channelIndex, operatorIndex: operatorIndex)
}
return nil
}
public func getNetworkOperator(_ toLayer: Int, channelID: String, operatorIndex: Int) ->DeepNetworkOperator?
{
if (toLayer >= 0 && toLayer < layers.count) {
if let index = layers[toLayer].getChannelIndex(channelID) {
return layers[toLayer].getNetworkOperator(index, operatorIndex: operatorIndex)
}
}
return nil
}
/// Functions to replace a network operator at the specified index
public func replaceNetworkOperator(_ toLayer: Int, channelIndex: Int, operatorIndex: Int, newOperator: DeepNetworkOperator)
{
if (toLayer >= 0 && toLayer < layers.count) {
layers[toLayer].replaceNetworkOperator(channelIndex, operatorIndex: operatorIndex, newOperator: newOperator)
}
}
public func replaceNetworkOperator(_ toLayer: Int, channelID: String, operatorIndex: Int, newOperator: DeepNetworkOperator)
{
if (toLayer >= 0 && toLayer < layers.count) {
if let index = layers[toLayer].getChannelIndex(channelID) {
layers[toLayer].replaceNetworkOperator(index, operatorIndex: operatorIndex, newOperator: newOperator)
}
}
}
/// Functions to remove a network operator from the network
public func removeNetworkOperator(_ layer: Int, channelIndex: Int, operatorIndex: Int)
{
if (layer >= 0 && layer < layers.count) {
layers[layer].removeNetworkOperator(channelIndex, operatorIndex: operatorIndex)
validated = false
}
}
public func removeNetworkOperator(_ layer: Int, channelID: String, operatorIndex: Int)
{
if let index = layers[layer].getChannelIndex(channelID) {
layers[layer].removeNetworkOperator(index, operatorIndex: operatorIndex)
validated = false
}
}
/// Function to validate a DeepNetwork
/// This method checks that the inputs to each layer are available, returning an array of strings describing any errors
/// The resulting size of each channel is updated as well
public func validateNetwork() -> [String]
{
var errorStrings: [String] = []
var prevLayer : DeepNetworkInputSource = self
for layer in 0..<layers.count {
errorStrings += layers[layer].validateAgainstPreviousLayer(prevLayer, layerIndex: layer)
prevLayer = layers[layer]
}
validated = (errorStrings.count == 0)
finalResultMin = 0.0
finalResultMax = 1.0
if let lastLayer = layers.last {
let range = lastLayer.getResultRange()
finalResultMin = range.minimum
finalResultMax = range.maximum
}
return errorStrings
}
/// Property to get if the network is validated
public var isValidated: Bool {
get { return validated }
}
/// Function to set all learnable parameters to random initialization again
public func initializeParameters()
{
// Have each layer initialize
for layer in 0..<layers.count {
layers[layer].initializeParameters()
}
}
/// Function to run the network forward. Assumes inputs have been set
/// Returns the values from the last layer
@discardableResult
public func feedForward() -> [Float]
{
// Make sure we are validated
if (!validated) {
_ = validateNetwork()
if !validated { return [] }
}
var prevLayer : DeepNetworkInputSource = self
for layer in 0..<layers.count {
layers[layer].feedForward(prevLayer)
prevLayer = layers[layer]
}
// Keep track of the number of outputs from the final layer, so we can generate an error term later
finalResults = prevLayer.getAllValues()
return finalResults
}
public func getResultClass() -> Int
{
if finalResults.count == 1 {
if finalResults[0] > ((finalResultMax + finalResultMin) * 0.5) { return 1 }
return 0
}
else {
var bestClass = 0
var highestResult = -Float.infinity
for classIndex in 0..<finalResults.count {
if (finalResults[classIndex] > highestResult) {
highestResult = finalResults[classIndex]
bestClass = classIndex
}
}
return bestClass
}
}
/// Function to clear weight-change accumulations for the start of a batch
public func startBatch()
{
for layer in layers {
layer.startBatch()
}
}
/// Function to run the network backward using an expected output array, propagating the error term. Assumes inputs have been set
public func backPropagate(_ expectedResults: [Float])
{
if (layers.count < 1) { return } // Can't backpropagate through non-existant layers
// Get an error vector to pass to the final layer. This is the gradient if using least-squares error
getErrorVector(expectedOutput: expectedResults)
// Propagate to the last layer
layers.last!.backPropagate(self)
// Propogate to all previous layers
for layerIndex in stride(from: (layers.count - 2), through: 0, by: -1) {
layers[layerIndex].backPropagate(layers[layerIndex+1])
}
}
/// Function to run the network backward using an expected class output, propagating the error term. Assumes inputs have been set
public func backPropagate(_ expectedResultClass: Int)
{
// Remember the expected result class
expectedClass = expectedResultClass
if (layers.count < 1) { return } // Can't backpropagate through non-existant layers
// Get an error vector to pass to the final layer. This is the gradient if using least-squares error
getErrorVector()
// Propagate to the last layer
layers.last!.backPropagate(self)
// Propogate to all previous layers
for layerIndex in stride(from: (layers.count - 2), through: 0, by: -1) {
layers[layerIndex].backPropagate(layers[layerIndex+1])
}
}
// Get the error vector - 𝟃E/𝟃o: derivitive of error with respect to output - from expected class
func getErrorVector()
{
// Get an error vector to pass to the final layer. This is the gradient if using least-squares error
// E = 0.5(output - expected)² --> 𝟃E/𝟃o = output - expected
errorVector = [Float](repeating: finalResultMin, count: finalResults.count)
if (finalResults.count == 1) {
if (expectedClass == 1) {
errorVector[0] = finalResults[0] - finalResultMax
}
else {
errorVector[0] = finalResults[0] - finalResultMin
}
}
else {
for index in 0..<finalResults.count {
if (index == expectedClass) {
errorVector[index] = finalResults[index] - finalResultMax
}
else {
errorVector[index] = finalResults[index] - finalResultMin
}
}
}
}
// Get the error vector - 𝟃E/𝟃o: derivitive of error with respect to output - from expected output array
func getErrorVector(expectedOutput: [Float])
{
// Get an error vector to pass to the final layer. This is the gradient if using least-squares error
// E = 0.5(output - expected)² --> 𝟃E/𝟃o = output - expected
errorVector = [Float](repeating: finalResultMin, count: finalResults.count)
for index in 0..<finalResults.count {
errorVector[index] = finalResults[index] - expectedOutput[index]
}
}
/// Function to get the expected network output for a given class
public func getExpectedOutput(_ forClass: Int) ->[Float]
{
var expectedOutputVector = [Float](repeating: finalResultMin, count: finalResults.count)
if (finalResults.count == 1) {
if (forClass == 1) { expectedOutputVector[0] = finalResultMax }
}
else {
if (forClass >= 0 && forClass < finalResults.count) {
expectedOutputVector[forClass] = finalResultMax
}
}
return expectedOutputVector
}
/// Function to get the total error with respect to an expected output class
public func getTotalError(_ expectedClass: Int) ->Float
{
var result : Float = 0.0
let expectedOutput = getExpectedOutput(expectedClass)
for index in 0..<expectedOutput.count {
result += abs(expectedOutput[index] - finalResults[index])
}
return result
}
/// Function to get the total error with respect to an expected output vector
public func getTotalError(_ expectedOutput: [Float]) ->Float
{
var result : Float = 0.0
for index in 0..<expectedOutput.count {
result += abs(expectedOutput[index] - finalResults[index])
}
return result
}
public func updateWeights(_ trainingRate : Float, weightDecay: Float)
{
for layer in layers {
layer.updateWeights(trainingRate, weightDecay: weightDecay)
}
}
/// Function to perform a gradient check on the network
/// Assumes forward pass and back-propogation have been performed already
public func gradientCheck(ε: Float, Δ: Float) -> Bool
{
// Have each layer check their gradients
var result = true
for layer in 0..<layers.count {
if (!layers[layer].gradientCheck(ε: ε, Δ: Δ, network: self)) { result = false }
}
return result
}
public func getResultLoss() -> [Float]
{
let resultCount = finalResults.count
var loss = [Float](repeating: 0.0, count: resultCount)
// Get the error vector
getErrorVector()
// Assume squared error loss
for i in 0..<resultCount {
loss[i] = errorVector[i] * errorVector[i] * 0.5
}
return loss
}
public func getValuesForID(_ inputID : String) -> [Float]
{
// Get the index
if let index = getInputIndex(inputID) {
return inputs[index].values
}
return []
}
public func getAllValues() -> [Float]
{
var result : [Float] = []
for input in inputs {
result += input.values
}
return result
}
func getGradientForSource(_ sourceID : String) -> [Float]
{
// We only have one 'channel', so just return the error
return errorVector
}
public func getResultOfItem(_ layer: Int, channelIndex: Int, operatorIndex: Int) ->(values : [Float], size: DeepChannelSize)?
{
if (layer >= 0 && layer < layers.count) {
return layers[layer].getResultOfItem(channelIndex, operatorIndex: operatorIndex)
}
return nil
}
public func getPersistenceDictionary() -> [String: AnyObject]
{
var resultDictionary : [String: AnyObject] = [:]
// Set the array of inputs
var inputArray : [[String: AnyObject]] = []
for input in inputs {
inputArray.append(input.getPersistenceDictionary())
}
resultDictionary["inputs"] = inputArray as AnyObject?
// Set the array of layers
var layerArray : [[String: AnyObject]] = []
for layer in layers {
layerArray.append(layer.getPersistenceDictionary())
}
resultDictionary["layers"] = layerArray as AnyObject?
return resultDictionary
}
}
| mit | e8b49aff7cf4cbca9c52dc9a08f8c1a6 | 32.858108 | 135 | 0.592696 | 4.685367 | false | false | false | false |
rugheid/Swift-MathEagle | MathEagleTests/GMP/BigIntTests.swift | 1 | 18223 | //
// BigIntTests.swift
// MathEagle
//
// Created by Rugen Heidbuchel on 15/12/15.
// Copyright © 2015 Jorestha Solutions. All rights reserved.
//
import Cocoa
import Foundation
import XCTest
import MathEagle
class BigIntTests: XCTestCase {
// MARK: Init
func testInit() {
let bigInt = BigInt()
XCTAssertEqual("0", bigInt.stringValue)
}
func testInitBigInt() {
let bigInt = BigInt(string: "-31692029223372036854775807")
let bigIntCopy = BigInt(bigInt: bigInt)
XCTAssertEqual(bigInt, bigIntCopy)
}
func testInitIntLiteral() {
var bigInt = BigInt()
bigInt = 2897
XCTAssertEqual(BigInt(int: 2897), bigInt)
}
// MARK: Conversion
func testIntValue() {
var bigInt = BigInt(string: "-4321")
XCTAssertEqual(-4321, bigInt.intValue)
bigInt = BigInt(string: "11" + "111111111111111111111111111111111111111111111111111111111111111", base: 2)
XCTAssertEqual(Int.max, bigInt.intValue)
}
func testUIntValue() {
let bigInt = BigInt(string: "-4321")
XCTAssertEqual(UInt(4321), bigInt.uintValue)
}
func testDoubleValue() {
let bigInt = BigInt(string: "-4321")
XCTAssertEqual(-4321.0, bigInt.doubleValue)
}
func testStringValue() {
var bigInt = BigInt(int: 123521)
XCTAssertEqual("11110001010000001", bigInt.stringValue(2))
XCTAssertEqual("361201", bigInt.stringValue(8))
XCTAssertEqual("123521", bigInt.stringValue(10))
XCTAssertEqual("1e281", bigInt.stringValue(16))
bigInt = BigInt(string: "-31692029223372036854775807")
XCTAssertEqual("-1101000110111000011000101100011000010110100011010110101011011010011111111111111111111", bigInt.stringValue(2))
XCTAssertEqual("-15067030543026432653323777777", bigInt.stringValue(8))
XCTAssertEqual("-31692029223372036854775807", bigInt.stringValue(10))
XCTAssertEqual("-1a370c58c2d1ad5b4fffff", bigInt.stringValue(16))
}
// MARK: Comparison
func testCompareBigInt() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertEqual(a.compare(b), ComparisonResult.orderedSame)
XCTAssertEqual(a.compare(c), ComparisonResult.orderedDescending)
XCTAssertEqual(c.compare(a), ComparisonResult.orderedAscending)
}
func testEqualityOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertTrue(a == a)
XCTAssertTrue(a == b)
XCTAssertFalse(a == c)
}
func testInequalityOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertTrue(a != c)
XCTAssertFalse(a != a)
XCTAssertFalse(a != b)
}
func testSmallerThanOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertTrue(c < a)
XCTAssertFalse(a < c)
XCTAssertFalse(a < b)
XCTAssertFalse(a < a)
}
func testSmallerThanOrEqualOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertTrue(c <= a)
XCTAssertTrue(a <= b)
XCTAssertTrue(a <= a)
XCTAssertFalse(a <= c)
}
func testGreaterThanOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertTrue(a > c)
XCTAssertFalse(c > a)
XCTAssertFalse(a > b)
XCTAssertFalse(a > a)
}
func testGreaterThanOrEqualOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertTrue(a >= c)
XCTAssertTrue(a >= b)
XCTAssertTrue(a >= a)
XCTAssertFalse(c >= a)
}
// MARK: Operation
func testAdd() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 106206), a.add(b))
XCTAssertEqual(BigInt(int: 106206), a.add(a))
XCTAssertEqual(BigInt(int: -47748739), a.add(c))
}
func testAddInPlace() {
var a = BigInt(int: 53103)
var b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
a.addInPlace(b)
b.addInPlace(c)
XCTAssertEqual(BigInt(int: 106206), a)
XCTAssertEqual(BigInt(int: -47748739), b)
}
func testAdditionOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 106206), a + b)
XCTAssertEqual(BigInt(int: 106206), a + a)
XCTAssertEqual(BigInt(int: -47748739), a + c)
}
func testAdditionAssignOperator() {
var a = BigInt(int: 53103)
var b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
a += b
b += c
XCTAssertEqual(BigInt(int: 106206), a)
XCTAssertEqual(BigInt(int: -47748739), b)
}
func testNegation() {
let a = BigInt(int: 53103)
let b = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: -53103), a.negation)
XCTAssertEqual(BigInt(int: 47801842), b.negation)
}
func testNegateInPlace() {
var a = BigInt(int: 53103)
var b = BigInt(int: -47801842)
a.negateInPlace()
b.negateInPlace()
XCTAssertEqual(BigInt(int: -53103), a)
XCTAssertEqual(BigInt(int: 47801842), b)
}
func testNegationOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: -53103), -a)
XCTAssertEqual(BigInt(int: 47801842), -b)
}
func testSubtract() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 0), a.subtract(b))
XCTAssertEqual(BigInt(int: 0), a.subtract(a))
XCTAssertEqual(BigInt(int: 47854945), a.subtract(c))
}
func testSubtractInPlace() {
var a = BigInt(int: 53103)
var b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
a.subtractInPlace(b)
b.subtractInPlace(c)
XCTAssertEqual(BigInt(int: 0), a)
XCTAssertEqual(BigInt(int: 47854945), b)
}
func testSubtractionOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 0), a - b)
XCTAssertEqual(BigInt(int: 0), a - a)
XCTAssertEqual(BigInt(int: 47854945), a - c)
}
func testSubtractionAssignOperator() {
var a = BigInt(int: 53103)
var b = BigInt(int: 53103)
let c = BigInt(int: -47801842)
a -= b
b -= c
XCTAssertEqual(BigInt(int: 0), a)
XCTAssertEqual(BigInt(int: 47854945), b)
}
func testMultiply() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 0), a.multiply(b))
XCTAssertEqual(BigInt(int: 2819928609), a.multiply(a))
XCTAssertEqual(BigInt(int: -2538421215726), a.multiply(c))
}
func testMultiplyInPlace() {
var a = BigInt(int: 53103)
let b = BigInt(int: 0)
var c = BigInt(int: -47801842)
let d = BigInt(int: 53103)
a.multiplyInPlace(b)
c.multiplyInPlace(d)
XCTAssertEqual(BigInt(int: 0), a)
XCTAssertEqual(BigInt(int: -2538421215726), c)
}
func testMultiplicationOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 0), a * b)
XCTAssertEqual(BigInt(int: 2819928609), a * a)
XCTAssertEqual(BigInt(int: -2538421215726), a * c)
}
func testMultiplicationAssignOperator() {
var a = BigInt(int: 53103)
let b = BigInt(int: 0)
var c = BigInt(int: -47801842)
let d = BigInt(int: 53103)
a *= b
c *= d
XCTAssertEqual(BigInt(int: 0), a)
XCTAssertEqual(BigInt(int: -2538421215726), c)
}
func testDivide() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 0), b.divide(a))
XCTAssertEqual(BigInt(int: 1), a.divide(a))
XCTAssertEqual(BigInt(int: -1), a.divide(c))
XCTAssertEqual(BigInt(int: -901), c.divide(a))
}
func testDivideInPlace() {
let a = BigInt(int: 53103)
var b = BigInt(int: 0)
var c = BigInt(int: -47801842)
c.divideInPlace(a)
b.divideInPlace(a)
XCTAssertEqual(BigInt(int: -901), c)
XCTAssertEqual(BigInt(int: 0), b)
}
func testDivisionOperator() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 0), b / a)
XCTAssertEqual(BigInt(int: 1), a / a)
XCTAssertEqual(BigInt(int: -1), a / c)
XCTAssertEqual(BigInt(int: -901), c / a)
}
func testDivisionAssignOperator() {
let a = BigInt(int: 53103)
var b = BigInt(int: 0)
var c = BigInt(int: -47801842)
c /= a
b /= a
XCTAssertEqual(BigInt(int: -901), c)
XCTAssertEqual(BigInt(int: 0), b)
}
func testModulo() {
let a = BigInt(int: 56789837)
let b = BigInt(int: 924720)
let c = BigInt(int: -924720)
let d = BigInt(int: 381917)
let zero = BigInt(int: 0)
XCTAssertEqual(d, a.modulo(b))
XCTAssertEqual(zero, zero.modulo(a))
XCTAssertEqual(b, b.modulo(a))
XCTAssertEqual(a + c, c.modulo(a))
XCTAssertEqual(d, a.modulo(c))
}
func testModuloInPlace() {
var a = BigInt(int: 56789837)
let b = BigInt(int: 924720)
var c = BigInt(int: -924720)
let d = BigInt(int: 381917)
var zero = BigInt(int: 0)
a.moduloInPlace(b)
XCTAssertEqual(d, a)
zero.moduloInPlace(b)
XCTAssertEqual(BigInt(int: 0), zero)
a = 56789837
a.moduloInPlace(c)
XCTAssertEqual(d, a)
a = 56789837
let e = a + c
c.moduloInPlace(a)
XCTAssertEqual(e, c)
}
func testModuloOperator() {
let a = BigInt(int: 56789837)
let b = BigInt(int: 924720)
let c = BigInt(int: -924720)
let d = BigInt(int: 381917)
let zero = BigInt(int: 0)
XCTAssertEqual(d, a % b)
XCTAssertEqual(zero, zero % a)
XCTAssertEqual(b, b % a)
XCTAssertEqual(a + c, c % a)
XCTAssertEqual(d, a % c)
}
func testModuloAssignmentOperator() {
var a = BigInt(int: 56789837)
let b = BigInt(int: 924720)
var c = BigInt(int: -924720)
let d = BigInt(int: 381917)
var zero = BigInt(int: 0)
a %= b
XCTAssertEqual(d, a)
zero %= b
XCTAssertEqual(BigInt(int: 0), zero)
a = 56789837
a %= c
XCTAssertEqual(d, a)
a = 56789837
let e = a + c
c %= a
XCTAssertEqual(e, c)
}
func testAbsoluteValue() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 53103), a.absoluteValue)
XCTAssertEqual(BigInt(int: 0), b.absoluteValue)
XCTAssertEqual(BigInt(int: 47801842), c.absoluteValue)
}
func testAbsoluteValueInPlace() {
var a = BigInt(int: 53103)
var b = BigInt(int: 0)
var c = BigInt(int: -47801842)
a.absoluteValueInPlace()
b.absoluteValueInPlace()
c.absoluteValueInPlace()
XCTAssertEqual(BigInt(int: 53103), a)
XCTAssertEqual(BigInt(int: 0), b)
XCTAssertEqual(BigInt(int: 47801842), c)
}
func testAbs() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertEqual(BigInt(int: 53103), abs(a))
XCTAssertEqual(BigInt(int: 0), abs(b))
XCTAssertEqual(BigInt(int: 47801842), abs(c))
}
func testSquareRoot() {
var a = BigInt(int: 53103)
XCTAssertEqual(a.squareRoot, BigInt(int: 230))
a = 0
XCTAssertEqual(a.squareRoot, BigInt(int: 0))
}
func testSquareRootInPlace() {
var a = BigInt(int: 53103)
a.squareRootInPlace()
XCTAssertEqual(a, BigInt(int: 230))
a = 0
a.squareRootInPlace()
XCTAssertEqual(a, BigInt(int: 0))
}
func testPowerModulo() {
let a = BigInt(int: 53103)
let b = BigInt(int: 234311)
let mod = BigInt(int: 1000000000000)
XCTAssertEqual(BigInt(uint: 919447180047), a.power(b, modulo: mod))
}
func testPowerModuloInPlace() {
var a = BigInt(int: 53103)
let b = BigInt(int: 234311)
let mod = BigInt(int: 1000000000000)
a.powerInPlace(b, modulo: mod)
XCTAssertEqual(BigInt(uint: 919447180047), a)
}
func testPower() {
let a = BigInt(int: 53103)
XCTAssertEqual(a.power(32), BigInt(string: "15988577176268060579004931089547253337461076707270626303439766786870881752448879429300926345888658367621823487912941530168589176115215538579849129034241"))
}
func testPowerInPlace() {
var a = BigInt(int: 53103)
a.powerInPlace(32)
XCTAssertEqual(a, BigInt(string: "15988577176268060579004931089547253337461076707270626303439766786870881752448879429300926345888658367621823487912941530168589176115215538579849129034241"))
}
func testFactorial() {
for (n, f_n) in [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000, 121645100408832000, 2432902008176640000].enumerated() {
XCTAssertEqual(BigInt.factorial(UInt(n)), BigInt(int: f_n))
}
XCTAssertEqual(BigInt.factorial(21), BigInt(string: "51090942171709440000"))
XCTAssertEqual(BigInt.factorial(22), BigInt(string: "1124000727777607680000"))
}
func testDoubleFactorial() {
for (n, f_n) in [1, 1, 2, 3, 8, 15, 48, 105, 384, 945, 3840, 10395, 46080, 135135, 645120, 2027025, 10321920, 34459425, 185794560, 654729075, 3715891200, 13749310575, 81749606400, 316234143225, 1961990553600, 7905853580625, 51011754393600].enumerated() {
XCTAssertEqual(BigInt.doubleFactorial(UInt(n)), BigInt(int: f_n))
}
}
func testMultiFactorial() {
for (n, f_n) in [1, 1, 2, 3, 4, 10, 18, 28, 80, 162, 280, 880, 1944, 3640, 12320, 29160, 58240, 209440, 524880, 1106560, 4188800, 11022480, 24344320, 96342400, 264539520, 608608000, 2504902400, 7142567040, 17041024000, 72642169600].enumerated() {
XCTAssertEqual(BigInt.factorial(UInt(n), multi: 3), BigInt(int: f_n))
}
for (n, f_n) in [1, 1, 2, 3, 4, 5, 12, 21, 32, 45, 120, 231, 384, 585, 1680, 3465, 6144, 9945, 30240, 65835, 122880, 208845, 665280, 1514205, 2949120, 5221125, 17297280, 40883535, 82575360, 151412625, 518918400, 1267389585, 2642411520, 4996616625].enumerated() {
XCTAssertEqual(BigInt.factorial(UInt(n), multi: 4), BigInt(int: f_n))
}
}
func testGCD() {
XCTAssertEqual(BigInt.gcd(0, 0), BigInt(int: 0))
XCTAssertEqual(BigInt.gcd(20, 10), BigInt(int: 10))
XCTAssertEqual(BigInt.gcd(20, -10), BigInt(int: 10))
XCTAssertEqual(BigInt.gcd(123123123123, 123123123123123123), BigInt(int: 123123))
XCTAssertEqual(BigInt.gcd(-123123123123, 123123123123123123), BigInt(int: 123123))
XCTAssertEqual(BigInt.gcd(37279462087332, 366983722766), BigInt(int: 564958))
}
func testGCDInPlace() {
var a = BigInt(int: 0)
a.gcdInPlace(0)
XCTAssertEqual(a, BigInt(int: 0))
a = 20
a.gcdInPlace(10)
XCTAssertEqual(a, BigInt(int: 10))
a = -20
a.gcdInPlace(10)
XCTAssertEqual(a, BigInt(int: 10))
a = 37279462087332
a.gcdInPlace(366983722766)
XCTAssertEqual(a, BigInt(int: 564958))
}
func testNumberOfDigits() {
var a = BigInt(int: 56789) // 0b1101110111010101, 0o156725, 0xDDD5
XCTAssertEqual(a.numberOfDigits, 5)
XCTAssertEqual(a.numberOfDigits(), 5)
XCTAssertEqual(numberOfDigits(a), 5)
XCTAssertEqual(a.numberOfDigits(inBase: 2), 16)
XCTAssertEqual(a.numberOfDigits(inBase: 8), 6)
XCTAssertEqual(a.numberOfDigits(inBase: 16), 4)
a = -56789
XCTAssertEqual(a.numberOfDigits, 5)
XCTAssertEqual(a.numberOfDigits(), 5)
XCTAssertEqual(numberOfDigits(a), 5)
XCTAssertEqual(a.numberOfDigits(inBase: 2), 16)
XCTAssertEqual(a.numberOfDigits(inBase: 8), 6)
XCTAssertEqual(a.numberOfDigits(inBase: 16), 4)
a = 0
XCTAssertEqual(a.numberOfDigits, 1)
XCTAssertEqual(a.numberOfDigits(), 1)
XCTAssertEqual(numberOfDigits(a), 1)
XCTAssertEqual(a.numberOfDigits(inBase: 2), 1)
XCTAssertEqual(a.numberOfDigits(inBase: 8), 1)
XCTAssertEqual(a.numberOfDigits(inBase: 16), 1)
}
// MARK: SetCompliant
func testIsNatural() {
let a = BigInt(int: 53103)
let b = BigInt(int: 0)
let c = BigInt(int: -47801842)
XCTAssertTrue(a.isNatural)
XCTAssertTrue(b.isNatural)
XCTAssertFalse(c.isNatural)
}
}
| mit | 59e5a6fed2e7cb8f8fe3fc6b41ef8e5a | 31.655914 | 270 | 0.585336 | 3.634949 | false | true | false | false |
Bijiabo/F-Client-iOS | F/F/Models/User.swift | 1 | 424 | //
// User.swift
// F
//
// Created by huchunbo on 15/11/7.
// Copyright © 2015年 TIDELAB. All rights reserved.
//
import Foundation
class User {
let id: Int
var name: String
var email: String
var valid: Bool
init (id: Int, name: String, email: String, valid: Bool = true) {
self.id = id
self.name = name
self.email = email
self.valid = valid
}
} | gpl-2.0 | ac9e56bda0fc5056f31d3125ff2e5eff | 16.583333 | 69 | 0.558195 | 3.368 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/Map/MapType.swift | 1 | 2463 | //
// MapType.swift
// MEGameTracker
//
// Created by Emily Ivie on 6/26/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import Foundation
/// Defines various map types. Allows for some general logic on sets of maps.
public enum MapType: String, Codable, CaseIterable {
case galaxy = "Galaxy"
// regional clusters have no map
case cluster = "Cluster"
case system = "System"
case planet = "Planet"
case moon = "Moon"
case asteroid = "Asteroid"
case city = "City"
case ship = "Ship"
case fleet = "Fleet"
case wreckage = "Wreckage"
case area = "Area"
case level = "Level"
case building = "Structure"
case location = "Location"
/// Returns the string values of all the enum variations.
private static let stringValues: [MapType: String] = {
return Dictionary(uniqueKeysWithValues: allCases.map { ($0, $0.stringValue) })
}()
/// Returns the heading string values of all the enum variations.
private static let headingValues: [MapType: String] = [
.galaxy: "Galaxies",
.cluster: "Clusters",
.system: "Systems",
.planet: "Planets",
.moon: "Moons",
.city: "Cities",
.ship: "Ships",
.fleet: "Fleets",
.wreckage: "Wreckage",
.area: "Areas",
.level: "Levels",
.building: "Structures",
.location: "Locations",
]
/// Creates an enum from a string value, if possible.
public init?(stringValue: String?) {
self.init(rawValue: stringValue ?? "")
}
/// Returns the string value of an enum.
public var stringValue: String {
return rawValue
}
/// Creates an enum from a heading string value, if possible.
public init?(headingValue: String?) {
guard let type = MapType.headingValues
.filter({ $0.1 == headingValue }).map({ $0.0 }).first
else {
return nil
}
self = type
}
/// Returns the heading string value of an enum.
public var headingValue: String {
return MapType.headingValues[self] ?? "Unknown"
}
/// Returns the int value of an enum.
public var intValue: Int? {
return MapType.allCases.firstIndex(of: self)
}
/// Provides a window title for a map of the specified enum type.
public var windowTitle: String {
if self == .location {
return "Map"
}
return stringValue
}
/// Makes general decision about whether to offer the explorable checkbox for a map of this type.
public var isExplorable: Bool {
switch self {
case .galaxy: fallthrough
case .cluster: fallthrough
case .system: return true
default: return false
}
}
}
| mit | 2034a3fb964e6e4f40c4e1feee771d61 | 23.868687 | 98 | 0.677092 | 3.300268 | false | false | false | false |
fireunit/login | Pods/Material/Sources/iOS/MaterialCollectionViewCell.swift | 2 | 17667 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Material nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE 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 UIKit
@IBDesignable
@objc(MaterialCollectionViewCell)
public class MaterialCollectionViewCell : UICollectionViewCell {
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
public private(set) lazy var visualLayer: CAShapeLayer = CAShapeLayer()
/**
A base delegate reference used when subclassing MaterialView.
*/
public weak var delegate: MaterialDelegate?
/// An Array of pulse layers.
public private(set) lazy var pulseLayers: Array<CAShapeLayer> = Array<CAShapeLayer>()
/// The opcaity value for the pulse animation.
@IBInspectable public var pulseOpacity: CGFloat = 0.25
/// The color of the pulse effect.
@IBInspectable public var pulseColor: UIColor = MaterialColor.grey.base
/// The type of PulseAnimation.
public var pulseAnimation: PulseAnimation = .AtPointWithBacking {
didSet {
visualLayer.masksToBounds = .CenterRadialBeyondBounds != pulseAnimation
}
}
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable public var image: UIImage? {
didSet {
visualLayer.contents = image?.CGImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
@IBInspectable public var contentsRect: CGRect {
get {
return visualLayer.contentsRect
}
set(value) {
visualLayer.contentsRect = value
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
@IBInspectable public var contentsCenter: CGRect {
get {
return visualLayer.contentsCenter
}
set(value) {
visualLayer.contentsCenter = value
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the view. By default, this value is set to the MaterialDevice.scale.
*/
@IBInspectable public var contentsScale: CGFloat {
get {
return visualLayer.contentsScale
}
set(value) {
visualLayer.contentsScale = value
}
}
/// A Preset for the contentsGravity property.
public var contentsGravityPreset: MaterialGravity {
didSet {
contentsGravity = MaterialGravityToValue(contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable public var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/// A preset wrapper around contentInset.
public var contentInsetPreset: MaterialEdgeInset {
get {
return contentView.grid.contentInsetPreset
}
set(value) {
contentView.grid.contentInsetPreset = value
}
}
/// A wrapper around grid.contentInset.
@IBInspectable public var contentInset: UIEdgeInsets {
get {
return contentView.grid.contentInset
}
set(value) {
contentView.grid.contentInset = value
}
}
/// A preset wrapper around spacing.
public var spacingPreset: MaterialSpacing = .None {
didSet {
spacing = MaterialSpacingToValue(spacingPreset)
}
}
/// A wrapper around grid.spacing.
@IBInspectable public var spacing: CGFloat {
get {
return contentView.grid.spacing
}
set(value) {
contentView.grid.spacing = value
}
}
/**
This property is the same as clipsToBounds. It crops any of the view's
contents from bleeding past the view's frame. If an image is set using
the image property, then this value does not need to be set, since the
visualLayer's maskToBounds is set to true by default.
*/
@IBInspectable public var masksToBounds: Bool {
get {
return layer.masksToBounds
}
set(value) {
layer.masksToBounds = value
}
}
/// A property that accesses the backing layer's backgroundColor.
@IBInspectable public override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.CGColor
}
}
/// A property that accesses the layer.frame.origin.x property.
@IBInspectable public var x: CGFloat {
get {
return layer.frame.origin.x
}
set(value) {
layer.frame.origin.x = value
}
}
/// A property that accesses the layer.frame.origin.y property.
@IBInspectable public var y: CGFloat {
get {
return layer.frame.origin.y
}
set(value) {
layer.frame.origin.y = value
}
}
/**
A property that accesses the layer.frame.size.width property.
When setting this property in conjunction with the shape property having a
value that is not .None, the height will be adjusted to maintain the correct
shape.
*/
@IBInspectable public var width: CGFloat {
get {
return layer.frame.size.width
}
set(value) {
layer.frame.size.width = value
if .None != shape {
layer.frame.size.height = value
}
}
}
/**
A property that accesses the layer.frame.size.height property.
When setting this property in conjunction with the shape property having a
value that is not .None, the width will be adjusted to maintain the correct
shape.
*/
@IBInspectable public var height: CGFloat {
get {
return layer.frame.size.height
}
set(value) {
layer.frame.size.height = value
if .None != shape {
layer.frame.size.width = value
}
}
}
/// A property that accesses the backing layer's shadowColor.
@IBInspectable public var shadowColor: UIColor? {
didSet {
layer.shadowColor = shadowColor?.CGColor
}
}
/// A property that accesses the backing layer's shadowOffset.
@IBInspectable public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set(value) {
layer.shadowOffset = value
}
}
/// A property that accesses the backing layer's shadowOpacity.
@IBInspectable public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set(value) {
layer.shadowOpacity = value
}
}
/// A property that accesses the backing layer's shadowRadius.
@IBInspectable public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set(value) {
layer.shadowRadius = value
}
}
/// A property that accesses the backing layer's shadowPath.
@IBInspectable public var shadowPath: CGPath? {
get {
return layer.shadowPath
}
set(value) {
layer.shadowPath = value
}
}
/// Enables automatic shadowPath sizing.
@IBInspectable public var shadowPathAutoSizeEnabled: Bool = true {
didSet {
if shadowPathAutoSizeEnabled {
layoutShadowPath()
} else {
shadowPath = nil
}
}
}
/**
A property that sets the shadowOffset, shadowOpacity, and shadowRadius
for the backing layer. This is the preferred method of setting depth
in order to maintain consitency across UI objects.
*/
public var depth: MaterialDepth {
didSet {
let value: MaterialDepthType = MaterialDepthToValue(depth)
shadowOffset = value.offset
shadowOpacity = value.opacity
shadowRadius = value.radius
layoutShadowPath()
}
}
/**
A property that sets the cornerRadius of the backing layer. If the shape
property has a value of .Circle when the cornerRadius is set, it will
become .None, as it no longer maintains its circle shape.
*/
public var cornerRadiusPreset: MaterialRadius {
didSet {
if let v: MaterialRadius = cornerRadiusPreset {
cornerRadius = MaterialRadiusToValue(v)
}
}
}
/// A property that accesses the layer.cornerRadius.
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set(value) {
layer.cornerRadius = value
layoutShadowPath()
if .Circle == shape {
shape = .None
}
}
}
/**
A property that manages the overall shape for the object. If either the
width or height property is set, the other will be automatically adjusted
to maintain the shape of the object.
*/
public var shape: MaterialShape {
didSet {
if .None != shape {
if width < height {
frame.size.width = height
} else {
frame.size.height = width
}
layoutShadowPath()
}
}
}
/// A preset property to set the borderWidth.
public var borderWidthPreset: MaterialBorder = .None {
didSet {
borderWidth = MaterialBorderToValue(borderWidthPreset)
}
}
/// A property that accesses the layer.borderWith.
@IBInspectable public var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set(value) {
layer.borderWidth = value
}
}
/// A property that accesses the layer.borderColor property.
@IBInspectable public var borderColor: UIColor? {
get {
return nil == layer.borderColor ? nil : UIColor(CGColor: layer.borderColor!)
}
set(value) {
layer.borderColor = value?.CGColor
}
}
/// A property that accesses the layer.position property.
@IBInspectable public var position: CGPoint {
get {
return layer.position
}
set(value) {
layer.position = value
}
}
/// A property that accesses the layer.zPosition property.
@IBInspectable public var zPosition: CGFloat {
get {
return layer.zPosition
}
set(value) {
layer.zPosition = value
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
depth = .None
cornerRadiusPreset = .None
shape = .None
contentsGravityPreset = .ResizeAspectFill
super.init(coder: aDecoder)
prepareView()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
depth = .None
cornerRadiusPreset = .None
shape = .None
contentsGravityPreset = .ResizeAspectFill
super.init(frame: frame)
prepareView()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: CGRectZero)
}
public override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
if self.layer == layer {
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
}
/**
A method that accepts CAAnimation objects and executes them on the
view's backing layer.
- Parameter animation: A CAAnimation instance.
*/
public func animate(animation: CAAnimation) {
animation.delegate = self
if let a: CABasicAnimation = animation as? CABasicAnimation {
a.fromValue = (nil == layer.presentationLayer() ? layer : layer.presentationLayer() as! CALayer).valueForKeyPath(a.keyPath!)
}
if let a: CAPropertyAnimation = animation as? CAPropertyAnimation {
layer.addAnimation(a, forKey: a.keyPath!)
} else if let a: CAAnimationGroup = animation as? CAAnimationGroup {
layer.addAnimation(a, forKey: nil)
} else if let a: CATransition = animation as? CATransition {
layer.addAnimation(a, forKey: kCATransition)
}
}
/**
A delegation method that is executed when the backing layer starts
running an animation.
- Parameter anim: The currently running CAAnimation instance.
*/
public override func animationDidStart(anim: CAAnimation) {
(delegate as? MaterialAnimationDelegate)?.materialAnimationDidStart?(anim)
}
/**
A delegation method that is executed when the backing layer stops
running an animation.
- Parameter anim: The CAAnimation instance that stopped running.
- Parameter flag: A boolean that indicates if the animation stopped
because it was completed or interrupted. True if completed, false
if interrupted.
*/
public override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if let a: CAPropertyAnimation = anim as? CAPropertyAnimation {
if let b: CABasicAnimation = a as? CABasicAnimation {
if let v: AnyObject = b.toValue {
if let k: String = b.keyPath {
layer.setValue(v, forKeyPath: k)
layer.removeAnimationForKey(k)
}
}
}
(delegate as? MaterialAnimationDelegate)?.materialAnimationDidStop?(anim, finished: flag)
} else if let a: CAAnimationGroup = anim as? CAAnimationGroup {
for x in a.animations! {
animationDidStop(x, finished: true)
}
}
}
/**
Triggers the pulse animation.
- Parameter point: A Optional point to pulse from, otherwise pulses
from the center.
*/
public func pulse(point: CGPoint? = nil) {
let p: CGPoint = nil == point ? CGPointMake(CGFloat(width / 2), CGFloat(height / 2)) : point!
MaterialAnimation.pulseExpandAnimation(layer, visualLayer: visualLayer, pulseColor: pulseColor, pulseOpacity: pulseOpacity, point: p, width: width, height: height, pulseLayers: &pulseLayers, pulseAnimation: pulseAnimation)
MaterialAnimation.delay(0.35) { [weak self] in
if let s: MaterialCollectionViewCell = self {
MaterialAnimation.pulseContractAnimation(s.layer, visualLayer: s.visualLayer, pulseColor: s.pulseColor, pulseLayers: &s.pulseLayers, pulseAnimation: s.pulseAnimation)
}
}
}
/**
A delegation method that is executed when the view has began a
touch event.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
MaterialAnimation.pulseExpandAnimation(layer, visualLayer: visualLayer, pulseColor: pulseColor, pulseOpacity: pulseOpacity, point: layer.convertPoint(touches.first!.locationInView(self), fromLayer: layer), width: width, height: height, pulseLayers: &pulseLayers, pulseAnimation: pulseAnimation)
}
/**
A delegation method that is executed when the view touch event has
ended.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
MaterialAnimation.pulseContractAnimation(layer, visualLayer: visualLayer, pulseColor: pulseColor, pulseLayers: &pulseLayers, pulseAnimation: pulseAnimation)
}
/**
A delegation method that is executed when the view touch event has
been cancelled.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
MaterialAnimation.pulseContractAnimation(layer, visualLayer: visualLayer, pulseColor: pulseColor, pulseLayers: &pulseLayers, pulseAnimation: pulseAnimation)
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
public func prepareView() {
contentScaleFactor = MaterialDevice.scale
prepareVisualLayer()
}
/// Prepares the visualLayer property.
internal func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
/// Manages the layout for the visualLayer property.
internal func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
/// Manages the layout for the shape of the view instance.
internal func layoutShape() {
if .Circle == shape {
let w: CGFloat = (width / 2)
if w != cornerRadius {
cornerRadius = w
}
}
}
/// Sets the shadow path.
internal func layoutShadowPath() {
if shadowPathAutoSizeEnabled {
if .None == depth {
shadowPath = nil
} else if nil == shadowPath {
shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
} else {
animate(MaterialAnimation.shadowPath(UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath, duration: 0))
}
}
}
} | mit | bcfad243472113b3b50cc2e23795de46 | 28.155116 | 296 | 0.732156 | 3.976367 | false | false | false | false |
AppLovin/iOS-SDK-Demo | Swift Demo App/iOS-SDK-Demo/ALDemoNativeAdFeedTableViewController.swift | 1 | 3160 | //
// ALDemoNativeAdFeedTableViewController.swift
// iOS-SDK-Demo
//
// Created by Thomas So on 9/25/15.
// Copyright © 2015 AppLovin. All rights reserved.
//
import UIKit
class ALDemoNativeAdFeedTableViewController : UITableViewController
{
let kArticleCellIdentifier = "articleCell"
let kAdCellIdentifier = "adCell"
let kCellTagTitleLabel = 2
let kCellTagSubtitleLabel = 3
let kCellTagDescriptionLabel = 4
var articles = [ALDemoArticle]()
// MARK: View Lifecycle
override func viewDidLoad()
{
super.viewDidLoad()
ALDemoRSSFeedRetriever.shared().startParsing(completion: { (error: Error?, articles: [ALDemoArticle]!) in
DispatchQueue.main.async {
guard error == nil && articles.count > 0 else {
let alert = UIAlertController(title: "ERROR", message: error?.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction) -> Void in
self.navigationController?.popViewController(animated: true)
}))
self.present(alert, animated: true, completion: nil)
return
}
self.articles = articles
self.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
{
return articles.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
return articles[indexPath.row].isAd ? 360 : 280
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
var cell: UITableViewCell!
let article = articles[indexPath.row]
if article.isAd
{
// You can configure carousels in ALCarouselViewSettings.h
cell = tableView.dequeueReusableCell(withIdentifier: kAdCellIdentifier, for: indexPath)
}
else
{
cell = tableView.dequeueReusableCell(withIdentifier: kArticleCellIdentifier, for: indexPath)
(cell.viewWithTag(kCellTagTitleLabel) as! UILabel).text = article.title
(cell.viewWithTag(kCellTagSubtitleLabel) as! UILabel).text = article.creator + " - " + article.pubDate
(cell.viewWithTag(kCellTagDescriptionLabel) as! UILabel).text = article.articleDescription
}
return cell
}
// MARK: Table View Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
tableView.deselectRow(at: indexPath, animated: true)
UIApplication.shared.openURL(articles[indexPath.row].link)
}
}
| mit | 589f2a719b2ddaab61c44140073672bc | 32.606383 | 127 | 0.604305 | 5.27379 | false | false | false | false |
russbishop/swift | test/ClangModules/autolinking.swift | 1 | 2007 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend %s -sdk %S/Inputs -I %S/Inputs/custom-modules -emit-ir -o %t/without-adapter.ll
// RUN: FileCheck %s < %t/without-adapter.ll
// RUN: %target-swift-frontend -emit-module %S/Inputs/adapter.swift -sdk %S/Inputs -module-link-name SwiftAdapter -module-name ClangModuleWithAdapter -I %S/Inputs/custom-modules -o %t
// RUN: %target-swift-frontend %s -sdk %S/Inputs -I %S/Inputs/custom-modules -I %t -emit-ir -o %t/with-adapter.ll
// RUN: FileCheck %s < %t/with-adapter.ll
// RUN: FileCheck --check-prefix=CHECK-WITH-SWIFT %s < %t/with-adapter.ll
// RUN: %target-swift-frontend %s -sdk %S/Inputs -I %S/Inputs/custom-modules -emit-ir -disable-autolink-framework LinkFramework -o %t/with-disabled.ll
// RUN: FileCheck --check-prefix=CHECK-WITH-DISABLED %s < %t/with-disabled.ll
// Linux uses a different autolinking mechanism, based on
// swift-autolink-extract. This file tests the Darwin mechanism.
// UNSUPPORTED: OS=linux-gnu
// UNSUPPORTED: OS=linux-gnueabihf
// UNSUPPORTED: OS=freebsd
// UNSUPPORTED: OS=linux-androideabi
import LinkMusket
import LinkFramework
import ClangModuleUser
import IndirectFrameworkImporter
import UsesSubmodule
_ = LinkFramework.IComeFromLinkFramework
UsesSubmodule.useSomethingFromSubmodule()
// CHECK: !{{[0-9]+}} = !{i32 6, !"Linker Options", ![[LINK_LIST:[0-9]+]]}
// CHECK: ![[LINK_LIST]] = !{
// CHECK-DAG: !{{[0-9]+}} = !{!"-lLock"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-lStock"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"Barrel"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"LinkFramework"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-lUnderlyingClangLibrary"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"Indirect"}
// CHECK-DAG: !{{[0-9]+}} = !{!"-framework", !"HasSubmodule"}
// CHECK-WITH-SWIFT: !{{[0-9]+}} = !{!"-lSwiftAdapter"}
// CHECK-WITH-DISABLED: !{!"-framework", !"Barrel"}
// CHECK-WITH-DISABLED-NOT: !{!"-framework", !"LinkFramework"}
// CHECK-WITH-DISABLED: !{!"-framework", !"Indirect"}
| apache-2.0 | f0759151331eba6d736dd0daa4bb74da | 43.6 | 183 | 0.662182 | 3.140845 | false | false | false | false |
jtbandes/swift | test/IRGen/sil_witness_tables.swift | 6 | 3859 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-module -o %t %S/sil_witness_tables_external_conformance.swift
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -I %t -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
import sil_witness_tables_external_conformance
// FIXME: This should be a SIL test, but we can't parse sil_witness_tables
// yet.
protocol A {}
protocol P {
associatedtype Assoc: A
static func staticMethod()
func instanceMethod()
}
protocol Q : P {
func qMethod()
}
protocol QQ {
func qMethod()
}
struct AssocConformer: A {}
struct Conformer: Q, QQ {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK: [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE:@_T039sil_witness_tables_external_conformance17ExternalConformerVAA0F1PAAWP]] = external global i8*, align 8
// CHECK: [[CONFORMER_Q_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1QAAWP]] = hidden constant [2 x i8*] [
// CHECK: i8* bitcast ([4 x i8*]* [[CONFORMER_P_WITNESS_TABLE:@_T018sil_witness_tables9ConformerVAA1PAAWP]] to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1QA2aDP7qMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER_P_WITNESS_TABLE]] = hidden constant [4 x i8*] [
// CHECK: i8* bitcast (%swift.type* ()* @_T018sil_witness_tables14AssocConformerVMa to i8*),
// CHECK: i8* bitcast (i8** ()* @_T018sil_witness_tables14AssocConformerVAA1AAAWa to i8*)
// CHECK: i8* bitcast (void (%swift.type*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PA2aDP12staticMethod{{[_0-9a-zA-Z]*}}FZTW to i8*),
// CHECK: i8* bitcast (void (%T18sil_witness_tables9ConformerV*, %swift.type*, i8**)* @_T018sil_witness_tables9ConformerVAA1PA2aDP14instanceMethod{{[_0-9a-zA-Z]*}}FTW to i8*)
// CHECK: ]
// CHECK: [[CONFORMER2_P_WITNESS_TABLE:@_T018sil_witness_tables10Conformer2VAA1PAAWP]] = hidden constant [4 x i8*]
struct Conformer2: Q {
typealias Assoc = AssocConformer
static func staticMethod() {}
func instanceMethod() {}
func qMethod() {}
}
// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables7erasureAA2QQ_pAA9ConformerV1c_tF(%T18sil_witness_tables2QQP* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T18sil_witness_tables2QQP, %T18sil_witness_tables2QQP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* [[CONFORMER_QQ_WITNESS_TABLE:@_T0.*WP]], i32 0, i32 0), i8*** [[WITNESS_TABLE_ADDR]], align 8
func erasure(c c: Conformer) -> QQ {
return c
}
// CHECK-LABEL: define hidden swiftcc void @_T018sil_witness_tables15externalErasure0a1_b1_c1_D12_conformance9ExternalP_pAC0G9ConformerV1c_tF(%T39sil_witness_tables_external_conformance9ExternalPP* noalias nocapture sret)
// CHECK: [[WITNESS_TABLE_ADDR:%.*]] = getelementptr inbounds %T39sil_witness_tables_external_conformance9ExternalPP, %T39sil_witness_tables_external_conformance9ExternalPP* %0, i32 0, i32 2
// CHECK-NEXT: store i8** [[EXTERNAL_CONFORMER_EXTERNAL_P_WITNESS_TABLE]], i8*** %2, align 8
func externalErasure(c c: ExternalConformer) -> ExternalP {
return c
}
// FIXME: why do these have different linkages?
// CHECK-LABEL: define hidden %swift.type* @_T018sil_witness_tables14AssocConformerVMa()
// CHECK: ret %swift.type* bitcast (i64* getelementptr inbounds {{.*}} @_T018sil_witness_tables14AssocConformerVMf, i32 0, i32 1) to %swift.type*)
// CHECK-LABEL: define hidden i8** @_T018sil_witness_tables9ConformerVAA1PAAWa()
// CHECK: ret i8** getelementptr inbounds ([4 x i8*], [4 x i8*]* @_T018sil_witness_tables9ConformerVAA1PAAWP, i32 0, i32 0)
| apache-2.0 | e36017adee33ce955e688e399fa14eb2 | 47.2375 | 221 | 0.717025 | 3.20515 | false | false | false | false |
kingslay/KSJSONHelp | Core/Source/Value.swift | 1 | 8556 | /// - Warning: `Binding` is a protocol that SQLite.swift uses internally to
/// directly map SQLite types to Swift types.
///
/// Do not conform custom types to the Binding protocol. See the `Value`
/// protocol, instead.
import Foundation
///数据库绑定类型
public protocol Binding {
static var declaredDatatype: String { get }
var datatypeValue: Binding { get }
static func toAnyObject(_ datatypeValue: Binding) -> AnyObject
}
func wrapValue<A: Binding>(_ v: Binding) -> A {
return A.toAnyObject(v) as! A
}
func wrapValue<A: Binding>(_ v: Binding?) -> A {
return wrapValue(v!)
}
///进行序列化如:把对象专为字典
public protocol Serialization {
var serialization: AnyObject { get }
}
///进行反序列化:把字典转为对象
public protocol Deserialization {
func deserialization(_ type: Any.Type) -> AnyObject
}
public protocol Number {
}
extension Double : Binding, Number {
public static let declaredDatatype = "REAL"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return datatypeValue as! Double as AnyObject
}
public var datatypeValue: Binding {
return self
}
}
extension Float : Binding, Number {
public static let declaredDatatype = "REAL"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return datatypeValue as! Double as AnyObject
}
public var datatypeValue: Binding {
return Double(self)
}
}
extension Int : Binding, Number {
public static var declaredDatatype = Int64.declaredDatatype
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return Int(datatypeValue as! Int64) as AnyObject
}
public var datatypeValue: Binding {
return Int64(self)
}
}
extension UInt : Binding, Number {
public static var declaredDatatype = Int64.declaredDatatype
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return UInt(datatypeValue as! Int64) as AnyObject
}
public var datatypeValue: Binding {
return Int64(self)
}
}
extension Int64 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return (datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return self
}
public var serialization: AnyObject {
return NSNumber(value: self as Int64)
}
}
extension UInt64 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return UInt64(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as UInt64)
}
}
extension Int32 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return Int32(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as Int32)
}
}
extension UInt32 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return UInt32(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as UInt32)
}
}
extension Int16 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return Int16(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as Int16)
}
}
extension UInt16 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return UInt16(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as UInt16)
}
}
extension Int8 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return Int8(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as Int8)
}
}
extension UInt8 : Binding, Number, Serialization {
public static let declaredDatatype = "INTEGER"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return UInt8(datatypeValue as! Int64).serialization
}
public var datatypeValue: Binding {
return Int64(self)
}
public var serialization: AnyObject {
return NSNumber(value: self as UInt8)
}
}
extension Bool : Binding {
public static var declaredDatatype = Int64.declaredDatatype
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return ((datatypeValue as! Int64) != 0) as! AnyObject
}
public var datatypeValue: Binding {
return self ? 1 : 0
}
}
extension Date : Binding, Number {
public static var declaredDatatype: String {
return "REAL"
}
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return Date(timeIntervalSince1970: datatypeValue as! Double) as AnyObject
}
public var datatypeValue: Binding {
return self.timeIntervalSince1970
}
}
extension NSNumber : Binding, Number {
public class var declaredDatatype: String {
return "REAL"
}
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
if let double = datatypeValue as? Double {
return NSNumber(value: double as Double)
}else if let longLong = datatypeValue as? Int64 {
return NSNumber(value: longLong as Int64)
}else{
return NSNumber()
}
}
public var datatypeValue: Binding {
let typeString = String(cString: self.objCType)
switch typeString {
case "c":
return Int64(self.int8Value)
case "i":
return Int64(self.int32Value)
case "s":
return Int64(self.int16Value)
case "l":
return Int64(self.int32Value)
case "q":
return self.int64Value
case "C":
return Int64(self.int8Value)
case "I":
return Int64(self.uint32Value)
case "S":
return Int64(self.uint16Value)
case "L":
return Int64(self.uintValue)
case "Q":
return Int64(self.uint64Value)
case "B":
return Int64(self.boolValue ? 1 : 0)
case "f", "d":
return self.doubleValue
default:
return self.description
}
}
}
extension String : Binding {
public static let declaredDatatype = "TEXT"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return datatypeValue as! String as AnyObject
}
public var datatypeValue: Binding {
return self
}
}
extension Character : Binding {
public static let declaredDatatype = "TEXT"
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return datatypeValue as! String as AnyObject
}
public var datatypeValue: Binding {
return String(self)
}
}
extension NSString : Binding {
public class var declaredDatatype: String {
return String.declaredDatatype
}
public static func toAnyObject(_ datatypeValue: Binding) -> AnyObject {
return datatypeValue as! String as AnyObject
}
public var datatypeValue: Binding {
return self as String
}
}
| mit | ce13e0729aadc1f319f0ac75064c7622 | 26.822951 | 81 | 0.648126 | 4.79435 | false | false | false | false |
Eonil/EditorLegacy | Modules/EditorUIComponents/EditorUIComponents/Internals/Text.swift | 2 | 1402 | //
// Text.swift
// EditorDebuggingFeature
//
// Created by Hoon H. on 2015/02/03.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
import AppKit
/// A utility to make `NSAttributedString` easily.
struct Text {
private var s = NSAttributedString()
init() {
}
init(_ s:String) {
self.s = NSMutableAttributedString(string: s)
}
init(_ s:NSAttributedString) {
self.s = s
}
var attributedString:NSAttributedString {
get {
return s
}
}
func setFont(font:NSFont) -> Text {
return textByResettingAttribute(NSFontAttributeName, value: font)
}
func setTextColor(color:NSColor) -> Text {
return textByResettingAttribute(NSForegroundColorAttributeName, value: color)
}
func setKern(kern:CGFloat) -> Text {
return textByResettingAttribute(NSKernAttributeName, value: NSNumber(double: Double(kern)))
}
private func textByResettingAttribute(attribute:NSString, value:AnyObject) -> Text {
let a1 = [attribute: value]
let s2 = NSMutableAttributedString(attributedString: s)
let r1 = NSRange(location: 0, length: (s2.string as NSString).length)
s2.addAttribute(attribute as! String, value: value, range: r1)
return Text(s2)
}
}
func + (left:Text, right:Text) -> Text {
let s1 = NSMutableAttributedString()
s1.appendAttributedString(left.attributedString)
s1.appendAttributedString(right.attributedString)
return Text(s1)
}
| mit | 226dd6363870239ecde8d24d09fbe8d3 | 21.253968 | 93 | 0.724679 | 3.268065 | false | false | false | false |
whitepixelstudios/Material | Sources/iOS/View.swift | 1 | 6097 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE 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 UIKit
open class View: UIView {
open override var intrinsicContentSize: CGSize {
return bounds.size
}
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable
open var image: UIImage? {
get {
guard let v = visualLayer.contents else {
return nil
}
return UIImage(cgImage: v as! CGImage)
}
set(value) {
visualLayer.contents = value?.cgImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
@IBInspectable
open var contentsRect: CGRect {
get {
return visualLayer.contentsRect
}
set(value) {
visualLayer.contentsRect = value
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
@IBInspectable
open var contentsCenter: CGRect {
get {
return visualLayer.contentsCenter
}
set(value) {
visualLayer.contentsCenter = value
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the view. By default, this value is set to the Screen.scale.
*/
@IBInspectable
open var contentsScale: CGFloat {
get {
return visualLayer.contentsScale
}
set(value) {
visualLayer.contentsScale = value
}
}
/// A Preset for the contentsGravity property.
@IBInspectable
open var contentsGravityPreset: Gravity {
didSet {
contentsGravity = GravityToValue(gravity: contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable
open var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.cgColor
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentsGravityPreset = .resizeAspectFill
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
contentsGravityPreset = .resizeAspectFill
super.init(frame: frame)
prepare()
}
/// Convenience initializer.
public convenience init() {
self.init(frame: .zero)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
contentScaleFactor = Screen.scale
backgroundColor = .white
prepareVisualLayer()
}
}
extension View {
/// Prepares the visualLayer property.
fileprivate func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
}
extension View {
/// Manages the layout for the visualLayer property.
fileprivate func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = layer.cornerRadius
}
}
| bsd-3-clause | a8273bb75e2375616f4fa1481100628d | 29.333333 | 88 | 0.702149 | 4.726357 | false | false | false | false |
iHunterX/SocketIODemo | DemoSocketIO/Utils/PAPermissions/Classes/PAPermissionsTableViewCell.swift | 1 | 8894 | //
// PAPermissionsTableViewCell.swift
// PAPermissionsApp
//
// Created by Pasquale Ambrosini on 05/09/16.
// Copyright © 2016 Pasquale Ambrosini. All rights reserved.
//
import UIKit
class PAPermissionsTableViewCell: UITableViewCell {
var didSelectItem: ((PAPermissionsItem) -> ())?
weak var iconImageView: UIImageView!
weak var titleLabel: UILabel!
weak var detailsLabel: UILabel!
weak var permission: PAPermissionsItem!
fileprivate weak var rightDetailsContainer: UIView!
fileprivate weak var enableButton: UIButton!
fileprivate weak var checkingIndicator: UIActivityIndicatorView!
fileprivate var _permissionStatus = PAPermissionsStatus.disabled
var permissionStatus: PAPermissionsStatus {
get {
return self._permissionStatus
}
set(newStatus) {
self._permissionStatus = newStatus
self.setupEnableButton(newStatus)
}
}
override var tintColor: UIColor! {
get {
return super.tintColor
}
set(newTintColor) {
super.tintColor = newTintColor
self.updateTintColor()
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .default, reuseIdentifier: reuseIdentifier)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func updateTintColor() {
self.setupImageView()
self.setupTitleLabel()
self.setupDetailsLabel()
self.setupEnableButton(self.permissionStatus)
}
fileprivate func setupUI() {
self.backgroundColor = UIColor.clear
self.separatorInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
self.setupImageView()
self.setupTitleLabel()
self.setupDetailsLabel()
self.setupRightDetailsContainer()
let views = ["iconImageView": self.iconImageView,
"titleLabel": self.titleLabel,
"detailsLabel": self.detailsLabel,
"rightDetailsContainer": self.rightDetailsContainer] as [String:UIView]
let allConstraints = PAConstraintsUtils.concatenateConstraintsFromString([
"V:|-2-[iconImageView]-2-|",
"H:|-0-[iconImageView(15)]",
"V:|-2-[rightDetailsContainer]-2-|",
"H:[rightDetailsContainer(58)]-0-|",
"V:|-8-[titleLabel(18)]-2-[detailsLabel(13)]",
"H:[iconImageView]-8-[titleLabel]-4-[rightDetailsContainer]",
"H:[iconImageView]-8-[detailsLabel]-4-[rightDetailsContainer]"
], views: views)
if #available(iOS 8.0, *) {
NSLayoutConstraint.activate(allConstraints)
} else {
self.addConstraints(allConstraints)
}
self.setupEnableButton(.disabled)
}
fileprivate func setupImageView() {
if self.iconImageView == nil {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
self.addSubview(imageView)
self.iconImageView = imageView
self.iconImageView.backgroundColor = UIColor.clear
self.iconImageView.translatesAutoresizingMaskIntoConstraints = false
}
self.iconImageView.tintColor = self.tintColor
}
fileprivate func setupTitleLabel() {
if self.titleLabel == nil {
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(titleLabel)
self.titleLabel = titleLabel
self.titleLabel.text = "Title"
self.titleLabel.adjustsFontSizeToFitWidth = true
}
self.titleLabel.font = UIFont(name: "HelveticaNeue-Light", size: 15)
self.titleLabel.minimumScaleFactor = 0.1
self.titleLabel.textColor = self.tintColor
}
fileprivate func setupDetailsLabel() {
if self.detailsLabel == nil {
let detailsLabel = UILabel()
detailsLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(detailsLabel)
self.detailsLabel = detailsLabel
self.detailsLabel.text = "details"
self.detailsLabel.adjustsFontSizeToFitWidth = true
}
self.detailsLabel.font = UIFont(name: "HelveticaNeue-Light", size: 11)
self.detailsLabel.minimumScaleFactor = 0.1
self.detailsLabel.textColor = self.tintColor
}
fileprivate func setupRightDetailsContainer() {
if self.rightDetailsContainer == nil {
let rightDetailsContainer = UIView()
rightDetailsContainer.backgroundColor = UIColor.clear
rightDetailsContainer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(rightDetailsContainer)
self.rightDetailsContainer = rightDetailsContainer
self.rightDetailsContainer.backgroundColor = UIColor.clear
}
}
fileprivate func setupEnableButton(_ status: PAPermissionsStatus) {
if self.enableButton == nil {
let enableButton = UIButton(type: .system)
enableButton.translatesAutoresizingMaskIntoConstraints = false
self.rightDetailsContainer.addSubview(enableButton)
self.enableButton = enableButton
self.enableButton.backgroundColor = UIColor.red
self.enableButton.addTarget(self, action: #selector(PAPermissionsTableViewCell._didSelectItem), for: .touchUpInside)
let checkingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
checkingIndicator.translatesAutoresizingMaskIntoConstraints = false
self.rightDetailsContainer.addSubview(checkingIndicator)
self.checkingIndicator = checkingIndicator
let views = ["enableButton": self.enableButton,
"checkingIndicator": self.checkingIndicator] as [String : UIView]
var allConstraints = PAConstraintsUtils.concatenateConstraintsFromString([
"V:[enableButton(30)]",
"H:|-2-[enableButton]-2-|",
"V:|-0-[checkingIndicator]-0-|",
"H:|-0-[checkingIndicator]-0-|"
], views: views)
allConstraints.append(NSLayoutConstraint.init(item: self.enableButton, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.enableButton.superview, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0))
if #available(iOS 8.0, *) {
NSLayoutConstraint.activate(allConstraints)
} else {
self.rightDetailsContainer.addConstraints(allConstraints)
}
}
self.enableButton.tintColor = self.tintColor
if status == .enabled {
if !self.permission.canBeDisabled {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle("", for: UIControlState())
self.enableButton.layer.cornerRadius = 0.0
self.enableButton.layer.borderColor = UIColor.clear.cgColor
self.enableButton.layer.borderWidth = 0.0
self.enableButton.setImage(UIImage(named: "pa_checkmark_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil), for: UIControlState())
self.enableButton.imageView?.contentMode = .scaleAspectFit
self.enableButton.isUserInteractionEnabled = false
}else{
self.setupEnableDisableButton(title: "Disable")
}
}else if status == .disabled || status == .denied {
self.setupEnableDisableButton(title: "Enable")
}else if status == .checking {
self.enableButton.isHidden = true
self.checkingIndicator.isHidden = false
self.checkingIndicator.startAnimating()
}else if status == .unavailable {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle("", for: UIControlState())
self.enableButton.layer.cornerRadius = 0.0
self.enableButton.layer.borderColor = UIColor.clear.cgColor
self.enableButton.layer.borderWidth = 0.0
self.enableButton.setImage(UIImage(named: "pa_cancel_icon", in: Bundle(for: PAPermissionsViewController.self), compatibleWith: nil), for: UIControlState())
self.enableButton.imageView?.contentMode = .scaleAspectFit
self.enableButton.isUserInteractionEnabled = false
}
}
private func setupEnableDisableButton(title: String) {
self.enableButton.isHidden = false
self.checkingIndicator.isHidden = true
self.checkingIndicator.stopAnimating()
self.enableButton.setTitle(NSLocalizedString(title, comment: ""), for: UIControlState())
self.enableButton.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
self.enableButton.setImage(nil, for: UIControlState())
self.enableButton.titleLabel?.minimumScaleFactor = 0.1
self.enableButton.titleLabel?.adjustsFontSizeToFitWidth = true
self.enableButton.setTitleColor(self.tintColor, for: UIControlState())
self.enableButton.backgroundColor = UIColor.clear
self.enableButton.layer.cornerRadius = 2.0
self.enableButton.layer.borderColor = self.tintColor.cgColor
self.enableButton.layer.borderWidth = 1.0
self.enableButton.clipsToBounds = true
self.enableButton.isUserInteractionEnabled = true
}
@objc fileprivate func _didSelectItem() {
if self.didSelectItem != nil {
self.didSelectItem!(self.permission)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| gpl-3.0 | 084896fad33a76a1cd1dc54a5b30064a | 34.289683 | 254 | 0.752614 | 4.066301 | false | false | false | false |
SunnyPRO/Taylor | TaylorFrameworkTests/CapriceTests/Tests/OptionsProcessorTests.swift | 1 | 18893 | //
// OptionsProcessorTests.swift
// Caprices
//
// Created by Dmitrii Celpan on 9/9/15.
// Copyright © 2015 yopeso.dmitriicelpan. All rights reserved.
//
import Quick
import Nimble
@testable import TaylorFramework
class OptionsProcessorTests: QuickSpec {
override func spec() {
describe("OptionsProcessor") {
do {
let currentPath = FileManager.default.currentDirectoryPath
var optionsProcessor : OptionsProcessor!
func forceProcessOptions(_ options: [String]) -> Options {
return try! optionsProcessor.processOptions(arguments: options)
}
beforeEach {
optionsProcessor = OptionsProcessor()
}
afterEach {
optionsProcessor = nil
}
context("when arguments contain reporter option") {
it("should create ReporterOption and append it to reporterOptions array") {
let reporterArgument = "plain:/path/to/plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
_ = forceProcessOptions(inputArguments)
let reporterArg = optionsProcessor.factory.filterClassesOfType(ReporterOption().name)[0].optionArgument
let equal = (reporterArg == reporterArgument)
expect(equal).to(beTrue())
}
it("should return empty dictionary if reporter argument does not contain : symbol and is not xcode reporter") {
let reporterArgument = "plain/path/to/plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if reporter argument contain more than one : symbol") {
let reporterArgument = "plain:/path/to/:plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if reporters type doesn't match possible types") {
let reporterArgument = "errorType:/path/to/plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should not return empty dictionary(as when error occurs) when xcode is passed as argument for rule customization option") {
let reporterArgument = "xcode"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).toNot(beEmpty())
}
}
context("when arguments contain multiple reporterOptions") {
it("should append multiple reporterOptions to reporterOptions array") {
let reporterArgument1 = "plain:/path/to/plain-output.txt"
let reporterArgument2 = "json:/path/to/plain-output.json"
let reporterArgument3 = "xcode"
let inputArguments = [currentPath, ReporterLong, reporterArgument1, ReporterShort, reporterArgument2, ReporterShort, reporterArgument3]
_ = forceProcessOptions(inputArguments)
var reportersArguments = [String]()
for arg in optionsProcessor.factory.filterClassesOfType(ReporterOption().name) {
reportersArguments.append(arg.optionArgument)
}
let equal = (reportersArguments == [reporterArgument1, reporterArgument2, reporterArgument3])
expect(equal).to(beTrue())
}
it("should return empty dictionary if reportedOption type is repeated") {
let reporterArgument = "plain:/path/to/plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument, ReporterShort, reporterArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if one of reportedOptions is not valid") {
let reporterArgument1 = "plain:/path/to/plain-output.txt"
let reporterArgument2 = "plain/path/to/plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument1, ReporterShort, reporterArgument2]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
}
context("when valid reporterOptions indicated") {
it("should set reporters property with dictionaries(type and fileName key)") {
let reporterArgument = "plain:/path/to/plain-output.txt"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.getReporters() == [["type" : "plain", "fileName" : "/path/to/plain-output.txt"]]).to(beTrue())
}
it("should ser reporters property with type: xcode and fileName : EmptyString for xcode type reporter") {
let reporterArgument = "xcode"
let inputArguments = [currentPath, ReporterLong, reporterArgument]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.getReporters() == [["type" : "xcode", "fileName" : ""]]).to(beTrue())
}
it("should set multiple reporters into array of dictionaries(type and fileName key)") {
let reporterArgument = "plain:/path/to/plain-output.txt"
let reporterArgument1 = "xcode"
let inputArguments = [currentPath, ReporterLong, reporterArgument, ReporterLong, reporterArgument1]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.getReporters() == [["type" : "plain", "fileName" : "/path/to/plain-output.txt"], ["type" : "xcode", "fileName" : ""]]).to(beTrue())
}
}
context("when arguments contain rule customization option") {
it("should create ruleCustomizationOption and append it to ruleCustomizationOptions array") {
let rcArgument = "ExcessiveMethodLength=10"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument]
_ = forceProcessOptions(inputArguments)
let rcArguments = optionsProcessor.factory.filterClassesOfType(RuleCustomizationOption().name)[0].optionArgument
let equal = (rcArgument == rcArguments)
expect(equal).to(beTrue())
}
it("should return empty dictionary if ruleCustommization argument does not contain = symbol") {
let rcArgument = "ExcessiveMethodLength10"
let inputArguments = [currentPath, RuleCustomizationShort, rcArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if ruleCustommization argument contain more than one = symbol") {
let rcArgument = "ExcessiveMethodLength=10=20"
let inputArguments = [currentPath, RuleCustomizationShort, rcArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if ruleCustommizations type doesn't match possible types") {
let rcArgument = "SomeErrorCaseCustomization=10"
let inputArguments = [currentPath, RuleCustomizationShort, rcArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if argument for rule is not an integer") {
let rcArgument = "SomeErrorCaseCustomization=1a0c"
let inputArguments = [currentPath, RuleCustomizationShort, rcArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
}
context("when arguments contain multiple customization rules") {
it("should append multiple customization rules to ruleCustomizationOptions array") {
let rcArgument1 = "ExcessiveMethodLength=10"
let rcArgument2 = "ExcessiveClassLength=400"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument1, RuleCustomizationShort, rcArgument2]
_ = forceProcessOptions(inputArguments)
var rcArguments = [String]()
for arg in optionsProcessor.factory.filterClassesOfType(RuleCustomizationOption().name) {
rcArguments.append(arg.optionArgument)
}
let equal = ([rcArgument1, rcArgument2] == rcArguments)
expect(equal).to(beTrue())
}
it("should return empty dictionary if rule customization types are repeated") {
let rcArgument = "ExcessiveMethodLength=10"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument, RuleCustomizationShort, rcArgument]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
it("should return empty dictionary if one of rulesCustomizations is not valid") {
let rcArgument1 = "ExcessiveMethodLength=10"
let rcArgument2 = "ExcessiveClassLength400"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument1, RuleCustomizationShort, rcArgument2]
let resultDictionary = forceProcessOptions(inputArguments)
expect(resultDictionary).to(beEmpty())
}
}
context("when valid customizationRule is indicated") {
it("should set customizationRules propery with dictionary(rule : complexity)") {
let rcArgument1 = "ExcessiveMethodLength=10"
let rcArgument2 = "ExcessiveClassLength=400"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument1, RuleCustomizationShort, rcArgument2]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.customizationRules).to(equal(["ExcessiveMethodLength" : 10, "ExcessiveClassLength" : 400]))
}
it("should set new customizationRules propery TooManyParameters") {
let rcArgument1 = "ExcessiveParameterList=10"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument1]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.customizationRules).to(equal(["ExcessiveParameterList" : 10]))
}
it("should return empty dictionary if multiple rules of type TooManyParameters are indicated") {
let rcArgument1 = "TooManyParameters=10"
let inputArguments = [currentPath, RuleCustomizationLong, rcArgument1, RuleCustomizationShort, rcArgument1]
expect(forceProcessOptions(inputArguments)).to(beEmpty())
}
}
it("should set default verbosity level to error when initialized") {
let inputArguments = [currentPath]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.verbosityLevel).to(equal(VerbosityLevel.error))
}
context("when verbosity level is inidicated") {
it("should set optionsProcessor verbosityLevel property to indicated one") {
let verbosityArgument = "info"
let inputArguments = [currentPath, VerbosityLong, verbosityArgument]
_ = forceProcessOptions(inputArguments)
expect(optionsProcessor.factory.verbosityLevel).to(equal(VerbosityLevel.info))
}
it("should return empty dictionary if verbosity argument doesn't math possible arguments") {
let verbosityArgument = "errorArgument"
let inputArguments = [currentPath, VerbosityLong, verbosityArgument]
expect(forceProcessOptions(inputArguments)).to(beEmpty())
}
it("should return empty dictionary if multiple verbosity options are indicated") {
let verbosityArgument = "info"
let inputArguments = [currentPath, VerbosityLong, verbosityArgument, VerbosityShort, verbosityArgument]
expect(forceProcessOptions(inputArguments)).to(beEmpty())
}
}
context("when setDefaultValuesToResultDictionary is called") {
it("should set default values only for keys that was not indicated") {
var dictionary = [ResultDictionaryTypeKey : ["someType"]]
optionsProcessor.setDefaultValuesToResultDictionary(&dictionary)
expect(dictionary == [ResultDictionaryPathKey : [currentPath], ResultDictionaryTypeKey : ["someType"]]).to(beTrue())
}
it("should set default values for dictionary") {
var dictionary = Options()
optionsProcessor.setDefaultValuesToResultDictionary(&dictionary)
expect(dictionary == [ResultDictionaryPathKey : [currentPath], ResultDictionaryTypeKey : [DefaultExtensionType]]).to(beTrue())
}
it("should not change values if they are already setted") {
var dictionary = [ResultDictionaryPathKey : ["SomePath"], ResultDictionaryTypeKey : ["SomeExtension"]]
optionsProcessor.setDefaultValuesToResultDictionary(&dictionary)
expect(dictionary == [ResultDictionaryPathKey : ["SomePath"], ResultDictionaryTypeKey : ["SomeExtension"]]).to(beTrue())
}
it("should set exclude paths from default excludesFile") {
let pathToExcludesFile = MockFileManager().testFile("excludes", fileType: "yml")
let pathToExcludesFileRootFolder = pathToExcludesFile.replacingOccurrences(of: "/excludes.yml", with: "")
var dictionary = [ResultDictionaryPathKey : [pathToExcludesFileRootFolder]]
optionsProcessor.setDefaultValuesToResultDictionary(&dictionary)
let resultsArrayOfExcludes = ["file.txt".formattedExcludePath(pathToExcludesFileRootFolder), "path/to/file.txt".formattedExcludePath(pathToExcludesFileRootFolder), "folder".formattedExcludePath(pathToExcludesFileRootFolder), "path/to/folder".formattedExcludePath(pathToExcludesFileRootFolder)]
expect(dictionary == [ResultDictionaryPathKey : [pathToExcludesFileRootFolder], ResultDictionaryTypeKey : [DefaultExtensionType], ResultDictionaryExcludesKey : resultsArrayOfExcludes]).to(beTrue())
}
}
}
}
}
}
func ==<U: Hashable, T: Sequence>(lhs: [U: T], rhs: [U: T]) -> Bool where T.Iterator.Element: Equatable {
guard lhs.count == rhs.count else { return false }
for (key, lValue) in lhs {
guard let rValue = rhs[key], Array(lValue) == Array(rValue) else {
return false
}
}
return true
}
func ==<T: Hashable, U: Equatable>(lhs: [[T: U]], rhs: [[T: U]]) -> Bool {
guard lhs.count == rhs.count else { return false }
for (index, dictionary) in lhs.enumerated() {
if dictionary != rhs[index] { return false }
}
return true
}
| mit | aa4e2b8c1647f28e218ee5f17f1ac5a0 | 59.165605 | 317 | 0.545046 | 6.133766 | false | false | false | false |
semonchan/LearningSwift | 语法/2.Swift基础语法.playground/Contents.swift | 1 | 2606 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class VideoMode {
var interlaced = false
var frameRate = 0.0
var name: String?
}
let tenEighty = VideoMode()
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
let alsoTenEighty = tenEighty
alsoTenEighty.name = "1080"
print(alsoTenEighty.name ?? "8080", "tenEighty\(String(describing: tenEighty.name))")
// 因为类是引用类型, 所以 tenEighty和alsoTenEighty 实际上引用的是相同的VideoMode实例
struct FixedLengthRange {
var firstValue: Int = 0
let length: Int
}
let fixed = FixedLengthRange(firstValue: 10, length: 10)
//fixed.firstValue = 100
class TestClass {
var name: String = ""
var age: Int {
get {
return 16
}
}
var height: Double = 0.0
}
let testClass = TestClass()
testClass.age
/*
注意:
class 必须初始化属性, 而结构体不是必须要初始化属性
class 没有简便构造器, 而结构体会自动生成带初始化属性的简便构造器
class 可以把一个引用类型的实例赋值给一个常量后, 还可以改变该实例的变量属性, 而struct则不行
*/
// 延迟存储属性是指当第一次被调用的时候才会计算其初始值的属性, 在属性声明前使用lazy来标示一个延迟存储属性
// 注意: 必须将延迟存储属性声明成变量, 因为属性的初始值可能在实例构造完成之后才会得到. 而常量在构造过程完成之前必须初始化,因此无法声明成延迟属性
// 可以为除了延迟存储属性之外的其他存储属性添加属性观察器
// 观察属性
class StepCounter {
var totalSteps: Int = 0 {
didSet {
if totalSteps > oldValue {
print("Added \(totalSteps - oldValue)steps")
}
}
}
}
let stepCounter = StepCounter()
stepCounter.totalSteps = 100
// 类型属性
// 无论创建了多少个该类型的实例, 这些属性都只有唯一一份
// 存储型类型属性是延迟初始化的, 它们只有在第一次被访问的时候才会被初始化. 即使它们被多个线程同时访问, 系统也保证只会对其进行一次初始化, 并且不需要对其使用lazy修饰符
class SomeClass {
static var storedTypeProperty = "Some Value" // 类属性
static var computedTypeProperty: Int { // 类属性, get方法, 只读
return 20
}
}
SomeClass.computedTypeProperty
SomeClass.storedTypeProperty = "Another value"
print(SomeClass.storedTypeProperty)
| mit | c0abac9f1cb8e5fa1d0991b57285315a | 19.483516 | 90 | 0.695815 | 3.122278 | false | false | false | false |
hacktoolkit/hacktoolkit-ios_lib | Hacktoolkit/utils/HTKImageUtils.swift | 1 | 1627 | //
// HTKImageUtils.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
class HTKImageUtils {
var imageCache = [String: UIImage]()
class var sharedInstance : HTKImageUtils {
struct Static {
static var token : dispatch_once_t = 0
static var instance : HTKImageUtils? = nil
}
dispatch_once(&Static.token) {
Static.instance = HTKImageUtils()
}
return Static.instance!
}
func displayImageUrl(imageUrl: String, imageView: UIImageView) {
var urlRequest = NSURLRequest(URL: NSURL(string: imageUrl)!)
imageView.setImageWithURLRequest(
urlRequest,
placeholderImage: nil,
success: {
(request: NSURLRequest!, response: NSHTTPURLResponse!, image: UIImage!) -> Void in
imageView.image = image
self.storeImageToCache(imageUrl, image: image)
},
failure: {
(request: NSURLRequest!, response: NSHTTPURLResponse!, error: NSError!) -> Void in
HTKNotificationUtils.displayNetworkErrorMessage()
}
)
}
func storeImageToCache(imageUrl: String, image: UIImage) {
self.imageCache[imageUrl] = image
}
class func getLocalImage(resource: String, ofType imageType: String) -> UIImage {
var imagePath = NSBundle.mainBundle().pathForResource(resource, ofType: imageType)
var image = UIImage(contentsOfFile: imagePath!)!
return image
}
}
| mit | 4ab69ed3e5f443e08bc5868b8bb073a1 | 31.54 | 98 | 0.619545 | 4.813609 | false | false | false | false |
Drusy/auvergne-webcams-ios | ParisWebcams/LoadingViewController.swift | 1 | 1389 | //
// LoadingViewController.swift
// AuvergneWebcams
//
// Created by Drusy on 28/03/2017.
//
//
import UIKit
class LoadingViewController: AbstractLoadingViewController {
@IBOutlet weak var cloudOneImageView: UIImageView!
@IBOutlet weak var cloudTwoImageView: UIImageView!
@IBOutlet weak var sunImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
animateClouds()
}
// MARK: -
func animateClouds() {
let options: UIViewAnimationOptions = [.autoreverse, .curveEaseInOut, .repeat]
let baseDuration: TimeInterval = 12
UIView.animate(
withDuration: baseDuration,
delay: 0,
options: options,
animations: { [weak self] in
self?.cloudOneImageView.transform = CGAffineTransform(translationX: 150, y: 0)
},
completion: nil)
UIView.animate(
withDuration: baseDuration / 1.25,
delay: 0,
options: options,
animations: { [weak self] in
self?.cloudTwoImageView.transform = CGAffineTransform(translationX: -150, y: 0)
self?.sunImageView.transform = CGAffineTransform(translationX: 25, y: -10).scaledBy(x: 0.7, y: 0.7)
},
completion: nil)
}
}
| apache-2.0 | f1ea2d126dff8ac3c170a7a1b5017aba | 27.346939 | 115 | 0.578834 | 4.890845 | false | false | false | false |
rrbrambley/starred-github-repos | StarredGithubRepos/StarredGithubRepos/RepositoryTableViewController.swift | 1 | 3111 | //
// ViewController.swift
// StarredGithubRepos
//
// Created by Robert Brambley on 4/23/16.
// Copyright © 2016 AATT. All rights reserved.
//
import OctoKit
import UIKit
class RepositoryTableViewController: UITableViewController {
private var repositories: Array<OCTRepository>?
private var contributors = [String: OCTContributor]()
let reuseIdentifier: String = "RepositoryCell"
//MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "repository_table_view:title".localized
self.tableView.allowsSelection = false
self.refreshControl!.beginRefreshing()
fetchRepositories()
}
//MARK: UITableViewDelegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return RepositoryTableViewCell.heightForCell()
}
//MARK: UITableViewDataSource
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let repository: OCTRepository = repositories![indexPath.row]
let cell: RepositoryTableViewCell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! RepositoryTableViewCell
cell.nameLabel.text = repository.name
cell.starCountLabel.text = String(repository.stargazersCount)
if let contributor = contributors[repository.objectID] {
cell.contributorNameLabel.text = contributor.name
cell.contributorActivityIndicator.hidden = true
cell.contributorActivityIndicator.stopAnimating()
} else {
cell.contributorActivityIndicator.startAnimating()
cell.contributorActivityIndicator.hidden = false
}
return cell
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.repositories == nil ? 0 : self.repositories!.count
}
//MARK: Internal
private func fetchRepositories() {
GithubDataManager.sharedInstance.fetchStarredRepositories { (repositories: Array<OCTRepository>) in
self.refreshControl?.endRefreshing()
self.repositories = repositories
self.tableView.reloadData()
for i in 0...repositories.count-1 {
self.fetchContributors(repositories[i], index: i)
}
}
}
private func fetchContributors(repository: OCTRepository, index: Int) {
GithubDataManager.sharedInstance.fetchContributors(repository, completion: { (contributors: Array<OCTContributor>) in
let c: OCTContributor = contributors.first!
self.contributors[repository.objectID] = c
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
print("repository: \(repository.name); top contributor: \(c.login, c.contributions)")
})
}
}
| mit | 405ba6a1b06c99131af7a48b2e223b80 | 36.02381 | 157 | 0.679743 | 5.563506 | false | false | false | false |
coffee-cup/solis | SunriseSunset/WNotificationsViewController.swift | 1 | 1084 | //
// WNotificationsViewController.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-07-31.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import UIKit
class WNotificationsViewController: UIViewController {
@IBOutlet weak var headingLabel: UILabel!
var timer: Timer!
let emojis = ["☀️", "🌙", "🌅", "🌄"]
var emojiIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateHeading), userInfo: nil, repeats: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
@objc func updateHeading() {
if let text = headingLabel.text {
emojiIndex = emojiIndex + 1
if emojiIndex >= emojis.count {
emojiIndex = 0
}
let newEmoji = emojis[emojiIndex]
headingLabel.text = "\(String(text.dropLast()))\(newEmoji)"
}
}
}
| mit | ddd3b15bba170896ce48a8ca73129133 | 24.47619 | 133 | 0.58972 | 4.476987 | false | false | false | false |
boztalay/GameOfLifeScreenSaver | GameOfLifeScreenSaver/GameOfLifeScreenSaver/GameOfLife.swift | 1 | 3685 | //
// GameOfLife.swift
// GameOfLifeScreenSaver
//
// Created by Ben Oztalay on 10/24/20.
//
import Foundation
enum GameOfLifeCellState {
case dead
case alive
case born
case dying
var isAlive: Bool {
return (self == .alive || self == .born)
}
var isTransitioning: Bool {
return (self == .born || self == .dying)
}
}
class GameOfLife {
private static let initialProportionAlive = 0.3
private(set) var width: Int
private(set) var height: Int
private var previousCells: [[GameOfLifeCellState]]
private var cells: [[GameOfLifeCellState]]
private var nextCells: [[GameOfLifeCellState]]
init(width: Int, height: Int) {
self.width = width
self.height = height
self.previousCells = Array(repeating: Array(repeating: .dead, count: self.height), count: self.width)
self.cells = Array(repeating: Array(repeating: .dead, count: self.height), count: self.width)
self.nextCells = Array(repeating: Array(repeating: .dead, count: self.height), count: self.width)
}
func mapCells(block: (Int, Int, GameOfLifeCellState) -> ()) {
for x in 0 ..< self.width {
for y in 0 ..< self.height {
block(x, y, self.cells[x][y])
}
}
}
func randomizeCells() {
self.mapCells { x, y, _ in
self.nextCells[x][y] = (Double.random(in: 0.0 ..< 1.0) < GameOfLife.initialProportionAlive) ? .born : .dead
}
}
func step() {
self.previousCells = self.cells
self.cells = self.nextCells
self.mapCells { x, y, cell in
let livingNeighbors = self.livingNeighbors(ofCellAtX: x, cellY: y)
let nextCell: GameOfLifeCellState
if cell.isAlive {
if livingNeighbors >= 2 && livingNeighbors <= 3 {
nextCell = .alive
} else {
nextCell = .dying
}
} else {
if livingNeighbors == 3 {
nextCell = .born
} else {
nextCell = .dead
}
}
self.nextCells[x][y] = nextCell
}
if self.isGameStatic() || self.isGameAlternating() {
self.randomizeCells()
}
}
private func livingNeighbors(ofCellAtX cellX: Int, cellY: Int) -> Int {
var aliveCount = 0
for x in (cellX - 1) ... (cellX + 1) {
for y in (cellY - 1) ... (cellY + 1) {
guard x != cellX || y != cellY else {
continue
}
let wrappedX = (x + self.width) % self.width
let wrappedY = (y + self.height) % self.height
if self.cells[wrappedX][wrappedY].isAlive {
aliveCount += 1
}
}
}
return aliveCount
}
private func isGameStatic() -> Bool {
return self.areCellGridsEqual(cellsA: self.cells, cellsB: self.previousCells)
}
private func isGameAlternating() -> Bool {
return self.areCellGridsEqual(cellsA: self.nextCells, cellsB: self.previousCells)
}
private func areCellGridsEqual(cellsA: [[GameOfLifeCellState]], cellsB: [[GameOfLifeCellState]]) -> Bool {
var areEqual = true
self.mapCells { x, y, _ in
if cellsA[x][y].isAlive != cellsB[x][y].isAlive {
areEqual = false
}
}
return areEqual
}
}
| mit | d8a8ceb7f4897f400ea11f30ed26cf9a | 27.789063 | 119 | 0.51289 | 4.182747 | false | false | false | false |
velvetroom/columbus | Source/View/PlansDetail/VPlansDetailListHeader+Constants.swift | 1 | 309 | import UIKit
extension VPlansDetailListHeader
{
struct Constants
{
static let iconWidth:CGFloat = 60
static let durationPadding:CGFloat = 10
static let distancePadding:CGFloat = -5
static let contentHeight:CGFloat = 86
static let fontSize:CGFloat = 12
}
}
| mit | c551537b3aab1e51874af279d29ef9c1 | 22.769231 | 47 | 0.666667 | 4.828125 | false | false | false | false |
gudjao/XLPagerTabStrip | Example/Example/ButtonBarExampleViewController.swift | 2 | 3577 | // ButtonBarExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class ButtonBarExampleViewController: ButtonBarPagerTabStripViewController {
var isReload = false
override func viewDidLoad() {
super.viewDidLoad()
buttonBarView.selectedBar.backgroundColor = .orange
buttonBarView.backgroundColor = UIColor(red: 7/255, green: 185/255, blue: 155/255, alpha: 1)
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .plain, itemInfo: "Table View")
let child_2 = ChildExampleViewController(itemInfo: "View")
let child_3 = TableChildExampleViewController(style: .grouped, itemInfo: "Table View 2")
let child_4 = ChildExampleViewController(itemInfo: "View 2")
let child_5 = TableChildExampleViewController(style: .plain, itemInfo: "Table View 3")
let child_6 = ChildExampleViewController(itemInfo: "View 3")
let child_7 = TableChildExampleViewController(style: .grouped, itemInfo: "Table View 4")
let child_8 = ChildExampleViewController(itemInfo: "View 4")
guard isReload else {
return [child_1, child_2, child_3, child_4, child_5, child_6, child_7, child_8]
}
var childViewControllers = [child_1, child_2, child_3, child_4, child_6, child_7, child_8]
for (index, _) in childViewControllers.enumerated(){
let nElements = childViewControllers.count - index
let n = (Int(arc4random()) % nElements) + index
if n != index{
swap(&childViewControllers[index], &childViewControllers[n])
}
}
let nItems = 1 + (arc4random() % 8)
return Array(childViewControllers.prefix(Int(nItems)))
}
override func reloadPagerTabStripView() {
isReload = true
if arc4random() % 2 == 0 {
pagerBehaviour = .progressive(skipIntermediateViewControllers: arc4random() % 2 == 0, elasticIndicatorLimit: arc4random() % 2 == 0 )
}
else {
pagerBehaviour = .common(skipIntermediateViewControllers: arc4random() % 2 == 0)
}
super.reloadPagerTabStripView()
}
}
| mit | ce9757fe62eb914fa82478fd7306dbcb | 44.858974 | 144 | 0.684932 | 4.615484 | false | false | false | false |
etamity/AlienBlast | Source/SentryFinger.swift | 1 | 1721 | //
// SentryFinger.swift
// AlienBlastSwift
//
// Created by Joey etamity on 29/03/2016.
// Copyright © 2016 Innovation Apps. All rights reserved.
//
import Foundation
class SentryFinger: Finger {
weak var leftCanon: CCParticleSystem! = nil
weak var rightCanon: CCParticleSystem! = nil
override func didLoadFromCCB() {
super.didLoadFromCCB()
self.type = FingerType.Sentry
}
func onShootBullet(){
OALSimpleAudio.sharedInstance().playEffect(StaticData.getSoundFile(GameSoundType.LASER.rawValue))
self.shootBullet(self.convertToWorldSpace(leftCanon.position))
self.shootBullet(self.convertToWorldSpace(rightCanon.position))
self.shootBullet(self.position)
}
func shootBullet(startPos:CGPoint){
var rotationRadians: Float = 0.0;
rotationRadians = CC_DEGREES_TO_RADIANS(Float(0));
let directionVector :CGPoint = ccp(CGFloat(sinf(rotationRadians)),CGFloat(cosf(rotationRadians)));
let bulletOffset :CGPoint = ccpMult(directionVector, 1);
weak var bullet: CCNode! = nil;
bullet = CCBReader.load("Objects/Laser");
bullet.physicsBody.collisionGroup = "blaster";
bullet.position = ccpAdd(startPos, bulletOffset);
bullet.position.y += 20
let force: CGPoint = ccpMult(directionVector, 8000);
bullet.physicsBody.applyForce(force);
self.parent.addChild(bullet);
}
override func onEnter() {
super.onEnter()
self.schedule(#selector(self.onShootBullet), interval: 0.2)
}
override func onExit() {
super.onExit()
self.unscheduleAllSelectors()
}
} | mit | 76f8bb373e14d18e0ba7600f8303f816 | 29.192982 | 107 | 0.652907 | 4.105012 | false | false | false | false |
azizuysal/NetKit | NetKit/NetKit/WebDelegate.swift | 1 | 4582 | //
// WebDelegate.swift
// NetKit
//
// Created by Aziz Uysal on 2/16/16.
// Copyright © 2016 Aziz Uysal. All rights reserved.
//
import Foundation
class WebDelegate: NSObject {
var tasks = [Int:WebTask]()
var handlers = [Int:Any]()
var datas = [Int: NSMutableData?]()
var locations = [Int: URL?]()
let fileHandlerQueue = OperationQueue()
weak var webService: WebService?
}
extension WebDelegate: URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let webTask = tasks[task.taskIdentifier]
webTask?.authenticate(challenge.protectionSpace.authenticationMethod, completionHandler: completionHandler)
}
@objc(URLSessionDidFinishEventsForBackgroundURLSession:) func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
if let completionHandler = webService?.backgroundCompletionHandler {
webService?.backgroundCompletionHandler = nil
DispatchQueue.main.async {
completionHandler()
}
}
}
}
extension WebDelegate: URLSessionDelegate {
@objc(URLSession:task:didCompleteWithError:) func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if task.isKind(of: URLSessionDataTask.self) || task.isKind(of: URLSessionUploadTask.self) {
if let handler = handlers[task.taskIdentifier] as? DataTaskHandler, let data = datas[task.taskIdentifier] {
handler(data as Data?, task.response, error as NSError?)
}
datas.removeValue(forKey: task.taskIdentifier)
} else if task.isKind(of: URLSessionDownloadTask.self) {
if let handler = handlers[task.taskIdentifier] as? DownloadTaskHandler {
fileHandlerQueue.waitUntilAllOperationsAreFinished()
let url = locations[task.taskIdentifier]
handler(url ?? nil, task.response, error as NSError?)
}
}
handlers.removeValue(forKey: task.taskIdentifier)
}
}
extension WebDelegate: URLSessionDataDelegate {
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let taskData = datas[dataTask.taskIdentifier] {
taskData?.append(data)
}
}
}
extension WebDelegate: URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
fileHandlerQueue.isSuspended = true
fileHandlerQueue.addOperation {
// just wait
}
let webTask = tasks[downloadTask.taskIdentifier]
webTask?.downloadFile(location, response: downloadTask.response)
fileHandlerQueue.isSuspended = false
}
}
class TaskSource {
class func defaultSource(_ configuration: URLSessionConfiguration, delegate: URLSessionDelegate?, delegateQueue: OperationQueue?) -> SessionTaskSource {
if configuration.identifier != nil {
return BackgroundTaskSource(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
}
return URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
}
}
class BackgroundTaskSource {
var urlSession: URLSession
let webDelegate: WebDelegate?
init(configuration: URLSessionConfiguration, delegate: URLSessionDelegate?, delegateQueue: OperationQueue?) {
webDelegate = delegate as? WebDelegate
urlSession = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
}
}
extension BackgroundTaskSource: SessionTaskSource {
@objc func nkDataTask(with request: URLRequest, completionHandler: @escaping DataTaskHandler) -> URLSessionDataTask {
let task = urlSession.dataTask(with: request)
webDelegate?.handlers[task.taskIdentifier] = completionHandler
webDelegate?.datas[task.taskIdentifier] = NSMutableData()
return task
}
@objc func nkDownloadTask(with request: URLRequest, completionHandler: @escaping DownloadTaskHandler) -> URLSessionDownloadTask {
let task = urlSession.downloadTask(with: request)
webDelegate?.handlers[task.taskIdentifier] = completionHandler
return task
}
@objc func nkUploadTask(with request: URLRequest, from data: Data?, completionHandler: @escaping UploadTaskHandler) -> URLSessionUploadTask {
let task = urlSession.uploadTask(with: request, from: data!)
webDelegate?.handlers[task.taskIdentifier] = completionHandler
webDelegate?.datas[task.taskIdentifier] = NSMutableData()
return task
}
}
| mit | 3d960f765a189eacb02405929c653a11 | 38.153846 | 206 | 0.753111 | 5.084351 | false | true | false | false |
SoCM/iOS-FastTrack-2014-2015 | 04-App Architecture/Swift 2/Breadcrumbs/Solution/BackgroundTest/BCModel.swift | 1 | 5308 | //
// BCModel.swift
// Breadcrumbs
//
// Created by Nicholas Outram on 07/01/2016.
// Copyright © 2016 Plymouth University. All rights reserved.
//
import Foundation
import CoreLocation
import CloudKit
//Simple singleton model
let globalModel : BCModel = BCModel()
final class BCModel {
// CloudKit database
let publicDB = CKContainer.defaultContainer().publicCloudDatabase
private let archivePath = pathToFileInDocumentsFolder("locations")
private var arrayOfLocations = [CLLocation]()
private let queue : dispatch_queue_t = dispatch_queue_create("uk.ac.plmouth.bc", DISPATCH_QUEUE_SERIAL)
private let archiveKey = "LocationArray"
// MARK: Life-cycle
//The constructor is private, so it cannot be instantiated anywhere else
private init() {
//Phase 1 has nothing to do
//Call superclass if you subclass
// super.init()
//Phase 2 - self is now available
if let m = NSKeyedUnarchiver.unarchiveObjectWithFile(self.archivePath) as? [CLLocation] {
arrayOfLocations = m
}
}
// MARK: Public API
// All these methods are serialsed on a background thread. KEY POINT: None can preempt the other.
// For example, if save is called multiple times, each save operation will complete before the next is allowed to start.
//
// Furthermore, if an addRecord is called, but there is a save in front, this could take a significant time.
// As everthing is queued on a separate thread, there is no risk of blocking the main thread.
// Each method invokes a closure on the main thread when completed
/// Save the array to persistant storage (simple method) serialised on a background thread
func save(done done : ()->() )
{
//Save on a background thread - note this is a serial queue, so multiple calls to save will be performed
//in strict sequence (to avoid races)
dispatch_async(queue) {
//Persist data to file
NSKeyedArchiver.archiveRootObject(self.arrayOfLocations, toFile:self.archivePath)
//Call back on main thread (posted to main runloop)
dispatch_sync(dispatch_get_main_queue(), done)
}
}
/// Erase all data (serialised on a background thread)
func erase(done done : ()->() ) {
dispatch_async(queue) {
self.arrayOfLocations.removeAll()
//Call back on main thread (posted to main runloop)
dispatch_sync(dispatch_get_main_queue(), done)
}
}
/// Add a record (serialised on a background thread)
func addRecord(record : CLLocation, done : ()->() ) {
dispatch_async(queue){
self.arrayOfLocations.append(record)
//Call back on main thread (posted to main runloop)
dispatch_sync(dispatch_get_main_queue(), done)
}
}
/// Add an array of records
func addRecords(records : [CLLocation], done : ()->() ) {
dispatch_async(queue){
for r in records {
self.arrayOfLocations.append(r)
}
//Call back on main thread (posted to main runloop)
dispatch_sync(dispatch_get_main_queue(), done)
}
}
/// Thread-safe read access
func getArray(done done : (array : [CLLocation]) -> () ) {
var copyOfArray : [CLLocation]!
dispatch_async(queue){
//Call back on main thread (posted to main runloop)
copyOfArray = self.arrayOfLocations
dispatch_sync(dispatch_get_main_queue(), { done(array: copyOfArray) })
}
}
/// Query if the container is empty
func isEmpty(done done : (isEmpty : Bool) -> () ) {
dispatch_async(queue) {
let result = self.arrayOfLocations.count == 0 ? true : false
dispatch_sync(dispatch_get_main_queue(), { done(isEmpty: result) })
}
}
// MARK: Cloud Kit
/// Upload the array of data to CloudKit
func uploadToCloudKit(done : (didSucceed : Bool)->() ) {
//Fetch a copy of the array
getArray() { (array : [CLLocation]) in
//Back on the main thread
let record = CKRecord(recordType: "Locations")
record.setObject("My Only Route", forKey: "title")
record.setObject(array, forKey: "route")
self.publicDB.saveRecord(record) { (rec : CKRecord?, err: NSError?) in
if let _ = err {
done(didSucceed: false)
} else {
done(didSucceed: true)
}
}
}
}
//Delete records from cloudkit
func deleteDataFromCloudKit(done : (didSucceed : Bool)->() ) {
let p = NSPredicate(format: "title == %@", "My Only Route")
let query = CKQuery(recordType: "Locations", predicate: p)
publicDB.performQuery(query, inZoneWithID: nil) { (results : [CKRecord]?, error : NSError?) in
if let _ = error {
done(didSucceed: false)
return
}
guard let res = results else {
done(didSucceed: false)
return
}
for r : CKRecord in res {
self.publicDB.deleteRecordWithID(r.recordID) { r, err in
if let _ = err {
done(didSucceed: false)
return
}
}
}
done(didSucceed: true)
}
}
}
| mit | eb54031e2b7b544c64e9259642df2839 | 33.019231 | 123 | 0.609195 | 4.411471 | false | false | false | false |
tkremenek/swift | test/IRGen/async/class_resilience.swift | 1 | 2318 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-experimental-concurrency -disable-availability-checking -enable-library-evolution -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class %S/Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-experimental-concurrency -disable-availability-checking -enable-library-evolution %s | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-cpu %s
// REQUIRES: concurrency
import resilient_class
open class MyBaseClass<T> {
var value: T
open func wait() async -> Int {
return 0
}
open func wait() async -> T {
return value
}
open func waitThrows() async throws -> Int {
return 0
}
open func waitThrows() async throws -> T {
return value
}
// FIXME
// open func waitGeneric<T>(_: T) async -> T
// open func waitGenericThrows<T>(_: T) async throws -> T
public init(_ value: T) {
self.value = value
}
}
// CHECK-LABEL: @"$s16class_resilience11MyBaseClassC4waitxyYaFTjTu" = {{(dllexport )?}}{{(protected )?}}global %swift.async_func_pointer
// CHECK-LABEL: @"$s16class_resilience11MyBaseClassCMn" = {{(dllexport )?}}{{(protected )?}}constant
// CHECK-SAME: %swift.async_func_pointer* @"$s16class_resilience11MyBaseClassC4waitxyYaFTu"
// CHECK-LABEL: @"$s16class_resilience9MyDerivedCMn" = hidden constant
// CHECK-SAME: %swift.async_func_pointer* @"$s16class_resilience9MyDerivedC4waitSiyYaF010resilient_A09BaseClassCADxyYaFTVTu"
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swift{{(tail)?}}cc void @"$s16class_resilience14callsAwaitableyx010resilient_A09BaseClassCyxGYalF"(%swift.opaque* noalias nocapture %0, %swift.context* swiftasync %1{{.*}})
// CHECK: %swift.async_func_pointer* @"$s15resilient_class9BaseClassC4waitxyYaFTjTu"
// CHECK: ret void
public func callsAwaitable<T>(_ c: BaseClass<T>) async -> T {
return await c.wait()
}
// CHECK-LABEL: define {{(dllexport )?}}{{(protected )?}}swift{{(tail)?}}cc void @"$s16class_resilience11MyBaseClassC4waitxyYaFTj"(%swift.opaque* noalias nocapture %0, %swift.context* swiftasync %1, %T16class_resilience11MyBaseClassC* swiftself %2) {{#([0-9]+)}} {
class MyDerived : BaseClass<Int> {
override func wait() async -> Int {
return await super.wait()
}
}
| apache-2.0 | a19052d0cdd48936b83d46e0a0be92a8 | 39.666667 | 264 | 0.713546 | 3.490964 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.