repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
SuPair/firefox-ios
Client/Helpers/DynamicFontHelper.swift
5
6536
/* 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 private let iPadFactor: CGFloat = 1.06 private let iPhoneFactor: CGFloat = 0.88 class DynamicFontHelper: NSObject { static var defaultHelper: DynamicFontHelper { struct Singleton { static let instance = DynamicFontHelper() } return Singleton.instance } override init() { defaultStandardFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).pointSize // 14pt -> 17pt -> 23pt deviceFontSize = defaultStandardFontSize * (UIDevice.current.userInterfaceIdiom == .pad ? iPadFactor : iPhoneFactor) defaultMediumFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .footnote).pointSize // 12pt -> 13pt -> 19pt defaultSmallFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .caption2).pointSize // 11pt -> 11pt -> 17pt super.init() } /** * Starts monitoring the ContentSizeCategory chantes */ func startObserving() { NotificationCenter.default.addObserver(self, selector: #selector(contentSizeCategoryDidChange), name: .UIContentSizeCategoryDidChange, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } /** * Device specific */ fileprivate var deviceFontSize: CGFloat var DeviceFontSize: CGFloat { return deviceFontSize } var DeviceFont: UIFont { return UIFont.systemFont(ofSize: deviceFontSize, weight: UIFont.Weight.medium) } var DeviceFontLight: UIFont { return UIFont.systemFont(ofSize: deviceFontSize, weight: UIFont.Weight.light) } var DeviceFontSmall: UIFont { return UIFont.systemFont(ofSize: deviceFontSize - 1, weight: UIFont.Weight.medium) } var DeviceFontSmallLight: UIFont { return UIFont.systemFont(ofSize: deviceFontSize - 1, weight: UIFont.Weight.light) } var DeviceFontSmallHistoryPanel: UIFont { return UIFont.systemFont(ofSize: deviceFontSize - 3, weight: UIFont.Weight.light) } var DeviceFontHistoryPanel: UIFont { return UIFont.systemFont(ofSize: deviceFontSize) } var DeviceFontSmallBold: UIFont { return UIFont.boldSystemFont(ofSize: deviceFontSize - 1) } var DeviceFontLarge: UIFont { return UIFont.systemFont(ofSize: deviceFontSize + 3) } var DeviceFontMedium: UIFont { return UIFont.systemFont(ofSize: deviceFontSize + 1) } var DeviceFontLargeBold: UIFont { return UIFont.boldSystemFont(ofSize: deviceFontSize + 2) } var DeviceFontMediumBold: UIFont { return UIFont.boldSystemFont(ofSize: deviceFontSize + 1) } var DeviceFontExtraLargeBold: UIFont { return UIFont.boldSystemFont(ofSize: deviceFontSize + 4) } /* Activity Stream supports dynamic fonts up to a certain point. Large fonts dont work. Max out the supported font size. Small = 14, medium = 18, larger = 20 */ var MediumSizeRegularWeightAS: UIFont { let size = min(deviceFontSize, 18) return UIFont.systemFont(ofSize: size) } var LargeSizeRegularWeightAS: UIFont { let size = min(deviceFontSize + 2, 20) return UIFont.systemFont(ofSize: size) } var MediumSizeHeavyWeightAS: UIFont { let size = min(deviceFontSize + 2, 18) return UIFont.systemFont(ofSize: size, weight: UIFont.Weight.heavy) } var SmallSizeMediumWeightAS: UIFont { let size = min(defaultSmallFontSize, 14) return UIFont.systemFont(ofSize: size, weight: UIFont.Weight.medium) } var MediumSizeBoldFontAS: UIFont { let size = min(deviceFontSize, 18) return UIFont.boldSystemFont(ofSize: size) } var SmallSizeRegularWeightAS: UIFont { let size = min(defaultSmallFontSize, 14) return UIFont.systemFont(ofSize: size) } /** * Small */ fileprivate var defaultSmallFontSize: CGFloat var DefaultSmallFontSize: CGFloat { return defaultSmallFontSize } var DefaultSmallFont: UIFont { return UIFont.systemFont(ofSize: defaultSmallFontSize, weight: UIFont.Weight.regular) } var DefaultSmallFontBold: UIFont { return UIFont.boldSystemFont(ofSize: defaultSmallFontSize) } /** * Medium */ fileprivate var defaultMediumFontSize: CGFloat var DefaultMediumFontSize: CGFloat { return defaultMediumFontSize } var DefaultMediumFont: UIFont { return UIFont.systemFont(ofSize: defaultMediumFontSize, weight: UIFont.Weight.regular) } var DefaultMediumBoldFont: UIFont { return UIFont.boldSystemFont(ofSize: defaultMediumFontSize) } /** * Standard */ fileprivate var defaultStandardFontSize: CGFloat var DefaultStandardFontSize: CGFloat { return defaultStandardFontSize } var DefaultStandardFont: UIFont { return UIFont.systemFont(ofSize: defaultStandardFontSize, weight: UIFont.Weight.regular) } var DefaultStandardFontBold: UIFont { return UIFont.boldSystemFont(ofSize: defaultStandardFontSize) } /** * Reader mode */ var ReaderStandardFontSize: CGFloat { return defaultStandardFontSize - 2 } var ReaderBigFontSize: CGFloat { return defaultStandardFontSize + 5 } /** * Intro mode */ var IntroStandardFontSize: CGFloat { return min(defaultStandardFontSize - 1, 16) } var IntroBigFontSize: CGFloat { return min(defaultStandardFontSize + 1, 18) } func refreshFonts() { defaultStandardFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body).pointSize deviceFontSize = defaultStandardFontSize * (UIDevice.current.userInterfaceIdiom == .pad ? iPadFactor : iPhoneFactor) defaultMediumFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .footnote).pointSize defaultSmallFontSize = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .caption2).pointSize } @objc func contentSizeCategoryDidChange(_ notification: Notification) { refreshFonts() let notification = Notification(name: .DynamicFontChanged, object: nil) NotificationCenter.default.post(notification) } }
mpl-2.0
16a9e4c635c2272a3b3c1bf1f03ec892
32.865285
155
0.690942
5.232986
false
false
false
false
kmikiy/SpotMenu
MusicPlayer/Bridges/iTunesBridge/iTunesBridge.swift
1
39724
import AppKit import ScriptingBridge // MARK: iTunesEKnd @objc public enum iTunesEKnd : AEKeyword { case trackListing = 0x6b54726b /* 'kTrk' */ case albumListing = 0x6b416c62 /* 'kAlb' */ case cdInsert = 0x6b434469 /* 'kCDi' */ } // MARK: iTunesEnum @objc public enum iTunesEnum : AEKeyword { case standard = 0x6c777374 /* 'lwst' */ case detailed = 0x6c776474 /* 'lwdt' */ } // MARK: iTunesEPlS @objc public enum iTunesEPlS : AEKeyword { case stopped = 0x6b505353 /* 'kPSS' */ case playing = 0x6b505350 /* 'kPSP' */ case paused = 0x6b505370 /* 'kPSp' */ case fastForwarding = 0x6b505346 /* 'kPSF' */ case rewinding = 0x6b505352 /* 'kPSR' */ } // MARK: iTunesERpt @objc public enum iTunesERpt : AEKeyword { case off = 0x6b52704f /* 'kRpO' */ case one = 0x6b527031 /* 'kRp1' */ case all = 0x6b416c6c /* 'kAll' */ } // MARK: iTunesEShM @objc public enum iTunesEShM : AEKeyword { case songs = 0x6b536853 /* 'kShS' */ case albums = 0x6b536841 /* 'kShA' */ case groupings = 0x6b536847 /* 'kShG' */ } // MARK: iTunesEVSz @objc public enum iTunesEVSz : AEKeyword { case small = 0x6b565353 /* 'kVSS' */ case medium = 0x6b56534d /* 'kVSM' */ case large = 0x6b56534c /* 'kVSL' */ } // MARK: iTunesESrc @objc public enum iTunesESrc : AEKeyword { case library = 0x6b4c6962 /* 'kLib' */ case iPod = 0x6b506f64 /* 'kPod' */ case audioCD = 0x6b414344 /* 'kACD' */ case mp3CD = 0x6b4d4344 /* 'kMCD' */ case radioTuner = 0x6b54756e /* 'kTun' */ case sharedLibrary = 0x6b536864 /* 'kShd' */ case iTunesStore = 0x6b495453 /* 'kITS' */ case unknown = 0x6b556e6b /* 'kUnk' */ } // MARK: iTunesESrA @objc public enum iTunesESrA : AEKeyword { case albums = 0x6b53724c /* 'kSrL' */ case all = 0x6b416c6c /* 'kAll' */ case artists = 0x6b537252 /* 'kSrR' */ case composers = 0x6b537243 /* 'kSrC' */ case displayed = 0x6b537256 /* 'kSrV' */ case songs = 0x6b537253 /* 'kSrS' */ } // MARK: iTunesESpK @objc public enum iTunesESpK : AEKeyword { case none = 0x6b4e6f6e /* 'kNon' */ case books = 0x6b537041 /* 'kSpA' */ case folder = 0x6b537046 /* 'kSpF' */ case genius = 0x6b537047 /* 'kSpG' */ case iTunesU = 0x6b537055 /* 'kSpU' */ case library = 0x6b53704c /* 'kSpL' */ case movies = 0x6b537049 /* 'kSpI' */ case music = 0x6b53705a /* 'kSpZ' */ case podcasts = 0x6b537050 /* 'kSpP' */ case purchasedMusic = 0x6b53704d /* 'kSpM' */ case tvShows = 0x6b537054 /* 'kSpT' */ } // MARK: iTunesEMdK @objc public enum iTunesEMdK : AEKeyword { case alertTone = 0x6b4d644c /* 'kMdL' */ case audiobook = 0x6b4d6441 /* 'kMdA' */ case book = 0x6b4d6442 /* 'kMdB' */ case homeVideo = 0x6b4d6448 /* 'kMdH' */ case iTunesU = 0x6b4d6449 /* 'kMdI' */ case movie = 0x6b4d644d /* 'kMdM' */ case music = 0x6b4d6453 /* 'kMdS' */ case musicVideo = 0x6b4d6456 /* 'kMdV' */ case podcast = 0x6b4d6450 /* 'kMdP' */ case ringtone = 0x6b4d6452 /* 'kMdR' */ case tvShow = 0x6b4d6454 /* 'kMdT' */ case voiceMemo = 0x6b4d644f /* 'kMdO' */ case unknown = 0x6b556e6b /* 'kUnk' */ } // MARK: iTunesEVdK @objc public enum iTunesEVdK : AEKeyword { case none = 0x6b4e6f6e /* 'kNon' */ case homeVideo = 0x6b566448 /* 'kVdH' */ case movie = 0x6b56644d /* 'kVdM' */ case musicVideo = 0x6b566456 /* 'kVdV' */ case tvShow = 0x6b566454 /* 'kVdT' */ } // MARK: iTunesERtK @objc public enum iTunesERtK : AEKeyword { case user = 0x6b527455 /* 'kRtU' */ case computed = 0x6b527443 /* 'kRtC' */ } // MARK: iTunesEAPD @objc public enum iTunesEAPD : AEKeyword { case computer = 0x6b415043 /* 'kAPC' */ case airPortExpress = 0x6b415058 /* 'kAPX' */ case appleTV = 0x6b415054 /* 'kAPT' */ case airPlayDevice = 0x6b41504f /* 'kAPO' */ case unknown = 0x6b415055 /* 'kAPU' */ } // MARK: iTunesEClS @objc public enum iTunesEClS : AEKeyword { case unknown = 0x6b556e6b /* 'kUnk' */ case purchased = 0x6b507572 /* 'kPur' */ case matched = 0x6b4d6174 /* 'kMat' */ case uploaded = 0x6b55706c /* 'kUpl' */ case ineligible = 0x6b52656a /* 'kRej' */ case removed = 0x6b52656d /* 'kRem' */ case error = 0x6b457272 /* 'kErr' */ case duplicate = 0x6b447570 /* 'kDup' */ case subscription = 0x6b537562 /* 'kSub' */ case noLongerAvailable = 0x6b526576 /* 'kRev' */ case notUploaded = 0x6b557050 /* 'kUpP' */ } // MARK: iTunesGenericMethods @objc public protocol iTunesGenericMethods { @objc optional func printPrintDialog(_ printDialog: Bool, withProperties: iTunesPrintSettings!, kind: iTunesEKnd, theme: String!) // Print the specified object(s) @objc optional func close() // Close an object @objc optional func delete() // Delete an element from an object @objc optional func duplicateTo(_ to: SBObject!) -> SBObject // Duplicate one or more object(s) @objc optional func exists() -> Bool // Verify if an object exists @objc optional func `open`() // Open the specified object(s) @objc optional func save() // Save the specified object(s) @objc optional func playOnce(_ once: Bool) // play the current track or the specified track or file. @objc optional func select() // select the specified object(s) } // MARK: iTunesPrintSettings @objc public protocol iTunesPrintSettings: SBObjectProtocol, iTunesGenericMethods { @objc optional var copies: Int { get } // the number of copies of a document to be printed @objc optional var collating: Bool { get } // Should printed copies be collated? @objc optional var startingPage: Int { get } // the first page of the document to be printed @objc optional var endingPage: Int { get } // the last page of the document to be printed @objc optional var pagesAcross: Int { get } // number of logical pages laid across a physical page @objc optional var pagesDown: Int { get } // number of logical pages laid out down a physical page @objc optional var errorHandling: iTunesEnum { get } // how errors are handled @objc optional var requestedPrintTime: Date { get } // the time at which the desktop printer should print the document @objc optional var printerFeatures: [Any] { get } // printer specific options @objc optional var faxNumber: String { get } // for fax number @objc optional var targetPrinter: String { get } // for target printer } extension SBObject: iTunesPrintSettings {} // MARK: iTunesApplication @objc public protocol iTunesApplication: SBApplicationProtocol { @objc optional func AirPlayDevices() -> SBElementArray @objc optional func browserWindows() -> SBElementArray @objc optional func encoders() -> SBElementArray @objc optional func EQPresets() -> SBElementArray @objc optional func EQWindows() -> SBElementArray @objc optional func miniplayerWindows() -> SBElementArray @objc optional func playlistWindows() -> SBElementArray @objc optional func sources() -> SBElementArray @objc optional func videoWindows() -> SBElementArray @objc optional func visuals() -> SBElementArray @objc optional func windows() -> SBElementArray @objc optional var AirPlayEnabled: Bool { get } // is AirPlay currently enabled? @objc optional var converting: Bool { get } // is a track currently being converted? @objc optional var currentAirPlayDevices: [iTunesAirPlayDevice] { get } // the currently selected AirPlay device(s) @objc optional var currentEncoder: iTunesEncoder { get } // the currently selected encoder (MP3, AIFF, WAV, etc.) @objc optional var currentEQPreset: iTunesEQPreset { get } // the currently selected equalizer preset @objc optional var currentPlaylist: iTunesPlaylist { get } // the playlist containing the currently targeted track @objc optional var currentStreamTitle: String { get } // the name of the current song in the playing stream (provided by streaming server) @objc optional var currentStreamURL: String { get } // the URL of the playing stream or streaming web site (provided by streaming server) @objc optional var currentTrack: iTunesTrack { get } // the current targeted track @objc optional var currentVisual: iTunesVisual { get } // the currently selected visual plug-in @objc optional var EQEnabled: Bool { get } // is the equalizer enabled? @objc optional var fixedIndexing: Bool { get } // true if all AppleScript track indices should be independent of the play order of the owning playlist. @objc optional var frontmost: Bool { get } // is iTunes the frontmost application? @objc optional var fullScreen: Bool { get } // are visuals displayed using the entire screen? @objc optional var name: String { get } // the name of the application @objc optional var mute: Bool { get } // has the sound output been muted? @objc optional var playerPosition: Double { get } // the player’s position within the currently playing track in seconds. @objc optional var playerState: iTunesEPlS { get } // is iTunes stopped, paused, or playing? @objc optional var selection: SBObject { get } // the selection visible to the user @objc optional var shuffleEnabled: Bool { get } // are songs played in random order? @objc optional var shuffleMode: iTunesEShM { get } // the playback shuffle mode @objc optional var songRepeat: iTunesERpt { get } // the playback repeat mode @objc optional var soundVolume: Int { get } // the sound output volume (0 = minimum, 100 = maximum) @objc optional var version: String { get } // the version of iTunes @objc optional var visualsEnabled: Bool { get } // are visuals currently being displayed? @objc optional var visualSize: iTunesEVSz { get } // the size of the displayed visual @objc optional func printPrintDialog(_ printDialog: Bool, withProperties: iTunesPrintSettings!, kind: iTunesEKnd, theme: String!) // Print the specified object(s) @objc optional func run() // Run iTunes @objc optional func quit() // Quit iTunes @objc optional func add(_ x: [URL]!, to: SBObject!) -> iTunesTrack // add one or more files to a playlist @objc optional func backTrack() // reposition to beginning of current track or go to previous track if already at start of current track @objc optional func convert(_ x: [SBObject]!) -> iTunesTrack // convert one or more files or tracks @objc optional func eject() // eject the specified iPod @objc optional func fastForward() // skip forward in a playing track @objc optional func nextTrack() // advance to the next track in the current playlist @objc optional func pause() // pause playback @objc optional func playOnce(_ once: Bool) // play the current track or the specified track or file. @objc optional func playpause() // toggle the playing/paused state of the current track @objc optional func previousTrack() // return to the previous track in the current playlist @objc optional func resume() // disable fast forward/rewind and resume playback, if playing. @objc optional func rewind() // skip backwards in a playing track @objc optional func stop() // stop playback @objc optional func subscribe(_ x: String!) // subscribe to a podcast feed @objc optional func update() // update the specified iPod @objc optional func updateAllPodcasts() // update all subscribed podcast feeds @objc optional func updatePodcast() // update podcast feed @objc optional func openLocation(_ x: String!) // Opens a Music Store or audio stream URL @objc optional func setCurrentAirPlayDevices(_ currentAirPlayDevices: [iTunesAirPlayDevice]!) // the currently selected AirPlay device(s) @objc optional func setCurrentEncoder(_ currentEncoder: iTunesEncoder!) // the currently selected encoder (MP3, AIFF, WAV, etc.) @objc optional func setCurrentEQPreset(_ currentEQPreset: iTunesEQPreset!) // the currently selected equalizer preset @objc optional func setCurrentVisual(_ currentVisual: iTunesVisual!) // the currently selected visual plug-in @objc optional func setEQEnabled(_ EQEnabled: Bool) // is the equalizer enabled? @objc optional func setFixedIndexing(_ fixedIndexing: Bool) // true if all AppleScript track indices should be independent of the play order of the owning playlist. @objc optional func setFrontmost(_ frontmost: Bool) // is iTunes the frontmost application? @objc optional func setFullScreen(_ fullScreen: Bool) // are visuals displayed using the entire screen? @objc optional func setMute(_ mute: Bool) // has the sound output been muted? @objc optional func setPlayerPosition(_ playerPosition: Double) // the player’s position within the currently playing track in seconds. @objc optional func setShuffleEnabled(_ shuffleEnabled: Bool) // are songs played in random order? @objc optional func setShuffleMode(_ shuffleMode: iTunesEShM) // the playback shuffle mode @objc optional func setSongRepeat(_ songRepeat: iTunesERpt) // the playback repeat mode @objc optional func setSoundVolume(_ soundVolume: Int) // the sound output volume (0 = minimum, 100 = maximum) @objc optional func setVisualsEnabled(_ visualsEnabled: Bool) // are visuals currently being displayed? @objc optional func setVisualSize(_ visualSize: iTunesEVSz) // the size of the displayed visual } extension SBApplication: iTunesApplication {} // MARK: iTunesItem @objc public protocol iTunesItem: SBObjectProtocol, iTunesGenericMethods { @objc optional var container: SBObject { get } // the container of the item @objc optional func id() -> Int // the id of the item @objc optional var index: Int { get } // The index of the item in internal application order. @objc optional var name: String { get } // the name of the item @objc optional var persistentID: String { get } // the id of the item as a hexadecimal string. This id does not change over time. @objc optional var properties: [AnyHashable : Any] { get } // every property of the item @objc optional func download() // download a cloud track or playlist, or a podcast episode @objc optional func reveal() // reveal and select a track or playlist @objc optional func setName(_ name: String!) // the name of the item @objc optional func setProperties(_ properties: [AnyHashable : Any]!) // every property of the item } extension SBObject: iTunesItem {} // MARK: iTunesAirPlayDevice @objc public protocol iTunesAirPlayDevice: iTunesItem { @objc optional var active: Bool { get } // is the device currently being played to? @objc optional var available: Bool { get } // is the device currently available? @objc optional var kind: iTunesEAPD { get } // the kind of the device @objc optional var networkAddress: String { get } // the network (MAC) address of the device @objc optional func protected() -> Bool // is the device password- or passcode-protected? @objc optional var selected: Bool { get } // is the device currently selected? @objc optional var supportsAudio: Bool { get } // does the device support audio playback? @objc optional var supportsVideo: Bool { get } // does the device support video playback? @objc optional var soundVolume: Int { get } // the output volume for the device (0 = minimum, 100 = maximum) @objc optional func setSelected(_ selected: Bool) // is the device currently selected? @objc optional func setSoundVolume(_ soundVolume: Int) // the output volume for the device (0 = minimum, 100 = maximum) } extension SBObject: iTunesAirPlayDevice {} // MARK: iTunesArtwork @objc public protocol iTunesArtwork: iTunesItem { @objc optional var data: NSImage { get } // data for this artwork, in the form of a picture @objc optional var objectDescription: String { get } // description of artwork as a string @objc optional var downloaded: Bool { get } // was this artwork downloaded by iTunes? @objc optional var format: NSNumber { get } // the data format for this piece of artwork @objc optional var kind: Int { get } // kind or purpose of this piece of artwork @objc optional var rawData: Data { get } // data for this artwork, in original format @objc optional func setData(_ data: NSImage!) // data for this artwork, in the form of a picture @objc optional func setObjectDescription(_ objectDescription: String!) // description of artwork as a string @objc optional func setKind(_ kind: Int) // kind or purpose of this piece of artwork @objc optional func setRawData(_ rawData: Data!) // data for this artwork, in original format } extension SBObject: iTunesArtwork {} // MARK: iTunesEncoder @objc public protocol iTunesEncoder: iTunesItem { @objc optional var format: String { get } // the data format created by the encoder } extension SBObject: iTunesEncoder {} // MARK: iTunesEQPreset @objc public protocol iTunesEQPreset: iTunesItem { @objc optional var band1: Double { get } // the equalizer 32 Hz band level (-12.0 dB to +12.0 dB) @objc optional var band2: Double { get } // the equalizer 64 Hz band level (-12.0 dB to +12.0 dB) @objc optional var band3: Double { get } // the equalizer 125 Hz band level (-12.0 dB to +12.0 dB) @objc optional var band4: Double { get } // the equalizer 250 Hz band level (-12.0 dB to +12.0 dB) @objc optional var band5: Double { get } // the equalizer 500 Hz band level (-12.0 dB to +12.0 dB) @objc optional var band6: Double { get } // the equalizer 1 kHz band level (-12.0 dB to +12.0 dB) @objc optional var band7: Double { get } // the equalizer 2 kHz band level (-12.0 dB to +12.0 dB) @objc optional var band8: Double { get } // the equalizer 4 kHz band level (-12.0 dB to +12.0 dB) @objc optional var band9: Double { get } // the equalizer 8 kHz band level (-12.0 dB to +12.0 dB) @objc optional var band10: Double { get } // the equalizer 16 kHz band level (-12.0 dB to +12.0 dB) @objc optional var modifiable: Bool { get } // can this preset be modified? @objc optional var preamp: Double { get } // the equalizer preamp level (-12.0 dB to +12.0 dB) @objc optional var updateTracks: Bool { get } // should tracks which refer to this preset be updated when the preset is renamed or deleted? @objc optional func setBand1(_ band1: Double) // the equalizer 32 Hz band level (-12.0 dB to +12.0 dB) @objc optional func setBand2(_ band2: Double) // the equalizer 64 Hz band level (-12.0 dB to +12.0 dB) @objc optional func setBand3(_ band3: Double) // the equalizer 125 Hz band level (-12.0 dB to +12.0 dB) @objc optional func setBand4(_ band4: Double) // the equalizer 250 Hz band level (-12.0 dB to +12.0 dB) @objc optional func setBand5(_ band5: Double) // the equalizer 500 Hz band level (-12.0 dB to +12.0 dB) @objc optional func setBand6(_ band6: Double) // the equalizer 1 kHz band level (-12.0 dB to +12.0 dB) @objc optional func setBand7(_ band7: Double) // the equalizer 2 kHz band level (-12.0 dB to +12.0 dB) @objc optional func setBand8(_ band8: Double) // the equalizer 4 kHz band level (-12.0 dB to +12.0 dB) @objc optional func setBand9(_ band9: Double) // the equalizer 8 kHz band level (-12.0 dB to +12.0 dB) @objc optional func setBand10(_ band10: Double) // the equalizer 16 kHz band level (-12.0 dB to +12.0 dB) @objc optional func setPreamp(_ preamp: Double) // the equalizer preamp level (-12.0 dB to +12.0 dB) @objc optional func setUpdateTracks(_ updateTracks: Bool) // should tracks which refer to this preset be updated when the preset is renamed or deleted? } extension SBObject: iTunesEQPreset {} // MARK: iTunesPlaylist @objc public protocol iTunesPlaylist: iTunesItem { @objc optional func tracks() -> SBElementArray @objc optional func artworks() -> SBElementArray @objc optional var objectDescription: String { get } // the description of the playlist @objc optional var duration: Int { get } // the total length of all songs (in seconds) @objc optional var name: String { get } // the name of the playlist @objc optional var loved: Bool { get } // is this playlist loved? @objc optional var parent: iTunesPlaylist { get } // folder which contains this playlist (if any) @objc optional var size: Int { get } // the total size of all songs (in bytes) @objc optional var specialKind: iTunesESpK { get } // special playlist kind @objc optional var time: String { get } // the length of all songs in MM:SS format @objc optional var visible: Bool { get } // is this playlist visible in the Source list? @objc optional func moveTo(_ to: SBObject!) // Move playlist(s) to a new location @objc optional func searchFor(_ for_: String!, only: iTunesESrA) -> iTunesTrack // search a playlist for tracks matching the search string. Identical to entering search text in the Search field in iTunes. @objc optional func setObjectDescription(_ objectDescription: String!) // the description of the playlist @objc optional func setName(_ name: String!) // the name of the playlist @objc optional func setLoved(_ loved: Bool) // is this playlist loved? } extension SBObject: iTunesPlaylist {} // MARK: iTunesAudioCDPlaylist @objc public protocol iTunesAudioCDPlaylist: iTunesPlaylist { @objc optional func audioCDTracks() -> SBElementArray @objc optional var artist: String { get } // the artist of the CD @objc optional var compilation: Bool { get } // is this CD a compilation album? @objc optional var composer: String { get } // the composer of the CD @objc optional var discCount: Int { get } // the total number of discs in this CD’s album @objc optional var discNumber: Int { get } // the index of this CD disc in the source album @objc optional var genre: String { get } // the genre of the CD @objc optional var year: Int { get } // the year the album was recorded/released @objc optional func setArtist(_ artist: String!) // the artist of the CD @objc optional func setCompilation(_ compilation: Bool) // is this CD a compilation album? @objc optional func setComposer(_ composer: String!) // the composer of the CD @objc optional func setDiscCount(_ discCount: Int) // the total number of discs in this CD’s album @objc optional func setDiscNumber(_ discNumber: Int) // the index of this CD disc in the source album @objc optional func setGenre(_ genre: String!) // the genre of the CD @objc optional func setYear(_ year: Int) // the year the album was recorded/released } extension SBObject: iTunesAudioCDPlaylist {} // MARK: iTunesLibraryPlaylist @objc public protocol iTunesLibraryPlaylist: iTunesPlaylist { @objc optional func fileTracks() -> SBElementArray @objc optional func URLTracks() -> SBElementArray @objc optional func sharedTracks() -> SBElementArray } extension SBObject: iTunesLibraryPlaylist {} // MARK: iTunesRadioTunerPlaylist @objc public protocol iTunesRadioTunerPlaylist: iTunesPlaylist { @objc optional func URLTracks() -> SBElementArray } extension SBObject: iTunesRadioTunerPlaylist {} // MARK: iTunesSource @objc public protocol iTunesSource: iTunesItem { @objc optional func audioCDPlaylists() -> SBElementArray @objc optional func libraryPlaylists() -> SBElementArray @objc optional func playlists() -> SBElementArray @objc optional func radioTunerPlaylists() -> SBElementArray @objc optional func subscriptionPlaylists() -> SBElementArray @objc optional func userPlaylists() -> SBElementArray @objc optional var capacity: Int64 { get } // the total size of the source if it has a fixed size @objc optional var freeSpace: Int64 { get } // the free space on the source if it has a fixed size @objc optional var kind: iTunesESrc { get } @objc optional func eject() // eject the specified iPod @objc optional func update() // update the specified iPod } extension SBObject: iTunesSource {} // MARK: iTunesSubscriptionPlaylist @objc public protocol iTunesSubscriptionPlaylist: iTunesPlaylist { @objc optional func fileTracks() -> SBElementArray @objc optional func URLTracks() -> SBElementArray } extension SBObject: iTunesSubscriptionPlaylist {} // MARK: iTunesTrack @objc public protocol iTunesTrack: iTunesItem { @objc optional func artworks() -> SBElementArray @objc optional var album: String { get } // the album name of the track @objc optional var albumArtist: String { get } // the album artist of the track @objc optional var albumLoved: Bool { get } // is the album for this track loved? @objc optional var albumRating: Int { get } // the rating of the album for this track (0 to 100) @objc optional var albumRatingKind: iTunesERtK { get } // the rating kind of the album rating for this track @objc optional var artist: String { get } // the artist/source of the track @objc optional var bitRate: Int { get } // the bit rate of the track (in kbps) @objc optional var bookmark: Double { get } // the bookmark time of the track in seconds @objc optional var bookmarkable: Bool { get } // is the playback position for this track remembered? @objc optional var bpm: Int { get } // the tempo of this track in beats per minute @objc optional var category: String { get } // the category of the track @objc optional var cloudStatus: iTunesEClS { get } // the iCloud status of the track @objc optional var comment: String { get } // freeform notes about the track @objc optional var compilation: Bool { get } // is this track from a compilation album? @objc optional var composer: String { get } // the composer of the track @objc optional var databaseID: Int { get } // the common, unique ID for this track. If two tracks in different playlists have the same database ID, they are sharing the same data. @objc optional var dateAdded: Date { get } // the date the track was added to the playlist @objc optional var objectDescription: String { get } // the description of the track @objc optional var discCount: Int { get } // the total number of discs in the source album @objc optional var discNumber: Int { get } // the index of the disc containing this track on the source album @objc optional var downloaderAppleID: String { get } // the Apple ID of the person who downloaded this track @objc optional var downloaderName: String { get } // the name of the person who downloaded this track @objc optional var duration: Double { get } // the length of the track in seconds @objc optional var enabled: Bool { get } // is this track checked for playback? @objc optional var episodeID: String { get } // the episode ID of the track @objc optional var episodeNumber: Int { get } // the episode number of the track @objc optional var EQ: String { get } // the name of the EQ preset of the track @objc optional var finish: Double { get } // the stop time of the track in seconds @objc optional var gapless: Bool { get } // is this track from a gapless album? @objc optional var genre: String { get } // the music/audio genre (category) of the track @objc optional var grouping: String { get } // the grouping (piece) of the track. Generally used to denote movements within a classical work. @objc optional var kind: String { get } // a text description of the track @objc optional var longDescription: String { get } @objc optional var loved: Bool { get } // is this track loved? @objc optional var lyrics: String { get } // the lyrics of the track @objc optional var mediaKind: iTunesEMdK { get } // the media kind of the track @objc optional var modificationDate: Date { get } // the modification date of the content of this track @objc optional var playedCount: Int { get } // number of times this track has been played @objc optional var playedDate: Date { get } // the date and time this track was last played @objc optional var purchaserAppleID: String { get } // the Apple ID of the person who purchased this track @objc optional var purchaserName: String { get } // the name of the person who purchased this track @objc optional var rating: Int { get } // the rating of this track (0 to 100) @objc optional var ratingKind: iTunesERtK { get } // the rating kind of this track @objc optional var releaseDate: Date { get } // the release date of this track @objc optional var sampleRate: Int { get } // the sample rate of the track (in Hz) @objc optional var seasonNumber: Int { get } // the season number of the track @objc optional var shufflable: Bool { get } // is this track included when shuffling? @objc optional var skippedCount: Int { get } // number of times this track has been skipped @objc optional var skippedDate: Date { get } // the date and time this track was last skipped @objc optional var show: String { get } // the show name of the track @objc optional var sortAlbum: String { get } // override string to use for the track when sorting by album @objc optional var sortArtist: String { get } // override string to use for the track when sorting by artist @objc optional var sortAlbumArtist: String { get } // override string to use for the track when sorting by album artist @objc optional var sortName: String { get } // override string to use for the track when sorting by name @objc optional var sortComposer: String { get } // override string to use for the track when sorting by composer @objc optional var sortShow: String { get } // override string to use for the track when sorting by show name @objc optional var size: Int64 { get } // the size of the track (in bytes) @objc optional var start: Double { get } // the start time of the track in seconds @objc optional var time: String { get } // the length of the track in MM:SS format @objc optional var trackCount: Int { get } // the total number of tracks on the source album @objc optional var trackNumber: Int { get } // the index of the track on the source album @objc optional var unplayed: Bool { get } // is this track unplayed? @objc optional var videoKind: iTunesEVdK { get } // kind of video track @objc optional var volumeAdjustment: Int { get } // relative volume adjustment of the track (-100% to 100%) @objc optional var year: Int { get } // the year the track was recorded/released @objc optional func setAlbum(_ album: String!) // the album name of the track @objc optional func setAlbumArtist(_ albumArtist: String!) // the album artist of the track @objc optional func setAlbumLoved(_ albumLoved: Bool) // is the album for this track loved? @objc optional func setAlbumRating(_ albumRating: Int) // the rating of the album for this track (0 to 100) @objc optional func setArtist(_ artist: String!) // the artist/source of the track @objc optional func setBookmark(_ bookmark: Double) // the bookmark time of the track in seconds @objc optional func setBookmarkable(_ bookmarkable: Bool) // is the playback position for this track remembered? @objc optional func setBpm(_ bpm: Int) // the tempo of this track in beats per minute @objc optional func setCategory(_ category: String!) // the category of the track @objc optional func setComment(_ comment: String!) // freeform notes about the track @objc optional func setCompilation(_ compilation: Bool) // is this track from a compilation album? @objc optional func setComposer(_ composer: String!) // the composer of the track @objc optional func setObjectDescription(_ objectDescription: String!) // the description of the track @objc optional func setDiscCount(_ discCount: Int) // the total number of discs in the source album @objc optional func setDiscNumber(_ discNumber: Int) // the index of the disc containing this track on the source album @objc optional func setEnabled(_ enabled: Bool) // is this track checked for playback? @objc optional func setEpisodeID(_ episodeID: String!) // the episode ID of the track @objc optional func setEpisodeNumber(_ episodeNumber: Int) // the episode number of the track @objc optional func setEQ(_ EQ: String!) // the name of the EQ preset of the track @objc optional func setFinish(_ finish: Double) // the stop time of the track in seconds @objc optional func setGapless(_ gapless: Bool) // is this track from a gapless album? @objc optional func setGenre(_ genre: String!) // the music/audio genre (category) of the track @objc optional func setGrouping(_ grouping: String!) // the grouping (piece) of the track. Generally used to denote movements within a classical work. @objc optional func setLongDescription(_ longDescription: String!) @objc optional func setLoved(_ loved: Bool) // is this track loved? @objc optional func setLyrics(_ lyrics: String!) // the lyrics of the track @objc optional func setMediaKind(_ mediaKind: iTunesEMdK) // the media kind of the track @objc optional func setPlayedCount(_ playedCount: Int) // number of times this track has been played @objc optional func setPlayedDate(_ playedDate: Date!) // the date and time this track was last played @objc optional func setRating(_ rating: Int) // the rating of this track (0 to 100) @objc optional func setSeasonNumber(_ seasonNumber: Int) // the season number of the track @objc optional func setShufflable(_ shufflable: Bool) // is this track included when shuffling? @objc optional func setSkippedCount(_ skippedCount: Int) // number of times this track has been skipped @objc optional func setSkippedDate(_ skippedDate: Date!) // the date and time this track was last skipped @objc optional func setShow(_ show: String!) // the show name of the track @objc optional func setSortAlbum(_ sortAlbum: String!) // override string to use for the track when sorting by album @objc optional func setSortArtist(_ sortArtist: String!) // override string to use for the track when sorting by artist @objc optional func setSortAlbumArtist(_ sortAlbumArtist: String!) // override string to use for the track when sorting by album artist @objc optional func setSortName(_ sortName: String!) // override string to use for the track when sorting by name @objc optional func setSortComposer(_ sortComposer: String!) // override string to use for the track when sorting by composer @objc optional func setSortShow(_ sortShow: String!) // override string to use for the track when sorting by show name @objc optional func setStart(_ start: Double) // the start time of the track in seconds @objc optional func setTrackCount(_ trackCount: Int) // the total number of tracks on the source album @objc optional func setTrackNumber(_ trackNumber: Int) // the index of the track on the source album @objc optional func setUnplayed(_ unplayed: Bool) // is this track unplayed? @objc optional func setVideoKind(_ videoKind: iTunesEVdK) // kind of video track @objc optional func setVolumeAdjustment(_ volumeAdjustment: Int) // relative volume adjustment of the track (-100% to 100%) @objc optional func setYear(_ year: Int) // the year the track was recorded/released } extension SBObject: iTunesTrack {} // MARK: iTunesAudioCDTrack @objc public protocol iTunesAudioCDTrack: iTunesTrack { @objc optional var location: URL { get } // the location of the file represented by this track } extension SBObject: iTunesAudioCDTrack {} // MARK: iTunesFileTrack @objc public protocol iTunesFileTrack: iTunesTrack { @objc optional var location: URL { get } // the location of the file represented by this track @objc optional func refresh() // update file track information from the current information in the track’s file @objc optional func setLocation(_ location: URL!) // the location of the file represented by this track } extension SBObject: iTunesFileTrack {} // MARK: iTunesSharedTrack @objc public protocol iTunesSharedTrack: iTunesTrack { } extension SBObject: iTunesSharedTrack {} // MARK: iTunesURLTrack @objc public protocol iTunesURLTrack: iTunesTrack { @objc optional var address: String { get } // the URL for this track @objc optional func setAddress(_ address: String!) // the URL for this track } extension SBObject: iTunesURLTrack {} // MARK: iTunesUserPlaylist @objc public protocol iTunesUserPlaylist: iTunesPlaylist { @objc optional func fileTracks() -> SBElementArray @objc optional func URLTracks() -> SBElementArray @objc optional func sharedTracks() -> SBElementArray @objc optional var shared: Bool { get } // is this playlist shared? @objc optional var smart: Bool { get } // is this a Smart Playlist? @objc optional var genius: Bool { get } // is this a Genius Playlist? @objc optional func setShared(_ shared: Bool) // is this playlist shared? } extension SBObject: iTunesUserPlaylist {} // MARK: iTunesFolderPlaylist @objc public protocol iTunesFolderPlaylist: iTunesUserPlaylist { } extension SBObject: iTunesFolderPlaylist {} // MARK: iTunesVisual @objc public protocol iTunesVisual: iTunesItem { } extension SBObject: iTunesVisual {} // MARK: iTunesWindow @objc public protocol iTunesWindow: iTunesItem { @objc optional var bounds: NSRect { get } // the boundary rectangle for the window @objc optional var closeable: Bool { get } // does the window have a close button? @objc optional var collapseable: Bool { get } // does the window have a collapse button? @objc optional var collapsed: Bool { get } // is the window collapsed? @objc optional var fullScreen: Bool { get } // is the window full screen? @objc optional var position: NSPoint { get } // the upper left position of the window @objc optional var resizable: Bool { get } // is the window resizable? @objc optional var visible: Bool { get } // is the window visible? @objc optional var zoomable: Bool { get } // is the window zoomable? @objc optional var zoomed: Bool { get } // is the window zoomed? @objc optional func setBounds(_ bounds: NSRect) // the boundary rectangle for the window @objc optional func setCollapsed(_ collapsed: Bool) // is the window collapsed? @objc optional func setFullScreen(_ fullScreen: Bool) // is the window full screen? @objc optional func setPosition(_ position: NSPoint) // the upper left position of the window @objc optional func setVisible(_ visible: Bool) // is the window visible? @objc optional func setZoomed(_ zoomed: Bool) // is the window zoomed? } extension SBObject: iTunesWindow {} // MARK: iTunesBrowserWindow @objc public protocol iTunesBrowserWindow: iTunesWindow { @objc optional var selection: SBObject { get } // the selected songs @objc optional var view: iTunesPlaylist { get } // the playlist currently displayed in the window @objc optional func setView(_ view: iTunesPlaylist!) // the playlist currently displayed in the window } extension SBObject: iTunesBrowserWindow {} // MARK: iTunesEQWindow @objc public protocol iTunesEQWindow: iTunesWindow { } extension SBObject: iTunesEQWindow {} // MARK: iTunesMiniplayerWindow @objc public protocol iTunesMiniplayerWindow: iTunesWindow { } extension SBObject: iTunesMiniplayerWindow {} // MARK: iTunesPlaylistWindow @objc public protocol iTunesPlaylistWindow: iTunesWindow { @objc optional var selection: SBObject { get } // the selected songs @objc optional var view: iTunesPlaylist { get } // the playlist displayed in the window } extension SBObject: iTunesPlaylistWindow {} // MARK: iTunesVideoWindow @objc public protocol iTunesVideoWindow: iTunesWindow { } extension SBObject: iTunesVideoWindow {}
mit
6a6466dfff585475e9bcce3bacde61d1
62.5424
208
0.712847
4.160277
false
false
false
false
AntonTheDev/XCode-DI-Templates
Source/FileTemplates-tvOS/Transitioning Container VC.xctemplate/___FILEBASENAME___.swift
1
3072
// // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. //___COPYRIGHT___ // import Foundation import UIKit /* Add the following in the registerViewControllers() method of the Services class. viewControllerContainer.register(___FILEBASENAME___.self) { _ in ___FILEBASENAME___(container: self.viewControllerContainer) } .initCompleted { (r, controller) in // controller.setActiveViewController = .... } */ @objc protocol ___FILEBASENAME___Delegate : class { @objc func containerViewController(_ containerViewController : ___FILEBASENAME___, didSelectViewController : UIViewController) @objc optional func containerViewController(_ containerViewController: ___FILEBASENAME___, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? } class ___FILEBASENAME___ : BaseViewController { weak var delegate : ___FILEBASENAME___Delegate? fileprivate var activeViewController: BaseViewController? { didSet { activeViewController?.view.frame = view.bounds self.animate(fromVC: oldValue, toVC: activeViewController!) } } func setActiveViewController(viewController : BaseViewController) { activeViewController = viewController } func animate(fromVC : BaseViewController?, toVC : BaseViewController) { if fromVC != toVC { fromVC?.willMove(toParentViewController: nil) addChildViewController(activeViewController!) } if fromVC == nil { view.addSubview(activeViewController!.view) activeViewController?.didMove(toParentViewController: self) return } guard let fromVC = fromVC else { return } guard let animator = delegate?.containerViewController!(self, animationControllerForTransitionFrom: fromVC, to: toVC) else { view.addSubview(activeViewController!.view) activeViewController?.didMove(toParentViewController: self) return } let transitioningContext = ContainerTransitioningContext(withFromViewController: fromVC, toViewController: activeViewController!, rightDirection: true) transitioningContext.isAnimated = true transitioningContext.isInteractive = false transitioningContext.setCompletion {[unowned self] (complete) in fromVC.view.removeFromSuperview() fromVC.removeFromParentViewController() self.activeViewController?.didMove(toParentViewController: self) self.delegate = self.activeViewController as? ___FILEBASENAME___Delegate } animator.animateTransition(using: transitioningContext) } }
mit
f2f1667d1e3c5bee2a10ca590282fc24
35.571429
134
0.626628
6.62069
false
false
false
false
google/GoogleDataTransport
GoogleDataTransport/GDTWatchOSTestApp/GDTWatchOSTestAppWatchKitExtension/InterfaceController.swift
1
2653
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import WatchKit import Foundation import Dispatch import GoogleDataTransport class InterfaceController: WKInterfaceController { let transport = GDTCORTransport(mappingID: "1234", transformers: nil, target: GDTCORTarget.test)! override func awake(withContext context: Any?) { super.awake(withContext: context) // Configure interface objects here. } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } @IBAction func generateDataEvent(sender: AnyObject?) { print("Generating data event") let event: GDTCOREvent = transport.eventForTransport() event.dataObject = TestDataObject() transport.sendDataEvent(event) } @IBAction func generateTelemetryEvent(sender: AnyObject?) { print("Generating telemetry event") let event: GDTCOREvent = transport.eventForTransport() event.dataObject = TestDataObject() transport.sendTelemetryEvent(event) } @IBAction func generateHighPriorityEvent(sender: AnyObject?) { print("Generating high priority event") let event: GDTCOREvent = transport.eventForTransport() event.dataObject = TestDataObject() event.qosTier = GDTCOREventQoS.qoSFast transport.sendDataEvent(event) } @IBAction func generateWifiOnlyEvent(sender: AnyObject?) { print("Generating wifi only event") let event: GDTCOREvent = transport.eventForTransport() event.dataObject = TestDataObject() event.qosTier = GDTCOREventQoS.qoSWifiOnly transport.sendDataEvent(event) } @IBAction func generateDailyEvent(sender: AnyObject?) { print("Generating daily event") let event: GDTCOREvent = transport.eventForTransport() event.dataObject = TestDataObject() event.qosTier = GDTCOREventQoS.qoSDaily transport.sendDataEvent(event) } } class TestDataObject: NSObject, GDTCOREventDataObject { func transportBytes() -> Data { return "Normally, some SDK's data object would populate this. \(Date())" .data(using: String.Encoding.utf8)! } }
apache-2.0
badb50aeb755b9fa0de0e71b95cc947c
32.1625
99
0.740671
4.638112
false
true
false
false
xuech/OMS-WH
OMS-WH/Utilities/Extensions/UIButton+Category.swift
1
4554
// // UIButton+Category.swift // MaiLuo // // Created by xuech on 16/6/15. // Copyright © 2016年 obizsoft. All rights reserved. // import UIKit extension UIButton{ enum ImagePosition { case left case right case top case bottom } convenience init(imageName:String,fontSize: CGFloat,color: UIColor,title:String,bgColor:UIColor) { self.init() self.setTitle(title, for: UIControlState()) self.setImage(UIImage(named: imageName), for: UIControlState()) self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize) self.setTitleColor(color, for: UIControlState()) self.contentMode = .scaleAspectFit self.backgroundColor = bgColor } ///快速生产一个不带背景图的按钮 /// /// - Parameters: /// - title: 按钮文字 /// - titleColor: 按钮颜色 /// - target: 按钮的事件 /// - action: action convenience init(_ title: String?, titleColor: UIColor?, target: AnyObject?, action: Selector,needLayer:Bool?=false) { self.init() self.setTitle(title, for: UIControlState()) self.titleLabel?.font = UIFont.systemFont(ofSize: 14) if needLayer! { self.layer.borderWidth = 1 self.layer.borderColor = titleColor?.cgColor self.layer.masksToBounds = true self.layer.cornerRadius = 6 } self.setTitleColor(titleColor, for: UIControlState()) // self.setImage(UIImage(named: imageName), for: UIControlState()) // self.setImage(UIImage(named: imageName + "_highlighted"), for: UIControlState.highlighted) self.addTarget(target, action: action, for: UIControlEvents.touchUpInside) } /// 调整图片位置,返回调整后所需要的size /// 调用本方法前,请先确保imageView和titleLabel有值。 @discardableResult func adjustImage(position: ImagePosition, spacing: CGFloat) -> CGSize { guard imageView != nil && titleLabel != nil else { return CGSize.zero } let imageSize = self.imageView!.intrinsicContentSize let titleSize = self.titleLabel!.intrinsicContentSize // 布局 switch (position) { case .left: imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: spacing / 2) titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: -spacing / 2) contentEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: spacing / 2) case .right: imageEdgeInsets = UIEdgeInsets(top: 0, left: (titleSize.width + spacing / 2), bottom: 0, right: -(titleSize.width + spacing / 2)) titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageSize.width + spacing / 2), bottom: 0, right: (imageSize.width + spacing / 2)) contentEdgeInsets = UIEdgeInsetsMake(0, spacing / 2, 0, spacing / 2); case .top, .bottom: let imageOffsetX = (imageSize.width + titleSize.width) / 2 - imageSize.width / 2 let imageOffsetY = imageSize.height / 2 + spacing / 2 let titleOffsetX = (imageSize.width + titleSize.width / 2) - (imageSize.width + titleSize.width) / 2 let titleOffsetY = titleSize.height / 2 + spacing / 2 let changedWidth = titleSize.width + imageSize.width - max(titleSize.width, imageSize.width) let changedHeight = titleSize.height + imageSize.height + spacing - max(imageSize.height, imageSize.height) if position == .top { imageEdgeInsets = UIEdgeInsets(top: -imageOffsetY, left: imageOffsetX, bottom: imageOffsetY, right: -imageOffsetX) titleEdgeInsets = UIEdgeInsets(top: titleOffsetY, left: -titleOffsetX, bottom: -titleOffsetY, right: titleOffsetX) self.contentEdgeInsets = UIEdgeInsetsMake(imageOffsetY, -changedWidth / 2, changedHeight - imageOffsetY, -changedWidth / 2); } else { imageEdgeInsets = UIEdgeInsets(top: imageOffsetY, left: imageOffsetX, bottom: -imageOffsetY, right: -imageOffsetX) titleEdgeInsets = UIEdgeInsets(top: -titleOffsetY, left: -titleOffsetX, bottom: titleOffsetY, right: titleOffsetX) self.contentEdgeInsets = UIEdgeInsetsMake(changedHeight - imageOffsetY, -changedWidth / 2, imageOffsetY, -changedWidth / 2); } } return self.intrinsicContentSize } }
mit
aac5cd64dde303457957e5ee6bf72eff
44.214286
141
0.630783
4.544615
false
false
false
false
myTargetSDK/mytarget-ios
myTargetDemoSwift/myTargetDemo/Views/PlayerAdButton.swift
1
1435
// // PlayerAdButton.swift // myTargetDemo // // Created by Alexander Vorobyev on 22.08.2022. // Copyright © 2022 Mail.ru Group. All rights reserved. // import UIKit final class PlayerAdButton: UIButton { init(title: String) { super.init(frame: .zero) setTitle(title, for: .normal) setup() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard #available(iOS 13.0, *), traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) else { return } layer.borderColor = UIColor.foregroundColor().cgColor } private func setup() { backgroundColor = .backgroundColor().withAlphaComponent(0.3) layer.borderColor = UIColor.foregroundColor().cgColor layer.borderWidth = 1 layer.cornerRadius = 4 setTitleColor(.foregroundColor(), for: .normal) setTitleColor(.disabledColor(), for: .disabled) titleLabel?.font = UIFont.systemFont(ofSize: 12) titleLabel?.lineBreakMode = .byTruncatingTail contentEdgeInsets = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8) } }
lgpl-3.0
f9b1a5c335ba27069c3b15094655adba
28.875
126
0.642259
4.979167
false
false
false
false
colbylwilliams/bugtrap
iOS/Code/Swift/bugTrap/bugTrapKit/Controllers/TableViewControllers/BtNewBugDetailsTableViewController.swift
1
15547
// // BtNewBugDetailsTableViewController.swift // bugTrap // // Created by Colby L Williams on 6/30/14. // Copyright (c) 2014 bugTrap. All rights reserved. // import UIKit import Photos class BtNewBugDetailsTableViewController : BtTableViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var saveButton: UIBarButtonItem! @IBOutlet var submitButton: UIBarButtonItem! @IBOutlet var cancelButton: UIBarButtonItem! @IBOutlet var activityButton: UIBarButtonItem! @IBOutlet var activityIndicator: UIActivityIndicatorView! let scale = UIScreen.mainScreen().scale let cellSize = CGSize(width: 125, height: 125) var thumbSize = CGSize.zeroSize var didAssignTitleFirstResponder = false //index path will be updated to the date picker cell when it's selected var datePickerIndexPath : NSIndexPath! var datePickerCellOpen: Bool = false { didSet { tableView.reloadSections(NSIndexSet(index: datePickerIndexPath.section), withRowAnimation: .Automatic) } } var assetsFetchResults: PHFetchResult? var imageRequests: [Int: PHImageRequestID] = [:] var options = PHFetchOptions() override func viewDidLoad() { super.viewDidLoad() if let tracker = TrackerService.Shared.currentTracker { screenName = "\(GAIKeys.ScreenNames.bugDetails) (\(tracker.type.rawValue))" } thumbSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale) options.sortDescriptors = [ NSSortDescriptor(key: "modificationDate", ascending: false) ] assetsFetchResults = PHAsset.fetchAssetsWithLocalIdentifiers(TrapState.Shared.getLocalIdentifiersForActiveSnapshots(), options: self.options) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController!.hidesBarsOnTap = false if !isMovingToParentViewController() { if let state = TrackerService.Shared.currentTracker?.trackerState { tableView.reloadSections(NSIndexSet(index: state.ActiveBugDetail), withRowAnimation: .Automatic) } assetsFetchResults = PHAsset.fetchAssetsWithLocalIdentifiers(TrapState.Shared.getLocalIdentifiersForActiveSnapshots(), options: self.options) reloadEmbeddedImageCollectinView() } } func reloadEmbeddedImageCollectinView() { if TrapState.Shared.hasSnapshotImages { if let imageCell = (tableView.visibleCells.filter({$0 as? BtEmbeddedImageCollectionViewTableViewCell != nil})).first as? BtEmbeddedImageCollectionViewTableViewCell { imageCell.reloadCollectionView() } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) validateBugDetails() if let state = TrackerService.Shared.currentTracker?.trackerState { if state.IsActiveTopLevelDetail && state.hasProject { if let textFieldCell = (tableView.visibleCells.filter({$0 as? BtTextFieldTableViewCell != nil})).first as? BtTextFieldTableViewCell { didAssignTitleFirstResponder = textFieldCell.textFieldShouldBecomeFirstResponder() } } } } override func canBecomeFirstResponder() -> Bool { return true } override func becomeFirstResponder() -> Bool { validateBugDetails() if didAssignTitleFirstResponder { didAssignTitleFirstResponder = false if let textViewCell = (tableView.visibleCells.filter({$0 as? BtTextViewTableViewCell != nil})).first as? BtTextViewTableViewCell { tableView.scrollRectToVisible(tableView.rectForRowAtIndexPath(tableView.indexPathForCell(textViewCell)!), animated: true) textViewCell.textViewShouldBecomeFirstResponder() } } return true } // MARK: Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { if let details = TrackerService.Shared.currentTracker?.TrackerDetails { return details.count } return 0 } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { if let isDate = TrackerService.Shared.currentTracker?.TrackerDetails[section]?.isDate() { return isDate && datePickerCellOpen ? 2 : 1 } return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.row > 0 { return tableView.dequeueReusableCellWithIdentifier(BugDetails.DetailType.DatePicker(NSDate(), "Date").cellId(), forIndexPath: indexPath) as! BtNewBugDetailsTableViewCell } if let tracker = TrackerService.Shared.currentTracker { if let cellValue = tracker.TrackerDetails[indexPath.section] { let value = tracker.trackerState.getValueForDetail(indexPath.section) let cell = tableView.dequeueReusableCellWithIdentifier(cellValue.cellId(), forIndexPath: indexPath) as! BtNewBugDetailsTableViewCell switch cellValue { case .Images: cell.setData() case let .Selection (label, title): cell.setData(title, detail: value, auxiliary: label) case let .TextField (label, title): cell.setData(title, detail: value, auxiliary: label) case let .TextView (label, title): cell.setData(title, detail: value, auxiliary: label) case let .DateDisplay (label, title): cell.setData(title, detail: value, auxiliary: label) case let .DatePicker (_, label): cell.setData(label) } return cell } } return tableView.dequeueReusableCellWithIdentifier("BtTitlePlaceholderTableViewCell", forIndexPath: indexPath) as! BtNewBugDetailsTableViewCell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row > 0 { return 163.0 } if let height = TrackerService.Shared.currentTracker?.TrackerDetails[indexPath.section]?.cellHeight() { return height } return 44.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)!.selected = false TrackerService.Shared.currentTracker?.trackerState.ActiveBugDetail = indexPath.section if let cellType = TrackerService.Shared.currentTracker?.trackerState.getActiveCellType() { switch cellType { case .Selection: if let newBugDetailSelectTvController = storyboard!.instantiateViewControllerWithIdentifier("BtNewBugDetailsSelectTableViewController") as? BtNewBugDetailsSelectTableViewController { showViewController(newBugDetailSelectTvController, sender: self) } case .Date: datePickerIndexPath = NSIndexPath(forRow: 1, inSection: indexPath.section) datePickerCellOpen = !datePickerCellOpen default: break; } } } @IBAction func tapRecognized(sender: AnyObject) { didAssignTitleFirstResponder = false validateBugDetails() view.endEditing(true) } @IBAction func cancelClicked(sender: AnyObject) { TrapState.Shared.resetSnapshotImages() dismissControllerAndResetTrapState(false) TrackerService.Shared.setCurrentTrackerType(.None) } @IBAction func saveClicked(sender: AnyObject) { navigationController!.dismissViewControllerAnimated(true, completion: nil) } @IBAction func submitClicked(sender: AnyObject) { if validateBugDetails() { // TODO color the activity indicator red if TrapState.Shared.inActionExtension { activityIndicator.color = Colors.Theme.uiColor } navigationItem.setRightBarButtonItem(activityButton, animated: true) TrackerService.Shared.currentTracker?.createIssue() { result in switch result { case let .Error(error): Log.error(self.screenName!, error) self.dismissControllerAndResetTrapState(true) case let .Value(wrapped): self.dismissControllerAndResetTrapState(true) if let boolResult = wrapped.value { Log.info(boolResult) } } } } } @IBAction func datePickerValueChanged(sender: UIDatePicker) { if let dateDisplayCell = (tableView.visibleCells.filter({$0 as? BtDateDisplayTableViewCell != nil})).first as? BtDateDisplayTableViewCell { if let _ = TrackerService.Shared.currentTracker?.trackerState { TrackerService.Shared.currentTracker?.trackerState.bugDueDate = sender.date if let index = tableView.indexPathForCell(dateDisplayCell) { tableView.reloadRowsAtIndexPaths([ index ], withRowAnimation: UITableViewRowAnimation.None) } } } } func dismissControllerAndResetTrapState(successful: Bool) { navigationItem.setRightBarButtonItem(submitButton, animated: true) if TrapState.Shared.inActionExtension { if navigationController?.extensionContext != nil { if let navController = navigationController as? BtAnnotateImageNavigationController { if successful { navController.CompleteExtensionForSubmit() } else { navController.CompleteExtensionForCancel() } } } else if let navController = presentingViewController?.childViewControllers[0] as? BtAnnotateImageNavigationController { if navController.extensionContext != nil { if successful { navController.CompleteExtensionForSubmit() } else { navController.CompleteExtensionForCancel() } } } } else { TrapState.Shared.resetSnapshotImages() TrackerService.Shared.resetAndRemoveCurrentTracker() navigationController?.dismissViewControllerAnimated(true) { } } } func validateBugDetails () -> Bool { if let state = TrackerService.Shared.currentTracker?.trackerState { if let textFieldCell = (tableView.visibleCells.filter({$0 as? BtTextFieldTableViewCell != nil})).first as? BtTextFieldTableViewCell { if textFieldCell.TextField.hasText() { TrackerService.Shared.currentTracker?.trackerState.bugTitle = textFieldCell.TextField.text ?? "" } } if let textViewCell = (tableView.visibleCells.filter({$0 as? BtTextViewTableViewCell != nil})).first as? BtTextViewTableViewCell { if textViewCell.TextView.hasText() { TrackerService.Shared.currentTracker?.trackerState.bugDescription = textViewCell.TextView.text } } submitButton.enabled = state.isValid return state.isValid } return false } func getScaledSizeForAsset(asset: PHAsset, scaleSize: Bool) -> CGSize { let size = CGSize(width: asset.pixelWidth, height: asset.pixelHeight) var scaled = (standardSize.height / size.height) if scaleSize { scaled *= scale } return CGSizeApplyAffineTransform(size, CGAffineTransformMakeScale(scaled, scaled)) } // #pragma mark - Collection view data source let addSnapshotCell = "BtEmbeddedAddImageCollectionViewCell", snapshotCell = "BtEmbeddedImageCollectionViewCell" func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var assetFetchResultsCount = 0 if let assetFetchResults = assetsFetchResults { assetFetchResultsCount = assetFetchResults.count } return TrapState.Shared.inActionExtension ? TrapState.Shared.getExtensionSnapshotImageCount() : assetFetchResultsCount + 1 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if TrapState.Shared.inActionExtension { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(snapshotCell, forIndexPath: indexPath) as! BtEmbeddedImageCollectionViewCell cell.setData(TrapState.Shared.getExtensionSnapshotImageAtIndex(indexPath.item)) return cell } else if indexPath.item == 0 { return collectionView.dequeueReusableCellWithReuseIdentifier(addSnapshotCell, forIndexPath: indexPath) as UICollectionViewCell } else { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(snapshotCell, forIndexPath: indexPath) as! BtEmbeddedImageCollectionViewCell let manager = PHImageManager.defaultManager() let index = indexPath.item - 1 if let request = imageRequests[index] { manager.cancelImageRequest(request) } let asset = assetsFetchResults![index] as! PHAsset imageRequests[index] = manager.requestImageForAsset(asset, targetSize: getScaledSizeForAsset(asset, scaleSize: true), contentMode: .AspectFill, options: nil) { (result, _) in cell.setData(result) } return cell } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if TrapState.Shared.inActionExtension { TrapState.Shared.setActiveSnapshotImage(indexPath.item) displayAnnotateImageNavigationController() } else if indexPath.item == 0 { if let _ = navigationController as? BtNewBugDetailsNavigationController { if let annotateImageNavController = presentingViewController?.childViewControllers[0] as? BtAnnotateImageNavigationController { dismissViewControllerAnimated(true) { if let imageNavController = annotateImageNavController.imageNavigationController { imageNavController.selectingSnapshotImagesForExport = true; annotateImageNavController.presentViewController(imageNavController, animated: true) {} } } } else if let annotateImageNavController = presentingViewController as? BtAnnotateImageNavigationController { dismissViewControllerAnimated(true) { if let imageNavController = annotateImageNavController.imageNavigationController { imageNavController.selectingSnapshotImagesForExport = true; annotateImageNavController.presentViewController(imageNavController, animated: true) {} } } } } return } else { let asset = assetsFetchResults![indexPath.item - 1] as! PHAsset TrapState.Shared.setActiveSnapshotImage(asset.localIdentifier) { self.displayAnnotateImageNavigationController() } } } func displayAnnotateImageNavigationController () { if let annotateImageNavController = storyboard?.instantiateViewControllerWithIdentifier("BtAnnotateImageNavigationController") as? BtAnnotateImageNavigationController { presentViewController(annotateImageNavController, animated: true, completion: nil) } } let standardSize = CGSize(width: 70, height: 125) func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if TrapState.Shared.inActionExtension { // let index = indexPath.item - (TrapState.Shared.inActionExtension ? 0 : 1) if let size = TrapState.Shared.getExtensionSnapshotImageAtIndex(indexPath.item)?.size { let scaled = standardSize.height / size.height return CGSizeApplyAffineTransform(size, CGAffineTransformMakeScale(scaled, scaled)) } else { return standardSize } } if indexPath.item == 0 { return standardSize } else { let index = indexPath.item - 1 // let manager = PHImageManager.defaultManager() let asset = assetsFetchResults![index] as! PHAsset return getScaledSizeForAsset(asset, scaleSize: false) } } override func prefersStatusBarHidden() -> Bool { return true } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } }
mit
6c0c56a164b20653d32ebd10a9c6954e
27.580882
186
0.738663
4.898236
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Developer/DeveloperOptionsController.swift
1
7187
// // 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 WireSyncEngine import MessageUI import UIKit final class DeveloperOptionsController: UIViewController { /// Cells var tableCells: [UITableViewCell]! /// Map from UISwitch to the action it should perform. /// The parameter of the action is whether the switch is on or off var uiSwitchToAction: [UISwitch: (Bool) -> Void] = [:] /// Map from UIButton to the action it should perform. var uiButtonToAction: [UIButton: () -> Void] = [:] var mailViewController: MFMailComposeViewController? override func loadView() { setupNavigationTitle() view = UIView() edgesForExtendedLayout = UIRectEdge() view.backgroundColor = .clear tableCells = [forwardLogCell()] + ZMSLog.allTags.sorted().map { logSwitchCell(tag: $0) } let tableView = UITableView() tableView.dataSource = self tableView.backgroundColor = .clear tableView.translatesAutoresizingMaskIntoConstraints = false tableView.allowsSelection = false view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leftAnchor.constraint(equalTo: view.leftAnchor), tableView.rightAnchor.constraint(equalTo: view.rightAnchor) ]) } private func setupNavigationTitle() { navigationItem.setupNavigationBarTitle(title: L10n.Localizable.Self.Settings.DeveloperOptions.Loggin.title.capitalized) } // MARK: - Cells /// Creates a cell to switch a specific log tag on or off func logSwitchCell(tag: String) -> UITableViewCell { return createCellWithSwitch(labelText: tag, isOn: ZMSLog.getLevel(tag: tag) == .debug) { (isOn) in Settings.shared.set(logTag: tag, enabled: isOn) } } /// Creates a cell to forward logs func forwardLogCell() -> UITableViewCell { return createCellWithButton(labelText: "Forward log records") { let alert = UIAlertController(title: "Add explanation", message: "Please explain the problem that made you send the logs", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Send to Devs", style: .default, handler: { _ in guard let text = alert.textFields?.first?.text else { return } DebugLogSender.sendLogsByEmail(message: text) })) alert.addAction(UIAlertAction(title: "Send to Devs & AVS", style: .default, handler: { _ in guard let text = alert.textFields?.first?.text else { return } DebugLogSender.sendLogsByEmail(message: text, shareWithAVS: true) })) alert.addTextField(configurationHandler: {(textField: UITextField!) in textField.placeholder = "Please explain the problem" }) self.present(alert, animated: true, completion: nil) } } /// Creates a cell to forward logs func createCellWithButton(labelText: String, onTouchDown: @escaping () -> Void) -> UITableViewCell { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Go!", for: .normal) button.titleLabel?.textAlignment = .right button.setTitleColor( SemanticColors.Label.textDefault, for: .normal) if let titleLabel = button.titleLabel { NSLayoutConstraint.activate([ titleLabel.rightAnchor.constraint(equalTo: button.rightAnchor) ]) } button.addTarget(self, action: #selector(DeveloperOptionsController.didPressButton(sender:)), for: .touchDown) uiButtonToAction[button] = onTouchDown return createCellWithLabelAndView(labelText: labelText, view: button) } /// Creates and sets the layout of a cell with a UISwitch func createCellWithSwitch(labelText: String, isOn: Bool, onValueChange: @escaping (Bool) -> Void ) -> UITableViewCell { let toggle = Switch(style: .default) toggle.translatesAutoresizingMaskIntoConstraints = false toggle.isOn = isOn toggle.addTarget(self, action: #selector(DeveloperOptionsController.switchDidChange(sender:)), for: .valueChanged) uiSwitchToAction[toggle] = onValueChange return createCellWithLabelAndView(labelText: labelText, view: toggle) } /// Creates and sets the layout of a cell with a label and a view func createCellWithLabelAndView(labelText: String, view: UIView) -> UITableViewCell { let cell = UITableViewCell() cell.backgroundColor = .clear let label = UILabel() label.text = labelText label.textColor = SemanticColors.Label.textDefault label.translatesAutoresizingMaskIntoConstraints = false [label, view].forEach { cell.contentView.addSubview($0) } NSLayoutConstraint.activate([ label.centerYAnchor.constraint(equalTo: cell.contentView.centerYAnchor), label.leftAnchor.constraint(equalTo: cell.contentView.leftAnchor, constant: 20), view.trailingAnchor.constraint(equalTo: cell.contentView.trailingAnchor, constant: -20), label.trailingAnchor.constraint(equalTo: view.leadingAnchor), view.centerYAnchor.constraint(equalTo: label.centerYAnchor) ]) return cell } // MARK: - Actions /// Invoked when one of the switches changes @objc func switchDidChange(sender: AnyObject) { if let toggle = sender as? UISwitch { guard let action = uiSwitchToAction[toggle] else { fatalError("Unknown switch?") } action(toggle.isOn) } } /// Invoked when one of the buttons is pressed @objc func didPressButton(sender: AnyObject) { if let button = sender as? UIButton { guard let action = uiButtonToAction[button] else { fatalError("Unknown button?") } action() } } } extension DeveloperOptionsController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableCells.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableCells[indexPath.row] } }
gpl-3.0
cea69fff25c18a26d29698c6fdd9c080
38.489011
158
0.666064
5.061268
false
false
false
false
jasnig/DouYuTVMutate
DouYuTVMutate/DouYuTV/Main/View/EasyHUD.swift
1
2467
// // SimpleHUD.swift // DouYuTVMutate // // Created by ZeroJ on 16/7/19. // Copyright © 2016年 ZeroJ. All rights reserved. // import UIKit class EasyHUD: UIView { /// 加载错误提示 private lazy var messageLabel: UILabel = { let label = UILabel(frame: CGRectZero) label.font = UIFont.boldSystemFontOfSize(16.0) label.backgroundColor = UIColor.blackColor() label.layer.masksToBounds = true label.textColor = UIColor.whiteColor() label.textAlignment = .Center return label }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clearColor() addSubview(messageLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /// /// /// - parameter autoHide: 是否自动隐藏 /// - parameter time: 自动隐藏的时间 只有当autoHide = true的时候有效 class func showHUD(text: String, autoHide: Bool, afterTime time: Double) { if let window = UIApplication.sharedApplication().keyWindow { let hud = EasyHUD(frame: CGRect(origin: CGPointZero, size: window.bounds.size)) window.addSubview(hud) hud.messageLabel.text = text let textSize = (text as NSString).boundingRectWithSize(CGSizeMake(CGFloat(MAXFLOAT), 0.0), options: .UsesLineFragmentOrigin, attributes: [NSFontAttributeName: hud.messageLabel.font], context: nil) hud.messageLabel.frame = CGRect(x: (UIScreen.mainScreen().bounds.width - textSize.width - 16)*0.5, y: (UIScreen.mainScreen().bounds.height - 40.0)*0.5, width: textSize.width + 16, height: 40.0) hud.messageLabel.layer.cornerRadius = hud.messageLabel.bounds.height / 2 if autoHide { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { EasyHUD.hideHUD() }) } } } class func hideHUD() { if let window = UIApplication.sharedApplication().keyWindow { for subview in window.subviews { if subview is EasyHUD { subview.removeFromSuperview() } } } } }
mit
2c8f55f2b51371e9c4e0b6c8b7dc5260
31.133333
208
0.578008
4.62572
false
false
false
false
joninsky/TUView
Pod/Classes/TutorialViewCell.swift
1
1497
// // TutorialViewCellCollectionViewCell.swift // TutorialView // // Created by JV on 11/4/15. // Copyright © 2015 PebbleBee. All rights reserved. // import UIKit public class TutorialViewCell: UICollectionViewCell { var cellImage: UIImageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) self.translatesAutoresizingMaskIntoConstraints = false cellImage.translatesAutoresizingMaskIntoConstraints = false self.cellImage.contentMode = UIViewContentMode.ScaleAspectFit self.addSubview(self.cellImage) self.constrainImageView() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func constrainImageView() { var constraints = [NSLayoutConstraint]() let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[image]|", options: [], metrics: nil, views: ["image":self.cellImage]) for c in verticalConstraints { constraints.append(c) } let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[image]|", options: [], metrics: nil, views: ["image":self.cellImage]) for c in horizontalConstraints { constraints.append(c) } self.addConstraints(constraints) } }
mit
cbdb64b06786d1b5b74f173e696e6e5c
24.793103
157
0.620321
5.753846
false
false
false
false
JoeLago/MHGDB-iOS
Pods/GRDB.swift/GRDB/Utils/Utils.swift
2
2262
import Foundation // MARK: - Public extension String { /// Returns the receiver, quoted for safe insertion as an identifier in an /// SQL query. /// /// db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)") public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html return "\"" + self + "\"" } } /// Return as many question marks separated with commas as the *count* argument. /// /// databaseQuestionMarks(count: 3) // "?,?,?" public func databaseQuestionMarks(count: Int) -> String { return Array(repeating: "?", count: count).joined(separator: ",") } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// This protocol is an implementation detail of GRDB. Don't use it. /// /// :nodoc: public protocol _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: associatedtype _Wrapped } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// This conformance is an implementation detail of GRDB. Don't rely on it. /// /// :nodoc: extension Optional : _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: public typealias _Wrapped = Wrapped } // MARK: - Internal /// Reserved for GRDB: do not use. func GRDBPrecondition(_ condition: @autoclosure() -> Bool, _ message: @autoclosure() -> String = "", file: StaticString = #file, line: UInt = #line) { /// Custom precondition function which aims at solving /// https://bugs.swift.org/browse/SR-905 and /// https://github.com/groue/GRDB.swift/issues/37 if !condition() { fatalError(message, file: file, line: line) } } // Workaround Swift inconvenience around factory methods of non-final classes func cast<T, U>(_ value: T) -> U? { return value as? U } extension Array { /// Removes the first object that matches *predicate*. mutating func removeFirst(_ predicate: (Element) throws -> Bool) rethrows { if let index = try index(where: predicate) { remove(at: index) } } }
mit
9d5e2a6e6972c92d7c0cf924653bec26
29.986301
150
0.650309
3.947644
false
false
false
false
benlangmuir/swift
validation-test/IDE/issues_fixed/rdar63063279.swift
5
2409
// RUN: %empty-directory(%t) // RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t enum A { case one, two } struct B<T> { let value: T init(_ value: T) { self.value = value } static func void() -> B<Void> { return B<Void>(()) } static func data(_ data: Data) -> B<Data> { return B<Data>(data) } } class C { func a(s: String = "", a: A) {} func b(s: String = "", i: Int = 0, a: A) {} } class D { func a<T>(b: B<T>, s: String = "") {} func b<T>(s: String = "", i: Int = 0, b: B<T>) {} } // type a point "." in placeholders to see the substitution list // correct substitution C().a(s: .#^STR_1?check=STRING^#, a: .#^A_1?check=A^#) C().a(a: .#^A_2?check=A^#) C().b(s: .#^STR_2?check=STRING^#, i: .#^INT_1?check=INT^#, a: .#^A_3?check=A^#) C().b(i: .#^INT_2?check=INT^#, a: .#^A_4?check=A^#) C().b(a: .#^A_5?check=A^#) D().a(b: .#^B_1?check=B^#, s: .#^STR_3?check=STRING^#) D().a(b: .#^B_2?check=B^#) D().b(s: .#^STR_4?check=STRING^#, i: .#^INT_3?check=INT^#, b: .#^B_3?check=B^#) // // incorrect substitution from previous parameter D().b(i: .#^INT_4?check=INT^#, b: .#^B_4?check=B^#) D().b(b: .#^B_5?check=B^#) // INT: Begin completions // INT-DAG: Decl[Constructor]/CurrNominal/IsSystem/TypeRelation[Convertible]: init({#bitPattern: UInt#})[#Int#]; name=init(bitPattern:) // INT: End completions // STRING: Begin completions // STRING-DAG: Decl[Constructor]/CurrNominal/IsSystem/TypeRelation[Convertible]: init()[#String#]; name=init() // STRING: End completions // A: Begin completions, 3 items // A-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: one[#A#]; name=one // A-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: two[#A#]; name=two // A-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): A#})[#(into: inout Hasher) -> Void#]; name=hash(:) // A: End completions // B: Begin completions, 3 items // B-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Convertible]: init({#(value): T#})[#B<T>#]; name=init(:) // B-DAG: Decl[StaticMethod]/CurrNominal/TypeRelation[Convertible]: void()[#B<Void>#]; name=void() // B-DAG: Decl[StaticMethod]/CurrNominal: data({#(data): <<error type>>#})[#<<error type>>#]; name=data(:) // B: End completions
apache-2.0
d0805dbd292a33a1117433fad833fa01
32.929577
135
0.60523
3.018797
false
false
false
false
eugenepavlyuk/swift-algorithm-club
MinimumCoinChange/Tests/MinimumCoinChangeTests/MinimumCoinChangeTests.swift
5
862
import XCTest @testable import MinimumCoinChange class MinimumCoinChangeTests: XCTestCase { func testExample() { let mcc = MinimumCoinChange(coinSet: [1, 2, 5, 10, 20, 25]) print("Coin set: \(mcc.sortedCoinSet)") do { for i in 0..<100 { let greedy = try mcc.changeGreedy(i) let dynamic = try mcc.changeDynamic(i) XCTAssertEqual(greedy.reduce(0, +), dynamic.reduce(0, +), "Greedy and Dynamic return two different changes") if greedy.count != dynamic.count { print("\(i): greedy = \(greedy) dynamic = \(dynamic)") } } } catch { XCTFail("Test Failed: impossible to change with the given coin set") } } static var allTests = [ ("testExample", testExample), ] }
mit
41cf87aa6dccad65ddc28b20716d18c7
29.785714
124
0.544084
4.659459
false
true
false
false
sakishum/mac2imgur
Dependencies/Just.swift
3
34001
// // Just.swift // Just // // Created by Daniel Duan on 4/21/15. // Copyright (c) 2015 JustHTTP. All rights reserved. // import Foundation // stolen from python-requests let statusCodeDescriptions = [ // Informational. 100: "continue" , 101: "switching protocols" , 102: "processing" , 103: "checkpoint" , 122: "uri too long" , 200: "ok" , 201: "created" , 202: "accepted" , 203: "non authoritative info" , 204: "no content" , 205: "reset content" , 206: "partial content" , 207: "multi status" , 208: "already reported" , 226: "im used" , // Redirection. 300: "multiple choices" , 301: "moved permanently" , 302: "found" , 303: "see other" , 304: "not modified" , 305: "use proxy" , 306: "switch proxy" , 307: "temporary redirect" , 308: "permanent redirect" , // Client Error. 400: "bad request" , 401: "unauthorized" , 402: "payment required" , 403: "forbidden" , 404: "not found" , 405: "method not allowed" , 406: "not acceptable" , 407: "proxy authentication required" , 408: "request timeout" , 409: "conflict" , 410: "gone" , 411: "length required" , 412: "precondition failed" , 413: "request entity too large" , 414: "request uri too large" , 415: "unsupported media type" , 416: "requested range not satisfiable" , 417: "expectation failed" , 418: "im a teapot" , 422: "unprocessable entity" , 423: "locked" , 424: "failed dependency" , 425: "unordered collection" , 426: "upgrade required" , 428: "precondition required" , 429: "too many requests" , 431: "header fields too large" , 444: "no response" , 449: "retry with" , 450: "blocked by windows parental controls" , 451: "unavailable for legal reasons" , 499: "client closed request" , // Server Error. 500: "internal server error" , 501: "not implemented" , 502: "bad gateway" , 503: "service unavailable" , 504: "gateway timeout" , 505: "http version not supported" , 506: "variant also negotiates" , 507: "insufficient storage" , 509: "bandwidth limit exceeded" , 510: "not extended" , ] public class Just: NSObject, NSURLSessionDelegate { private struct Shared { static let instance = Just() } class var shared: Just { return Shared.instance } public init(session:NSURLSession? = nil, defaults:JustSessionDefaults? = nil) { super.init() if let initialSession = session { self.session = initialSession } else { self.session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate:self, delegateQueue:nil) } if let initialDefaults = defaults { self.defaults = initialDefaults } else { self.defaults = JustSessionDefaults() } } var taskConfigs:[TaskID:TaskConfiguration]=[:] var defaults:JustSessionDefaults! var session: NSURLSession! var invalidURLError = NSError( domain: errorDomain, code: 0, userInfo: [NSLocalizedDescriptionKey:"[Just] URL is invalid"] ) var syncResultAccessError = NSError( domain: errorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey:"[Just] You are accessing asynchronous result synchronously."] ) func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)", value) } } else { components.extend([(percentEncodeString(key), percentEncodeString("\(value)"))]) } return components } func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += self.queryComponents(key, value) } return "&".join(components.map{"\($0)=\($1)"} as [String]) } func percentEncodeString(originalObject: AnyObject) -> String { if originalObject is NSNull { return "null" } else { return "\(originalObject)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) ?? "" } } func makeTask(request:NSURLRequest, configuration: TaskConfiguration) -> NSURLSessionDataTask? { let task = session.dataTaskWithRequest(request) taskConfigs[task.taskIdentifier] = configuration return task } func synthesizeMultipartBody(data:[String:AnyObject], files:[String:HTTPFile]) -> NSData? { let body = NSMutableData() let boundary = "--\(self.defaults.multipartBoundary)\r\n".dataUsingEncoding(defaults.encoding)! for (k,v) in data { let valueToSend:AnyObject = v is NSNull ? "null" : v body.appendData(boundary) body.appendData("Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n".dataUsingEncoding(defaults.encoding)!) body.appendData("\(valueToSend)\r\n".dataUsingEncoding(defaults.encoding)!) } for (k,v) in files { body.appendData(boundary) var partContent: NSData? = nil var partFilename:String? = nil var partMimetype:String? = nil switch v { case let .URL(URL, mimetype): if let component = URL.lastPathComponent { partFilename = component } if let URLContent = NSData(contentsOfURL: URL) { partContent = URLContent } partMimetype = mimetype case let .Text(filename, text, mimetype): partFilename = filename if let textData = text.dataUsingEncoding(defaults.encoding) { partContent = textData } partMimetype = mimetype case let .Data(filename, data, mimetype): partFilename = filename partContent = data partMimetype = mimetype } if let content = partContent, let filename = partFilename { body.appendData(NSData(data: "Content-Disposition: form-data; name=\"\(k)\"; filename=\"\(filename)\"\r\n".dataUsingEncoding(defaults.encoding)!)) if let type = partMimetype { body.appendData("Content-Type: \(type)\r\n\r\n".dataUsingEncoding(defaults.encoding)!) } else { body.appendData("\r\n".dataUsingEncoding(defaults.encoding)!) } body.appendData(content) body.appendData("\r\n".dataUsingEncoding(defaults.encoding)!) } } if body.length > 0 { body.appendData("--\(self.defaults.multipartBoundary)--\r\n".dataUsingEncoding(defaults.encoding)!) } return body } func synthesizeRequest( method:HTTPMethod, URLString:String, params:[String:AnyObject], data:[String:AnyObject], json:[String:AnyObject]?, headers:CaseInsensitiveDictionary<String,String>, files:[String:HTTPFile], timeout:Double?, requestBody:NSData?, URLQuery:String? ) -> NSURLRequest? { if let urlComponent = NSURLComponents(string: URLString) { let queryString = query(params) if queryString.characters.count > 0 { urlComponent.percentEncodedQuery = queryString } var finalHeaders = headers var contentType:String? = nil var body:NSData? if let requestData = requestBody { body = requestData } else if files.count > 0 { body = synthesizeMultipartBody(data, files:files) contentType = "multipart/form-data; boundary=\(self.defaults.multipartBoundary)" } else { if let requestJSON = json { contentType = "application/json" do { body = try NSJSONSerialization.dataWithJSONObject(requestJSON, options: defaults.JSONWritingOptions) } catch _ { body = nil } } else { if data.count > 0 { if headers["content-type"]?.lowercaseString == "application/json" { // assume user wants JSON if she is using this header do { body = try NSJSONSerialization.dataWithJSONObject(data, options: defaults.JSONWritingOptions) } catch _ { body = nil } } else { contentType = "application/x-www-form-urlencoded" body = query(data).dataUsingEncoding(defaults.encoding) } } } } if let contentTypeValue = contentType { finalHeaders["Content-Type"] = contentTypeValue } if let URL = urlComponent.URL { let request = NSMutableURLRequest(URL: URL) request.cachePolicy = .ReloadIgnoringLocalCacheData request.HTTPBody = body request.HTTPMethod = method.rawValue if let requestTimeout = timeout { request.timeoutInterval = requestTimeout } for (k,v) in defaults.headers { request.addValue(v, forHTTPHeaderField: k) } for (k,v) in finalHeaders { request.addValue(v, forHTTPHeaderField: k) } return request } } return nil } func request( method:HTTPMethod, URLString:String, params:[String:AnyObject], data:[String:AnyObject], json:[String:AnyObject]?, headers:[String:String], files:[String:HTTPFile], auth:Credentials?, cookies: [String:String], redirects:Bool, timeout:Double?, URLQuery:String?, requestBody:NSData?, asyncProgressHandler:TaskProgressHandler?, asyncCompletionHandler:((HTTPResult!) -> Void)?) -> HTTPResult { let isSync = asyncCompletionHandler == nil let semaphore = dispatch_semaphore_create(0) var requestResult:HTTPResult = HTTPResult(data: nil, response: nil, error: syncResultAccessError, request: nil) let caseInsensitiveHeaders = CaseInsensitiveDictionary<String,String>(dictionary:headers) if let request = synthesizeRequest( method, URLString: URLString, params: params, data: data, json: json, headers: caseInsensitiveHeaders, files: files, timeout:timeout, requestBody:requestBody, URLQuery: URLQuery ) { addCookies(request.URL!, newCookies: cookies) let config = TaskConfiguration( credential:auth, redirects:redirects, originalRequest:request, data:NSMutableData(), progressHandler: asyncProgressHandler ) { (result) in if let handler = asyncCompletionHandler { handler(result) } if isSync { requestResult = result dispatch_semaphore_signal(semaphore) } } if let task = makeTask(request, configuration:config) { task.resume() } if isSync { dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) return requestResult } } else { let erronousResult = HTTPResult(data: nil, response: nil, error: invalidURLError, request: nil) if let handler = asyncCompletionHandler { handler(erronousResult) } else { return erronousResult } } return requestResult } func addCookies(URL:NSURL, newCookies:[String:String]) { for (k,v) in newCookies { if let cookie = NSHTTPCookie(properties: [ NSHTTPCookieName: k, NSHTTPCookieValue: v, NSHTTPCookieOriginURL: URL, NSHTTPCookiePath: "/" ]) { session.configuration.HTTPCookieStorage?.setCookie(cookie) } } } } extension Just { public class func delete( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, URLQuery:String? = nil, requestBody:NSData? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .DELETE, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout:timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func get( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, allowRedirects:Bool = true, cookies:[String:String] = [:], timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .GET, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout:timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func head( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .HEAD, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func options( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .OPTIONS, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func patch( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .OPTIONS, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func post( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .POST, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } public class func put( URLString:String, params:[String:AnyObject] = [:], data:[String:AnyObject] = [:], json:[String:AnyObject]? = nil, headers:[String:String] = [:], files:[String:HTTPFile] = [:], auth:(String,String)? = nil, cookies:[String:String] = [:], allowRedirects:Bool = true, timeout:Double? = nil, requestBody:NSData? = nil, URLQuery:String? = nil, asyncProgressHandler:((HTTPProgress!) -> Void)? = nil, asyncCompletionHandler:((HTTPResult!) -> Void)? = nil ) -> HTTPResult { return Just.shared.request( .PUT, URLString: URLString, params: params, data: data, json: json, headers: headers, files:files, auth: auth, cookies: cookies, redirects: allowRedirects, timeout: timeout, URLQuery: URLQuery, requestBody: requestBody, asyncProgressHandler: asyncProgressHandler, asyncCompletionHandler: asyncCompletionHandler ) } } public enum HTTPFile { case URL(NSURL,String?) // URL to a file, mimetype case Data(String,NSData,String?) // filename, data, mimetype case Text(String,String,String?) // filename, text, mimetype } // Supported request types enum HTTPMethod: String { case DELETE = "DELETE" case GET = "GET" case HEAD = "HEAD" case OPTIONS = "OPTIONS" case PATCH = "PATCH" case POST = "POST" case PUT = "PUT" } /// The only reason this is not a struct is the requirements for /// lazy evaluation of `headers` and `cookies`, which is mutating the /// struct. This would make those properties unusable with `HTTPResult`s /// declared with `let` public final class HTTPResult : NSObject { public final var content:NSData? public var response:NSURLResponse? public var error:NSError? public var request:NSURLRequest? public var encoding = NSUTF8StringEncoding public var JSONReadingOptions = NSJSONReadingOptions(rawValue: 0) public var reason:String { if let code = self.statusCode, let text = statusCodeDescriptions[code] { return text } if let error = self.error { return error.localizedDescription } return "Unkown" } public var isRedirect:Bool { if let code = self.statusCode { return code >= 300 && code < 400 } return false } public var isPermanentRedirect:Bool { return self.statusCode == 301 } public override var description:String { if let status = statusCode, urlString = request?.URL?.absoluteString, method = request?.HTTPMethod { return "\(method) \(urlString) \(status)" } else { return "<Empty>" } } init(data:NSData?, response:NSURLResponse?, error:NSError?, request:NSURLRequest?) { self.content = data self.response = response self.error = error self.request = request } public var json:AnyObject? { if let theData = self.content { do { return try NSJSONSerialization.JSONObjectWithData(theData, options: JSONReadingOptions) } catch _ { return nil } } return nil } public var statusCode: Int? { if let theResponse = self.response as? NSHTTPURLResponse { return theResponse.statusCode } return nil } public var text:String? { if let theData = self.content { return NSString(data:theData, encoding:encoding) as? String } return nil } public lazy var headers:CaseInsensitiveDictionary<String,String> = { return CaseInsensitiveDictionary<String,String>(dictionary: (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String:String] ?? [:]) }() public lazy var cookies:[String:NSHTTPCookie] = { let foundCookies: [NSHTTPCookie] if let responseHeaders = (self.response as? NSHTTPURLResponse)?.allHeaderFields as? [String: String] { foundCookies = NSHTTPCookie.cookiesWithResponseHeaderFields(responseHeaders, forURL:NSURL(string:"")!) as [NSHTTPCookie] } else { foundCookies = [] } var result:[String:NSHTTPCookie] = [:] for cookie in foundCookies { result[cookie.name] = cookie } return result }() public var ok:Bool { return statusCode != nil && !(statusCode! >= 400 && statusCode! < 600) } public var url:NSURL? { return response?.URL } } public struct CaseInsensitiveDictionary<Key: Hashable, Value>: CollectionType, DictionaryLiteralConvertible { private var _data:[Key: Value] = [:] private var _keyMap: [String: Key] = [:] public typealias Element = (Key, Value) public typealias Index = DictionaryIndex<Key, Value> public var startIndex: Index public var endIndex: Index public var count: Int { assert(_data.count == _keyMap.count, "internal keys out of sync") return _data.count } public var isEmpty: Bool { return _data.isEmpty } public init() { startIndex = _data.startIndex endIndex = _data.endIndex } public init(dictionaryLiteral elements: (Key, Value)...) { for (key, value) in elements { _keyMap["\(key)".lowercaseString] = key _data[key] = value } startIndex = _data.startIndex endIndex = _data.endIndex } public init(dictionary:[Key:Value]) { for (key, value) in dictionary { _keyMap["\(key)".lowercaseString] = key _data[key] = value } startIndex = _data.startIndex endIndex = _data.endIndex } public subscript (position: Index) -> Element { return _data[position] } public subscript (key: Key) -> Value? { get { if let realKey = _keyMap["\(key)".lowercaseString] { return _data[realKey] } return nil } set(newValue) { let lowerKey = "\(key)".lowercaseString if _keyMap[lowerKey] == nil { _keyMap[lowerKey] = key } _data[_keyMap[lowerKey]!] = newValue } } public func generate() -> DictionaryGenerator<Key, Value> { return _data.generate() } public var keys: LazyForwardCollection<MapCollection<[Key : Value], Key>> { return _data.keys } public var values: LazyForwardCollection<MapCollection<[Key : Value], Value>> { return _data.values } } typealias TaskID = Int typealias Credentials = (username:String, password:String) typealias TaskProgressHandler = (HTTPProgress!) -> Void typealias TaskCompletionHandler = (HTTPResult) -> Void struct TaskConfiguration { let credential:Credentials? let redirects:Bool let originalRequest: NSURLRequest? var data: NSMutableData let progressHandler: TaskProgressHandler? let completionHandler: TaskCompletionHandler? } public struct JustSessionDefaults { public var JSONReadingOptions = NSJSONReadingOptions(rawValue: 0) public var JSONWritingOptions = NSJSONWritingOptions(rawValue: 0) public var headers:[String:String] = [:] public var multipartBoundary = "Ju5tH77P15Aw350m3" public var encoding = NSUTF8StringEncoding } public struct HTTPProgress { public enum Type { case Upload case Download } public let type:Type public let bytesProcessed:Int64 public let bytesExpectedToProcess:Int64 public var percent: Float { return Float(bytesProcessed) / Float(bytesExpectedToProcess) } } let errorDomain = "net.justhttp.Just" extension Just: NSURLSessionTaskDelegate, NSURLSessionDataDelegate { public func URLSession( session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void ) { var endCredential:NSURLCredential? = nil if let credential = taskConfigs[task.taskIdentifier]?.credential { if !(challenge.previousFailureCount > 0) { endCredential = NSURLCredential(user: credential.0, password: credential.1, persistence: .ForSession) } } completionHandler(.UseCredential, endCredential) } public func URLSession( session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest?) -> Void ) { if let allowRedirects = taskConfigs[task.taskIdentifier]?.redirects { if !allowRedirects { completionHandler(nil) return } completionHandler(request) } else { completionHandler(request) } } public func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64 ) { if let handler = taskConfigs[task.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .Upload, bytesProcessed: totalBytesSent, bytesExpectedToProcess: totalBytesExpectedToSend ) ) } } public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let handler = taskConfigs[dataTask.taskIdentifier]?.progressHandler { handler( HTTPProgress( type: .Download, bytesProcessed: dataTask.countOfBytesReceived, bytesExpectedToProcess: dataTask.countOfBytesExpectedToReceive ) ) } if taskConfigs[dataTask.taskIdentifier]?.data != nil { taskConfigs[dataTask.taskIdentifier]?.data.appendData(data) } } public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let config = taskConfigs[task.taskIdentifier], let handler = config.completionHandler { let result = HTTPResult( data: config.data, response: task.response, error: error, request: config.originalRequest ?? task.originalRequest ) result.JSONReadingOptions = self.defaults.JSONReadingOptions result.encoding = self.defaults.encoding handler(result) } taskConfigs.removeValueForKey(task.taskIdentifier) } }
gpl-3.0
d15f02a753f329aa17e5cd19d7d27112
36.322722
162
0.523514
5.657404
false
false
false
false
KSMissQXC/KS_DYZB
KS_DYZB/KS_DYZB/Classes/Tools/KSCommon.swift
1
353
// // KSCommon.swift // KS_DYZB // // Created by 耳动人王 on 2016/10/28. // Copyright © 2016年 KS. All rights reserved. // import UIKit let KStatusBarH : CGFloat = 20 let KNavigationBarH : CGFloat = 44 let KTabBarH : CGFloat = 44 let KScreenW : CGFloat = UIScreen.main.bounds.width let KScreenH : CGFloat = UIScreen.main.bounds.height
mit
82d415a263ebeb1d98e61831163a952b
15.285714
52
0.69883
3.196262
false
false
false
false
Swinject/SwinjectMVVMExample
Carthage/Checkouts/SwinjectStoryboard/Carthage/Checkouts/Swinject/Carthage/Checkouts/Quick/Externals/Nimble/Tests/NimbleTests/Matchers/BeCloseToTest.swift
10
7082
import Foundation import XCTest import Nimble final class BeCloseToTest: XCTestCase, XCTestCaseProvider { static var allTests: [(String, (BeCloseToTest) -> () throws -> Void)] { return [ ("testBeCloseTo", testBeCloseTo), ("testBeCloseToWithin", testBeCloseToWithin), ("testBeCloseToWithNSNumber", testBeCloseToWithNSNumber), ("testBeCloseToWithDate", testBeCloseToWithDate), ("testBeCloseToOperator", testBeCloseToOperator), ("testBeCloseToWithinOperator", testBeCloseToWithinOperator), ("testPlusMinusOperator", testPlusMinusOperator), ("testBeCloseToOperatorWithDate", testBeCloseToOperatorWithDate), ("testBeCloseToWithinOperatorWithDate", testBeCloseToWithinOperatorWithDate), ("testPlusMinusOperatorWithDate", testPlusMinusOperatorWithDate), ("testBeCloseToArray", testBeCloseToArray), ("testBeCloseToWithCGFloat", testBeCloseToWithCGFloat), ] } func testBeCloseTo() { expect(1.2).to(beCloseTo(1.2001)) expect(1.2 as CDouble).to(beCloseTo(1.2001)) expect(1.2 as Float).to(beCloseTo(1.2001)) failsWithErrorMessage("expected to not be close to <1.2001> (within 0.0001), got <1.2>") { expect(1.2).toNot(beCloseTo(1.2001)) } } func testBeCloseToWithin() { expect(1.2).to(beCloseTo(9.300, within: 10)) failsWithErrorMessage("expected to not be close to <1.2001> (within 1), got <1.2>") { expect(1.2).toNot(beCloseTo(1.2001, within: 1.0)) } } func testBeCloseToWithNSNumber() { expect(NSNumber(value:1.2)).to(beCloseTo(9.300, within: 10)) expect(NSNumber(value:1.2)).to(beCloseTo(NSNumber(value:9.300), within: 10)) expect(1.2).to(beCloseTo(NSNumber(value:9.300), within: 10)) failsWithErrorMessage("expected to not be close to <1.2001> (within 1), got <1.2>") { expect(NSNumber(value:1.2)).toNot(beCloseTo(1.2001, within: 1.0)) } } func testBeCloseToWithCGFloat() { expect(CGFloat(1.2)).to(beCloseTo(1.2001)) expect(CGFloat(1.2)).to(beCloseTo(CGFloat(1.2001))) let got: String #if _runtime(_ObjC) got = "1.2" #else got = "CGFloat(native: 1.2)" #endif failsWithErrorMessage("expected to be close to <1.2001> (within 1), got <\(got)>") { expect(CGFloat(1.2)).to(beCloseTo(1.2001, within: 1.0)) } } func testBeCloseToWithDate() { expect(Date(dateTimeString: "2015-08-26 11:43:00")).to(beCloseTo(Date(dateTimeString: "2015-08-26 11:43:05"), within: 10)) failsWithErrorMessage("expected to not be close to <2015-08-26 11:43:00.0050> (within 0.004), got <2015-08-26 11:43:00.0000>") { let expectedDate = Date(dateTimeString: "2015-08-26 11:43:00").addingTimeInterval(0.005) expect(Date(dateTimeString: "2015-08-26 11:43:00")).toNot(beCloseTo(expectedDate, within: 0.004)) } } func testBeCloseToOperator() { expect(1.2) ≈ 1.2001 expect(1.2 as CDouble) ≈ 1.2001 failsWithErrorMessage("expected to be close to <1.2002> (within 0.0001), got <1.2>") { expect(1.2) ≈ 1.2002 } } func testBeCloseToWithinOperator() { expect(1.2) ≈ (9.300, 10) expect(1.2) == (9.300, 10) failsWithErrorMessage("expected to be close to <1> (within 0.1), got <1.2>") { expect(1.2) ≈ (1.0, 0.1) } failsWithErrorMessage("expected to be close to <1> (within 0.1), got <1.2>") { expect(1.2) == (1.0, 0.1) } } func testPlusMinusOperator() { expect(1.2) ≈ 9.300 ± 10 expect(1.2) == 9.300 ± 10 failsWithErrorMessage("expected to be close to <1> (within 0.1), got <1.2>") { expect(1.2) ≈ 1.0 ± 0.1 } failsWithErrorMessage("expected to be close to <1> (within 0.1), got <1.2>") { expect(1.2) == 1.0 ± 0.1 } } func testBeCloseToOperatorWithDate() { expect(Date(dateTimeString: "2015-08-26 11:43:00")) ≈ Date(dateTimeString: "2015-08-26 11:43:00") failsWithErrorMessage("expected to be close to <2015-08-26 11:43:00.0050> (within 0.0001), got <2015-08-26 11:43:00.0000>") { let expectedDate = Date(dateTimeString: "2015-08-26 11:43:00").addingTimeInterval(0.005) expect(Date(dateTimeString: "2015-08-26 11:43:00")) ≈ expectedDate } } func testBeCloseToWithinOperatorWithDate() { expect(Date(dateTimeString: "2015-08-26 11:43:00")) ≈ (Date(dateTimeString: "2015-08-26 11:43:05"), 10) expect(Date(dateTimeString: "2015-08-26 11:43:00")) == (Date(dateTimeString: "2015-08-26 11:43:05"), 10) failsWithErrorMessage("expected to be close to <2015-08-26 11:43:00.0050> (within 0.006), got <2015-08-26 11:43:00.0000>") { let expectedDate = Date(dateTimeString: "2015-08-26 11:43:00").addingTimeInterval(0.005) expect(Date(dateTimeString: "2015-08-26 11:43:00")) ≈ (expectedDate, 0.006) } failsWithErrorMessage("expected to be close to <2015-08-26 11:43:00.0050> (within 0.006), got <2015-08-26 11:43:00.0000>") { let expectedDate = Date(dateTimeString: "2015-08-26 11:43:00").addingTimeInterval(0.005) expect(Date(dateTimeString: "2015-08-26 11:43:00")) == (expectedDate, 0.006) } } func testPlusMinusOperatorWithDate() { expect(Date(dateTimeString: "2015-08-26 11:43:00")) ≈ Date(dateTimeString: "2015-08-26 11:43:05") ± 10 expect(Date(dateTimeString: "2015-08-26 11:43:00")) == Date(dateTimeString: "2015-08-26 11:43:05") ± 10 failsWithErrorMessage("expected to be close to <2015-08-26 11:43:00.0050> (within 0.006), got <2015-08-26 11:43:00.0000>") { let expectedDate = Date(dateTimeString: "2015-08-26 11:43:00").addingTimeInterval(0.005) expect(Date(dateTimeString: "2015-08-26 11:43:00")) ≈ expectedDate ± 0.006 } failsWithErrorMessage("expected to be close to <2015-08-26 11:43:00.0050> (within 0.006), got <2015-08-26 11:43:00.0000>") { let expectedDate = Date(dateTimeString: "2015-08-26 11:43:00").addingTimeInterval(0.005) expect(Date(dateTimeString: "2015-08-26 11:43:00")) == expectedDate ± 0.006 } } func testBeCloseToArray() { expect([0.0, 1.1, 2.2]) ≈ [0.0001, 1.1001, 2.2001] expect([0.0, 1.1, 2.2]).to(beCloseTo([0.1, 1.2, 2.3], within: 0.1)) failsWithErrorMessage("expected to be close to <[0, 1]> (each within 0.0001), got <[0, 1.1]>") { expect([0.0, 1.1]) ≈ [0.0, 1.0] } failsWithErrorMessage("expected to be close to <[0.2, 1.2]> (each within 0.1), got <[0, 1.1]>") { expect([0.0, 1.1]).to(beCloseTo([0.2, 1.2], within: 0.1)) } } }
mit
97934e267667396f17ec5ee35572cccc
42.481481
136
0.599375
3.616016
false
true
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Renderers/LineChartRenderer.swift
19
24853
// // LineChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/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 import CoreGraphics import UIKit @objc public protocol LineChartRendererDelegate { func lineChartRendererData(renderer: LineChartRenderer) -> LineChartData! func lineChartRenderer(renderer: LineChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func lineChartRendererFillFormatter(renderer: LineChartRenderer) -> ChartFillFormatter func lineChartDefaultRendererValueFormatter(renderer: LineChartRenderer) -> NSNumberFormatter! func lineChartRendererChartYMax(renderer: LineChartRenderer) -> Double func lineChartRendererChartYMin(renderer: LineChartRenderer) -> Double func lineChartRendererChartXMax(renderer: LineChartRenderer) -> Double func lineChartRendererChartXMin(renderer: LineChartRenderer) -> Double func lineChartRendererMaxVisibleValueCount(renderer: LineChartRenderer) -> Int } public class LineChartRenderer: ChartDataRendererBase { public weak var delegate: LineChartRendererDelegate? public init(delegate: LineChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(#context: CGContext) { var lineData = delegate!.lineChartRendererData(self) if (lineData === nil) { return } for (var i = 0; i < lineData.dataSetCount; i++) { var set = lineData.getDataSetByIndex(i) if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! LineChartDataSet) } } } internal struct CGCPoint { internal var x: CGFloat = 0.0 internal var y: CGFloat = 0.0 /// x-axis distance internal var dx: CGFloat = 0.0 /// y-axis distance internal var dy: CGFloat = 0.0 internal init(x: CGFloat, y: CGFloat) { self.x = x self.y = y } } internal func drawDataSet(#context: CGContext, dataSet: LineChartDataSet) { var entries = dataSet.yVals if (entries.count < 1) { return } CGContextSaveGState(context) CGContextSetLineWidth(context, dataSet.lineWidth) if (dataSet.lineDashLengths != nil) { CGContextSetLineDash(context, dataSet.lineDashPhase, dataSet.lineDashLengths, dataSet.lineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } // if drawing cubic lines is enabled if (dataSet.isDrawCubicEnabled) { drawCubic(context: context, dataSet: dataSet, entries: entries) } else { // draw normal (straight) lines drawLinear(context: context, dataSet: dataSet, entries: entries) } CGContextRestoreGState(context) } internal func drawCubic(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { var trans = delegate?.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) var phaseX = _animator.phaseX var phaseY = _animator.phaseY // get the color that is specified for this position from the DataSet var drawingColor = dataSet.colors.first! var intensity = dataSet.cubicIntensity // the path for the cubic-spline var cubicPath = CGPathCreateMutable() var valueToPixelMatrix = trans!.valueToPixelMatrix var size = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) if (size - minx >= 2) { var prevDx: CGFloat = 0.0 var prevDy: CGFloat = 0.0 var curDx: CGFloat = 0.0 var curDy: CGFloat = 0.0 var prevPrev = entries[minx] var prev = entries[minx] var cur = entries[minx] var next = entries[minx + 1] // let the spline start CGPathMoveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) prevDx = CGFloat(cur.xIndex - prev.xIndex) * intensity prevDy = CGFloat(cur.value - prev.value) * intensity curDx = CGFloat(next.xIndex - cur.xIndex) * intensity curDy = CGFloat(next.value - cur.value) * intensity // the first cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) for (var j = minx + 1, count = min(size, entries.count - 1); j < count; j++) { prevPrev = entries[j == 1 ? 0 : j - 2] prev = entries[j - 1] cur = entries[j] next = entries[j + 1] prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } if (size > entries.count - 1) { prevPrev = entries[entries.count - (entries.count >= 3 ? 3 : 2)] prev = entries[entries.count - 2] cur = entries[entries.count - 1] next = cur prevDx = CGFloat(cur.xIndex - prevPrev.xIndex) * intensity prevDy = CGFloat(cur.value - prevPrev.value) * intensity curDx = CGFloat(next.xIndex - prev.xIndex) * intensity curDy = CGFloat(next.value - prev.value) * intensity // the last cubic CGPathAddCurveToPoint(cubicPath, &valueToPixelMatrix, CGFloat(prev.xIndex) + prevDx, (CGFloat(prev.value) + prevDy) * phaseY, CGFloat(cur.xIndex) - curDx, (CGFloat(cur.value) - curDy) * phaseY, CGFloat(cur.xIndex), CGFloat(cur.value) * phaseY) } } CGContextSaveGState(context) if (dataSet.isDrawFilledEnabled) { drawCubicFill(context: context, dataSet: dataSet, spline: cubicPath, matrix: valueToPixelMatrix, from: minx, to: size) } CGContextBeginPath(context) CGContextAddPath(context, cubicPath) CGContextSetStrokeColorWithColor(context, drawingColor.CGColor) CGContextStrokePath(context) CGContextRestoreGState(context) } internal func drawCubicFill(#context: CGContext, dataSet: LineChartDataSet, spline: CGMutablePath, var matrix: CGAffineTransform, from: Int, to: Int) { CGContextSaveGState(context) var fillMin = delegate!.lineChartRendererFillFormatter(self).getFillLinePosition( dataSet: dataSet, data: delegate!.lineChartRendererData(self), chartMaxY: delegate!.lineChartRendererChartYMax(self), chartMinY: delegate!.lineChartRendererChartYMin(self)) var pt1 = CGPoint(x: CGFloat(to - 1), y: fillMin) var pt2 = CGPoint(x: CGFloat(from), y: fillMin) pt1 = CGPointApplyAffineTransform(pt1, matrix) pt2 = CGPointApplyAffineTransform(pt2, matrix) CGContextBeginPath(context) CGContextAddPath(context, spline) CGContextAddLineToPoint(context, pt1.x, pt1.y) CGContextAddLineToPoint(context, pt2.x, pt2.y) CGContextClosePath(context) CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor) CGContextSetAlpha(context, dataSet.fillAlpha) CGContextFillPath(context) CGContextRestoreGState(context) } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawLinear(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry]) { var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) var valueToPixelMatrix = trans.valueToPixelMatrix var phaseX = _animator.phaseX var phaseY = _animator.phaseY CGContextSaveGState(context) var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) // more than 1 color if (dataSet.colors.count > 1) { if (_lineSegments.count != 2) { _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) } for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { if (count > 1 && j == count - 1) { // Last point, we have already drawn a line to this point break } var e = entries[j] _lineSegments[0].x = CGFloat(e.xIndex) _lineSegments[0].y = CGFloat(e.value) * phaseY _lineSegments[0] = CGPointApplyAffineTransform(_lineSegments[0], valueToPixelMatrix) if (j + 1 < count) { e = entries[j + 1] _lineSegments[1].x = CGFloat(e.xIndex) _lineSegments[1].y = CGFloat(e.value) * phaseY _lineSegments[1] = CGPointApplyAffineTransform(_lineSegments[1], valueToPixelMatrix) } else { _lineSegments[1] = _lineSegments[0] } if (!viewPortHandler.isInBoundsRight(_lineSegments[0].x)) { break } // make sure the lines don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(_lineSegments[1].x) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y)) || (!viewPortHandler.isInBoundsTop(_lineSegments[0].y) && !viewPortHandler.isInBoundsBottom(_lineSegments[1].y))) { continue } // get the color that is set for this line-segment CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextStrokeLineSegments(context, _lineSegments, 2) } } else { // only one color per dataset var e1: ChartDataEntry! var e2: ChartDataEntry! if (_lineSegments.count != max((entries.count - 1) * 2, 2)) { _lineSegments = [CGPoint](count: max((entries.count - 1) * 2, 2), repeatedValue: CGPoint()) } e1 = entries[minx] var count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))) for (var x = count > 1 ? minx + 1 : minx, j = 0; x < count; x++) { e1 = entries[x == 0 ? 0 : (x - 1)] e2 = entries[x] _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e1.xIndex), y: CGFloat(e1.value) * phaseY), valueToPixelMatrix) _lineSegments[j++] = CGPointApplyAffineTransform(CGPoint(x: CGFloat(e2.xIndex), y: CGFloat(e2.value) * phaseY), valueToPixelMatrix) } var size = max((count - minx - 1) * 2, 2) CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextStrokeLineSegments(context, _lineSegments, size) } CGContextRestoreGState(context) // if drawing filled is enabled if (dataSet.isDrawFilledEnabled && entries.count > 0) { drawLinearFill(context: context, dataSet: dataSet, entries: entries, minx: minx, maxx: maxx, trans: trans) } } internal func drawLinearFill(#context: CGContext, dataSet: LineChartDataSet, entries: [ChartDataEntry], minx: Int, maxx: Int, trans: ChartTransformer) { CGContextSaveGState(context) CGContextSetFillColorWithColor(context, dataSet.fillColor.CGColor) // filled is usually drawn with less alpha CGContextSetAlpha(context, dataSet.fillAlpha) var filled = generateFilledPath( entries, fillMin: delegate!.lineChartRendererFillFormatter(self).getFillLinePosition( dataSet: dataSet, data: delegate!.lineChartRendererData(self), chartMaxY: delegate!.lineChartRendererChartYMax(self), chartMinY: delegate!.lineChartRendererChartYMin(self)), from: minx, to: maxx, matrix: trans.valueToPixelMatrix) CGContextBeginPath(context) CGContextAddPath(context, filled) CGContextFillPath(context) CGContextRestoreGState(context) } /// Generates the path that is used for filled drawing. private func generateFilledPath(entries: [ChartDataEntry], fillMin: CGFloat, from: Int, to: Int, var matrix: CGAffineTransform) -> CGPath { var phaseX = _animator.phaseX var phaseY = _animator.phaseY var filled = CGPathCreateMutable() CGPathMoveToPoint(filled, &matrix, CGFloat(entries[from].xIndex), fillMin) CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[from].xIndex), CGFloat(entries[from].value) * phaseY) // create a new path for (var x = from + 1, count = Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))); x < count; x++) { var e = entries[x] CGPathAddLineToPoint(filled, &matrix, CGFloat(e.xIndex), CGFloat(e.value) * phaseY) } // close up CGPathAddLineToPoint(filled, &matrix, CGFloat(entries[max(min(Int(ceil(CGFloat(to - from) * phaseX + CGFloat(from))) - 1, entries.count - 1), 0)].xIndex), fillMin) CGPathCloseSubpath(filled) return filled } public override func drawValues(#context: CGContext) { var lineData = delegate!.lineChartRendererData(self) if (lineData === nil) { return } var defaultValueFormatter = delegate!.lineChartDefaultRendererValueFormatter(self) if (CGFloat(lineData.yValCount) < CGFloat(delegate!.lineChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX) { var dataSets = lineData.dataSets for (var i = 0; i < dataSets.count; i++) { var dataSet = dataSets[i] as! LineChartDataSet if (!dataSet.isDrawValuesEnabled) { continue } var valueFont = dataSet.valueFont var valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) // make sure the values do not interfear with the circles var valOffset = Int(dataSet.circleRadius * 1.75) if (!dataSet.isDrawCirclesEnabled) { valOffset = valOffset / 2 } var entries = dataSet.yVals var entryFrom = dataSet.entryForXIndex(_minX) var entryTo = dataSet.entryForXIndex(_maxX) var minx = max(dataSet.entryIndex(entry: entryFrom!, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo!, isEqual: true) + 1, entries.count) var positions = trans.generateTransformedValuesLine( entries, phaseX: _animator.phaseX, phaseY: _animator.phaseY, from: minx, to: maxx) for (var j = 0, count = positions.count; j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break } if (!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y)) { continue } var val = entries[j + minx].value ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(val)!, point: CGPoint(x: positions[j].x, y: positions[j].y - CGFloat(valOffset) - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(#context: CGContext) { drawCircles(context: context) } private func drawCircles(#context: CGContext) { var phaseX = _animator.phaseX var phaseY = _animator.phaseY var lineData = delegate!.lineChartRendererData(self) var dataSets = lineData.dataSets var pt = CGPoint() var rect = CGRect() CGContextSaveGState(context) for (var i = 0, count = dataSets.count; i < count; i++) { var dataSet = lineData.getDataSetByIndex(i) as! LineChartDataSet! if (!dataSet.isVisible || !dataSet.isDrawCirclesEnabled) { continue } var trans = delegate!.lineChartRenderer(self, transformerForAxis: dataSet.axisDependency) var valueToPixelMatrix = trans.valueToPixelMatrix var entries = dataSet.yVals var circleRadius = dataSet.circleRadius var circleDiameter = circleRadius * 2.0 var circleHoleDiameter = circleRadius var circleHoleRadius = circleHoleDiameter / 2.0 var isDrawCircleHoleEnabled = dataSet.isDrawCircleHoleEnabled var entryFrom = dataSet.entryForXIndex(_minX)! var entryTo = dataSet.entryForXIndex(_maxX)! var minx = max(dataSet.entryIndex(entry: entryFrom, isEqual: true), 0) var maxx = min(dataSet.entryIndex(entry: entryTo, isEqual: true) + 1, entries.count) for (var j = minx, count = Int(ceil(CGFloat(maxx - minx) * phaseX + CGFloat(minx))); j < count; j++) { var e = entries[j] pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the circles don't do shitty things outside bounds if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y)) { continue } CGContextSetFillColorWithColor(context, dataSet.getCircleColor(j)!.CGColor) rect.origin.x = pt.x - circleRadius rect.origin.y = pt.y - circleRadius rect.size.width = circleDiameter rect.size.height = circleDiameter CGContextFillEllipseInRect(context, rect) if (isDrawCircleHoleEnabled) { CGContextSetFillColorWithColor(context, dataSet.circleHoleColor.CGColor) rect.origin.x = pt.x - circleHoleRadius rect.origin.y = pt.y - circleHoleRadius rect.size.width = circleHoleDiameter rect.size.height = circleHoleDiameter CGContextFillEllipseInRect(context, rect) } } } CGContextRestoreGState(context) } var _highlightPtsBuffer = [CGPoint](count: 4, repeatedValue: CGPoint()) public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { var lineData = delegate!.lineChartRendererData(self) var chartXMax = delegate!.lineChartRendererChartXMax(self) var chartYMax = delegate!.lineChartRendererChartYMax(self) var chartYMin = delegate!.lineChartRendererChartYMin(self) CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { var set = lineData.getDataSetByIndex(indices[i].dataSetIndex) as! LineChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX) { continue } let yValue = set.yValForXIndex(xIndex) if (yValue.isNaN) { continue } var y = CGFloat(yValue) * _animator.phaseY; // get the y-position _highlightPtsBuffer[0] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMax)) _highlightPtsBuffer[1] = CGPoint(x: CGFloat(xIndex), y: CGFloat(chartYMin)) _highlightPtsBuffer[2] = CGPoint(x: CGFloat(delegate!.lineChartRendererChartXMin(self)), y: y) _highlightPtsBuffer[3] = CGPoint(x: CGFloat(chartXMax), y: y) var trans = delegate!.lineChartRenderer(self, transformerForAxis: set.axisDependency) trans.pointValuesToPixel(&_highlightPtsBuffer) // draw the highlight lines CGContextStrokeLineSegments(context, _highlightPtsBuffer, 4) } CGContextRestoreGState(context) } }
mit
520e898ffb54769fd320844fcd229e1d
38.576433
306
0.555909
5.562444
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/GroupCallSchedule.swift
1
6975
// // GroupCallSchedule.swift // Telegram // // Created by Mikhail Filimonov on 06.04.2021. // Copyright © 2021 Telegram. All rights reserved. // import Foundation import TGUIKit import SwiftSignalKit import TelegramCore import Postbox private final class GroupCallScheduleTimerView : View { private let counter = DynamicCounterTextView(frame: .zero) private var nextTimer: SwiftSignalKit.Timer? private let headerView = TextView() private let descView = TextView() private let maskImage: CGImage private let mask: View required init(frame frameRect: NSRect) { mask = View(frame: NSMakeRect(0, 0, frameRect.width, 64)) let purple = GroupCallTheme.purple let pink = GroupCallTheme.pink headerView.userInteractionEnabled = false headerView.isSelectable = false descView.userInteractionEnabled = false descView.isSelectable = false maskImage = generateImage(mask.frame.size, contextGenerator: { size, ctx in ctx.clear(size.bounds) let colorSpace = CGColorSpaceCreateDeviceRGB() var locations:[CGFloat] = [0.0, 0.85, 1.0] let gradient = CGGradient(colorsSpace: colorSpace, colors: [pink.cgColor, purple.cgColor, purple.cgColor] as CFArray, locations: &locations)! ctx.drawLinearGradient(gradient, start: CGPoint(x: 0, y: 0.0), end: CGPoint(x: size.width, y: size.height), options: []) })! super.init(frame: frameRect) addSubview(mask) addSubview(headerView) addSubview(descView) isEventLess = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(time timeValue: Int32, animated: Bool) { let time = Int(timeValue - Int32(Date().timeIntervalSince1970)) let text = timerText(time, addminus: false) let value = DynamicCounterTextView.make(for: text, count: text, font: .digitalRound(50), textColor: .white, width: frame.width) counter.update(value, animated: animated, reversed: true) counter.change(size: value.size, animated: animated) counter.change(pos: focus(value.size).origin, animated: animated) self.nextTimer = SwiftSignalKit.Timer(timeout: 0.5, repeat: false, completion: { [weak self] in self?.update(time: timeValue, animated: true) }, queue: .mainQueue()) let counterSubviews = counter.effectiveSubviews while mask.subviews.count > counterSubviews.count { mask.subviews.removeLast() } while mask.subviews.count < counterSubviews.count { let view = ImageView() view.image = maskImage view.sizeToFit() mask.addSubview(view) } for (i, mask) in mask.subviews.enumerated() { mask.layer?.mask = counterSubviews[i].layer } mask.setFrameSize(value.size) mask.change(pos: NSMakePoint(round((frame.width - value.size.width) / 2), focus(mask.frame.size).minY), animated: animated) self.nextTimer?.start() if time <= 5 { if mask.layer?.animation(forKey: "opacity") == nil { let animation: CABasicAnimation = CABasicAnimation(keyPath: "opacity") animation.timingFunction = .init(name: .easeInEaseOut) animation.fromValue = 1 animation.toValue = 0.5 animation.duration = 1.0 animation.autoreverses = true animation.isRemovedOnCompletion = true animation.fillMode = CAMediaTimingFillMode.forwards mask.layer?.add(animation, forKey: "opacity") } } else { mask.layer?.removeAnimation(forKey: "opacity") } let headerText = time >= 0 ? strings().voiceChatScheduledHeader : strings().voiceChatScheduledHeaderLate let headerLayout = TextViewLayout.init(.initialize(string: headerText, color: GroupCallTheme.customTheme.textColor, font: .avatar(26))) headerLayout.measure(width: frame.width - 60) headerView.update(headerLayout) headerView.centerX(y: mask.frame.minY - headerView.frame.height) let descLayout = TextViewLayout.init(.initialize(string: stringForMediumDate(timestamp: timeValue), color: GroupCallTheme.customTheme.textColor, font: .avatar(26))) descLayout.measure(width: frame.width - 60) descView.update(descLayout) descView.centerX(y: mask.frame.maxY) } override func layout() { super.layout() mask.center() headerView.centerX(y: mask.frame.minY - headerView.frame.height) descView.centerX(y: mask.frame.maxY) } } final class GroupCallScheduleView : View { private weak var currentView: View? private var timerView: GroupCallScheduleTimerView? required init(frame frameRect: NSRect) { super.init(frame: frameRect) isEventLess = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(_ state: GroupCallUIState, arguments: GroupCallUIArguments?, animated: Bool) { if let scheduleTimestamp = state.state.scheduleTimestamp { let current: GroupCallScheduleTimerView if let timerView = timerView { current = timerView } else { current = GroupCallScheduleTimerView(frame: NSMakeRect(0, 0, frame.width, frame.height)) self.timerView = current addSubview(current) if animated { current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } if current != self.currentView { if let view = self.currentView { if animated { view.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak view] _ in view?.removeFromSuperview() }) } else { view.removeFromSuperview() } } } self.timerView?.update(time: scheduleTimestamp, animated: animated) self.currentView = current } } func updateLayout(size: NSSize, transition: ContainedViewLayoutTransition) { if let view = currentView { transition.updateFrame(view: view, frame: NSMakeRect(0, 0, size.width, size.height)) } } override func layout() { super.layout() updateLayout(size: self.frame.size, transition: .immediate) } }
gpl-2.0
ef01dac1038b1bf80359e3da2ae1ee92
36.294118
172
0.599943
4.876923
false
false
false
false
Yoseob/Trevi
Trevi/Library/OutgoingMessage.swift
1
746
// // HttpStream.swift // Trevi // // Created by LeeYoseob on 2016. 3. 3.. // Copyright © 2016년 LeeYoseob. All rights reserved. // import Foundation //temp class public class OutgoingMessage { var socket: Socket! public var connection: Socket! public var header: [String: String]! public var shouldKeepAlive = false public var chunkEncoding = false public init(socket: AnyObject){ header = [String: String]() } deinit{ socket = nil connection = nil } public func _end(data: NSData, encoding: Any! = nil){ self.socket.write(data, handle: self.socket.handle) if shouldKeepAlive == false { self.socket.close() } } }
apache-2.0
3841a3d0d64bbe26df559730f4950ede
18.552632
59
0.600269
4.082418
false
false
false
false
Rivukis/Spry
Sources/Spry/Constant.swift
1
7268
import Foundation private func fatalError(title: String, entries: [String]) -> Never { let titleString = "\n --- FATAL ERROR: \(title) ---" let entriesString = entries.map { "\n → " + $0 }.joined() + "\n" let errorString = titleString + entriesString SpryConfiguration.fatalErrorClosure(errorString) fatalError(errorString) } private func routeString(filePath: String, line: String) -> String { let file = filePath.components(separatedBy: "/").last ?? filePath return file + ":" + line } internal enum Constant { enum FatalError { static func wrongNumberOfArgsBeingCompared<T>(fakeType: T.Type, functionName: String, specifiedArguments: [SpryEquatable?], actualArguments: [Any?]) -> Never { let title = "Wrong number of arguments to compare" let entries = [ "Type: \(T.self)", "Function: \(fakeType)", "Specified count: \(specifiedArguments.count)", "Received count: \(actualArguments.count)", "Specified arguments: \(descriptionOfArguments(specifiedArguments))", "Actual arguments: \(descriptionOfArguments(actualArguments))" ] fatalError(title: title, entries: entries) } static func doesNotConformToEquatable(_ value: SpryEquatable) -> Never { let title = "Improper SpryEquatable" let entries = [ "\(type(of: value)) must either conform to Equatable or be changed to a reference type (i.e. class)" ] fatalError(title: title, entries: entries) } static func doesNotConformToSpryEquatable(_ value: Any) -> Never { let title = "SpryEquatable required" let entries = [ "\(type(of: value)) must conform to SpryEquatable" ] fatalError(title: title, entries: entries) } static func shouldNotConformToOptionalType(_ value: Any) -> Never { let title = "Not allowed to conform to 'OptionalType'" let entries = [ "Violating Type: \(type(of: value))", "Nothing should NOT conform to OptionalType. This is reserved for Optional<Wrapped>" ] fatalError(title: title, entries: entries) } static func argumentCaptorCouldNotReturnSpecifiedType<T>(value: Any?, type: T.Type) -> Never { let title = "Argument Capture: wrong argument type" let entries = [ "Captured argument: \(value as Any)", "Specified type: \(T.self)" ] fatalError(title: title, entries: entries) } static func capturedArgumentsOutOfBounds(index: Int, capturedArguments: [Any?]) -> Never { let title = "Argument Capture: index out of bounds" let entries = [ "Index \(index) is out of bounds for captured arguments", "Current captured arguments: \(descriptionOfArguments(capturedArguments))" ] fatalError(title: title, entries: entries) } static func noReturnValueFoundForInstanceFunction<S: Stubbable, R>(stubbable: S, function: S.Function, arguments: [Any?], returnType: R.Type) -> Never { noReturnValueFoundForFunction(stubbableType: S.self, functionName: function.rawValue, arguments: arguments, returnType: R.self, stubsDictionary: stubbable._stubsDictionary) } static func noReturnValueFoundForClassFunction<S: Stubbable, R>(stubbableType _: S.Type, function: S.ClassFunction, arguments: [Any?], returnType: R.Type) -> Never { noReturnValueFoundForFunction(stubbableType: S.self, functionName: function.rawValue, arguments: arguments, returnType: R.self, stubsDictionary: S._stubsDictionary) } static func noReturnValueSourceFound(functionName: String) -> Never { let title = "Incomplete Stub" let entries = [ "Must add '.andReturn()', '.andDo()', or '.andThrow()' when stubbing a function" ] fatalError(title: title, entries: entries) } static func andThrowOnNonThrowingInstanceFunction<S: Stubbable>(stubbable: S, function: S.Function) -> Never { andThrowOnNonThrowingFunction(type: S.self, functionName: function.rawValue) } static func andThrowOnNonThrowingClassFunction<S: Stubbable>(stubbable: S.Type, function: S.ClassFunction) -> Never { andThrowOnNonThrowingFunction(type: S.self, functionName: function.rawValue) } static func noFunctionFound<T>(functionName: String, type: T.Type, file: String, line: Int) -> Never { let caseName = functionName.removeAfter(startingCharacter: "(") ?? functionName let probableMessage = "case \(caseName) = \"\(functionName)\"" let title = "Unable to find function" let entries = [ "Type: \(type)", "Function signature: \(functionName)", "Error occured on: \(routeString(filePath: file, line: "\(line)"))", "Possible Fix: ↴", probableMessage, ] fatalError(title: title, entries: entries) } static func stubbingSameFunctionWithSameArguments(stub: Stub) -> Never { let title = "Stubbing the same function with the same arguments" let entries = [ "Function: \(stub.functionName)", "Arguments: \(descriptionOfArguments(stub.arguments))", "In most cases, stubbing the same function with the same arguments is a \"code smell\"", "However, if this is intentional then use `.stubAgain()`" ] fatalError(title: title, entries: entries) } // MARK: - Private private static func noReturnValueFoundForFunction<S, R>(stubbableType: S.Type, functionName: String, arguments: [Any?], returnType: R.Type, stubsDictionary: StubsDictionary) -> Never { let title = "No return value found" let entries = [ "Stubbable: \(S.self)", "Function: \(functionName)", "Arguments: \(descriptionOfArguments(arguments))", "Return Type: \(R.self)", "Current stubs: \(stubsDictionary.stubs)" ] fatalError(title: title, entries: entries) } private static func andThrowOnNonThrowingFunction<T>(type: T.Type, functionName: String) -> Never { let title = "Used '.andThrow()' on non-throwing function" let entries = [ "Stubbable: \(T.self)", "Function: \(functionName)", "If this function can throw, then ensure that the fake is calling 'spryifyThrows()' or 'stubbedValueThrows()' as the return value of this function." ] fatalError(title: title, entries: entries) } private static func descriptionOfArguments(_ arguments: [Any?]) -> String { return arguments .map{"<\($0 as Any)>"} .joined(separator: ", ") } } }
mit
bd6eb7b38b4ca9bb9921d41fb4f4de4b
42.238095
192
0.595402
4.951602
false
false
false
false
katsana/katsana-sdk-ios
KatsanaSDK/Object/VehicleSubscription.swift
1
2434
// // VehicleSubscription.swift // KatsanaSDK // // Created by Wan Lutfi on 09/04/2018. // Copyright © 2018 pixelated. All rights reserved. // @objc public enum VehicleSubscriptionStatus: Int{ case active case expiring case expired case terminated case unknown } @objcMembers open class VehicleSubscription: NSObject { override open class func fastCodingKeys() -> [Any]? { return ["deviceId", "deviceImei", "vehicleNumber", "vehicleDescription", "vehicleExpiredAt", "subscriptionId", "subscriptionPrice", "subscriptionStartAt", "subscriptionEndAt", "subscriptionPriceWithTax", "subscriptionTax", "planId", "planName", "planDescription", "planPrice", "planBillingCycle", "planQuickBooksId", "planRenewalAddonId", "planTagId", "planType", "planCreatedAt", "planUpdatedAt", "isReseller"] } open var deviceId: String! open var deviceImei: String! open var vehicleNumber: String! open var vehicleDescription: String! open var vehicleExpiredAt: Date! open var subscriptionId: String! open var subscriptionPrice: Int = 0 open var subscriptionPriceWithTax: Int = 0 open var subscriptionTax: Float = 0 open var subscriptionStartAt: Date! open var subscriptionEndAt: Date! open var planId: String! open var planName: String! open var planDescription: String! open var planPrice: Int = 0 // open var planTaxRate: Int = 0 //Should not be used // open var planTaxValue: Int = 0 //Should not be used open var planBillingCycle: Int = 0 open var planQuickBooksId: String! open var planRenewalAddonId: String! open var planTagId: String! open var planType: String! open var planCreatedAt: Date! open var planUpdatedAt: Date! open var isReseller = false open func status() -> VehicleSubscriptionStatus { if let date = vehicleExpiredAt { var status = VehicleSubscriptionStatus.unknown let dayDuration = date.daysAfterDate(Date()) if dayDuration >= 60 { status = .active } else if dayDuration >= 0, dayDuration < 60{ status = .expiring } else if dayDuration < 0, dayDuration > -60{ status = .expired }else{ status = .terminated } return status } return .unknown } }
apache-2.0
2bde6c61fb4fb0e2020507a5236d8d34
32.328767
419
0.645705
4.415608
false
false
false
false
Lves/LLRefresh
LLRefreshDemo/Demos/GifRefreshViewController.swift
1
2581
// // GifRefreshViewController.swift // LLRefreshDemo // // Created by lixingle on 2017/3/7. // Copyright © 2017年 com.lvesli. All rights reserved. // import UIKit import LLRefresh class GifRefreshViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dataArray:[String] = [] override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() //1.0 set header & footer by block setRefreshByBlock() //2.0 set header & footer by target // setRefreshByTarget() tableView.ll_header?.beginRefreshing() } //MARK: Block实现方式 func setRefreshByBlock(){ //1.0 tableView.ll_header = LLEatHeader(refreshingBlock: {[weak self] _ in self?.loadNewData() }) tableView.ll_footer = LLEatFooter(refreshingBlock: { [weak self] _ in self?.loadMoreDate() }) } //MARK: Target实现方式 func setRefreshByTarget(){ tableView.ll_header = LLEatHeader(target: self, action: #selector(loadNewData)) tableView.ll_footer = LLEatFooter(target: self, action: #selector(loadMoreDate)) } func loadNewData() { //update data let format = DateFormatter() format.dateFormat = "HH:mm:ss" for _ in 0...2 { dataArray.insert(format.string(from: Date()), at: 0) } sleep(2) //end refreshing tableView.ll_header?.endRefreshing() tableView.reloadData() } func loadMoreDate() { //update data let format = DateFormatter() format.dateFormat = "HH:mm:ss" for _ in 0...2 { dataArray.append(format.string(from: Date())) } sleep(2) //end refreshing tableView.ll_footer?.endRefreshing() tableView.reloadData() } // MARK: - Table view data source func numberOfSectionsInTableView(_ tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } cell?.textLabel?.text = dataArray[indexPath.row] return cell! } }
mit
856d77de353c7e63b9cbec89fc6546e6
28.448276
109
0.59797
4.591398
false
false
false
false
Zingoer/ViewFinder-Playground
ViewFinder.playground/Sources/ViewFinderPainter.swift
1
3532
import Foundation import UIKit public class ViewFinderPainter{ let frame: CGRect // Gloden ratio multiplier let ratio:CGFloat = 1.618 // Color alpha let alpha:CGFloat = 0.6 // Parent View Width var pWidth: CGFloat{ get{ return frame.width } } // Parent View Height var pHeight: CGFloat{ get{ return frame.height } } var x: CGFloat{ get{ return (pWidth - pWidth/ratio)/2 } } var y: CGFloat{ get{ return (pHeight - pWidth/ratio)/2 } } var finderSideLenght: CGFloat{ get{ return pWidth/ratio } } /** Create the ViewFinder view in certain frame */ public init(frame: CGRect){ self.frame = frame } public func createGrayMask() -> UIView{ // Create a gray view let gray = UIView(frame: CGRect(x: 0.0, y: 0.0, width: pWidth, height: pHeight)) gray.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(alpha) // Mask the view let maskLayer = createMaskLayer() gray.layer.mask = maskLayer let frameView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: pWidth, height: pHeight)) frameView.layer.addSublayer(createFrameLayer()) gray.addSubview(frameView) gray.clipsToBounds = true return gray } public func createFrame() -> UIView{ let frameView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: pWidth, height: pHeight)) frameView.layer.addSublayer(createFrameLayer()) frameView.clipsToBounds = true return frameView } func createMaskLayer() -> CAShapeLayer{ // Create mask sublayer let maskLayer = CAShapeLayer() // Init the path let path = CGPathCreateMutable() // More tutorial can be find on here: http://stackoverflow.com/questions/28448698/how-do-i-create-a-uiview-with-a-transparent-circle-inside-in-swift // Create two Rect and combine together to create the mask shape CGPathAddRect(path, nil, CGRectMake(0, 0, pWidth, pHeight)) CGPathAddRect(path, nil, CGRectMake(x, y, finderSideLenght, finderSideLenght)) maskLayer.path = path; maskLayer.fillRule = kCAFillRuleEvenOdd return maskLayer } func createFrameLayer() -> CAShapeLayer{ let path = UIBezierPath() let bottom = y+finderSideLenght let right = x+finderSideLenght let cornerLength = finderSideLenght * 0.2 // Draw the left half finder frame path.moveToPoint(CGPointMake(x+cornerLength, y)) path.addLineToPoint(CGPointMake(x, y)) path.addLineToPoint(CGPointMake(x, bottom)) path.addLineToPoint(CGPointMake(x+cornerLength, bottom)) // Draw the right half finder frame path.moveToPoint(CGPointMake(right-cornerLength, y)) path.addLineToPoint(CGPointMake(right, y)) path.addLineToPoint(CGPointMake(right, bottom)) path.addLineToPoint(CGPointMake(right-cornerLength, bottom)) let frameLayer = CAShapeLayer() frameLayer.path = path.CGPath frameLayer.strokeColor = UIColor.whiteColor().CGColor frameLayer.lineWidth = 8.0 frameLayer.fillColor = UIColor.clearColor().CGColor return frameLayer } }
mit
ce73dbcfb067fb3f534a4f4527968a9c
28.198347
156
0.600793
4.74094
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Providers/Core Data Providers/Buckets/ManagedBucketsRequester.swift
1
3114
// // ManagedBucketsRequester.swift // Inbbbox // // Created by Lukasz Wolanczyk on 2/23/16. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit import PromiseKit import CoreData import SwiftyJSON class ManagedBucketsRequester { let managedObjectContext: NSManagedObjectContext let managedObjectsProvider: ManagedObjectsProvider init(managedObjectContext: NSManagedObjectContext = (UIApplication.shared.delegate as? AppDelegate)!.managedObjectContext) { self.managedObjectContext = managedObjectContext managedObjectsProvider = ManagedObjectsProvider(managedObjectContext: managedObjectContext) } func addBucket(_ name: String, description: NSAttributedString?) -> Promise<BucketType> { let bucket = Bucket( identifier: ProcessInfo.processInfo.globallyUniqueString.replacingOccurrences(of: "-", with: ""), name: name, attributedDescription: description, shotsCount: 0, createdAt: Date(), owner: User(json: guestJSON) ) let managedBucket = managedObjectsProvider.managedBucket(bucket) return Promise<BucketType> { fulfill, reject in do { try managedObjectContext.save() fulfill(managedBucket) } catch { reject(error) } } } func addShot(_ shot: ShotType, toBucket bucket: BucketType) -> Promise<Void> { let managedBucket = managedObjectsProvider.managedBucket(bucket) let managedShot = managedObjectsProvider.managedShot(shot) if let _ = managedBucket.shots { managedBucket.addShot(managedShot) } else { managedBucket.shots = NSSet(object: managedShot) } managedBucket.mngd_shotsCount += 1 return Promise<Void> { fulfill, reject in do { fulfill(try managedObjectContext.save()) } catch { reject(error) } } } func removeShot(_ shot: ShotType, fromBucket bucket: BucketType) -> Promise<Void> { let managedBucket = managedObjectsProvider.managedBucket(bucket) let managedShot = managedObjectsProvider.managedShot(shot) if let managedShots = managedBucket.shots { let mutableShots = NSMutableSet(set: managedShots) mutableShots.remove(managedShot) managedBucket.shots = mutableShots.copy() as? NSSet managedBucket.mngd_shotsCount -= 1 } return Promise<Void> { fulfill, reject in do { fulfill(try managedObjectContext.save()) } catch { reject(error) } } } } var guestJSON: JSON { let guestDictionary = [ "id" : "guest.identifier", "name" : "guest.name", "username" : "guest.username", "avatar_url" : "guest.avatar.url", "shots_count" : 0, "param_to_omit" : "guest.param", "type" : "User" ] as [String : Any] return JSON(guestDictionary) }
gpl-3.0
16d549d1d2df437658278286235816f6
31.092784
128
0.615805
4.949126
false
false
false
false
marcusellison/Yelply
Yelp/BusinessesViewController.swift
1
5071
// // BusinessesViewController.swift // Yelp // // Created by Marcus J. Ellison on 5/12/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit class BusinessesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, FiltersViewControllerDelegate { @IBOutlet weak var tableView: UITableView! // @IBOutlet weak var businessSearchBar: UISearchBar! // instantiating the class prevents a nil value error from occuring in the tableview count section var businesses: [Business]! = [Business]() // search bar var businessSearchBar: UISearchBar? var searchActive : Bool = false var filtered: [Business] = [Business]() override func viewDidLoad() { super.viewDidLoad() // cues the table view to use autolayout to determine row height tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension tableView.dataSource = self tableView.delegate = self //search bar self.businessSearchBar = UISearchBar(frame :CGRectMake(0, 0, 320, 64)) businessSearchBar!.center = CGPointMake(160, 284) self.businessSearchBar!.delegate = self navigationItem.titleView = businessSearchBar Business.searchWithTerm("Thai", completion: { (businesses: [Business]!, error: NSError!) -> Void in self.businesses = businesses // reload the tableView data once api call finishes self.tableView.reloadData() }) // Business.searchWithTerm("Restaurants", sort: .Distance, categories: ["burgers"], deals: true) { (businesses: [Business]!, error: NSError!) -> Void in // self.businesses = businesses // // self.tableView.reloadData() // // for business in businesses { // println(business.name!) // println(business.address!) // } // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if businesses != nil { // if searchActive true return filtered.count otherwise return business.count return searchActive ? filtered.count : businesses.count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("BusinessCell", forIndexPath: indexPath) as! BusinessCell if searchActive { cell.business = filtered[indexPath.row] } else { cell.business = businesses![indexPath.row]; } // cell.business = businesses![indexPath.row] return cell } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let navigationController = segue.destinationViewController as! UINavigationController let filtersViewController = navigationController.topViewController as! FiltersViewController filtersViewController.delegate = self } func filtersViewController(filtersViewController:FiltersViewController, didUpdateFilters filters: [String: AnyObject]) { var categories = filters["categories"] as? [String] Business.searchWithTerm("restaurants", sort: nil, categories: categories, deals: nil) { (businesses:[Business]!, error: NSError!) -> Void in self.businesses = businesses self.tableView.reloadData() } } // search bar functions func searchBarTextDidBeginEditing(searchBar: UISearchBar) { searchActive = true; } func searchBarTextDidEndEditing(searchBar: UISearchBar) { searchActive = false; } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchActive = false; } func searchBarSearchButtonClicked(searchBar: UISearchBar) { searchActive = false; } func searchBar(businessSearchBar: UISearchBar, textDidChange searchText: String) { filtered = businesses!.filter({ (text) -> Bool in let tmp: AnyObject? = text.name let range = tmp!.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch) return range.location != NSNotFound }) if filtered.count == 0 { searchActive = false; } else { searchActive = true; } self.tableView.reloadData() } }
mit
9ec79eb6a6343f41d187e007e7ae8b59
33.496599
159
0.62256
5.736425
false
false
false
false
gperdomor/sygnaler
Sources/Sygnaler/Models/Notification.swift
1
3833
import Vapor enum Priority: String { case high case low } final class Notification: NodeConvertible { var id: String /// The type of the event as in the event's type field. /// Required if the notification relates to a specific Matrix event. var type: String /// The sender of the event as in the corresponding event field. /// Required if the notification relates to a specific Matrix event var sender: String /// The current display name of the sender in the room in which the event occurred. var senderDisplayName: String? /// The priority of the notification. If omitted, high is assumed. This may be used by push gateways to /// deliver less time-sensitive notifications in a way that will preserve battery power on mobile devices. /// One of: ["high", "low"] var priority: Priority /// The ID of the room in which this event occurred. /// Required if the notification relates to a specific Matrix event. var roomId: String? /// The name of the room in which the event occurred var roomName: String? var membership: String? /// An alias to display for the room in which the event occurred var roomAlias: String? /// This is an array of devices that the notification should be sent to var devices = [Device]() /// The content field from the event, if present. If the event had no content field, this field is omitted. var content: Node? /// This is true if the user receiving the notification is the subject of a member event (i.e. the state_key of /// the member event is equal to the user's Matrix ID). var userIsTarget: Bool? /// This is a dictionary of the current number of unacknowledged communications for the recipient user. /// Counts whose value is zero are omitted. var counts: Counts? init(node: Node, in context: Context) throws { do { id = try node.extract("id") } catch { throw NotificationParseError.noId } do { type = try node.extract("type") } catch { throw NotificationParseError.noType } do { sender = try node.extract("sender") } catch { throw NotificationParseError.noSender } senderDisplayName = try node.extract("sender_display_name") if let prio = node["prio"]?.string { priority = Priority(rawValue: prio) ?? Priority.high } else { priority = Priority.high } roomId = try node.extract("room_id") roomName = try node.extract("room_name") roomAlias = try node.extract("room_alias") membership = try node.extract("membership") content = try node.extract("content") userIsTarget = try node.extract("user_is_target") ?? false if let deviceArray: [Node] = node["devices"]?.nodeArray { for device: Node in deviceArray { let d = try Device(node: device) devices.append(d) } } if let countNode: Node = try node.extract("counts") { counts = try Counts(node: countNode) } } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "type": type, "sender": sender, "prio": priority.rawValue, "sender_display_name": senderDisplayName, "room_id": roomId, "room_name": roomName, "room_alias": roomAlias, "membership": membership, "user_is_target": userIsTarget, "content": content, "counts": counts?.makeNode(), "devices": devices.makeNode() ]) } }
mit
99c880358bc0019f5669b32ce9a7b961
32.043103
115
0.595878
4.703067
false
false
false
false
slavapestov/swift
test/SILGen/objc_witnesses.swift
2
3380
// RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | FileCheck %s // REQUIRES: objc_interop import Foundation import gizmo protocol Fooable { func foo() -> String! } // Witnesses Fooable.foo with the original ObjC-imported -foo method . extension Foo: Fooable {} class Phoûx : NSObject, Fooable { @objc func foo() -> String! { return "phoûx!" } } // witness for Foo.foo uses the foreign-to-native thunk: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWCSo3Foo14objc_witnesses7FooableS0_FS1_3foo // CHECK: function_ref @_TTOFCSo3Foo3foo // *NOTE* We have an extra copy here for the time being right // now. This will change once we teach SILGen how to not emit the // extra copy. // // witness for Phoûx.foo uses the Swift vtable // CHECK-LABEL: _TFC14objc_witnessesX8Phox_xra3foo // CHECK: bb0([[IN_ADDR:%.*]] : // CHECK: [[STACK_SLOT:%.*]] = alloc_stack $Phoûx // CHECK: copy_addr [[IN_ADDR]] to [initialization] [[STACK_SLOT]] // CHECK: [[VALUE:%.*]] = load [[STACK_SLOT]] // CHECK: class_method [[VALUE]] : $Phoûx, #Phoûx.foo!1 protocol Bells { init(bellsOn: Int) } extension Gizmo : Bells { } // CHECK: sil hidden [transparent] [thunk] @_TTWCSo5Gizmo14objc_witnesses5BellsS0_FS1_C // CHECK: bb0([[SELF:%[0-9]+]] : $*Gizmo, [[I:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick Gizmo.Type): // CHECK: [[INIT:%[0-9]+]] = function_ref @_TFCSo5GizmoC{{.*}} : $@convention(thin) (Int, @thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo> // CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[I]], [[META]]) : $@convention(thin) (Int, @thick Gizmo.Type) -> @owned ImplicitlyUnwrappedOptional<Gizmo> // CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<Gizmo> // CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<Gizmo> // CHECK: [[UNWRAP_FUNC:%[0-9]+]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue // CHECK: [[UNWRAPPED_RESULT_TEMP:%[0-9]+]] = alloc_stack $Gizmo // CHECK: apply [[UNWRAP_FUNC]]<Gizmo>([[UNWRAPPED_RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in ImplicitlyUnwrappedOptional<τ_0_0>) -> () // CHECK: [[UNWRAPPED_RESULT:%[0-9]+]] = load [[UNWRAPPED_RESULT_TEMP]] : $*Gizmo // CHECK: store [[UNWRAPPED_RESULT]] to [[SELF]] : $*Gizmo // CHECK: dealloc_stack [[UNWRAPPED_RESULT_TEMP]] : $*Gizmo // CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<Gizmo> // Test extension of a native @objc class to conform to a protocol with a // subscript requirement. rdar://problem/20371661 protocol Subscriptable { subscript(x: Int) -> AnyObject { get } } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWCSo7NSArray14objc_witnesses13SubscriptableS0_FS1_g9subscriptFSiPs9AnyObject_ : $@convention(witness_method) (Int, @in_guaranteed NSArray) -> @owned AnyObject { // CHECK: function_ref @_TTOFCSo7NSArrayg9subscriptFSiPs9AnyObject_ : $@convention(method) (Int, @guaranteed NSArray) -> @owned AnyObject // CHECK-LABEL: sil shared @_TTOFCSo7NSArrayg9subscriptFSiPs9AnyObject_ : $@convention(method) (Int, @guaranteed NSArray) -> @owned AnyObject { // CHECK: class_method [volatile] %1 : $NSArray, #NSArray.subscript!getter.1.foreign extension NSArray: Subscriptable {}
apache-2.0
4dd4624fa1bf61936ced4474c304a450
46.478873
213
0.673984
3.429298
false
false
false
false
Desgard/Calendouer-iOS
Calendouer/Calendouer/App/Controller/tableview-future/TableViewConfigurationType.swift
1
1552
// // TableViewConfigurationType.swift // Calendouer // // Created by 木瓜 on 2017/3/17. // Copyright © 2017年 Desgard_Duan. All rights reserved. // import Foundation import UIKit public protocol TableCellData{ var identifier: String { get } var cellHeight: CGFloat? { get } func build(tableCell: UITableViewCell, at indexPath: IndexPath) func select(indexPath: IndexPath) } public class ListCellData<Cell>: NSObject { typealias CellConfiguration = ((Cell, IndexPath) -> Void) typealias CellSelection = ((IndexPath) -> Void) typealias CellHeight = (() -> CGFloat) public let identifier: String fileprivate let configuration: CellConfiguration? fileprivate let select: CellSelection? fileprivate let height: CellHeight? init(identifier: String = String(describing: Cell.self), configuration: CellConfiguration? = nil, selection: CellSelection? = nil, height: CellHeight? = nil) { self.identifier = identifier self.configuration = configuration self.select = selection self.height = height } public var cellHeight: CGFloat? { return self.height?() } } extension ListCellData: TableCellData { public func build(tableCell: UITableViewCell, at indexPath: IndexPath) { let cell = tableCell as! Cell configuration?(cell, indexPath) } public func select(indexPath: IndexPath) { select?(indexPath) } }
mit
2c6711b603ce9f4b791d3cd256d4ca2d
24.75
76
0.64466
4.739264
false
true
false
false
duliodenis/cs193p-Spring-2016
democode/FaceIt-L6/FaceIt/VCL.swift
2
4441
// // VCL.swift // FaceIt // // Created by CS193p Instructor. // Copyright © 2015-16 Stanford University. All rights reserved. // import UIKit private var faceMVCinstanceCount = 0 func getFaceMVCinstanceCount() -> Int { faceMVCinstanceCount += 1; return faceMVCinstanceCount } private var emotionsMVCinstanceCount = 0 func getEmotionsMVCinstanceCount() -> Int { emotionsMVCinstanceCount += 1; return emotionsMVCinstanceCount } var lastLog = NSDate() var logPrefix = "" func bumpLogDepth() { if lastLog.timeIntervalSinceNow < -1.0 { logPrefix += "__" lastLog = NSDate() } } // we haven't covered extensions as yet // but it's basically a way to add methods to a given class extension FaceViewController { func logVCL(msg: String) { bumpLogDepth() print("\(logPrefix)Face \(instance) " + msg) } override func awakeFromNib() { logVCL("awakeFromNib()") } override func viewDidLoad() { super.viewDidLoad() logVCL("viewDidLoad()") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) logVCL("viewWillAppear(animated = \(animated))") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) logVCL("viewDidAppear(animated = \(animated))") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) logVCL("viewWillDisappear(animated = \(animated))") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) logVCL("viewDidDisappear(animated = \(animated))") } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() logVCL("viewWillLayoutSubviews() bounds.size = \(view.bounds.size)") } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() logVCL("viewDidLayoutSubviews() bounds.size = \(view.bounds.size)") } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) logVCL("viewWillTransitionToSize") coordinator.animateAlongsideTransition({ (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.logVCL("animatingAlongsideTransition") }, completion: { context -> Void in self.logVCL("doneAnimatingAlongsideTransition") }) } } extension EmotionsViewController { func logVCL(msg: String) { bumpLogDepth() print("\(logPrefix)Emotions \(instance) " + msg) } override func awakeFromNib() { logVCL("awakeFromNib()") } override func viewDidLoad() { super.viewDidLoad() logVCL("viewDidLoad()") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) logVCL("viewWillAppear(animated = \(animated))") } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) logVCL("viewDidAppear(animated = \(animated))") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) logVCL("viewWillDisappear(animated = \(animated))") } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) logVCL("viewDidDisappear(animated = \(animated))") } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() logVCL("viewWillLayoutSubviews() bounds.size = \(view.bounds.size)") } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() logVCL("viewDidLayoutSubviews() bounds.size = \(view.bounds.size)") } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) logVCL("viewWillTransitionToSize") coordinator.animateAlongsideTransition({ (context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.logVCL("animatingAlongsideTransition") }, completion: { context -> Void in self.logVCL("doneAnimatingAlongsideTransition") }) } }
mit
9e0f303f00120227d3d9cfbc02cf0cf4
32.89313
136
0.673198
5.515528
false
false
false
false
shaps80/InkKit
Pod/Classes/Borders.swift
1
4023
/* Copyright © 13/05/2016 Shaps 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 CoreGraphics import GraphicsRenderer /** Defines the various border types available - Inner: The border will be drawn on the inside of the shapes edge - Outer: The border will be drawn on the outside of the shapes edge - Center: The border will be drawn along the center of the shapes edge */ public enum BorderType { case inner case outer case center } extension RendererDrawable { /** Draws a border along the shapes edge - parameter type: The type of border to draw - parameter path: The path to apply this border to - parameter attributesBlock: Any associated attributes for this drawing */ public func stroke(border type: BorderType, path: BezierPath, color: Color? = nil, thickness: CGFloat? = nil, attributes attributesBlock: AttributesBlock? = nil) { switch type { case .inner: addInnerBorder(path, color: color, thickness: thickness, attributes: attributesBlock) case .outer: addOuterBorder(path, color: color, thickness: thickness, attributes: attributesBlock) case .center: addCenterBorder(path, color: color, thickness: thickness, attributes: attributesBlock) } } private func addInnerBorder(_ path: BezierPath, color: Color? = nil, thickness: CGFloat? = nil, attributes attributesBlock: AttributesBlock? = nil) { cgContext.draw(inRect: path.bounds, attributes: attributesBlock) { (context, rect, attributes) in context.setLineWidth((thickness ?? attributes.lineWidth) * 2) if let color = color { context.setStrokeColor(color.cgColor) } context.addPath(path.cgPath) if !context.isPathEmpty { context.clip() } context.addPath(path.cgPath) context.strokePath() } } private func addOuterBorder(_ path: BezierPath, color: Color? = nil, thickness: CGFloat? = nil, attributes attributesBlock: AttributesBlock? = nil) { cgContext.draw(inRect: path.bounds, attributes: attributesBlock) { (context, rect, attributes) in context.setLineWidth((thickness ?? attributes.lineWidth) * 2) if let color = color { context.setStrokeColor(color.cgColor) } context.addPath(path.cgPath) context.strokePath() context.addPath(path.cgPath) context.fillPath() if !context.isPathEmpty { context.clip(using: .evenOdd) } } } private func addCenterBorder(_ path: BezierPath, color: Color? = nil, thickness: CGFloat? = nil, attributes attributesBlock: AttributesBlock? = nil) { cgContext.draw(inRect: path.bounds, attributes: attributesBlock) { (context, rect, attributes) in context.setLineWidth(thickness ?? attributes.lineWidth) if let color = color { context.setStrokeColor(color.cgColor) } context.addPath(path.cgPath) context.strokePath() } } }
mit
17c7012972968e0afbfd67817680a4fd
35.234234
165
0.700646
4.649711
false
false
false
false
jeffreybergier/WaterMe2
WaterMe/WaterMe/ReminderVesselMain/ReminderVesselViewAll/ReminderVesselMainViewController.swift
1
4506
// // ReminderVesselMainViewController.swift // WaterMe // // Created by Jeffrey Bergier on 5/31/17. // Copyright © 2017 Saturday Apps. // // This file is part of WaterMe. Simple Plant Watering Reminders for iOS. // // WaterMe 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. // // WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>. // import Datum import UIKit class ReminderVesselMainViewController: StandardViewController, HasProController, HasBasicController { class func newVC(basicController: BasicController?, proController: ProController? = nil, completionHandler: @escaping (UIViewController) -> Void) -> UINavigationController { let sb = UIStoryboard(name: "ReminderVesselMain", bundle: Bundle(for: self)) // swiftlint:disable:next force_cast let navVC = sb.instantiateInitialViewController() as! UINavigationController // swiftlint:disable:next force_cast var vc = navVC.viewControllers.first as! ReminderVesselMainViewController vc.title = LocalizedString.title // set here because it works better in UITabBarController vc.configure(with: basicController) vc.configure(with: proController) vc.completionHandler = completionHandler navVC.presentationController?.delegate = vc return navVC } /*@IBOutlet*/ private weak var collectionVC: ReminderVesselCollectionViewController? private lazy var doneBBI: UIBarButtonItem = UIBarButtonItem(localizedDoneButtonWithTarget: self, action: #selector(self.doneButtonTapped(_:))) private lazy var addReminderVesselBBI: UIBarButtonItem = UIBarButtonItem(__legacy_localizedAddReminderVesselBBIButtonWithTarget: self, action: #selector(self.addReminderVesselButtonTapped(_:))) var basicRC: BasicController? var proRC: ProController? private var completionHandler: ((UIViewController) -> Void)? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = self.addReminderVesselBBI self.navigationItem.rightBarButtonItem = self.doneBBI } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Analytics.log(viewOperation: .reminderVesselList) if let data = self.collectionVC?.data, case .failure(let error) = data { self.collectionVC?.data = nil UIAlertController.presentAlertVC(for: error, over: self) } } @IBAction private func addReminderVesselButtonTapped(_ sender: NSObject?) { self.editReminderVessel(nil) } @IBAction private func doneButtonTapped(_ sender: Any) { self.completionHandler?(self) } private func editReminderVessel(_ vessel: ReminderVessel?) { guard let basicRC = self.basicRC else { return } let deselectAction: (() -> Void)? = vessel == nil ? nil : { self.collectionVC?.collectionView?.deselectAllItems(animated: true) } let editVC = ReminderVesselEditViewController.newVC(basicController: basicRC, editVessel: vessel) { vc in vc.dismiss(animated: true, completion: deselectAction) } self.present(editVC, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if var destVC = segue.destination as? ReminderVesselCollectionViewController { self.collectionVC = destVC destVC.vesselChosen = { [unowned self] in self.editReminderVessel($0) } destVC.configure(with: self.basicRC) } } } extension ReminderVesselMainViewController /* UIAdaptivePresentationControllerDelegate */ { func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { self.completionHandler?(self) } }
gpl-3.0
0fac227e03e86d800a3f5600f04670fc
41.904762
138
0.685905
5.196078
false
false
false
false
tjw/swift
benchmark/utils/main.swift
1
8659
//===--- main.swift -------------------------------------------*- 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 is just a driver for performance overview tests. import TestsUtils import DriverUtils import Ackermann import AngryPhonebook import AnyHashableWithAClass import Array2D import ArrayAppend import ArrayInClass import ArrayLiteral import ArrayOfGenericPOD import ArrayOfGenericRef import ArrayOfPOD import ArrayOfRef import ArraySetElement import ArraySubscript import BinaryFloatingPointConversionFromBinaryInteger import BinaryFloatingPointProperties import BitCount import ByteSwap import COWTree import CString import CSVParsing import Calculator import CaptureProp import ChainedFilterMap import CharacterLiteralsLarge import CharacterLiteralsSmall import CharacterProperties import Chars import ClassArrayGetter import Combos import DataBenchmarks import DeadArray import DictOfArraysToArrayOfDicts import DictTest import DictTest2 import DictTest3 import DictTest4 import DictionaryBridge import DictionaryCopy import DictionaryGroup import DictionaryLiteral import DictionaryRemove import DictionarySubscriptDefault import DictionarySwap import DoubleWidthDivision import DropFirst import DropLast import DropWhile import ErrorHandling import Exclusivity import ExistentialPerformance import Fibonacci import FloatingPointPrinting import Hanoi import Hash import HashQuadratic import Histogram import Integrate import IterateData import Join import LazyFilter import LinkedList import LuhnAlgoEager import LuhnAlgoLazy import MapReduce import Memset import MonteCarloE import MonteCarloPi import NibbleSort import NSDictionaryCastToSwift import NSError import NSStringConversion import NopDeinit import ObjectAllocation import ObjectiveCBridging import ObjectiveCBridgingStubs import ObjectiveCNoBridgingStubs import ObserverClosure import ObserverForwarderStruct import ObserverPartiallyAppliedMethod import ObserverUnappliedMethod import OpenClose import PartialApplyDynamicType import Phonebook import PointerArithmetics import PolymorphicCalls import PopFront import PopFrontGeneric import Prefix import PrefixWhile import Prims import PrimsSplit import ProtocolDispatch import ProtocolDispatch2 import Queue import RC4 import RGBHistogram import RangeAssignment import RangeIteration import RangeReplaceableCollectionPlusDefault import RecursiveOwnedParameter import ReduceInto import RemoveWhere import ReversedCollections import RomanNumbers import SequenceAlgos import SetTests import SevenBoom import Sim2DArray import SortLargeExistentials import SortLettersInPlace import SortStrings import StackPromo import StaticArray import StrComplexWalk import StrToInt import StringBuilder import StringComparison import StringEdits import StringEnum import StringInterpolation import StringMatch import StringRemoveDupes import StringTests import StringWalk import Substring import Suffix import SuperChars import TwoSum import TypeFlood import UTF8Decode import Walsh import WordCount import XorLoop @inline(__always) private func registerBenchmark(_ bench: BenchmarkInfo) { registeredBenchmarks.append(bench) } @inline(__always) private func registerBenchmark< S : Sequence >(_ infos: S) where S.Element == BenchmarkInfo { registeredBenchmarks.append(contentsOf: infos) } registerBenchmark(Ackermann) registerBenchmark(AngryPhonebook) registerBenchmark(AnyHashableWithAClass) registerBenchmark(Array2D) registerBenchmark(ArrayAppend) registerBenchmark(ArrayInClass) registerBenchmark(ArrayLiteral) registerBenchmark(ArrayOfGenericPOD) registerBenchmark(ArrayOfGenericRef) registerBenchmark(ArrayOfPOD) registerBenchmark(ArrayOfRef) registerBenchmark(ArraySetElement) registerBenchmark(ArraySubscript) registerBenchmark(BinaryFloatingPointConversionFromBinaryInteger) registerBenchmark(BinaryFloatingPointPropertiesBinade) registerBenchmark(BinaryFloatingPointPropertiesNextUp) registerBenchmark(BinaryFloatingPointPropertiesUlp) registerBenchmark(BitCount) registerBenchmark(ByteSwap) registerBenchmark(COWTree) registerBenchmark(CString) registerBenchmark(CSVParsing) registerBenchmark(CSVParsingAlt) registerBenchmark(CSVParsingAltIndices) registerBenchmark(Calculator) registerBenchmark(CaptureProp) registerBenchmark(ChainedFilterMap) registerBenchmark(CharacterLiteralsLarge) registerBenchmark(CharacterLiteralsSmall) registerBenchmark(CharacterPropertiesFetch) registerBenchmark(CharacterPropertiesStashed) registerBenchmark(CharacterPropertiesStashedMemo) registerBenchmark(CharacterPropertiesPrecomputed) registerBenchmark(Chars) registerBenchmark(Combos) registerBenchmark(ClassArrayGetter) registerBenchmark(DataBenchmarks) registerBenchmark(DeadArray) registerBenchmark(DictOfArraysToArrayOfDicts) registerBenchmark(Dictionary) registerBenchmark(Dictionary2) registerBenchmark(Dictionary3) registerBenchmark(Dictionary4) registerBenchmark(DictionaryBridge) registerBenchmark(DictionaryCopy) registerBenchmark(DictionaryGroup) registerBenchmark(DictionaryLiteral) registerBenchmark(DictionaryRemove) registerBenchmark(DictionarySubscriptDefault) registerBenchmark(DictionarySwap) registerBenchmark(DoubleWidthDivision) registerBenchmark(DropFirst) registerBenchmark(DropLast) registerBenchmark(DropWhile) registerBenchmark(ErrorHandling) registerBenchmark(Exclusivity) registerBenchmark(ExistentialPerformance) registerBenchmark(Fibonacci) registerBenchmark(FloatingPointPrinting) registerBenchmark(Hanoi) registerBenchmark(HashTest) registerBenchmark(HashQuadratic) registerBenchmark(Histogram) registerBenchmark(IntegrateTest) registerBenchmark(IterateData) registerBenchmark(Join) registerBenchmark(LazyFilter) registerBenchmark(LinkedList) registerBenchmark(LuhnAlgoEager) registerBenchmark(LuhnAlgoLazy) registerBenchmark(MapReduce) registerBenchmark(Memset) registerBenchmark(MonteCarloE) registerBenchmark(MonteCarloPi) registerBenchmark(NSDictionaryCastToSwift) registerBenchmark(NSErrorTest) registerBenchmark(NSStringConversion) registerBenchmark(NibbleSort) registerBenchmark(NopDeinit) registerBenchmark(ObjectAllocation) registerBenchmark(ObjectiveCBridging) registerBenchmark(ObjectiveCBridgingStubs) registerBenchmark(ObjectiveCNoBridgingStubs) registerBenchmark(ObserverClosure) registerBenchmark(ObserverForwarderStruct) registerBenchmark(ObserverPartiallyAppliedMethod) registerBenchmark(ObserverUnappliedMethod) registerBenchmark(OpenClose) registerBenchmark(PartialApplyDynamicType) registerBenchmark(Phonebook) registerBenchmark(PointerArithmetics) registerBenchmark(PolymorphicCalls) registerBenchmark(PopFront) registerBenchmark(PopFrontArrayGeneric) registerBenchmark(Prefix) registerBenchmark(PrefixWhile) registerBenchmark(Prims) registerBenchmark(PrimsSplit) registerBenchmark(ProtocolDispatch) registerBenchmark(ProtocolDispatch2) registerBenchmark(QueueGeneric) registerBenchmark(QueueConcrete) registerBenchmark(RC4Test) registerBenchmark(RGBHistogram) registerBenchmark(RangeAssignment) registerBenchmark(RangeIteration) registerBenchmark(RangeReplaceableCollectionPlusDefault) registerBenchmark(RecursiveOwnedParameter) registerBenchmark(ReduceInto) registerBenchmark(RemoveWhere) registerBenchmark(ReversedCollections) registerBenchmark(RomanNumbers) registerBenchmark(SequenceAlgos) registerBenchmark(SetTests) registerBenchmark(SevenBoom) registerBenchmark(Sim2DArray) registerBenchmark(SortLargeExistentials) registerBenchmark(SortLettersInPlace) registerBenchmark(SortStrings) registerBenchmark(StackPromo) registerBenchmark(StaticArrayTest) registerBenchmark(StrComplexWalk) registerBenchmark(StrToInt) registerBenchmark(StringBuilder) registerBenchmark(StringComparison) registerBenchmark(StringEdits) registerBenchmark(StringEnum) registerBenchmark(StringInterpolation) registerBenchmark(StringInterpolationSmall) registerBenchmark(StringInterpolationManySmallSegments) registerBenchmark(StringMatch) registerBenchmark(StringRemoveDupes) registerBenchmark(StringTests) registerBenchmark(StringWalk) registerBenchmark(SubstringTest) registerBenchmark(Suffix) registerBenchmark(SuperChars) registerBenchmark(TwoSum) registerBenchmark(TypeFlood) registerBenchmark(UTF8Decode) registerBenchmark(Walsh) registerBenchmark(WordCount) registerBenchmark(XorLoop) main()
apache-2.0
40ea79b3f52b43850934836937e2c715
27.205212
80
0.88128
5.659477
false
true
false
false
kirthika/AuthenticationLibrary
AuthenticationLibrary/AuthLibrary.swift
1
5506
// // isJWTValid.swift // // Created by Pariveda Solutions. // import Foundation @objc open class AuthLibrary : NSObject { var keychainService: KeychainService let brand: String let azureProps: PListService required public init(_ branding: String) { keychainService = KeychainService() brand = branding.lowercased() azureProps = PListService("azure") } open func isAuthenticated(completion: @escaping (Bool) -> Void) { let id_token = keychainService.getToken(TokenType.id_token.rawValue) if (!id_token.isEmpty) { if (!isJwtValid(id_token)) { // An Id Token exists, but it's not valid renewTokens(completion: { (success) in if (success) { completion(success) } else { completion(false) } }) } else { completion(true) // A saved, valid token exists } } else { // No ID Token exists renewTokens(completion: { (success) in if (success) { completion(success) } else { completion(false) } }) } } // RenewTokens function: Retrieves refresh token from storage and requests a fresh set of tokens // from Azure AD B2C open func renewTokens(completion: @escaping (Bool) -> Void) { let refresh_token = keychainService.getToken(TokenType.refresh_token.rawValue) if (!refresh_token.isEmpty) { let tokenService = TokenService(brand, true) tokenService.getTokens(refresh_token) { (token: Token) in if (self.isJwtValid(token.id_token)) { self.keychainService.storeToken(token.id_token, TokenType.id_token.rawValue) self.keychainService.storeToken(token.refresh_token, TokenType.refresh_token.rawValue) self.keychainService.storeToken(token.access_token, TokenType.access_token.rawValue) completion(true) } else { self.keychainService.removeTokens() completion(false) } } } else { completion(false) } } open func login(state: String, resource: String, scopes: [String]) -> LoginViewController { let storyboard = UIStoryboard (name: "Login", bundle: Bundle(for: LoginViewController.self)) let viewController: LoginViewController = storyboard.instantiateInitialViewController() as! LoginViewController viewController.resource = resource viewController.scopes = scopes viewController.state = state viewController.brand = brand return viewController } open func isJwtValid(_ token: String?) -> Bool { print("token ",token ?? "kirth") var claims = convertTokenToClaims(token!) print("claims ",claims) var val = false if let issuer = claims["iss"]{ if let audience = claims["aud"]{ if ((issuer as! String == azureProps.getProperty("domain") + azureProps.getProperty("tenant") + "/v2.0/") && (audience as! String == azureProps.getProperty("clientId"))) { val = true } else { val = false } } } return val } open func getIdTokenClaims() -> [String: Any] { let id_token = keychainService.getToken(TokenType.id_token.rawValue) return getClaimsFromToken(id_token) } open func getAccessTokenClaims() -> [String: Any] { let access_token = keychainService.getToken(TokenType.access_token.rawValue) return getClaimsFromToken(access_token) } open func getClaimsFromToken(_ token: String) -> [String: Any] { if (!token.isEmpty) { return convertTokenToClaims(token) } else { return [String: Any]() } } open func getRoles() -> [String:Any] { let userInfo = getIdTokenClaims() var obj : [String: Any] = [:] if (userInfo["extension_IsShopper"] != nil) { obj["isShopper"] = true } else { obj["isShopper"] = false } if (userInfo["extension_IsBuyer"] != nil) { obj["isBuyer"] = true } else { obj["isBuyer"] = false } if (userInfo["extension_IsOwner"] != nil) { obj["isOwner"] = true } else { obj["isOwner"] = false } if (userInfo["extension_IsDriver"] != nil) { obj["isDriver"] = true } else { obj["isDriver"] = false } return obj } open func getAccessToken() -> String { return keychainService.getToken(TokenType.access_token.rawValue) } open func getIdToken() -> String { return keychainService.getToken(TokenType.id_token.rawValue) } open func clearIdToken() { keychainService.removeToken(TokenType.id_token.rawValue) } open func clearTokens() { keychainService.removeTokens() } func convertTokenToClaims(_ token: String) -> [String: Any] { let jwt = token.components(separatedBy: ".") print("jwt ",jwt) var claims = jwt[1] print("claims.characters.count ",claims.characters.count % 4) switch (claims.characters.count % 4) // Pad with trailing '='s { case 0: break; // No pad chars in this case case 1: claims += "==="; break; // Three pad chars case 2: claims += "=="; break; // Two pad chars case 3: claims += "="; break; // One pad char default: print("Illegal base64 string!") } do { let parsedData = try JSONSerialization.jsonObject(with: Data(base64Encoded: claims)!, options: .allowFragments) as! [String:Any] return parsedData } catch let error as NSError { print(error) } return [String: Any]() } }
mit
6ddbe1f541dded34b9553561dca9d8c8
28.923913
134
0.623138
4.168055
false
false
false
false
akolov/FlingChallenge
FlingChallenge/FlingChallenge/Extensions/RemoteImageView.swift
1
2215
// // RemoteImageView.swift // FlingChallenge // // Created by Alexander Kolov on 9/5/16. // Copyright © 2016 Alexander Kolov. All rights reserved. // import FlingChallengeKit import UIKit class RemoteImageView: UIImageView { override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { self.addSubview(progressIndicator) progressIndicator.centerXAnchor.constraintEqualToAnchor(centerXAnchor).active = true progressIndicator.centerYAnchor.constraintEqualToAnchor(centerYAnchor).active = true } static let operationQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.maxConcurrentOperationCount = 30 return queue }() var imageID: Int64? { didSet { cancelImageLoadingOperation() image = nil if let imageID = imageID { let _operation = GetPostImageOperation(imageID: imageID) _operation.delegate = self operation = _operation RemoteImageView.operationQueue.addOperation(_operation) } } } override var image: UIImage? { didSet { progressIndicator.hidden = image != nil } } private(set) lazy var progressIndicator: CircularProgressIndicator = { let progressIndicator = CircularProgressIndicator() progressIndicator.translatesAutoresizingMaskIntoConstraints = false return progressIndicator }() private weak var operation: GetPostImageOperation? func cancelImageLoadingOperation() { operation?.cancel() operation?.delegate = nil operation = nil progressIndicator.progress = 0 } } extension RemoteImageView: GetPostImageOperationDelegate { func getPostImageOperation(operation: GetPostImageOperation, didUpdateProgress progress: Float) { progressIndicator.progress = progress } func getPostImageOperation(operation: GetPostImageOperation, didFinishWithImage image: UIImage) { if operation.imageID == imageID { self.image = image } } func getPostImageOperation(operation: GetPostImageOperation, didFailWithError error: ErrorType) { print(error) } }
mit
a9edc6a09aecf4d8fe3eb5e262b88db0
23.6
99
0.722222
5.221698
false
false
false
false
erichoracek/Carthage
Source/CarthageKit/Git.swift
1
19786
// // Git.swift // Carthage // // Created by Alan Rogers on 14/10/2014. // Copyright (c) 2014 Carthage. All rights reserved. // import Foundation import Result import ReactiveCocoa import ReactiveTask /// Represents a URL for a Git remote. public struct GitURL: Equatable { /// The string representation of the URL. public let URLString: String /// A normalized URL string, without protocol, authentication, or port /// information. This is mostly useful for comparison, and not for any /// actual Git operations. private var normalizedURLString: String { let parsedURL: NSURL? = NSURL(string: URLString) if let parsedURL = parsedURL { // Normal, valid URL. let host = parsedURL.host ?? "" let path = stripGitSuffix(parsedURL.path ?? "") return "\(host)\(path)" } else if URLString.hasPrefix("/") { // Local path. return stripGitSuffix(URLString) } else { // scp syntax. var strippedURLString = URLString if let index = find(strippedURLString, "@") { strippedURLString.removeRange(Range(start: strippedURLString.startIndex, end: index)) } var host = "" if let index = find(strippedURLString, ":") { host = strippedURLString[Range(start: strippedURLString.startIndex, end: index.predecessor())] strippedURLString.removeRange(Range(start: strippedURLString.startIndex, end: index)) } var path = strippedURLString if !path.hasPrefix("/") { // This probably isn't strictly legit, but we'll have a forward // slash for other URL types. path.insert("/", atIndex: path.startIndex) } return "\(host)\(path)" } } /// The name of the repository, if it can be inferred from the URL. public var name: String? { let components = split(URLString, allowEmptySlices: false) { $0 == "/" } return components.last.map { self.stripGitSuffix($0) } } public init(_ URLString: String) { self.URLString = URLString } /// Strips any trailing .git in the given name, if one exists. private func stripGitSuffix(string: String) -> String { if string.hasSuffix(".git") { let nsString = string as NSString return nsString.substringToIndex(nsString.length - 4) as String } else { return string } } } public func ==(lhs: GitURL, rhs: GitURL) -> Bool { return lhs.normalizedURLString == rhs.normalizedURLString } extension GitURL: Hashable { public var hashValue: Int { return normalizedURLString.hashValue } } extension GitURL: Printable { public var description: String { return URLString } } /// A Git submodule. public struct Submodule: Equatable { /// The name of the submodule. Usually (but not always) the same as the /// path. public let name: String /// The relative path at which the submodule is checked out. public let path: String /// The URL from which the submodule should be cloned, if present. public var URL: GitURL /// The SHA checked out in the submodule. public var SHA: String public init(name: String, path: String, URL: GitURL, SHA: String) { self.name = name self.path = path self.URL = URL self.SHA = SHA } } public func ==(lhs: Submodule, rhs: Submodule) -> Bool { return lhs.name == rhs.name && lhs.path == rhs.path && lhs.URL == rhs.URL && lhs.SHA == rhs.SHA } extension Submodule: Hashable { public var hashValue: Int { return name.hashValue } } extension Submodule: Printable { public var description: String { return "\(name) @ \(SHA)" } } /// Shells out to `git` with the given arguments, optionally in the directory /// of an existing repository. public func launchGitTask(arguments: [String], repositoryFileURL: NSURL? = nil, standardInput: SignalProducer<NSData, NoError>? = nil, environment: [String: String]? = nil) -> SignalProducer<String, CarthageError> { let taskDescription = TaskDescription(launchPath: "/usr/bin/env", arguments: [ "git" ] + arguments, workingDirectoryPath: repositoryFileURL?.path, environment: environment, standardInput: standardInput) return launchTask(taskDescription) |> catch { error in SignalProducer(error: .TaskError(error)) } |> map { taskEvent in return taskEvent.value.map { data in return NSString(data: data, encoding: NSUTF8StringEncoding)! as String } } |> ignoreNil } /// Returns a signal that completes when cloning completes successfully. public func cloneRepository(cloneURL: GitURL, destinationURL: NSURL, bare: Bool = true) -> SignalProducer<String, CarthageError> { precondition(destinationURL.fileURL) var arguments = [ "clone" ] if bare { arguments.append("--bare") } return launchGitTask(arguments + [ "--quiet", cloneURL.URLString, destinationURL.path! ]) } /// Returns a signal that completes when the fetch completes successfully. public func fetchRepository(repositoryFileURL: NSURL, remoteURL: GitURL? = nil, refspec: String? = nil) -> SignalProducer<String, CarthageError> { precondition(repositoryFileURL.fileURL) var arguments = [ "fetch", "--tags", "--prune", "--quiet" ] if let remoteURL = remoteURL { arguments.append(remoteURL.URLString) } if let refspec = refspec { arguments.append(refspec) } return launchGitTask(arguments, repositoryFileURL: repositoryFileURL) } /// Sends each tag found in the given Git repository. public func listTags(repositoryFileURL: NSURL) -> SignalProducer<String, CarthageError> { return launchGitTask([ "tag" ], repositoryFileURL: repositoryFileURL) |> flatMap(.Concat) { (allTags: String) -> SignalProducer<String, CarthageError> in return SignalProducer { observer, disposable in let string = allTags as NSString string.enumerateSubstringsInRange(NSMakeRange(0, string.length), options: NSStringEnumerationOptions.ByLines | NSStringEnumerationOptions.Reverse) { line, substringRange, enclosingRange, stop in if disposable.disposed { stop.memory = true } sendNext(observer, line as String) } sendCompleted(observer) } } } /// Returns the text contents of the path at the given revision, or an error if /// the path could not be loaded. public func contentsOfFileInRepository(repositoryFileURL: NSURL, path: String, revision: String = "HEAD") -> SignalProducer<String, CarthageError> { let showObject = "\(revision):\(path)" return launchGitTask([ "show", showObject ], repositoryFileURL: repositoryFileURL) } /// Checks out the working tree of the given (ideally bare) repository, at the /// specified revision, to the given folder. If the folder does not exist, it /// will be created. public func checkoutRepositoryToDirectory(repositoryFileURL: NSURL, workingDirectoryURL: NSURL, revision: String = "HEAD", shouldCloneSubmodule: Submodule -> Bool = { _ in true }) -> SignalProducer<(), CarthageError> { return SignalProducer.try { var error: NSError? if !NSFileManager.defaultManager().createDirectoryAtURL(workingDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) { return .failure(CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: workingDirectoryURL, reason: "Could not create working directory", underlyingError: error)) } var environment = NSProcessInfo.processInfo().environment as! [String: String] environment["GIT_WORK_TREE"] = workingDirectoryURL.path! return .success(environment) } |> flatMap(.Concat) { environment in launchGitTask([ "checkout", "--quiet", "--force", revision ], repositoryFileURL: repositoryFileURL, environment: environment) } |> then(cloneSubmodulesForRepository(repositoryFileURL, workingDirectoryURL, revision: revision, shouldCloneSubmodule: shouldCloneSubmodule)) } /// Clones matching submodules for the given repository at the specified /// revision, into the given working directory. public func cloneSubmodulesForRepository(repositoryFileURL: NSURL, workingDirectoryURL: NSURL, revision: String = "HEAD", shouldCloneSubmodule: Submodule -> Bool = { _ in true }) -> SignalProducer<(), CarthageError> { return submodulesInRepository(repositoryFileURL, revision: revision) |> flatMap(.Concat) { submodule -> SignalProducer<(), CarthageError> in if shouldCloneSubmodule(submodule) { return cloneSubmoduleInWorkingDirectory(submodule, workingDirectoryURL) } else { return .empty } } |> filter { _ in false } } /// Clones the given submodule into the working directory of its parent /// repository, but without any Git metadata. public func cloneSubmoduleInWorkingDirectory(submodule: Submodule, workingDirectoryURL: NSURL) -> SignalProducer<(), CarthageError> { let submoduleDirectoryURL = workingDirectoryURL.URLByAppendingPathComponent(submodule.path, isDirectory: true) let purgeGitDirectories = NSFileManager.defaultManager().carthage_enumeratorAtURL(submoduleDirectoryURL, includingPropertiesForKeys: [ NSURLIsDirectoryKey, NSURLNameKey ], options: nil, catchErrors: true) |> flatMap(.Merge) { enumerator, URL -> SignalProducer<(), CarthageError> in var name: AnyObject? var error: NSError? if !URL.getResourceValue(&name, forKey: NSURLNameKey, error: &error) { return SignalProducer(error: CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not enumerate name of descendant at \(URL.path!)", underlyingError: error)) } if let name = name as? NSString { if name != ".git" { return .empty } } else { return .empty } var isDirectory: AnyObject? if !URL.getResourceValue(&isDirectory, forKey: NSURLIsDirectoryKey, error: &error) || isDirectory == nil { return SignalProducer(error: CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not determine whether \(URL.path!) is a directory", underlyingError: error)) } if let directory = isDirectory?.boolValue { if directory { enumerator.skipDescendants() } } if NSFileManager.defaultManager().removeItemAtURL(URL, error: &error) { return .empty } else { return SignalProducer(error: CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not remove \(URL.path!)", underlyingError: error)) } } return SignalProducer.try { var error: NSError? if !NSFileManager.defaultManager().removeItemAtURL(submoduleDirectoryURL, error: &error) { return .failure(CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: submoduleDirectoryURL, reason: "could not remove submodule checkout", underlyingError: error)) } return .success(workingDirectoryURL.URLByAppendingPathComponent(submodule.path)) } |> flatMap(.Concat) { submoduleDirectoryURL in cloneRepository(submodule.URL, submoduleDirectoryURL, bare: false) } |> then(checkoutSubmodule(submodule, submoduleDirectoryURL)) |> then(purgeGitDirectories) } /// Recursively checks out the given submodule's revision, in its working /// directory. private func checkoutSubmodule(submodule: Submodule, submoduleWorkingDirectoryURL: NSURL) -> SignalProducer<(), CarthageError> { return launchGitTask([ "checkout", "--quiet", submodule.SHA ], repositoryFileURL: submoduleWorkingDirectoryURL) |> then(launchGitTask([ "submodule", "--quiet", "update", "--init", "--recursive" ], repositoryFileURL: submoduleWorkingDirectoryURL)) |> then(.empty) } /// Parses each key/value entry from the given config file contents, optionally /// stripping a known prefix/suffix off of each key. private func parseConfigEntries(contents: String, keyPrefix: String = "", keySuffix: String = "") -> SignalProducer<(String, String), NoError> { let entries = split(contents, allowEmptySlices: false) { $0 == "\0" } return SignalProducer { observer, disposable in for entry in entries { if disposable.disposed { break } let components = split(entry, maxSplit: 1, allowEmptySlices: true) { $0 == "\n" } if components.count != 2 { continue } let value = components[1] let scanner = NSScanner(string: components[0]) if !scanner.scanString(keyPrefix, intoString: nil) { continue } var key: NSString? if !scanner.scanUpToString(keySuffix, intoString: &key) { continue } if let key = key as? String { sendNext(observer, (key, value)) } } sendCompleted(observer) } } /// Determines the SHA that the submodule at the given path is pinned to, in the /// revision of the parent repository specified. public func submoduleSHAForPath(repositoryFileURL: NSURL, path: String, revision: String = "HEAD") -> SignalProducer<String, CarthageError> { return launchGitTask([ "ls-tree", "-z", revision, path ], repositoryFileURL: repositoryFileURL) |> tryMap { string in // Example: // 160000 commit 083fd81ecf00124cbdaa8f86ef10377737f6325a External/ObjectiveGit let components = split(string, maxSplit: 3, allowEmptySlices: false) { $0 == " " || $0 == "\t" } if components.count >= 3 { return .success(components[2]) } else { return .failure(CarthageError.ParseError(description: "expected submodule commit SHA in ls-tree output: \(string)")) } } } /// Returns each submodule found in the given repository revision, or an empty /// signal if none exist. public func submodulesInRepository(repositoryFileURL: NSURL, revision: String = "HEAD") -> SignalProducer<Submodule, CarthageError> { let modulesObject = "\(revision):.gitmodules" let baseArguments = [ "config", "--blob", modulesObject, "-z" ] return launchGitTask(baseArguments + [ "--get-regexp", "submodule\\..*\\.path" ], repositoryFileURL: repositoryFileURL) |> catch { _ in SignalProducer<String, NoError>.empty } |> flatMap(.Concat) { value in parseConfigEntries(value, keyPrefix: "submodule.", keySuffix: ".path") } |> promoteErrors(CarthageError.self) |> flatMap(.Concat) { name, path -> SignalProducer<Submodule, CarthageError> in return launchGitTask(baseArguments + [ "--get", "submodule.\(name).url" ], repositoryFileURL: repositoryFileURL) |> map { GitURL($0) } |> zipWith(submoduleSHAForPath(repositoryFileURL, path, revision: revision)) |> map { URL, SHA in Submodule(name: name, path: path, URL: URL, SHA: SHA) } } } /// Determines whether the specified revision identifies a valid commit. /// /// If the specified file URL does not represent a valid Git repository, `false` /// will be sent. public func commitExistsInRepository(repositoryFileURL: NSURL, revision: String = "HEAD") -> SignalProducer<Bool, NoError> { return SignalProducer { observer, disposable in // NSTask throws a hissy fit (a.k.a. exception) if the working directory // doesn't exist, so pre-emptively check for that. var isDirectory: ObjCBool = false if !NSFileManager.defaultManager().fileExistsAtPath(repositoryFileURL.path!, isDirectory: &isDirectory) || !isDirectory { sendNext(observer, false) sendCompleted(observer) return } launchGitTask([ "rev-parse", "\(revision)^{commit}" ], repositoryFileURL: repositoryFileURL) |> then(SignalProducer<Bool, CarthageError>(value: true)) |> catch { _ in SignalProducer<Bool, NoError>(value: false) } |> startWithSignal { signal, signalDisposable in disposable.addDisposable(signalDisposable) signal.observe(observer) } } } /// Attempts to resolve the given reference into an object SHA. public func resolveReferenceInRepository(repositoryFileURL: NSURL, reference: String) -> SignalProducer<String, CarthageError> { return launchGitTask([ "rev-parse", "\(reference)^{object}" ], repositoryFileURL: repositoryFileURL) |> map { string in string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } |> catch { _ in SignalProducer(error: CarthageError.RepositoryCheckoutFailed(workingDirectoryURL: repositoryFileURL, reason: "No object named \"\(reference)\" exists", underlyingError: nil)) } } /// Returns the location of the .git folder within the given repository. private func gitDirectoryURLInRepository(repositoryFileURL: NSURL) -> NSURL { return repositoryFileURL.URLByAppendingPathComponent(".git") } /// Attempts to determine whether the given directory represents a Git /// repository. private func isGitRepository(directoryURL: NSURL) -> Bool { return NSFileManager.defaultManager().fileExistsAtPath(gitDirectoryURLInRepository(directoryURL).path!) } /// Adds the given submodule to the given repository, cloning from `fetchURL` if /// the desired revision does not exist or the submodule needs to be cloned. public func addSubmoduleToRepository(repositoryFileURL: NSURL, submodule: Submodule, fetchURL: GitURL) -> SignalProducer<(), CarthageError> { let submoduleDirectoryURL = repositoryFileURL.URLByAppendingPathComponent(submodule.path, isDirectory: true) return SignalProducer<Bool, CarthageError> { observer, disposable in sendNext(observer, isGitRepository(submoduleDirectoryURL)) sendCompleted(observer) } |> flatMap(.Merge) { submoduleExists in if (submoduleExists) { // Just check out and stage the correct revision. return fetchRepository(submoduleDirectoryURL, remoteURL: fetchURL, refspec: "+refs/heads/*:refs/remotes/origin/*") |> then(launchGitTask([ "config", "--file", ".gitmodules", "submodule.\(submodule.name).url", submodule.URL.URLString ], repositoryFileURL: repositoryFileURL)) |> then(launchGitTask([ "submodule", "--quiet", "sync" ], repositoryFileURL: repositoryFileURL)) |> then(checkoutSubmodule(submodule, submoduleDirectoryURL)) |> then(launchGitTask([ "add", "--force", submodule.path ], repositoryFileURL: repositoryFileURL)) |> then(.empty) } else { let addSubmodule = launchGitTask([ "submodule", "--quiet", "add", "--force", "--name", submodule.name, "--", submodule.URL.URLString, submodule.path ], repositoryFileURL: repositoryFileURL) // A .failure to add usually means the folder was already added // to the index. That's okay. |> catch { _ in SignalProducer<String, CarthageError>.empty } // If it doesn't exist, clone and initialize a submodule from our // local bare repository. return cloneRepository(fetchURL, submoduleDirectoryURL, bare: false) |> then(launchGitTask([ "remote", "set-url", "origin", submodule.URL.URLString ], repositoryFileURL: submoduleDirectoryURL)) |> then(checkoutSubmodule(submodule, submoduleDirectoryURL)) |> then(addSubmodule) |> then(launchGitTask([ "submodule", "--quiet", "init", "--", submodule.path ], repositoryFileURL: repositoryFileURL)) |> then(.empty) } } } /// Moves an item within a Git repository, or within a simple directory if a Git /// repository is not found. /// /// Sends the new URL of the item after moving. public func moveItemInPossibleRepository(repositoryFileURL: NSURL, #fromPath: String, #toPath: String) -> SignalProducer<NSURL, CarthageError> { let toURL = repositoryFileURL.URLByAppendingPathComponent(toPath) let parentDirectoryURL = toURL.URLByDeletingLastPathComponent! return SignalProducer<Bool, CarthageError>.try { var error: NSError? if !NSFileManager.defaultManager().createDirectoryAtURL(parentDirectoryURL, withIntermediateDirectories: true, attributes: nil, error: &error) { return .failure(CarthageError.WriteFailed(parentDirectoryURL, error)) } return .success(isGitRepository(repositoryFileURL)) } |> flatMap(.Merge) { isRepository -> SignalProducer<NSURL, CarthageError> in if isRepository { return launchGitTask([ "mv", "-k", fromPath, toPath ], repositoryFileURL: repositoryFileURL) |> then(SignalProducer(value: toURL)) } else { let fromURL = repositoryFileURL.URLByAppendingPathComponent(fromPath) var error: NSError? if NSFileManager.defaultManager().moveItemAtURL(fromURL, toURL: toURL, error: &error) { return SignalProducer(value: toURL) } else { return SignalProducer(error: .WriteFailed(toURL, error)) } } } }
mit
f611146aff3858c3709996f6faa54ca6
40.480084
218
0.732791
4.315376
false
false
false
false
SwiftStudies/OysterKit
Tests/STLRTests/HierarchyTests.swift
1
10140
// Copyright (c) 2014, RED When Excited // 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. // // 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 XCTest import OysterKit import STLR class HierarchyTests: XCTestCase { #warning("Test disabled pending implementation") // func testExample() { // return // // guard let grammarSource = try? String(contentsOfFile: "/Volumes/Personal/SPM/XMLDecoder/XML.stlr") else { // fatalError("Could not load grammar") // } // // let xmlLanguage : Grammar // // do { // xmlLanguage = try ProductionSTLR.build(grammarSource).grammar.dynamicRules // // } catch { // fatalError("Could not create language") // } // // let xmlSource = """ //<message subject='Hello, OysterKit!' priority="High"> // It's really <i>good</i> to meet you, // <p /> // I hope you are settling in OK, let me know if you need anything. // <p /> // Phatom Testers //</message> //""" // for _ in xmlLanguage.grammar { //// print("Rule:\n\t\(rule)") // } // // do { // _ = try AbstractSyntaxTreeConstructor().build(xmlSource, using: XML.grammar.language) //// print(tree.description) // } catch { //// print(error) // XCTFail("Could not parse source"); return // } // //// print(STLRParser.init(source: grammarSource).ast.swift(grammar: "XML")!) // } let xmlStlr = """ // // XML Grammar // // Scanner Rules @void ws = .whitespacesAndNewlines identifier = .letters (.letters | ("-" .letters))* singleQuote = "'" doubleQuote = "\"" value = (-singleQuote !singleQuote* @error("Expected closing '") -singleQuote) | (-doubleQuote !doubleQuote* @error("Expected closing \"") -doubleQuote) attribute = ws+ identifier (ws* -"=" ws* value)? attributes = attribute+ data = !"<"+ openTag = ws* -"<" identifier (attributes | ws*) -">" @void closeTag = ws* -"</" identifier ws* -">" inlineTag = ws* -"<" identifier (attribute+ | ws*) -"/>" nestingTag = @transient openTag contents @error("Expected closing tag") closeTag // Grammar Rules tag = @transient nestingTag | @transient inlineTag contents = @token("content") (data | tag)* // AST Root xml = tag """ } // // STLR Generated Swift File // // Generated: 2018-01-31 23:30:11 +0000 // import OysterKit // // XML Parser // enum XML : Int, TokenType { typealias T = XML // Cache for compiled regular expressions private static var regularExpressionCache = [String : NSRegularExpression]() /// Returns a pre-compiled pattern from the cache, or if not in the cache builds /// the pattern, caches and returns the regular expression /// /// - Parameter pattern: The pattern the should be built /// - Returns: A compiled version of the pattern /// private static func regularExpression(_ pattern:String)->NSRegularExpression{ if let cached = regularExpressionCache[pattern] { return cached } do { let new = try NSRegularExpression(pattern: pattern, options: []) regularExpressionCache[pattern] = new return new } catch { fatalError("Failed to compile pattern /\(pattern)/\n\(error)") } } /// The tokens defined by the grammar case `ws`, `identifier`, `singleQuote`, `doubleQuote`, `value`, `attribute`, `attributes`, `data`, `openTag`, `closeTag`, `inlineTag`, `nestingTag`, `tag`, `contents`, `xml` /// The rule for the token var rule : Rule { switch self { /// ws case .ws: return -[ CharacterSet.whitespacesAndNewlines.require(.one) ].sequence /// identifier case .identifier: return [ [ CharacterSet.letters.require(.one), [ CharacterSet.letters.require(.one), [ "-".require(.one), CharacterSet.letters.require(.one)].sequence ].choice ].sequence ].sequence.parse(as: self) /// singleQuote case .singleQuote: return [ "\'".require(.one) ].sequence.parse(as: self) /// doubleQuote case .doubleQuote: return [ "\\\"".require(.one) ].sequence.parse(as: self) /// value case .value: return [ [ [ -T.singleQuote.rule.require(.one), !T.singleQuote.rule.require(.zeroOrMore), -T.singleQuote.rule.require(.one)].sequence , [ -T.doubleQuote.rule.require(.one), !T.doubleQuote.rule.require(.zeroOrMore), -T.doubleQuote.rule.require(.one)].sequence ].choice ].sequence.parse(as: self) /// attribute case .attribute: return [ [ T.ws.rule.require(.oneOrMore), T.identifier.rule.require(.one), [ T.ws.rule.require(.zeroOrMore), -"=".require(.one), T.ws.rule.require(.zeroOrMore), T.value.rule.require(.one)].sequence ].sequence ].sequence.parse(as: self) /// attributes case .attributes: return [ T.attribute.rule.require(.oneOrMore) ].sequence.parse(as: self) /// data case .data: return [ !"<".require(.oneOrMore) ].sequence.parse(as: self) /// openTag case .openTag: return [ [ T.ws.rule.require(.zeroOrMore), -"<".require(.one), T.identifier.rule.require(.one), [ T.attributes.rule.require(.one), T.ws.rule.require(.zeroOrMore)].choice , -">".require(.one)].sequence ].sequence.parse(as: self) /// closeTag case .closeTag: return -[ [ T.ws.rule.require(.zeroOrMore), -"</".require(.one), T.identifier.rule.require(.one), T.ws.rule.require(.zeroOrMore), -">".require(.one)].sequence ].sequence /// inlineTag case .inlineTag: return [ [ T.ws.rule.require(.zeroOrMore), -"<".require(.one), T.identifier.rule.require(.one), [ T.attribute.rule.require(.oneOrMore), T.ws.rule.require(.zeroOrMore)].choice , -"/>".require(.one)].sequence ].sequence.parse(as: self) /// nestingTag case .nestingTag: return [ [ ~T.openTag.rule.require(.one), T.contents.rule.require(.one), T.closeTag.rule.require(.one)].sequence ].sequence.parse(as: self) /// tag case .tag: return [ [ ~T.nestingTag.rule.require(.one), ~T.inlineTag.rule.require(.one)].choice ].sequence.parse(as: self) /// contents case .contents: return [ [ T.data.rule.require(.one), T.tag.rule.require(.one)].choice ].sequence.parse(as: self) /// xml case .xml: return [ T.tag.rule.require(.one) ].sequence.parse(as: self) } } /// Create a language that can be used for parsing etc public static var grammar: [Rule] { return [T.xml.rule] } }
bsd-2-clause
6a775e3622ec647f26d89a780029dfa2
32.029316
177
0.491815
4.90566
false
false
false
false
DSanzh/ios_nanodegree
2_ud788_UIKit_Fundamentals/Other subtasks/Dice_Quiz/Dice_Quiz/DiceViewController.swift
1
1329
// // DiceViewController.swift // Dice_Quiz // // Created by Sanzhar on 6/13/17. // Copyright © 2017 Sanzhar D. All rights reserved. // import UIKit class DiceViewController: UIViewController { var firstValue: Int? var secondValue: Int? @IBOutlet weak var firstDie: UIImageView! @IBOutlet weak var secondDie: UIImageView! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let firstValue = self.firstValue { self.firstDie.image = UIImage(named: "d\(firstValue)") } else { self.firstDie.image = nil } if let secondValue = self.secondValue { self.secondDie.image = UIImage(named: "d\(secondValue)") } else { self.secondDie.image = nil } self.firstDie.alpha = 0 } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
59d26e1847ebf8fdc96f3b493678edc5
24.056604
106
0.608434
4.611111
false
false
false
false
con-beo-vang/Spendy
Spendy/View Controllers/SelectAccountOrCategoryViewController.swift
1
4841
// // SelectAccountOrCategoryViewController.swift // Spendy // // Created by Harley Trung on 9/17/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit import Parse import RealmSwift protocol SelectAccountOrCategoryDelegate { func selectAccountOrCategoryViewController(selectAccountOrCategoryController: SelectAccountOrCategoryViewController, selectedItem item: AnyObject, selectedType type: String?) } class SelectAccountOrCategoryViewController: UIViewController { // Account or Category var itemClass: String! // Income, Expense or Transfer var itemTypeFilter: String? // pass back selected item var delegate: SelectAccountOrCategoryDelegate? @IBOutlet weak var tableView: UITableView! var items: [HTRObject]? var backButton: UIButton? // var selectedItem: HTObject? var selectedItem: HTRObject? // MARK: - Main functions override func viewDidLoad() { super.viewDidLoad() addBarButton() loadItems() } func loadItems() { print("loadItems: itemTypeFilter \(itemTypeFilter), itemClass \(itemClass)") if itemClass == "Category" { navigationItem.title = "Select Category" switch itemTypeFilter { case .Some("Income"): items = Category.allIncomeType() case .Some("Expense"): items = Category.allExpenseType() case .Some("Transfer"): items = Category.allTransferType() default: print("WARNING: loadItems called on unrecognized type \(itemTypeFilter)") items = [] } tableView.reloadData() } else if itemClass == "Account" { navigationItem.title = "Select Account" items = Account.all as [Account]? tableView.reloadData() } } // MARK: Button func addBarButton() { backButton = UIButton() Helper.sharedInstance.customizeBarButton(self, button: backButton!, imageName: "Bar-Back", isLeft: true) backButton!.addTarget(self, action: "onBackButton:", forControlEvents: UIControlEvents.TouchUpInside) } func onBackButton(sender: UIButton!) { navigationController?.popViewControllerAnimated(true) } } // MARK: - Table view extension SelectAccountOrCategoryViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items?.count ?? 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 56 } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CategoryCell") as! CategoryCell if let item = items?[indexPath.row] { cell.nameLabel.text = item["name"] as! String? if item.id == selectedItem?.id { cell.selectedIcon.hidden = false } else { cell.selectedIcon.hidden = true } if let icon = item["icon"] as? String { cell.iconImageView.image = Helper.sharedInstance.createIcon(icon) switch itemTypeFilter { case .Some("Expense"): cell.iconImageView.layer.backgroundColor = Color.expenseColor.CGColor cell.selectedIcon.setNewTintColor(Color.expenseColor) case .Some("Income"): cell.iconImageView.layer.backgroundColor = Color.incomeColor.CGColor cell.selectedIcon.setNewTintColor(Color.incomeColor) case .Some("Transfer"): cell.iconImageView.layer.backgroundColor = Color.balanceColor.CGColor cell.selectedIcon.setNewTintColor(Color.balanceColor) default: // nothing cell } } if itemClass == "Account" { cell.iconImageView.image = Helper.sharedInstance.createIcon("Account") cell.iconImageView.layer.backgroundColor = Color.strongColor.CGColor cell.selectedIcon.setNewTintColor(Color.strongColor) } cell.iconImageView.setNewTintColor(UIColor.whiteColor()) } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // var cell = tableView.cellForRowAtIndexPath(indexPath) as! CategoryCell navigationController?.popViewControllerAnimated(true) delegate?.selectAccountOrCategoryViewController(self, selectedItem: items![indexPath.row], selectedType: itemTypeFilter) } }
mit
d0d736e7c02018fff5b07cf29c6f7d61
30.640523
186
0.692625
5.17754
false
false
false
false
Punch-In/PunchInIOSApp
PunchIn/DailyAttendanceCollectionViewCell.swift
1
2175
// // DailyAttendanceCollectionViewCell.swift // PunchIn // // Created by Nilesh Agrawal on 10/23/15. // Copyright © 2015 Nilesh Agrawal. All rights reserved. // import UIKit class DailyAttendanceCollectionViewCell: UICollectionViewCell { @IBOutlet private weak var className: UILabel! @IBOutlet private weak var classDate: UILabel! @IBOutlet private weak var attendanceStatusImageView: UIImageView! @IBOutlet private weak var attendanceStatusWrapperView: UIView! weak var student: Student! var displayClass: Class! { didSet { className.text = displayClass.name classDate.text = displayClass.shortDateString if displayClass.isFinished { attendanceStatusImageView.hidden = false if displayClass.didStudentAttend(student) { attendanceStatusImageView.image = UIImage(named: "selected_checkin") }else{ attendanceStatusImageView.image = UIImage(named: "redmark") } } else if displayClass.isStarted { attendanceStatusImageView.hidden = false if displayClass.didStudentAttend(student) { attendanceStatusImageView.image = UIImage(named: "selected_checkin") }else{ attendanceStatusImageView.image = UIImage(named: "unsurequestionmark") } }else{ // hide the attendance view because the class hasn't started yet attendanceStatusImageView.hidden = true } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } func setupUI() { className.textColor = ThemeManager.theme().primaryBlueColor() classDate.textColor = ThemeManager.theme().primaryBlueColor() attendanceStatusImageView.layer.cornerRadius = 6.0 attendanceStatusImageView.clipsToBounds = true attendanceStatusWrapperView.layer.cornerRadius = 6.0 attendanceStatusWrapperView.clipsToBounds = true } }
mit
926bb68782b4e17906f86ae28c84197e
32.96875
90
0.624655
5.828418
false
false
false
false
wei18810109052/CWWeChat
CWWeChat/ChatModule/CWChatKit/Message/View/TextMessageContentView.swift
2
2659
// // CWTextMessageContentView.swift // CWWeChat // // Created by chenwei on 2017/9/8. // Copyright © 2017年 cwwise. All rights reserved. // import UIKit import YYText class TextMessageContentView: MessageContentView { // 文本 private lazy var messageLabel: YYLabel = { let messageLabel = YYLabel() messageLabel.displaysAsynchronously = false messageLabel.ignoreCommonProperties = true messageLabel.highlightTapAction = ({[weak self] containerView, text, range, rect in guard let strongSelf = self else { return } strongSelf.didTapMessageLabelText(text, range: range) }) messageLabel.numberOfLines = 0 return messageLabel }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(messageLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func refresh(message: CWMessageModel) { super.refresh(message: message) messageLabel.textLayout = message.textLayout } override func layoutSubviews() { super.layoutSubviews() guard let message = message else { messageLabel.frame = self.bounds return } let edge: UIEdgeInsets if message.isSend == true { edge = ChatCellUI.right_edge_insets } else { edge = ChatCellUI.left_edge_insets } let x = self.bounds.minX + edge.left let y = self.bounds.minY + edge.top let width = self.bounds.width - edge.left - edge.right let height = self.bounds.height - edge.top - edge.bottom let frame = CGRect(x: x, y: y, width: width, height: height) messageLabel.frame = frame } // YYText点击事件 func didTapMessageLabelText(_ text: NSAttributedString, range: NSRange) { guard let hightlight = text.yy_attribute(YYTextHighlightAttributeName, at: UInt(range.location)) as? YYTextHighlight else { return } guard let info = hightlight.userInfo, info.count > 0, let delegate = self.delegate else { return } if let phone = info[kChatTextKeyPhone] as? String { // delegate.messageCellDidTapPhone(self, phone: phone) } else if let URLString = info[kChatTextKeyURL] as? String, let URL = URL(string: URLString) { // delegate.messageCellDidTapLink(self, link: URL) } } // 配置menuAction }
mit
4bc2aad429b7203beb90f68c3070248e
28.662921
131
0.600379
4.756757
false
false
false
false
neoneye/SwiftyFORM
Source/Form/OptionListViewController.swift
1
1324
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit class OptionListViewController: FormViewController, SelectOptionDelegate { typealias SelectOptionHandler = (OptionRowModel) -> Void let optionField: OptionPickerFormItem let selectOptionHandler: SelectOptionHandler init(optionField: OptionPickerFormItem, selectOptionHandler: @escaping SelectOptionHandler) { self.optionField = optionField self.selectOptionHandler = selectOptionHandler super.init() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func populate(_ builder: FormBuilder) { SwiftyFormLog("preselect option \(String(describing: optionField.selected?.title))") builder.navigationTitle = optionField.title for optionRow: OptionRowModel in optionField.options { let option = OptionRowFormItem() option.title = optionRow.title option.context = optionRow option.selected = (optionRow === optionField.selected) builder.append(option) } } func form_willSelectOption(option: OptionRowFormItem) { guard let selected = option.context as? OptionRowModel else { fatalError("Expected OptionRowModel when selecting option \(option.title)") } SwiftyFormLog("select option \(option.title)") selectOptionHandler(selected) } }
mit
4f411ebc088e490e0c481c29d3fe34e7
32.1
94
0.774169
4.326797
false
false
false
false
MrSuperJJ/JJSwiftNews
JJSwiftNews/View/JJTopicScrollView.swift
1
5622
// // JJtopicScrollView.swift // JJSwiftDemo // // Created by Mr.JJ on 2017/5/24. // Copyright © 2017年 yejiajun. All rights reserved. // import UIKit @objc(JJTopicScrollViewDelegate) protocol JJTopicScrollViewDelegate { func didtopicViewChanged(index: Int, value: String) } class JJTopicScrollView: UIView { // MARK: - Properties private lazy var topicScrollView: UIScrollView = { let topicScrollView = UIScrollView() topicScrollView.backgroundColor = UIColor.white topicScrollView.showsHorizontalScrollIndicator = false topicScrollView.showsVerticalScrollIndicator = false topicScrollView.bounces = false topicScrollView.delegate = self return topicScrollView }() private lazy var selectedBottomLine: UIView = { let selectedBottomLine = UIView() selectedBottomLine.backgroundColor = UIColor(valueRGB: 0x4285f4, alpha: 1) return selectedBottomLine }() private lazy var bottomLine: UIView = { let bottomLine = UIView() bottomLine.backgroundColor = UIColor(valueRGB: 0x999999, alpha: 0.5) return bottomLine }() private var topicViewWidth: CGFloat // 每个topicView宽度 private let topicViewTagIndex = 1000 // topicViewTag偏移量 private var lastTopicViewTag: Int // 最近一次选中topicView的Tag private var dataSourceArray: Array<String>? weak public var delegate: JJTopicScrollViewDelegate? // MARK: - Life Cycle init(frame: CGRect, topicViewWidth: CGFloat) { self.topicViewWidth = topicViewWidth self.lastTopicViewTag = topicViewTagIndex super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 设置内容 public func setupScrollViewContents(dataSourceArray: Array<String>) { guard dataSourceArray.count > 0 else { return } self.dataSourceArray = dataSourceArray topicScrollView.frame = CGRect(x: 0, y: 0, width: self.width, height: self.height) selectedBottomLine.frame = CGRect(x: 0, y: self.height - 2, width: topicViewWidth, height: 2) bottomLine.frame = CGRect(x: 0, y: self.height - 0.5, width: ScreenWidth, height: 0.5) topicScrollView.contentSize = CGSize(width: CGFloat(dataSourceArray.count) * topicViewWidth, height: 0) for (index, value) in dataSourceArray.enumerated() { let topicView = UIButton(frame: CGRect(x: CGFloat(index) * topicViewWidth , y: 0, width: topicViewWidth, height: self.height)) topicView.backgroundColor = UIColor.white topicView.setTitle(value, for: .normal) topicView.setTitleColor(index == 0 ? UIColor(valueRGB: 0x4285f4, alpha: 1) : UIColor(valueRGB: 0x999999, alpha: 1), for: .normal) topicView.titleLabel?.font = UIFont.systemFont(ofSize: CGFloat(adValue: 14)) topicView.tag = index + topicViewTagIndex topicView.addTarget(self, action: #selector(topicViewClicked(sender:)), for: .touchUpInside) topicScrollView.addSubview(topicView) } self.addSubview(topicScrollView) topicScrollView.addSubview(selectedBottomLine) self.addSubview(bottomLine) } // MARK: topic点击 @objc private func topicViewClicked(sender: UIButton) { let currTopicViewTag = sender.tag let lastView = topicScrollView.viewWithTag(lastTopicViewTag) as? UIButton let currView = topicScrollView.viewWithTag(currTopicViewTag) as? UIButton guard let currentTopicView = currView, let lastTopicView = lastView else { return } lastTopicViewTag = currTopicViewTag lastTopicView.setTitleColor(UIColor(valueRGB: 0x999999, alpha: 1), for: .normal) currentTopicView.setTitleColor(UIColor(valueRGB: 0x4285f4, alpha: 1), for: .normal) UIView.animate(withDuration: 0.3) { self.selectedBottomLine.frame = CGRect(x: currentTopicView.left, y: currentTopicView.bottom - 2, width: currentTopicView.width, height: 2) } if let dataSourceArray = dataSourceArray { let index = currTopicViewTag-topicViewTagIndex delegate?.didtopicViewChanged(index: index, value: dataSourceArray[index]) } } // MARK: topicView切换 public func switchToSelectedtopicView(index: Int) { let currentTopicViewTag = index + topicViewTagIndex let lastView = topicScrollView.viewWithTag(lastTopicViewTag) as? UIButton let currentView = topicScrollView.viewWithTag(currentTopicViewTag) as? UIButton guard let currentTopicView = currentView, let lastTopicView = lastView else { return } lastTopicViewTag = currentTopicViewTag lastTopicView.setTitleColor(UIColor(valueRGB: 0x999999, alpha: 1), for: .normal) currentTopicView.setTitleColor(UIColor(valueRGB: 0x4285f4, alpha: 1), for: .normal) UIView.animate(withDuration: 0.3) { self.selectedBottomLine.frame = CGRect(x: currentTopicView.left, y: currentTopicView.bottom - 2, width: currentTopicView.width, height: 2) } } } // MARK: - UIScrollViewDelegate extension JJTopicScrollView: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { var contentOffset = scrollView.contentOffset contentOffset.y = 0 scrollView.contentOffset = contentOffset } }
mit
4c0ae6eabd11b8898614aa62391eb255
41.557252
150
0.676413
4.916226
false
false
false
false
haskelash/github-onenote-sync
Sources/Run/Structs.swift
1
3171
// // Structs.swift // GitHubOneNoteSync // // Created by Haskel Ash on 7/23/17. // // import Foundation import App class Notebook { let id: String let name: String let sectionGroups: [SectionGroup] let sections: [Section] init(id: String, name: String, sectionGroups: [SectionGroup], sections: [Section]) { self.id = id; self.name = name; self.sectionGroups = sectionGroups; self.sections = sections } } class SectionGroup { let id: String let name: String let sectionGroups: [SectionGroup] let sections: [Section] init(node: Node) { let id = node["id"]!.string! let request = Request(method: .get, uri: "https://www.onenote.com/api/v1.0/me/notes/sectiongroups/\(id)?" + "select=id,name,sectionGroups,sections&expand=sectionGroups,sections") request.headers = ["Authorization": "Bearer \(token)"] request.body = .init("") drop.console.print("Fetching sectionGroup \(id)...") guard let response = try? drop.client.respond(to: request) else { fatalError("Error fetching section group \(id)") } drop.console.print("Returned from fetching with response:") drop.console.print(response.description) self.id = id self.name = node["name"]!.string! self.sectionGroups = response.data["sectionGroups"]!.array!.map{SectionGroup(node: $0)} self.sections = response.data["sections"]!.array!.map{Section(node: $0)} } } class Section { let id: String let name: String let pages: [Page] init(node: Node) { let id = node["id"]!.string! let request = Request(method: .get, uri: "https://www.onenote.com/api/v1.0/me/notes/sections/\(id)/pages?" + "select=id,title,createdTime,lastModifiedTime") request.headers = ["Authorization": "Bearer \(token)"] request.body = .init("") drop.console.print("Fetching pages in section \(id)...") guard let response = try? drop.client.respond(to: request) else { fatalError("Error fetching pages in section \(id)") } drop.console.print("Returned from fetching with response:") drop.console.print(response.description) self.id = id self.name = node["name"]!.string! self.pages = response.data["value"]!.array!.map{Page(node: $0)} } } class Page { let id: String let title: String let content: String init(node: Node) { let id = node["id"]!.string! let request = Request(method: .get, uri: "https://www.onenote.com/api/v1.0/me/notes/pages/\(id)/content?" + "includeIDs=true&preAuthenticated=true") request.headers = ["Authorization": "Bearer \(token)"] request.body = .init("") drop.console.print("Fetching page \(id)...") guard let response = try? drop.client.respond(to: request) else { fatalError("Error fetching page \(id)") } drop.console.print("Returned from fetching with response:") drop.console.print(response.description) self.id = id self.title = node["title"]!.string! self.content = response.body.bytes!.makeString() } }
mit
1ab1a9fbf095a6a98956387fc7c28436
33.467391
127
0.62567
3.862363
false
false
false
false
hatena/swift-Sample-GitHubSearch
GitHubSearch/GitHub.swift
1
13999
// The MIT License (MIT) // // Copyright (c) 2015 Hatena Co., Ltd. // // 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 AFNetworking public typealias JSONObject = [String: AnyObject] public enum HTTPMethod { case Get } /** API endpoint */ public protocol APIEndpoint { var path: String { get } var method: HTTPMethod { get } var parameters: Parameters { get } associatedtype ResponseType: JSONDecodable } /** Request parameters */ public struct Parameters: DictionaryLiteralConvertible { public private(set) var dictionary: [String: AnyObject] = [:] public typealias Key = String public typealias Value = AnyObject? /** Initialized from dictionary literals */ public init(dictionaryLiteral elements: (Parameters.Key, Parameters.Value)...) { for case let (key, value?) in elements { dictionary[key] = value } } } /** API error - UnexpectedResponse: Unexpected structure */ public enum APIError: ErrorType { case UnexpectedResponse } /** GitHub API - SeeAlso: https://developer.github.com/v3/ */ public class GitHubAPI { private let HTTPSessionManager: AFHTTPSessionManager = { let manager = AFHTTPSessionManager(baseURL: NSURL(string: "https://api.github.com/")) manager.requestSerializer.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept") return manager }() public init() { } /** Perform HTTP request for any endpoints. - Parameters: - endpoint: API endpoint. - handler: Request results handler. */ public func request<Endpoint: APIEndpoint>(endpoint: Endpoint, handler: (task: NSURLSessionDataTask, response: Endpoint.ResponseType?, error: ErrorType?) -> Void) { let success = { (task: NSURLSessionDataTask!, response: AnyObject!) -> Void in if let JSON = response as? JSONObject { do { let response = try Endpoint.ResponseType(JSON: JSON) handler(task: task, response: response, error: nil) } catch { handler(task: task, response: nil, error: error) } } else { handler(task: task, response: nil, error: APIError.UnexpectedResponse) } } let failure = { (task: NSURLSessionDataTask!, error: NSError!) -> Void in var error = error // If the error has any data, put it into "localized failure reason" if let errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] as? NSData, let errorDescription = NSString(data: errorData, encoding: NSUTF8StringEncoding) { var userInfo = error.userInfo userInfo[NSLocalizedFailureReasonErrorKey] = errorDescription error = NSError(domain: error.domain, code: error.code, userInfo: userInfo) } handler(task: task, response: nil, error: error) } switch endpoint.method { case .Get: HTTPSessionManager.GET(endpoint.path, parameters: endpoint.parameters.dictionary, success: success, failure: failure) } } // MARK: - Endpoints /** - SeeAlso: https://developer.github.com/v3/search/#search-repositories */ public struct SearchRepositories: APIEndpoint { public var path = "search/repositories" public var method = HTTPMethod.Get public var parameters: Parameters { return [ "q" : query, "page" : page, ] } public typealias ResponseType = SearchResult<Repository> public let query: String public let page: Int /** Search repositories - Parameters: - query: Search query. - page: Page. 1... - Returns: Search repositories API endpoint */ public init(query: String, page: Int) { self.query = query self.page = page } } } /** JSON decodable type */ public protocol JSONDecodable { init(JSON: JSONObject) throws } /** JSON decode error - MissingRequiredKey: Required key is missing - UnexpectedType: Value type is unexpected - CannotParseURL: Value cannot be parsed as URL - CannotParseDate: Value cannot be parsed as date */ public enum JSONDecodeError: ErrorType, CustomDebugStringConvertible { case MissingRequiredKey(String) case UnexpectedType(key: String, expected: Any.Type, actual: Any.Type) case CannotParseURL(key: String, value: String) case CannotParseDate(key: String, value: String) public var debugDescription: String { switch self { case .MissingRequiredKey(let key): return "JSON Decode Error: Required key '\(key)' missing" case let .UnexpectedType(key: key, expected: expected, actual: actual): return "JSON Decode Error: Unexpected type '\(actual)' was supplied for '\(key): \(expected)'" case let .CannotParseURL(key: key, value: value): return "JSON Decode Error: Cannot parse URL '\(value)' for key '\(key)'" case let .CannotParseDate(key: key, value: value): return "JSON Decode Error: Cannot parse date '\(value)' for key '\(key)'" } } } /** Search result data - SeeAlso: https://developer.github.com/v3/search/ */ public struct SearchResult<ItemType: JSONDecodable>: JSONDecodable { public let totalCount: Int public let incompleteResults: Bool public let items: [ItemType] /** Initialize from JSON object - Parameter JSON: JSON object - Throws: JSONDecodeError - Returns: SearchResult */ public init(JSON: JSONObject) throws { self.totalCount = try getValue(JSON, key: "total_count") self.incompleteResults = try getValue(JSON, key: "incomplete_results") self.items = try (getValue(JSON, key: "items") as [JSONObject]).mapWithRethrow { return try ItemType(JSON: $0) } } } /** Repository data - SeeAlso: https://developer.github.com/v3/search/#search-repositories */ public struct Repository: JSONDecodable { public let id: Int public let name: String public let fullName: String public let isPrivate: Bool public let HTMLURL: NSURL public let description: String? public let fork: Bool public let URL: NSURL public let createdAt: NSDate public let updatedAt: NSDate public let pushedAt: NSDate? public let homepage: String? public let size: Int public let stargazersCount: Int public let watchersCount: Int public let language: String? public let forksCount: Int public let openIssuesCount: Int public let masterBranch: String? public let defaultBranch: String public let score: Double public let owner: User /** Initialize from JSON object - Parameter JSON: JSON object - Throws: JSONDecodeError - Returns: SearchResult */ public init(JSON: JSONObject) throws { self.id = try getValue(JSON, key: "id") self.name = try getValue(JSON, key: "name") self.fullName = try getValue(JSON, key: "full_name") self.isPrivate = try getValue(JSON, key: "private") self.HTMLURL = try getURL(JSON, key: "html_url") self.description = try getOptionalValue(JSON, key: "description") self.fork = try getValue(JSON, key: "fork") self.URL = try getURL(JSON, key: "url") self.createdAt = try getDate(JSON, key: "created_at") self.updatedAt = try getDate(JSON, key: "updated_at") self.pushedAt = try getOptionalDate(JSON, key: "pushed_at") self.homepage = try getOptionalValue(JSON, key: "homepage") self.size = try getValue(JSON, key: "size") self.stargazersCount = try getValue(JSON, key: "stargazers_count") self.watchersCount = try getValue(JSON, key: "watchers_count") self.language = try getOptionalValue(JSON, key: "language") self.forksCount = try getValue(JSON, key: "forks_count") self.openIssuesCount = try getValue(JSON, key: "open_issues_count") self.masterBranch = try getOptionalValue(JSON, key: "master_branch") self.defaultBranch = try getValue(JSON, key: "default_branch") self.score = try getValue(JSON, key: "score") self.owner = try User(JSON: getValue(JSON, key: "owner") as JSONObject) } } /** User data - SeeAlso: https://developer.github.com/v3/search/#search-repositories */ public struct User: JSONDecodable { public let login: String public let id: Int public let avatarURL: NSURL public let gravatarID: String public let URL: NSURL public let receivedEventsURL: NSURL public let type: String /** Initialize from JSON object - Parameter JSON: JSON object - Throws: JSONDecodeError - Returns: SearchResult */ public init(JSON: JSONObject) throws { self.login = try getValue(JSON, key: "login") self.id = try getValue(JSON, key: "id") self.avatarURL = try getURL(JSON, key: "avatar_url") self.gravatarID = try getValue(JSON, key: "gravatar_id") self.URL = try getURL(JSON, key: "url") self.receivedEventsURL = try getURL(JSON, key: "received_events_url") self.type = try getValue(JSON, key: "type") } } // MARK: - Utilities /** Get URL from JSON for key - Parameters: - JSON: JSON object - key: Key - Throws: JSONDecodeError - Returns: URL */ private func getURL(JSON: JSONObject, key: String) throws -> NSURL { let URLString: String = try getValue(JSON, key: key) guard let URL = NSURL(string: URLString) else { throw JSONDecodeError.CannotParseURL(key: key, value: URLString) } return URL } /** Get URL from JSON for key - Parameters: - JSON: JSON object - key: Key - Throws: JSONDecodeError - Returns: URL or nil */ private func getOptionalURL(JSON: JSONObject, key: String) throws -> NSURL? { guard let URLString: String = try getOptionalValue(JSON, key: key) else { return nil } guard let URL = NSURL(string: URLString) else { throw JSONDecodeError.CannotParseURL(key: key, value: URLString) } return URL } /** Parse ISO 8601 format date string - SeeAlso: https://developer.github.com/v3/#schema */ private let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" return formatter }() /** Get date from JSON for key - Parameters: - JSON: JSON object - key: Key - Throws: JSONDecodeError - Returns: date */ private func getDate(JSON: JSONObject, key: String) throws -> NSDate { let dateString: String = try getValue(JSON, key: key) guard let date = dateFormatter.dateFromString(dateString) else { throw JSONDecodeError.CannotParseDate(key: key, value: dateString) } return date } /** Get date from JSON for key - Parameters: - JSON: JSON object - key: Key - Throws: JSONDecodeError - Returns: date or nil */ private func getOptionalDate(JSON: JSONObject, key: String) throws -> NSDate? { guard let dateString: String = try getOptionalValue(JSON, key: key) else { return nil } guard let date = dateFormatter.dateFromString(dateString) else { throw JSONDecodeError.CannotParseDate(key: key, value: dateString) } return date } /** Get typed value from JSON for key. Type `T` should be inferred from contexts. - Parameters: - JSON: JSON object - key: Key - Throws: JSONDecodeError - Returns: Typed value */ private func getValue<T>(JSON: JSONObject, key: String) throws -> T { guard let value = JSON[key] else { throw JSONDecodeError.MissingRequiredKey(key) } guard let typedValue = value as? T else { throw JSONDecodeError.UnexpectedType(key: key, expected: T.self, actual: value.dynamicType) } return typedValue } /** Get typed value from JSON for key. Type `T` should be inferred from contexts. - Parameters: - JSON: JSON object - key: Key - Throws: JSONDecodeError - Returns: Typed value or nil */ private func getOptionalValue<T>(JSON: JSONObject, key: String) throws -> T? { guard let value = JSON[key] else { return nil } if value is NSNull { return nil } guard let typedValue = value as? T else { throw JSONDecodeError.UnexpectedType(key: key, expected: T.self, actual: value.dynamicType) } return typedValue } private extension Array { /** Workaround for `map` with throwing closure */ func mapWithRethrow<T>(@noescape transform: (Array.Generator.Element) throws -> T) rethrows -> [T] { var mapped: [T] = [] for element in self { mapped.append(try transform(element)) } return mapped } }
mit
219bff73961fb4ad8a4565350c64ce93
31.405093
168
0.661047
4.356987
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Controller/Actions/DeleteViewController.swift
1
4108
// // DeleteViewController.swift // Digi Cloud // // Created by Mihai Cristescu on 26/10/16. // Copyright © 2016 Mihai Cristescu. All rights reserved. // import UIKit final class DeleteViewController: UITableViewController { // MARK: - Properties var onSelection: ( () -> Void)? private let isFolder: Bool // MARK: - Initializers and Deinitializers init(isFolder: Bool) { self.isFolder = isFolder super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Overridden Methods and Properties override func viewDidLoad() { super.viewDidLoad() setupViews() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.preferredContentSize.width = 350 self.preferredContentSize.height = tableView.contentSize.height - 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: nil) cell.selectionStyle = .blue cell.textLabel?.textAlignment = .center cell.textLabel?.font = UIFont.systemFont(ofSize: 16) if indexPath.row == 1 { cell.textLabel?.textColor = .defaultColor cell.textLabel?.text = NSLocalizedString("Cancel", comment: "") } else { cell.textLabel?.textColor = .red cell.textLabel?.text = NSLocalizedString("Delete", comment: "") } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { dismiss(animated: false) { if indexPath.row == 0 { self.onSelection?() } } } // MARK: - Helper Functions private func registerForNotificationCenter() { NotificationCenter.default.addObserver( self, selector: #selector(handleDismiss), name: .UIApplicationWillResignActive, object: nil) } private func setupViews() { let headerView: UIView = { let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 50)) view.backgroundColor = UIColor(white: 0.95, alpha: 1.0) return view }() let message: UILabel = { let label = UILabel() label.textAlignment = .center if isFolder { label.text = NSLocalizedString("Are you sure you want to delete this folder?", comment: "") } else { label.text = NSLocalizedString("Are you sure you want to delete this file?", comment: "") } label.font = UIFont.systemFont(ofSize: 14) return label }() let separator: UIView = { let view = UIView() view.backgroundColor = UIColor(white: 0.8, alpha: 1) return view }() headerView.addSubview(message) headerView.addConstraints(with: "H:|-10-[v0]-10-|", views: message) message.centerYAnchor.constraint(equalTo: headerView.centerYAnchor).isActive = true headerView.addSubview(separator) headerView.addConstraints(with: "H:|[v0]|", views: separator) headerView.addConstraints(with: "V:[v0(\(1 / UIScreen.main.scale))]|", views: separator) self.title = NSLocalizedString("Delete confirmation", comment: "") tableView.isScrollEnabled = false tableView.tableHeaderView = headerView tableView.rowHeight = AppSettings.tableViewRowHeight tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) } @objc private func handleDismiss() { self.dismiss(animated: false, completion: nil) } }
mit
60f935b7dba84393970b3a9c9e8f7220
29.879699
109
0.613587
4.954162
false
false
false
false
rentpath/RPValidationKit
RPValidationKit/RPValidationKit/Validators/RPMaxValueValidator.swift
1
2043
/* * Copyright (c) 2016 RentPath, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * 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. */ open class RPMaxValueValidator: RPValidator { open var maxValue: Double = 0 open override func getType() -> String { return "maxvalue" } public override init(string: String? = nil) { guard let _string = string, let value = Double(_string) else { return } maxValue = value } public init(maxValue: Double) { self.maxValue = maxValue } open override func validate(_ value: String) -> Bool { guard let number = Double(value) else { return true } return number <= maxValue } open override func validateField(_ fieldName: String, value: String) -> RPValidation { if validate(value) { return RPValidation.valid } else { return RPValidation.error(message: "\(fieldName) cannot be greater than \(maxValue)") } } }
mit
84d94c82f3f4da5b64688f9f7962e9d9
34.842105
97
0.669604
4.751163
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden/HTWDresden/GradesModel.swift
2
4525
// // GradesModel.swift // HTWGrades // // Created by Benjamin Herzog on 23/11/15. // Copyright © 2015 HTW Dresden. All rights reserved. // import Foundation import Alamofire import ObjectMapper let getPos = "https://wwwqis.htw-dresden.de/appservice/getcourses" let getGrade = "https://wwwqis.htw-dresden.de/appservice/getgrades" class GradesModel { var settings: Settings init(settings: Settings) { self.settings = settings } func start(completion: ([String: [Grade]] -> Void)? = nil) { loadCourses { success, data in if !success { print("course error") return } for course in data { self.loadGrades(course) { success, grades in if !success { print("grade error") return } completion?(self.groupGrades(grades)) } } } } private func groupGrades(grades: [Grade]) -> [String: [Grade]] { var result = [String: [Grade]]() for grade in grades { if result[grade.semester] == nil { result[grade.semester] = [] } result[grade.semester]?.append(grade) } return result } private func loadCourses(completion: (success: Bool, data: [Course]) -> Void) { guard let u = settings.sNumber, let p = settings.password else { print("Set a user first!!") return } Alamofire.request(.POST, getPos, parameters: ["sNummer": u, "RZLogin": p]) .responseJSON { response in guard let coursesArray = response.result.value as? [[String: String]] else { completion(success: false, data: []) return } let courses = coursesArray.map { element in return Mapper<Course>().map(element) }.filter { $0 != nil }.map { $0! } completion(success: true, data: courses) } } private func loadGrades(course: Course, completion: (success: Bool, data: [Grade]) -> Void) { guard let u = settings.sNumber, let p = settings.password else { print("Set a user first!!") return } Alamofire.request(.POST, getGrade, parameters: ["sNummer": u, "RZLogin": p, "AbschlNr": course.AbschlNr, "POVersion": course.POVersion, "StgNr": course.StgNr]) .responseJSON { jsonResponse in guard let allGrades = jsonResponse.result.value as? [[String: String]] else { completion(success: false, data: []) return } let grades = allGrades.map { Mapper<Grade>().map($0) }.filter { $0 != nil }.map { $0! } completion(success: true, data: grades) } } static func getAverage(grades: [[Grade]]) -> Double { // Fehler fixen wobei nachgeholte Prüfungen nicht die vorhergehende Note ersetzen let semesterAverages = grades.map { semester -> Double in let allCredits = semester.reduce(0.0) { $0 + $1.credits } let allWeightedGrades = semester.reduce(0.0) { $0 + ($1.credits * $1.grade) } return allWeightedGrades / allCredits } return semesterAverages.reduce(0.0, combine: +) / Double(semesterAverages.count) } } struct Course: Mappable { var AbschlNr: String var POVersion: String var StgNr: String init?(_ map: Map) { AbschlNr = map["AbschlNr"].valueOrFail() POVersion = map["POVersion"].valueOrFail() StgNr = map["StgNr"].valueOrFail() if !map.isValid { return nil } } mutating func mapping(map: Map) { } } struct Grade: Mappable, CustomStringConvertible { var nr: Int = 0 var subject: String var state: String var credits: Double = 0 var grade: Double = 0 var semester: String var semesterjahr: Int = 0 init?(_ map: Map) { subject = map["PrTxt"].valueOr("") state = map["Status"].valueOr("") semester = map["Semester"].valueOrFail() semesterjahr = Int(String(semester.characters.dropLast()))! semester = String(semester.characters.dropFirst(4)) if (semester == "1") { semester = "Sommersemester \(semesterjahr)" } else { semester = "Wintersemester \(semesterjahr)/" + String(String(semesterjahr + 1).characters.dropFirst(2)) } if !map.isValid { return nil } } mutating func mapping(map: Map) { let stringToIntTransform = TransformOf<Int, String>(fromJSON: { $0.map { Int($0) ?? 0} }, toJSON: { "\($0 ?? 0)"}) let stringToDoubleTransform = TransformOf<Double, String>(fromJSON: { $0.map { Double($0) ?? 0} }, toJSON: { "\($0 ?? 0)"}) nr <- (map["PrNr"], stringToIntTransform) credits <- (map["EctsCredits"], stringToDoubleTransform) grade <- (map["PrNote"], stringToDoubleTransform) grade /= 100 } var description: String { return "\nGrade:\n\tNr: \(nr)\n\tFach: \(subject)\n\tCredtis: \(credits)\n\tNote: \(grade)" } }
gpl-2.0
ce59036e369153459e292c27930622bb
22.931217
161
0.647358
3.275163
false
false
false
false
mperovic/my41
my41cx-ios/Display.swift
1
20282
// // Display.swift // my41 // // Created by Miroslav Perovic on 1/10/15. // Copyright (c) 2015 iPera. All rights reserved. // import Foundation import UIKit import SwiftUI typealias DisplayFont = [DisplaySegmentMap] typealias DisplaySegmentPaths = [UIBezierPath] class Display: UIView, Peripheral { var calculator: Calculator? let numDisplayCells = 12 let numAnnunciators = 12 let numDisplaySegments = 17 let numFontChars = 128 var updateCountdown: Int = 0 var on: Bool = true var registers = DisplayRegisters() var displayFont = DisplayFont() var segmentPaths = DisplaySegmentPaths() var annunciatorFont: UIFont? var annunciatorFontScale: CGFloat = 1.0 let annunciatorFontSize: CGFloat = 10.0 let annunciatorBottomMargin: CGFloat = 0.0 var annunciatorPositions: [CGPoint] = [CGPoint](repeating: CGPoint(x: 0.0, y: 0.0), count: 12) private var _contrast = Digit() var contrast: Digit { set { _contrast = newValue & 0xf scheduleUpdate() } get { return _contrast } } override func awakeFromNib() { backgroundColor = .clear calculator?.display = self displayFont = loadFont("hpfont") segmentPaths = DisplaySegmentPaths() on = true updateCountdown = 2 bus.installPeripheral(self, inSlot: 0xFD) bus.display = self for idx in 0..<numDisplayCells { registers.A[idx] = 0xA registers.B[idx] = 0x3 registers.C[idx] = 0x2 registers.E = 0xfff } //-- initialize the display character to unicode lookup table: // The table simply contains one unicode character for each X-41 hardware character // index (0x00..0x7f). The file can be tweaked for whatever translation is desired. // Character groups (approximated): // 0x00..0x1f: A-Z uppercase characters // 0x20..0x3f: ASCII-like symbols and numbers // 0x40..0x4f: a-e + "hangman" // 0x50..0x5f: some greek characters + "hangman" // 0x60..0x7f: a-z lowercase characters do { let filename: String = Bundle.main.path(forResource: CTULookupRsrcName, ofType: CTULookupRsrcType)! let CTULookup = try NSMutableString(contentsOfFile: filename, encoding: String.Encoding.unicode.rawValue) as String CTULookupLength = CTULookup.count } catch _ { } } override func draw(_ rect: CGRect) { if self.segmentPaths.count == 0 { self.annunciatorFont = UIFont( name: "Menlo", size: annunciatorFontScale * annunciatorFontSize ) segmentPaths = bezierPaths() annunciatorPositions = calculateAnnunciatorPositions(annunciatorFont!, inRect: bounds) } if on { if true { let context = UIGraphicsGetCurrentContext() context?.saveGState() for idx in 0..<numDisplayCells { let segmentsOn = segmentsForCell(idx) for seg in 0..<numDisplaySegments { if (segmentsOn & (1 << UInt32(seg))) != 0 { let path: UIBezierPath = segmentPaths[seg] context?.addPath(path.cgPath) } } context?.translateBy(x: cellWidth(), y: 0.0) } context?.drawPath(using: CGPathDrawingMode.fill) context?.restoreGState() } let attrs = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font): annunciatorFont! ] calculator?.prgmMode = false calculator?.alphaMode = false for idx in 0..<numAnnunciators { if annunciatorOn(idx) { if idx == 10 { calculator?.prgmMode = true } if idx == 11 { calculator?.alphaMode = true } let point = annunciatorPositions[idx] let context = UIGraphicsGetCurrentContext() context?.saveGState() context?.scaleBy(x: 1.0 / annunciatorFontScale, y: 1.0 / annunciatorFontScale ) context?.translateBy(x: point.x, y: point.y) let nsString = annunciatorStrings[idx] as NSString nsString.draw( at: CGPoint(x: 0.0, y: 0.0), withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attrs) ) context?.restoreGState() } } } } func bezierPaths() -> DisplaySegmentPaths { // let xRatio = self.bounds.size.width / 240.0 // let yRatio = self.bounds.size.height / 38.0 let xRatio: CGFloat = 1.0 let yRatio: CGFloat = 1.0 var paths: DisplaySegmentPaths = DisplaySegmentPaths() let bezierPath0 = UIBezierPath() bezierPath0.move(to: CGPoint(x: 4.617837 * xRatio, y: 2.000000 * yRatio)) bezierPath0.addLine(to: CGPoint(x: 2.375577 * xRatio, y: 0.000000 * yRatio)) bezierPath0.addLine(to: CGPoint(x: 15.073103 * xRatio, y: 0.000000 * yRatio)) bezierPath0.addLine(to: CGPoint(x: 12.304828 * xRatio, y: 2.000000 * yRatio)) bezierPath0.addLine(to: CGPoint(x: 4.617837 * xRatio, y: 2.000000 * yRatio)) bezierPath0.close() bezierPath0.move(to: CGPoint(x: 4.617837 * xRatio, y: 2.000000 * yRatio)) paths.append(bezierPath0) let bezierPath1 = UIBezierPath() bezierPath1.move(to: CGPoint(x: 1.026980 * xRatio, y: 10.703221 * yRatio)) bezierPath1.addLine(to: CGPoint(x: 1.935450 * xRatio, y: 0.710054 * yRatio)) bezierPath1.addLine(to: CGPoint(x: 3.443619 * xRatio, y: 6.210914 * yRatio)) bezierPath1.addLine(to: CGPoint(x: 3.136238 * xRatio, y: 9.592111 * yRatio)) bezierPath1.addLine(to: CGPoint(x: 1.026980 * xRatio, y: 10.703221 * yRatio)) bezierPath1.close() bezierPath1.move(to: CGPoint(x: 1.026980 * xRatio, y: 10.703221 * yRatio)) paths.append(bezierPath1) let bezierPath2 = UIBezierPath() bezierPath2.move(to: CGPoint(x: 3.931293 * xRatio, y: 6.098653 * yRatio)) bezierPath2.addLine(to: CGPoint(x: 2.464718 * xRatio, y: 0.749508 * yRatio)) bezierPath2.addLine(to: CGPoint(x: 4.320368 * xRatio, y: 2.404667 * yRatio)) bezierPath2.addLine(to: CGPoint(x: 6.413752 * xRatio, y: 6.591435 * yRatio)) bezierPath2.addLine(to: CGPoint(x: 7.149230 * xRatio, y: 10.489320 * yRatio)) bezierPath2.addLine(to: CGPoint(x: 5.669303 * xRatio, y: 9.574674 * yRatio)) bezierPath2.addLine(to: CGPoint(x: 3.931293 * xRatio, y: 6.098653 * yRatio)) bezierPath2.close() bezierPath2.move(to: CGPoint(x: 3.931293 * xRatio, y: 6.098653 * yRatio)) paths.append(bezierPath2) let bezierPath3 = UIBezierPath() bezierPath3.move(to: CGPoint(x: 6.905082 * xRatio, y: 6.498730 * yRatio)) bezierPath3.addLine(to: CGPoint(x: 7.291330 * xRatio, y: 2.250000 * yRatio)) bezierPath3.addLine(to: CGPoint(x: 9.299579 * xRatio, y: 2.250000 * yRatio)) bezierPath3.addLine(to: CGPoint(x: 8.884876 * xRatio, y: 6.811726 * yRatio)) bezierPath3.addLine(to: CGPoint(x: 7.585231 * xRatio, y: 10.103380 * yRatio)) bezierPath3.addLine(to: CGPoint(x: 6.905082 * xRatio, y: 6.498730 * yRatio)) bezierPath3.close() bezierPath3.move(to: CGPoint(x: 6.905082 * xRatio, y: 6.498730 * yRatio)) paths.append(bezierPath3) let bezierPath4 = UIBezierPath() bezierPath4.move(to: CGPoint(x: 9.352165 * xRatio, y: 6.989707 * yRatio)) bezierPath4.addLine(to: CGPoint(x: 12.565980 * xRatio, y: 2.428165 * yRatio)) bezierPath4.addLine(to: CGPoint(x: 14.879394 * xRatio, y: 0.756790 * yRatio)) bezierPath4.addLine(to: CGPoint(x: 12.461739 * xRatio, y: 6.048622 * yRatio)) bezierPath4.addLine(to: CGPoint(x: 9.993521 * xRatio, y: 9.551898 * yRatio)) bezierPath4.addLine(to: CGPoint(x: 7.963932 * xRatio, y: 10.505735 * yRatio)) bezierPath4.addLine(to: CGPoint(x: 9.352165 * xRatio, y: 6.989707 * yRatio)) bezierPath4.close() bezierPath4.move(to: CGPoint(x: 9.352165 * xRatio, y: 6.989707 * yRatio)) paths.append(bezierPath4) let bezierPath5 = UIBezierPath() bezierPath5.move(to: CGPoint(x: 14.524980 * xRatio, y: 10.725222 * yRatio)) bezierPath5.addLine(to: CGPoint(x: 12.617742 * xRatio, y: 9.614111 * yRatio)) bezierPath5.addLine(to: CGPoint(x: 12.924595 * xRatio, y: 6.238729 * yRatio)) bezierPath5.addLine(to: CGPoint(x: 15.431723 * xRatio, y: 0.751059 * yRatio)) bezierPath5.addLine(to: CGPoint(x: 14.524980 * xRatio, y: 10.725222 * yRatio)) bezierPath5.close() bezierPath5.move(to: CGPoint(x: 14.524980 * xRatio, y: 10.725222 * yRatio)) paths.append(bezierPath5) let bezierPath6 = UIBezierPath() bezierPath6.move(to: CGPoint(x: 3.213154 * xRatio, y: 12.000000 * yRatio)) bezierPath6.addLine(to: CGPoint(x: 1.515522 * xRatio, y: 11.011001 * yRatio)) bezierPath6.addLine(to: CGPoint(x: 3.434736 * xRatio, y: 10.000000 * yRatio)) bezierPath6.addLine(to: CGPoint(x: 5.406438 * xRatio, y: 10.000000 * yRatio)) bezierPath6.addLine(to: CGPoint(x: 6.997042 * xRatio, y: 10.983047 * yRatio)) bezierPath6.addLine(to: CGPoint(x: 5.072827 * xRatio, y: 12.000000 * yRatio)) bezierPath6.addLine(to: CGPoint(x: 3.213154 * xRatio, y: 12.000000 * yRatio)) bezierPath6.close() bezierPath6.move(to: CGPoint(x: 3.213154 * xRatio, y: 12.000000 * yRatio)) paths.append(bezierPath6) let bezierPath7 = UIBezierPath() bezierPath7.move(to: CGPoint(x: 9.674292 * xRatio, y: 12.000000 * yRatio)) bezierPath7.addLine(to: CGPoint(x: 8.033062 * xRatio, y: 11.025712 * yRatio)) bezierPath7.addLine(to: CGPoint(x: 10.215584 * xRatio, y: 10.000000 * yRatio)) bezierPath7.addLine(to: CGPoint(x: 12.286846 * xRatio, y: 10.000000 * yRatio)) bezierPath7.addLine(to: CGPoint(x: 13.984478 * xRatio, y: 10.988999 * yRatio)) bezierPath7.addLine(to: CGPoint(x: 12.065263 * xRatio, y: 12.000000 * yRatio)) bezierPath7.addLine(to: CGPoint(x: 9.674292 * xRatio, y: 12.000000 * yRatio)) bezierPath7.close() bezierPath7.move(to: CGPoint(x: 9.674292 * xRatio, y: 12.000000 * yRatio)) paths.append(bezierPath7) let bezierPath8 = UIBezierPath() bezierPath8.move(to: CGPoint(x: 0.070283 * xRatio, y: 21.226881 * yRatio)) bezierPath8.addLine(to: CGPoint(x: 0.975020 * xRatio, y: 11.274778 * yRatio)) bezierPath8.addLine(to: CGPoint(x: 2.882258 * xRatio, y: 12.385889 * yRatio)) bezierPath8.addLine(to: CGPoint(x: 2.594385 * xRatio, y: 15.552494 * yRatio)) bezierPath8.addLine(to: CGPoint(x: 0.070283 * xRatio, y: 21.226881 * yRatio)) bezierPath8.close() bezierPath8.move(to: CGPoint(x: 0.070283 * xRatio, y: 21.226881 * yRatio)) paths.append(bezierPath8) let bezierPath9 = UIBezierPath() bezierPath9.move(to: CGPoint(x: 3.058874 * xRatio, y: 15.738516 * yRatio)) bezierPath9.addLine(to: CGPoint(x: 5.306457 * xRatio, y: 12.442060 * yRatio)) bezierPath9.addLine(to: CGPoint(x: 7.047006 * xRatio, y: 11.522176 * yRatio)) bezierPath9.addLine(to: CGPoint(x: 5.594459 * xRatio, y: 15.569930 * yRatio)) bezierPath9.addLine(to: CGPoint(x: 2.864343 * xRatio, y: 19.574100 * yRatio)) bezierPath9.addLine(to: CGPoint(x: 0.613314 * xRatio, y: 21.236336 * yRatio)) bezierPath9.addLine(to: CGPoint(x: 3.058874 * xRatio, y: 15.738516 * yRatio)) bezierPath9.close() bezierPath9.move(to: CGPoint(x: 3.058874 * xRatio, y: 15.738516 * yRatio)) paths.append(bezierPath9) let bezierPath10 = UIBezierPath() bezierPath10.move(to: CGPoint(x: 6.065075 * xRatio, y: 15.738811 * yRatio)) bezierPath10.addLine(to: CGPoint(x: 7.435389 * xRatio, y: 11.920212 * yRatio)) bezierPath10.addLine(to: CGPoint(x: 8.120102 * xRatio, y: 15.224238 * yRatio)) bezierPath10.addLine(to: CGPoint(x: 7.708670 * xRatio, y: 19.750000 * yRatio)) bezierPath10.addLine(to: CGPoint(x: 5.700421 * xRatio, y: 19.750000 * yRatio)) bezierPath10.addLine(to: CGPoint(x: 6.065075 * xRatio, y: 15.738811 * yRatio)) bezierPath10.close() bezierPath10.move(to: CGPoint(x: 6.065075 * xRatio, y: 15.738811 * yRatio)) paths.append(bezierPath10) let bezierPath11 = UIBezierPath() bezierPath11.move(to: CGPoint(x: 8.609699 * xRatio, y: 15.122776 * yRatio)) bezierPath11.addLine(to: CGPoint(x: 7.859829 * xRatio, y: 11.504337 * yRatio)) bezierPath11.addLine(to: CGPoint(x: 9.419060 * xRatio, y: 12.429949 * yRatio)) bezierPath11.addLine(to: CGPoint(x: 11.534890 * xRatio, y: 16.308971 * yRatio)) bezierPath11.addLine(to: CGPoint(x: 13.018471 * xRatio, y: 21.263432 * yRatio)) bezierPath11.addLine(to: CGPoint(x: 11.046081 * xRatio, y: 19.589474 * yRatio)) bezierPath11.addLine(to: CGPoint(x: 8.609699 * xRatio, y: 15.122776 * yRatio)) bezierPath11.close() bezierPath11.move(to: CGPoint(x: 8.609699 * xRatio, y: 15.122776 * yRatio)) paths.append(bezierPath11) let bezierPath12 = UIBezierPath() bezierPath12.move(to: CGPoint(x: 12.020228 * xRatio, y: 16.186754 * yRatio)) bezierPath12.addLine(to: CGPoint(x: 12.363762 * xRatio, y: 12.407889 * yRatio)) bezierPath12.addLine(to: CGPoint(x: 14.473021 * xRatio, y: 11.296779 * yRatio)) bezierPath12.addLine(to: CGPoint(x: 13.560777 * xRatio, y: 21.331455 * yRatio)) bezierPath12.addLine(to: CGPoint(x: 12.020228 * xRatio, y: 16.186754 * yRatio)) bezierPath12.close() bezierPath12.move(to: CGPoint(x: 12.020228 * xRatio, y: 16.186754 * yRatio)) paths.append(bezierPath12) let bezierPath13 = UIBezierPath() bezierPath13.move(to: CGPoint(x: 0.420855 * xRatio, y: 22.000000 * yRatio)) bezierPath13.addLine(to: CGPoint(x: 3.129292 * xRatio, y: 20.000000 * yRatio)) bezierPath13.addLine(to: CGPoint(x: 10.757083 * xRatio, y: 20.000000 * yRatio)) bezierPath13.addLine(to: CGPoint(x: 13.113644 * xRatio, y: 22.000000 * yRatio)) bezierPath13.addLine(to: CGPoint(x: 0.420855 * xRatio, y: 22.000000 * yRatio)) bezierPath13.close() bezierPath13.move(to: CGPoint(x: 0.420855 * xRatio, y: 22.000000 * yRatio)) paths.append(bezierPath13) let bezierPath14 = UIBezierPath() bezierPath14.move(to: CGPoint(x: 19.506186 * xRatio, y: 11.000000 * yRatio)) bezierPath14.addLine(to: CGPoint(x: 19.506186 * xRatio, y: 11.000000 * yRatio)) bezierPath14.addCurve(to: CGPoint(x: 19.506186 * xRatio, y: 11.831843 * yRatio), controlPoint1: CGPoint(x: 18.831842 * xRatio, y: 12.506186 * yRatio), controlPoint2: CGPoint(x: 18.000000 * xRatio, y: 12.506186 * yRatio)) bezierPath14.addCurve(to: CGPoint(x: 17.168158 * xRatio, y: 12.506186 * yRatio), controlPoint1: CGPoint(x: 16.493814 * xRatio, y: 11.831843 * yRatio), controlPoint2: CGPoint(x: 16.493814 * xRatio, y: 11.000000 * yRatio)) bezierPath14.addLine(to: CGPoint(x: 16.493814 * xRatio, y: 11.000000 * yRatio)) bezierPath14.addLine(to: CGPoint(x: 16.493814 * xRatio, y: 11.000000 * yRatio)) bezierPath14.addCurve(to: CGPoint(x: 16.493814 * xRatio, y: 10.168157 * yRatio), controlPoint1: CGPoint(x: 17.168158 * xRatio, y: 9.493814 * yRatio), controlPoint2: CGPoint(x: 18.000000 * xRatio, y: 9.493814 * yRatio)) bezierPath14.addCurve(to: CGPoint(x: 18.831842 * xRatio, y: 9.493814 * yRatio), controlPoint1: CGPoint(x: 19.506186 * xRatio, y: 10.1681573 * yRatio), controlPoint2: CGPoint(x: 19.506186 * xRatio, y: 11.000000 * yRatio)) bezierPath14.addLine(to: CGPoint(x: 19.506186 * xRatio, y: 11.000000 * yRatio)) bezierPath14.close() bezierPath14.move(to: CGPoint(x: 19.506186 * xRatio, y: 11.000000 * yRatio)) paths.append(bezierPath14) let bezierPath15 = UIBezierPath() bezierPath15.move(to: CGPoint(x: 18.590910 * xRatio, y: 21.000000 * yRatio)) bezierPath15.addLine(to: CGPoint(x: 18.590910 * xRatio, y: 21.000000 * yRatio)) bezierPath15.addCurve(to: CGPoint(x: 18.590910 * xRatio, y: 21.828426 * yRatio), controlPoint1: CGPoint(x: 17.919336 * xRatio, y: 22.500000 * yRatio), controlPoint2: CGPoint(x: 17.090910 * xRatio, y: 22.500000 * yRatio)) bezierPath15.addCurve(to: CGPoint(x: 16.262484 * xRatio, y: 22.500000 * yRatio), controlPoint1: CGPoint(x: 15.590911, y: 21.828426 * yRatio), controlPoint2: CGPoint(x: 15.590911 * xRatio, y: 21.000000 * yRatio)) bezierPath15.addLine(to: CGPoint(x: 15.590911 * xRatio, y: 21.000000 * yRatio)) bezierPath15.addLine(to: CGPoint(x: 15.590911 * xRatio, y: 21.000000 * yRatio)) bezierPath15.addCurve(to: CGPoint(x: 15.590911 * xRatio, y: 20.1715747 * yRatio), controlPoint1: CGPoint(x: 16.262484 * xRatio, y: 19.500000 * yRatio), controlPoint2: CGPoint(x: 17.090910 * xRatio, y: 19.500000 * yRatio)) bezierPath15.addCurve(to: CGPoint(x: 17.919336 * xRatio, y: 19.500000 * yRatio), controlPoint1: CGPoint(x: 18.590910 * xRatio, y: 20.171574 * yRatio), controlPoint2: CGPoint(x: 18.590910 * xRatio, y: 21.000000 * yRatio)) bezierPath15.addLine(to: CGPoint(x: 18.590910 * xRatio, y: 21.000000 * yRatio)) bezierPath15.close() bezierPath15.move(to: CGPoint(x: 18.590910 * xRatio, y: 21.000000 * yRatio)) paths.append(bezierPath15) let bezierPath16 = UIBezierPath() bezierPath16.move(to: CGPoint(x: 18.474253 * xRatio, y: 22.083590 * yRatio)) bezierPath16.addLine(to: CGPoint(x: 18.474253 * xRatio, y: 22.083590 * yRatio)) bezierPath16.addCurve(to: CGPoint(x: 17.881054 * xRatio, y: 24.806688), controlPoint1: CGPoint(x: 15.208557 * xRatio, y: 26.546652 * yRatio), controlPoint2: CGPoint(x: 12.478299 * xRatio, y: 25.987333 * yRatio)) bezierPath16.addLine(to: CGPoint(x: 12.478300 * xRatio, y: 25.987331 * yRatio)) bezierPath16.addLine(to: CGPoint(x: 12.478301 * xRatio, y: 25.987333 * yRatio)) bezierPath16.addCurve(to: CGPoint(x: 14.211855 * xRatio, y: 25.12723), controlPoint1: CGPoint(x: 15.191052 * xRatio, y: 23.245596 * yRatio), controlPoint2: CGPoint(x: 17.354506 * xRatio, y: 22.737331 * yRatio)) bezierPath16.addLine(to: CGPoint(x: 15.353578 * xRatio, y: 21.263596 * yRatio)) bezierPath16.addLine(to: CGPoint(x: 15.353578 * xRatio, y: 21.263596 * yRatio)) bezierPath16.addCurve(to: CGPoint(x: 15.499158 * xRatio, y: 22.223097), controlPoint1: CGPoint(x: 16.395004 * xRatio, y: 22.882912 * yRatio), controlPoint2: CGPoint(x: 17.354506 * xRatio, y: 22.737331 * yRatio)) bezierPath16.addCurve(to: CGPoint(x: 17.797445 * xRatio, y: 22.670126), controlPoint1: CGPoint(x: 18.197989 * xRatio, y: 22.436277 * yRatio), controlPoint2: CGPoint(x: 18.474253 * xRatio, y: 22.083590 * yRatio)) bezierPath16.addLine(to: CGPoint(x: 18.474253 * xRatio, y: 22.083590 * yRatio)) bezierPath16.close() bezierPath16.move(to: CGPoint(x: 18.474253 * xRatio, y: 22.083590 * yRatio)) paths.append(bezierPath16) return paths } //MARK: - Font support /* func loadSegmentPaths(file: String) -> DisplaySegmentPaths { var paths: DisplaySegmentPaths = DisplaySegmentPaths() let path = NSBundle.mainBundle().pathForResource(file, ofType: "geom") var data = NSData(contentsOfFile: path!, options: .DataReadingMappedIfSafe, error: nil) var unarchiver = NSKeyedUnarchiver(forReadingWithData: data!) let dict = unarchiver.decodeObjectForKey("bezierPaths") as NSDictionary unarchiver.finishDecoding() for idx in 0..<numDisplaySegments { let key = String(idx) let path = dict[key]! as UIBezierPath paths.append(path) } return paths } */ func saveFile() { } func calculateAnnunciatorPositions(_ font: UIFont, inRect bounds: CGRect) -> [CGPoint] { // Distribute the annunciators evenly across the width of the display based on the sizes of their strings. // let xRatio = self.bounds.size.width / 240.0 // let yRatio = self.bounds.size.height / 38.0 var positions: [CGPoint] = [CGPoint](repeating: CGPoint(x: 0.0, y: 0.0), count: numAnnunciators) var annunciatorWidths: [CGFloat] = [CGFloat](repeating: 0.0, count: numAnnunciators) var spaceWidth: CGFloat = 0.0 var x: CGFloat = 0.0 var y: CGFloat = 0.0 var d: CGFloat = 0.0 var h: CGFloat = 0.0 var totalWidth: CGFloat = 0.0 let attrs = [ convertFromNSAttributedStringKey(NSAttributedString.Key.font): annunciatorFont! ] for idx in 0..<numAnnunciators { let nsString: NSString = annunciatorStrings[idx] as NSString let width = nsString.size(withAttributes: convertToOptionalNSAttributedStringKeyDictionary(attrs)).width annunciatorWidths[idx] = width totalWidth += width } spaceWidth = (bounds.size.width - totalWidth) / CGFloat(numAnnunciators - 1) d -= font.descender h = font.lineHeight y = bounds.size.height * annunciatorFontScale - annunciatorBottomMargin - (h - d) for idx in 0..<numAnnunciators { positions[idx] = CGPoint(x: x, y: y) x += annunciatorWidths[idx] + spaceWidth } return positions } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
bsd-3-clause
59eb5b070ea8d46e7acc121385723fae
46.947991
223
0.703974
3.096489
false
false
false
false
inamiy/ReactiveCocoaCatalog
ReactiveCocoaCatalog/AppDelegate.swift
1
3413
// // AppDelegate.swift // ReactiveCocoaCatalog // // Created by Yasuhiro Inami on 2015-09-16. // Copyright © 2015 Yasuhiro Inami. All rights reserved. // import UIKit import ReactiveSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func _setupAppearance() { let font = UIFont(name: "AvenirNext-Medium", size: 16)! UINavigationBar.appearance().titleTextAttributes = [ NSFontAttributeName: font ] UIBarButtonItem.appearance().setTitleTextAttributes([ NSFontAttributeName: font ], for: .normal) } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { self._setupAppearance() let splitVC = self.window!.rootViewController as! UISplitViewController splitVC.delegate = self splitVC.preferredDisplayMode = .allVisible let mainNavC = splitVC.viewControllers[0] as! UINavigationController let mainVC = mainNavC.topViewController as! MasterViewController // NOTE: use dispatch_after to check `splitVC.collapsed` after delegation is complete (for iPad) // FIXME: look for better solution DispatchQueue.main.asyncAfter(deadline: .now() + 1) { if !splitVC.isCollapsed { mainVC.showDetailViewController(at: 0) } } 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:. } func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool { return true } }
mit
74468d79f5319ce75ebb5519e8d497ea
45.108108
285
0.734467
5.724832
false
false
false
false
Obisoft2017/BeautyTeamiOS
BeautyTeam/BeautyTeam/Event.swift
1
1350
// // Event.swift // BeautyTeam // // Created by Carl Lee on 4/15/16. // Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved. // import Foundation class Event: INoticable { var eventId: Int! var eventName: String! var eventContent: String! var happenTime: String! var endTime: String! var costTime: String! required init(rawData: [String : AnyObject?]) { super.init(rawData: rawData) guard let eventId_raw = rawData["EventId"] as? Int else { fatalError() } guard let eventName_raw = rawData["EventName"] as? String else { fatalError() } guard let eventContent_raw = rawData["EventContent"] as? String else { fatalError() } guard let happenTime_raw = rawData["HappenTime"] as? String else { fatalError() } guard let endTime_raw = rawData["EndTime"] as? String else { fatalError() } guard let costTime_raw = rawData["CostTime"] as? String else { fatalError() } self.eventId = eventId_raw self.eventName = eventName_raw self.eventContent = eventContent_raw self.happenTime = happenTime_raw self.endTime = endTime_raw self.costTime = costTime_raw } }
apache-2.0
0b6218033f355574232bac94f49b8714
27.104167
78
0.58636
4.323718
false
false
false
false
BanyaKrylov/Learn-Swift
ListApp/ListApp/ViewController.swift
1
1952
// // ViewController.swift // ListApp // // Created by Иван Крылов on 26.08.17. // Copyright © 2017 Иван Крылов. All rights reserved. // import UIKit class ViewController: UIViewController { let lesson: [Lesson] = [ Lesson(numberOfDays: 1, themeLesson: "Basics", scaleLesson: 4, switcher: true), Lesson(numberOfDays: 2, themeLesson: "Basics1", scaleLesson: 5, switcher: true), Lesson(numberOfDays: 3, themeLesson: "Basics2", scaleLesson: 4, switcher: true), Lesson(numberOfDays: 4, themeLesson: "Basics3", scaleLesson: 5, switcher: true), Lesson(numberOfDays: 5, themeLesson: "Basics4", scaleLesson: 5, switcher: false), Lesson(numberOfDays: 6, themeLesson: "Basics5", scaleLesson: 4, switcher: false), ] @IBOutlet weak var tabel: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lesson.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let taskCells = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? TaskCellTableViewCell { let userToShow = lesson[indexPath.row] taskCells.mainImage.image = userToShow.photo taskCells.nameLabel.text = userToShow.name taskCells.messageLabel.text = userToShow.message return taskCells } return UITableViewCell() } }
apache-2.0
df924420ec7ed135e0238a61492834b6
32.293103
115
0.662869
4.756158
false
false
false
false
MukeshKumarS/Swift
test/Driver/linker.swift
1
7328
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt // RUN: FileCheck %s < %t.simple.txt // RUN: FileCheck -check-prefix SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt // RUN: FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt // RUN: FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt // RUN: FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt // RUN: FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt // RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt // RUN: FileCheck %s < %t.complex.txt // RUN: FileCheck -check-prefix COMPLEX %s < %t.complex.txt // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | FileCheck -check-prefix DEBUG %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s | FileCheck -check-prefix NO_ARCLITE %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios8.0 %s | FileCheck -check-prefix NO_ARCLITE %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | FileCheck -check-prefix INFERRED_NAME %s // RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | FileCheck -check-prefix INFERRED_NAME %s // There are more RUN lines further down in the file. // REQUIRES: X86 // FIXME: Need to set up a sysroot for osx so the DEBUG checks work on linux // rdar://problem/19692770 // XFAIL: linux // CHECK: swift // CHECK: -o [[OBJECTFILE:.*]] // CHECK-NEXT: bin/ld{{"? }} // CHECK-DAG: [[OBJECTFILE]] // CHECK-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift/macosx]] // CHECK-DAG: -rpath [[STDLIB_PATH]] // CHECK-DAG: -lSystem // CHECK-DAG: -arch x86_64 // CHECK-DAG: -force_load {{[^ ]+/lib/arc/libarclite_macosx.a}} -framework CoreFoundation // CHECK: -o {{[^ ]+}} // SIMPLE: bin/ld{{"? }} // SIMPLE-NOT: -syslibroot // SIMPLE-DAG: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}} // SIMPLE-NOT: -syslibroot // SIMPLE: -o linker // IOS_SIMPLE: swift // IOS_SIMPLE: -o [[OBJECTFILE:.*]] // IOS_SIMPLE: bin/ld{{"? }} // IOS_SIMPLE-DAG: [[OBJECTFILE]] // IOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/iphonesimulator}} // IOS_SIMPLE-DAG: -lSystem // IOS_SIMPLE-DAG: -arch x86_64 // IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}} // IOS_SIMPLE: -o linker // tvOS_SIMPLE: swift // tvOS_SIMPLE: -o [[OBJECTFILE:.*]] // tvOS_SIMPLE: bin/ld{{"? }} // tvOS_SIMPLE-DAG: [[OBJECTFILE]] // tvOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/appletvsimulator}} // tvOS_SIMPLE-DAG: -lSystem // tvOS_SIMPLE-DAG: -arch x86_64 // tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}} // tvOS_SIMPLE: -o linker // watchOS_SIMPLE: swift // watchOS_SIMPLE: -o [[OBJECTFILE:.*]] // watchOS_SIMPLE: bin/ld{{"? }} // watchOS_SIMPLE-DAG: [[OBJECTFILE]] // watchOS_SIMPLE-DAG: -L {{[^ ]+/lib/swift/watchsimulator}} // watchOS_SIMPLE-DAG: -lSystem // watchOS_SIMPLE-DAG: -arch i386 // watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}} // watchOS_SIMPLE: -o linker // LINUX-x86_64: swift // LINUX-x86_64: -o [[OBJECTFILE:.*]] // LINUX-x86_64: clang++{{"? }} // LINUX-x86_64-DAG: [[OBJECTFILE]] // LINUX-x86_64-DAG: -lswiftCore // LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-x86_64-DAG: -Xlinker -T /{{[^ ]+}}/linux/x86_64/swift.ld // LINUX-x86_64-DAG: -F foo // LINUX-x86_64-DAG: -framework bar // LINUX-x86_64-DAG: -L baz // LINUX-x86_64-DAG: -lboo // LINUX-x86_64-DAG: -Xlinker -undefined // LINUX-x86_64: -o linker // LINUX-armv7: swift // LINUX-armv7: -o [[OBJECTFILE:.*]] // LINUX-armv7: clang++{{"? }} // LINUX-armv7-DAG: [[OBJECTFILE]] // LINUX-armv7-DAG: -lswiftCore // LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+/lib/swift]] // LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]] // LINUX-armv7-DAG: -Xlinker -T /{{[^ ]+}}/linux/armv7/swift.ld // LINUX-armv7-DAG: -F foo // LINUX-armv7-DAG: -framework bar // LINUX-armv7-DAG: -L baz // LINUX-armv7-DAG: -lboo // LINUX-armv7-DAG: -Xlinker -undefined // LINUX-armv7: -o linker // COMPLEX: bin/ld{{"? }} // COMPLEX-DAG: -dylib // COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk // COMPLEX-DAG: -lfoo // COMPLEX-DAG: -framework bar // COMPLEX-DAG: -L baz // COMPLEX-DAG: -F garply // COMPLEX-DAG: -undefined dynamic_lookup // COMPLEX-DAG: -macosx_version_min 10.9.1 // COMPLEX: -o sdk.out // DEBUG: bin/swift // DEBUG-NEXT: bin/swift // DEBUG-NEXT: bin/ld{{"? }} // DEBUG: -add_ast_path {{.*}}/{{[^/]+}}.swiftmodule // DEBUG: -o linker // DEBUG-NEXT: bin/dsymutil // DEBUG: linker // DEBUG: -o linker.dSYM // NO_ARCLITE: bin/ld{{"? }} // NO_ARCLITE-NOT: arclite // NO_ARCLITE: -o {{[^ ]+}} // INFERRED_NAME: bin/swift // INFERRED_NAME: -module-name LINKER // INFERRED_NAME: bin/ld{{"? }} // INFERRED_NAME: -o libLINKER.dylib // Test ld detection. We use hard links to make sure // the Swift driver really thinks it's been moved. // RUN: rm -rf %t // RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/bin/ // RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld // RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld // RUN: ln %swift_driver_plain %t/DISTINCTIVE-PATH/usr/bin/swiftc // RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc %s -### | FileCheck -check-prefix=RELATIVE-LINKER %s // RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/swift // RELATIVE-LINKER: /DISTINCTIVE-PATH/usr/bin/ld // RELATIVE-LINKER: -o {{[^ ]+}} // Also test arclite detection. This uses xcrun to find arclite when it's not // next to Swift. // RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/bin // RUN: mkdir -p %t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc // RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun // RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=XCRUN_ARCLITE %s // XCRUN_ARCLITE: bin/ld{{"? }} // XCRUN_ARCLITE: /ANOTHER-DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a // XCRUN_ARCLITE: -o {{[^ ]+}} // RUN: mkdir -p %t/DISTINCTIVE-PATH/usr/lib/arc // RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | FileCheck -check-prefix=RELATIVE_ARCLITE %s // RELATIVE_ARCLITE: bin/ld{{"? }} // RELATIVE_ARCLITE: /DISTINCTIVE-PATH/usr/lib/arc/libarclite_macosx.a // RELATIVE_ARCLITE: -o {{[^ ]+}} // Clean up the test executable because hard links are expensive. // RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
apache-2.0
1997ff9b002b4cc871d55dbe0449f532
36.19797
242
0.666894
2.881636
false
false
false
false
Hua70/Trip-to-IOS-Design-Patterns
SimpleCode/BlueLibrary-Swift/BlueLibrarySwift/HorizontalScroller.swift
4
6331
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit @objc protocol HorizontalScrollerDelegate { // ask the delegate how many views he wants to present inside the horizontal scroller func numberOfViewsForHorizontalScroller(scroller: HorizontalScroller) -> Int // ask the delegate to return the view that should appear at <index> func horizontalScrollerViewAtIndex(scroller: HorizontalScroller, index:Int) -> UIView // inform the delegate what the view at <index> has been clicked func horizontalScrollerClickedViewAtIndex(scroller: HorizontalScroller, index:Int) // ask the delegate for the index of the initial view to display. this method is optional // and defaults to 0 if it's not implemented by the delegate optional func initialViewIndex(scroller: HorizontalScroller) -> Int } class HorizontalScroller: UIView { weak var delegate: HorizontalScrollerDelegate? // 1 private let VIEW_PADDING = 10 private let VIEW_DIMENSIONS = 100 private let VIEWS_OFFSET = 100 // 2 private var scroller : UIScrollView! // 3 var viewArray = [UIView]() override init(frame: CGRect) { super.init(frame: frame) initializeScrollView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeScrollView() } func initializeScrollView() { //1 scroller = UIScrollView() addSubview(scroller) //2 scroller.setTranslatesAutoresizingMaskIntoConstraints(false) //3 self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0.0)) //4 let tapRecognizer = UITapGestureRecognizer(target: self, action:Selector("scrollerTapped:")) scroller.addGestureRecognizer(tapRecognizer) } func viewAtIndex(index :Int) -> UIView { return viewArray[index] } func scrollerTapped(gesture: UITapGestureRecognizer) { let location = gesture.locationInView(gesture.view) if let delegate = self.delegate { for index in 0..<delegate.numberOfViewsForHorizontalScroller(self) { let view = scroller.subviews[index] as UIView if CGRectContainsPoint(view.frame, location) { delegate.horizontalScrollerClickedViewAtIndex(self, index: index) scroller.setContentOffset(CGPointMake(view.frame.origin.x - self.frame.size.width/2 + view.frame.size.width/2, 0), animated:true) break } } } } override func didMoveToSuperview() { reload() } func reload() { // 1 - Check if there is a delegate, if not there is nothing to load. if let delegate = self.delegate { //2 - Will keep adding new album views on reload, need to reset. viewArray = [] let views: NSArray = scroller.subviews // 3 - remove all subviews views.enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in object.removeFromSuperview() } // 4 - xValue is the starting point of the views inside the scroller var xValue = VIEWS_OFFSET for index in 0..<delegate.numberOfViewsForHorizontalScroller(self) { // 5 - add a view at the right position xValue += VIEW_PADDING let view = delegate.horizontalScrollerViewAtIndex(self, index: index) view.frame = CGRectMake(CGFloat(xValue), CGFloat(VIEW_PADDING), CGFloat(VIEW_DIMENSIONS), CGFloat(VIEW_DIMENSIONS)) scroller.addSubview(view) xValue += VIEW_DIMENSIONS + VIEW_PADDING // 6 - Store the view so we can reference it later viewArray.append(view) } // 7 scroller.contentSize = CGSizeMake(CGFloat(xValue + VIEWS_OFFSET), frame.size.height) // 8 - If an initial view is defined, center the scroller on it if let initialView = delegate.initialViewIndex?(self) { scroller.setContentOffset(CGPointMake(CGFloat(initialView)*CGFloat((VIEW_DIMENSIONS + (2 * VIEW_PADDING))), 0), animated: true) } } } func centerCurrentView() { var xFinal = scroller.contentOffset.x + CGFloat((VIEWS_OFFSET/2) + VIEW_PADDING) let viewIndex = xFinal / CGFloat((VIEW_DIMENSIONS + (2*VIEW_PADDING))) xFinal = viewIndex * CGFloat(VIEW_DIMENSIONS + (2*VIEW_PADDING)) scroller.setContentOffset(CGPointMake(xFinal, 0), animated: true) if let delegate = self.delegate { delegate.horizontalScrollerClickedViewAtIndex(self, index: Int(viewIndex)) } } } extension HorizontalScroller: UIScrollViewDelegate { func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { centerCurrentView() } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { centerCurrentView() } }
mit
048280a975aec09b6ef189941da33bfe
39.845161
167
0.720107
4.531854
false
false
false
false
cohix/MaterialKit
Source/BasicCardView.swift
1
13549
// // Copyright (C) 1615 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // import UIKit public class BasicCardView : MaterialCardView, Comparable, Equatable { // // :name: layoutConstraints // internal lazy var layoutConstraints: Array<NSLayoutConstraint> = Array<NSLayoutConstraint>() // // :name: views // internal lazy var views: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() /** :name: titleLabelVerticalInset */ public var titleLabelVerticalInset: CGFloat = MaterialTheme.verticalInset { didSet { titleLabelTopInset = titleLabelVerticalInset titleLabelBottomInset = titleLabelVerticalInset } } /** :name: titleLabelTopInset */ public var titleLabelTopInset: CGFloat = MaterialTheme.verticalInset /** :name: titleLabelBottomInset */ public var titleLabelBottomInset: CGFloat = MaterialTheme.verticalInset /** :name: titleLabelHorizontalInset */ public var titleLabelHorizontalInset: CGFloat = MaterialTheme.horizontalInset { didSet { titleLabelLeftInset = titleLabelHorizontalInset titleLabelRightInset = titleLabelHorizontalInset } } /** :name: titleLabelLeftInset */ public var titleLabelLeftInset: CGFloat = MaterialTheme.horizontalInset /** :name: titleLabelRightInset */ public var titleLabelRightInset: CGFloat = MaterialTheme.horizontalInset /** :name: detailLabelVerticalInset */ public var detailLabelVerticalInset: CGFloat = MaterialTheme.verticalInset { didSet { detailLabelTopInset = detailLabelVerticalInset detailLabelBottomInset = detailLabelVerticalInset } } /** :name: detailLabelTopInset */ public var detailLabelTopInset: CGFloat = MaterialTheme.verticalInset /** :name: detailLabelBottomInset */ public var detailLabelBottomInset: CGFloat = MaterialTheme.verticalInset /** :name: detailLabelHorizontalInset */ public var detailLabelHorizontalInset: CGFloat = MaterialTheme.horizontalInset { didSet { detailLabelLeftInset = detailLabelHorizontalInset detailLabelRightInset = detailLabelHorizontalInset } } /** :name: detailLabelLeftInset */ public var detailLabelLeftInset: CGFloat = MaterialTheme.horizontalInset /** :name: detailLabelRightInset */ public var detailLabelRightInset: CGFloat = MaterialTheme.horizontalInset /** :name: buttonVerticalInset */ public var buttonVerticalInset: CGFloat = MaterialTheme.verticalInset { didSet { buttonTopInset = buttonVerticalInset buttonBottomInset = buttonVerticalInset } } /** :name: buttonTopInset */ public var buttonTopInset: CGFloat = MaterialTheme.verticalInset /** :name: buttonBottomInset */ public var buttonBottomInset: CGFloat = MaterialTheme.verticalInset /** :name: buttonHorizontalInset */ public var buttonHorizontalInset: CGFloat = MaterialTheme.horizontalInset { didSet { buttonLeftInset = buttonHorizontalInset buttonRightInset = buttonHorizontalInset } } /** :name: buttonLeftInset */ public var buttonLeftInset: CGFloat = MaterialTheme.horizontalInset /** :name: buttonRightInset */ public var buttonRightInset: CGFloat = MaterialTheme.horizontalInset /** :name: titleLabelContainer */ public private(set) var titleLabelContainer: UIView? /** :name: shadow */ public var shadow: Bool = true { didSet { false == shadow ? removeShadow() : prepareShadow() } } /** :name: maximumTitleLabelHeight */ public var maximumTitleLabelHeight: CGFloat = 288 /** :name: titleLabel */ public var titleLabel: UILabel? { didSet { if let t = titleLabel { // container if nil == titleLabelContainer { titleLabelContainer = UIView() titleLabelContainer!.setTranslatesAutoresizingMaskIntoConstraints(false) titleLabelContainer!.backgroundColor = MaterialTheme.clear.color addSubview(titleLabelContainer!) } // text titleLabelContainer!.addSubview(t) t.setTranslatesAutoresizingMaskIntoConstraints(false) t.textColor = MaterialTheme.white.color t.backgroundColor = MaterialTheme.clear.color t.font = Roboto.medium t.numberOfLines = 0 t.lineBreakMode = .ByTruncatingTail prepareCard() } else { titleLabelContainer?.removeFromSuperview() } } } /** :name: maximumDetailLabelHeight */ public var maximumDetailLabelHeight: CGFloat = 1008 /** :name: detailLabelContainer */ public private(set) var detailLabelContainer: UIView? /** :name: detailLabel */ public var detailLabel: UILabel? { didSet { if let l = detailLabel { // container if nil == detailLabelContainer { detailLabelContainer = UIView() detailLabelContainer!.setTranslatesAutoresizingMaskIntoConstraints(false) detailLabelContainer!.backgroundColor = MaterialTheme.clear.color addSubview(detailLabelContainer!) } // text detailLabelContainer!.addSubview(l) l.setTranslatesAutoresizingMaskIntoConstraints(false) l.textColor = MaterialTheme.white.color l.backgroundColor = MaterialTheme.clear.color l.font = Roboto.light l.numberOfLines = 0 l.lineBreakMode = .ByTruncatingTail prepareCard() } else { detailLabelContainer?.removeFromSuperview() } } } /** :name: divider */ public var divider: UIView? { didSet { if let d = divider { d.setTranslatesAutoresizingMaskIntoConstraints(false) d.backgroundColor = MaterialTheme.blueGrey.color addSubview(d) prepareCard() } else { divider?.removeFromSuperview() } } } /** :name: buttonsContainer */ public private(set) var buttonsContainer: UIView? /** :name: leftButtons */ public var leftButtons: Array<MaterialButton>? { didSet { if let b = leftButtons { if nil == buttonsContainer { buttonsContainer = UIView() buttonsContainer!.setTranslatesAutoresizingMaskIntoConstraints(false) buttonsContainer!.backgroundColor = MaterialTheme.clear.color addSubview(buttonsContainer!) } prepareCard() } else { buttonsContainer?.removeFromSuperview() } } } /** :name: rightButtons */ public var rightButtons: Array<MaterialButton>? { didSet { if let b = rightButtons { if nil == buttonsContainer { buttonsContainer = UIView() buttonsContainer!.setTranslatesAutoresizingMaskIntoConstraints(false) buttonsContainer!.backgroundColor = MaterialTheme.clear.color addSubview(buttonsContainer!) } prepareCard() } else { buttonsContainer?.removeFromSuperview() } } } /** :name: init */ public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** :name: init */ public convenience init?(titleLabel: UILabel? = nil, detailLabel: UILabel? = nil, divider: UIView? = nil, leftButtons: Array<MaterialButton>? = nil, rightButtons: Array<MaterialButton>? = nil) { self.init(frame: CGRectZero) prepareProperties(titleLabel, detailLabel: detailLabel, divider: divider, leftButtons: leftButtons, rightButtons: rightButtons) } /** :name: init */ public required init(frame: CGRect) { super.init(frame: CGRectZero) } // // :name: prepareProperties // internal func prepareProperties(titleLabel: UILabel?, detailLabel: UILabel?, divider: UIView?, leftButtons: Array<MaterialButton>?, rightButtons: Array<MaterialButton>?) { self.titleLabel = titleLabel self.detailLabel = detailLabel self.divider = divider self.leftButtons = leftButtons self.rightButtons = rightButtons } // // :name: prepareView // internal override func prepareView() { super.prepareView() prepareShadow() backgroundColor = MaterialTheme.blueGrey.darken1 } // // :name: prepareCard // internal override func prepareCard() { super.prepareCard() // deactivate and clear all constraints NSLayoutConstraint.deactivateConstraints(layoutConstraints) layoutConstraints.removeAll(keepCapacity: false) // detect all components and create constraints var verticalFormat: String = "V:|" // title if nil != titleLabelContainer && nil != titleLabel { // clear for updated constraints titleLabelContainer!.removeConstraints(titleLabelContainer!.constraints()) // container layoutConstraints += Layout.constraint("H:|[titleLabelContainer]|", options: nil, metrics: nil, views: ["titleLabelContainer": titleLabelContainer!]) verticalFormat += "[titleLabelContainer]" views["titleLabelContainer"] = titleLabelContainer! // text Layout.expandToParentHorizontallyWithPad(titleLabelContainer!, child: titleLabel!, left: titleLabelLeftInset, right: titleLabelRightInset) titleLabelContainer!.addConstraints(Layout.constraint("V:|-(titleLabelTopInset)-[titleLabel(<=maximumTitleLabelHeight)]-(titleLabelBottomInset)-|", options: nil, metrics: ["titleLabelTopInset": titleLabelTopInset, "titleLabelBottomInset": titleLabelBottomInset, "maximumTitleLabelHeight": maximumTitleLabelHeight], views: ["titleLabel": titleLabel!])) } // detail if nil != detailLabelContainer && nil != detailLabel { // clear for updated constraints detailLabelContainer!.removeConstraints(detailLabelContainer!.constraints()) // container layoutConstraints += Layout.constraint("H:|[detailLabelContainer]|", options: nil, metrics: nil, views: ["detailLabelContainer": detailLabelContainer!]) verticalFormat += "[detailLabelContainer]" views["detailLabelContainer"] = detailLabelContainer! // text Layout.expandToParentHorizontallyWithPad(detailLabelContainer!, child: detailLabel!, left: detailLabelLeftInset, right: detailLabelRightInset) detailLabelContainer!.addConstraints(Layout.constraint("V:|-(detailLabelTopInset)-[detailLabel(<=maximumDetailLabelHeight)]-(detailLabelBottomInset)-|", options: nil, metrics: ["detailLabelTopInset": detailLabelTopInset, "detailLabelBottomInset": detailLabelBottomInset, "maximumDetailLabelHeight": maximumDetailLabelHeight], views: ["detailLabel": detailLabel!])) } // buttons if nil != buttonsContainer && (nil != leftButtons || nil != rightButtons) { // clear for updated constraints buttonsContainer!.removeConstraints(buttonsContainer!.constraints()) // divider if nil != divider { layoutConstraints += Layout.constraint("H:|[divider]|", options: nil, metrics: nil, views: ["divider": divider!]) views["divider"] = divider! verticalFormat += "[divider(1)]" } //container layoutConstraints += Layout.constraint("H:|[buttonsContainer]|", options: nil, metrics: nil, views: ["buttonsContainer": buttonsContainer!]) verticalFormat += "[buttonsContainer]" views["buttonsContainer"] = buttonsContainer! // leftButtons if nil != leftButtons { var horizontalFormat: String = "H:|" var buttonViews: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() for var i: Int = 0, l: Int = leftButtons!.count; i < l; ++i { let button: MaterialButton = leftButtons![i] buttonsContainer!.addSubview(button) buttonViews["button\(i)"] = button horizontalFormat += "-(buttonLeftInset)-[button\(i)]" Layout.expandToParentVerticallyWithPad(buttonsContainer!, child: button, top: buttonTopInset, bottom: buttonBottomInset) } buttonsContainer!.addConstraints(Layout.constraint(horizontalFormat, options: nil, metrics: ["buttonLeftInset": buttonLeftInset], views: buttonViews)) } // rightButtons if nil != rightButtons { var horizontalFormat: String = "H:" var buttonViews: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>() for var i: Int = 0, l: Int = rightButtons!.count; i < l; ++i { let button: MaterialButton = rightButtons![i] buttonsContainer!.addSubview(button) buttonViews["button\(i)"] = button horizontalFormat += "[button\(i)]-(buttonRightInset)-" Layout.expandToParentVerticallyWithPad(buttonsContainer!, child: button, top: buttonTopInset, bottom: buttonBottomInset) } buttonsContainer!.addConstraints(Layout.constraint(horizontalFormat + "|", options: nil, metrics: ["buttonRightInset": buttonRightInset], views: buttonViews)) } } verticalFormat += "|" // combine constraints if 0 < layoutConstraints.count { layoutConstraints += Layout.constraint(verticalFormat, options: nil, metrics: nil, views: views) NSLayoutConstraint.activateConstraints(layoutConstraints) } } } public func ==(lhs: BasicCardView, rhs: BasicCardView) -> Bool { return lhs.tag == rhs.tag } public func <=(lhs: BasicCardView, rhs: BasicCardView) -> Bool { return lhs.tag <= rhs.tag } public func >=(lhs: BasicCardView, rhs: BasicCardView) -> Bool { return lhs.tag >= rhs.tag } public func >(lhs: BasicCardView, rhs: BasicCardView) -> Bool { return lhs.tag > rhs.tag } public func <(lhs: BasicCardView, rhs: BasicCardView) -> Bool { return lhs.tag < rhs.tag }
agpl-3.0
ba316e8a8e6bda4a2922abfbf4dd93f4
28.582969
367
0.731272
4.369236
false
false
false
false
m-alani/contests
leetcode/searchForARange.swift
1
562
// // searchForARange.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/search-for-a-range/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // func searchRange(_ nums: [Int], _ target: Int) -> [Int] { let start = nums.index(of: target) if let s = start { var e = s while e < nums.count && nums[e] == target { e += 1 } return [s, e - 1] } else { return [-1, -1] } }
mit
0560bd8697b2b266cdaf360c35cfd715
25.761905
117
0.608541
3.175141
false
false
false
false
nubbel/swift-tensorflow
Xcode/Test/TestProvider.swift
1
4700
import Foundation class TestWorkerProvider:Tensorflow_Grpc_WorkerServiceProvider{ func getstatus(request : Tensorflow_GetStatusRequest, session : Tensorflow_Grpc_WorkerServiceGetStatusSession) throws -> Tensorflow_GetStatusResponse{ print("getstatus") let response = Tensorflow_GetStatusResponse() return response } func createworkersession(request : Tensorflow_CreateWorkerSessionRequest, session : Tensorflow_Grpc_WorkerServiceCreateWorkerSessionSession) throws -> Tensorflow_CreateWorkerSessionResponse{ print("createworkersession") let response = Tensorflow_CreateWorkerSessionResponse() return response } func registergraph(request : Tensorflow_RegisterGraphRequest, session : Tensorflow_Grpc_WorkerServiceRegisterGraphSession) throws -> Tensorflow_RegisterGraphResponse{ print("registergraph") let response = Tensorflow_RegisterGraphResponse() return response } func deregistergraph(request : Tensorflow_DeregisterGraphRequest, session : Tensorflow_Grpc_WorkerServiceDeregisterGraphSession) throws -> Tensorflow_DeregisterGraphResponse{ print("deregistergraph") let response = Tensorflow_DeregisterGraphResponse() return response } func rungraph(request : Tensorflow_RunGraphRequest, session : Tensorflow_Grpc_WorkerServiceRunGraphSession) throws -> Tensorflow_RunGraphResponse{ print("rungraph") let response = Tensorflow_RunGraphResponse() return response } func cleanupgraph(request : Tensorflow_CleanupGraphRequest, session : Tensorflow_Grpc_WorkerServiceCleanupGraphSession) throws -> Tensorflow_CleanupGraphResponse{ print("cleanupgraph") let response = Tensorflow_CleanupGraphResponse() return response } func cleanupall(request : Tensorflow_CleanupAllRequest, session : Tensorflow_Grpc_WorkerServiceCleanupAllSession) throws -> Tensorflow_CleanupAllResponse{ print("cleanupall") let response = Tensorflow_CleanupAllResponse() return response } func recvtensor(request : Tensorflow_RecvTensorRequest, session : Tensorflow_Grpc_WorkerServiceRecvTensorSession) throws -> Tensorflow_RecvTensorResponse{ print("recvtensor") let response = Tensorflow_RecvTensorResponse() return response } func logging(request : Tensorflow_LoggingRequest, session : Tensorflow_Grpc_WorkerServiceLoggingSession) throws -> Tensorflow_LoggingResponse{ print("logging") let response = Tensorflow_LoggingResponse() return response } func tracing(request : Tensorflow_TracingRequest, session : Tensorflow_Grpc_WorkerServiceTracingSession) throws -> Tensorflow_TracingResponse{ print("tracing") let response = Tensorflow_TracingResponse() return response } } class TestPredictionProvider:Tensorflow_Serving_PredictionServiceProvider{ func classify(request : Tensorflow_Serving_ClassificationRequest, session : Tensorflow_Serving_PredictionServiceClassifySession) throws -> Tensorflow_Serving_ClassificationResponse{ print("classify") let response = Tensorflow_Serving_ClassificationResponse() return response } func regress(request : Tensorflow_Serving_RegressionRequest, session : Tensorflow_Serving_PredictionServiceRegressSession) throws -> Tensorflow_Serving_RegressionResponse{ print("regress") let response = Tensorflow_Serving_RegressionResponse() return response } func predict(request : Tensorflow_Serving_PredictRequest, session : Tensorflow_Serving_PredictionServicePredictSession) throws -> Tensorflow_Serving_PredictResponse{ print("predict") let response = Tensorflow_Serving_PredictResponse() return response } func multiinference(request : Tensorflow_Serving_MultiInferenceRequest, session : Tensorflow_Serving_PredictionServiceMultiInferenceSession) throws -> Tensorflow_Serving_MultiInferenceResponse{ print("multiinference") let response = Tensorflow_Serving_MultiInferenceResponse() return response } func getmodelmetadata(request : Tensorflow_Serving_GetModelMetadataRequest, session : Tensorflow_Serving_PredictionServiceGetModelMetadataSession) throws -> Tensorflow_Serving_GetModelMetadataResponse{ print("getmodelmetadata") let response = Tensorflow_Serving_GetModelMetadataResponse() return response } } class TestEventListenerProvider:Tensorflow_EventListenerProvider{ func sendevents(session : Tensorflow_EventListenerSendEventsSession) throws{ print("sendevents") } }
mit
df9a0230494c961222d90a3afa43db7e
50.648352
205
0.753191
5.710814
false
false
false
false
OUCHUNYU/MockCoreMotion
MockCoreMotion/MockCMAltitudeData.swift
1
1205
// // MockCMAltitudeData.swift // MockCoreMotion // // Created by Chunyu Ou on 3/11/17. // Copyright © 2017 Chunyu Ou. All rights reserved. // import Foundation import CoreMotion open class MockCMAltitudeData: CMAltitudeData { // The change in altitude (in meters) since the last reported event. // We set default to 0 meannig we are at 0 meter private var _relativeAltitude: NSNumber = 0 // As Altitude set to 0 and assume air temperture around 10 - 20 degree C // the air pressure set to default 101325.00 private var _pressure: NSNumber = 101325.00 private var _timestamp: TimeInterval = Date().timeIntervalSinceReferenceDate open override var relativeAltitude: NSNumber { get { return _relativeAltitude } set { _relativeAltitude = newValue } } open override var pressure: NSNumber { get { return _pressure } set { _pressure = newValue } } open override var timestamp: TimeInterval { get { return _timestamp } set { _timestamp = newValue } } }
mit
37822fb1dbf4057a77248a2435f9b841
22.607843
80
0.593023
4.613027
false
false
false
false
mrdepth/EVEOnlineAPI
esicodegen/esicodegen/Scope.swift
1
2241
// // Scope.swift // ESI // // Created by Artem Shimanski on 12.04.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import Foundation class Scope: Namespace { let tag: String var operations = [Operation]() init(tag: String, parent: Namespace?) { self.tag = tag.camelCaps super.init(self.tag, parent: parent) } func typeDefinitions(isPublic: Bool) throws -> String { var definitions = [String: String]() for schema in namespaces[self] ?? [] { guard let s = schema.typeDefinition(isPublic: isPublic) else {continue} definitions[schema.typeName] = s } return definitions.values.joined(separator: "\n\n") } func scopeDefinition(isPublic: Bool) throws -> String { if tag.isEmpty { var s = "import Foundation\n" s += "import Alamofire\n" s += "import Futures\n\n" s += "public extension ESI {\n\n" s += try typeDefinitions(isPublic: isPublic) s += "\n\n" var template = try! String(contentsOf: securityURL) var scopes = [String]() var values = [String]() for (_, array) in security { for scope in array { values.append("static let \(scope.camelBack) = ESI.Scope(\"\(scope)\")") scopes.append(".\(scope.camelBack)") } } template = template.replacingOccurrences(of: "{values}", with: values.sorted().joined(separator: "\n")) template = template.replacingOccurrences(of: "{scopes}", with: scopes.sorted().joined(separator: ",\n")) /*s += "class func loadClassess() {\n" s += classLoaders.joined(separator: "\n") s += "\n}"*/ s += "\n}\n\n" s += template return s } else { var template = try! String(contentsOf: scopeURL) let variable = tag.camelBack var operations = [String]() for operation in self.operations { operations.append(operation.definition) } template = template.replacingOccurrences(of: "{classes}", with: try typeDefinitions(isPublic: true)) template = template.replacingOccurrences(of: "{variable}", with: variable) template = template.replacingOccurrences(of: "{scope}", with: tag) template = template.replacingOccurrences(of: "{operations}", with: operations.joined(separator: "\n")) return template } } }
mit
87de26ff20b0b3bb2ba7cf64e4fd9692
25.352941
107
0.645982
3.549921
false
false
false
false
Sage-Bionetworks/BridgeAppSDK
BridgeAppSDK/SBAConsentSharingStep.swift
1
6903
// // SBAConsentSharingStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit /** The consent sharing step is used to determine the sharing scope for consent. This allows the user to share their results *only* with the research team running the study or else more broadly with other researchers. */ open class SBAConsentSharingStep: ORKConsentSharingStep, SBALearnMoreActionStep { public var learnMoreAction: SBALearnMoreAction? open override func stepViewControllerClass() -> AnyClass { return SBAConsentSharingStepViewController.classForCoder() } public init(inputItem: SBASurveyItem) { let share = inputItem as? SBAConsentSharingOptions let investigatorShortDescription = share?.investigatorShortDescription let investigatorLongDescription = share?.investigatorLongDescription // Use placeholder values if the investigator is nil for either the short or long // description. This is because the super class will assert if these values are nil super.init(identifier: inputItem.identifier, investigatorShortDescription: investigatorShortDescription ?? "PLACEHOLDER", investigatorLongDescription: investigatorLongDescription ?? "PLACEHOLDER", localizedLearnMoreHTMLContent: "PLACEHOLDER") if investigatorLongDescription == nil { // If there is no long description then use the text from the input item self.text = inputItem.stepText } else if let additionalText = inputItem.stepText, let text = self.text { // Otherwise, append the text built by the super class self.text = String.localizedStringWithFormat("%@\n\n%@", text, additionalText) } // If the inputItem has custom values for the choices, use those if let form = inputItem as? SBAFormStepSurveyItem, let textChoices = form.items?.map({form.createTextChoice(from: $0)}) { self.answerFormat = ORKTextChoiceAnswerFormat(style: .singleChoice, textChoices: textChoices) } // Finally, setup the learn more. The learn more html from the parent is ignored if let learnMoreURLString = share?.localizedLearnMoreHTMLContent { self.learnMoreAction = SBAURLLearnMoreAction(identifier: learnMoreURLString) } } // MARK: NSCopy public override init(identifier: String) { super.init(identifier: identifier) } override open func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) guard let step = copy as? SBAConsentSharingStep else { return copy } step.learnMoreAction = self.learnMoreAction return step } // MARK: NSCoding required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder); self.learnMoreAction = aDecoder.decodeObject(forKey: #keyPath(learnMoreAction)) as? SBALearnMoreAction } override open func encode(with aCoder: NSCoder){ super.encode(with: aCoder) aCoder.encode(self.learnMoreAction, forKey: #keyPath(learnMoreAction)) } // MARK: Equality override open func isEqual(_ object: Any?) -> Bool { guard let object = object as? SBAInstructionStep else { return false } return super.isEqual(object) && SBAObjectEquality(self.learnMoreAction, object.learnMoreAction) } override open var hash: Int { return super.hash ^ SBAObjectHash(learnMoreAction) } } /** Allow developers to create their own step view controllers that do not inherit from `ORKQuestionStepViewController`. */ public protocol SBAConsentSharingStepController: SBAStepViewControllerProtocol, SBASharedInfoController { func goNext() } extension SBAConsentSharingStepController { public func updateSharingScope() { guard let sharingStep = self.step as? SBAConsentSharingStep else { assertionFailure("Step \(String(describing: self.step)) is not of the expected class (SBAConsentSharingStep).") return } // Set the user's sharing scope sharedUser.dataSharingScope = { guard let choice = self.result?.result(forIdentifier: sharingStep.identifier) as? ORKChoiceQuestionResult, let answer = choice.choiceAnswers?.first as? Bool else { return .none } return answer ? .all : .study }() goNext() } } open class SBAConsentSharingStepViewController: SBAGenericStepViewController, SBAConsentSharingStepController { lazy public var sharedAppDelegate: SBAAppInfoDelegate = { return UIApplication.shared.delegate as! SBAAppInfoDelegate }() // Override the default method for goForward and set the users sharing scope // Do not allow subclasses to override this method final public override func goForward() { self.updateSharingScope() } open func goNext() { // Then call super to go forward super.goForward() } }
bsd-3-clause
5b72904cccdbd3f984e56ba202c62846
39.840237
123
0.694002
5.392188
false
false
false
false
sachin004/firefox-ios
StorageTests/TestBrowserDB.swift
1
3145
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCTest import XCGLogger private let log = XCGLogger.defaultInstance() class TestBrowserDB: XCTestCase { let files = MockFiles() private func rm(path: String) { do { try files.remove(path) } catch { } } override func setUp() { super.setUp() rm("foo.db") rm("foo.db-shm") rm("foo.db-wal") rm("foo.db.bak.1") rm("foo.db.bak.1-shm") rm("foo.db.bak.1-wal") } class MockFailingTable: Table { var name: String { return "FAILURE" } var version: Int { return 1 } func exists(db: SQLiteDBConnection) -> Bool { return false } func drop(db: SQLiteDBConnection) -> Bool { return true } func create(db: SQLiteDBConnection) -> Bool { return false } func updateTable(db: SQLiteDBConnection, from: Int) -> Bool { return false } } func testMovesDB() { let db = BrowserDB(filename: "foo.db", files: self.files) XCTAssertTrue(db.createOrUpdate(BrowserTable())) db.run("CREATE TABLE foo (bar TEXT)").value // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // Grab a pointer to the -shm so we can compare later. let shmA = try! files.fileWrapper("foo.db-shm") let creationA = shmA.fileAttributes[NSFileCreationDate] as! NSDate let inodeA = (shmA.fileAttributes[NSFileSystemFileNumber] as! NSNumber).unsignedLongValue XCTAssertFalse(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) // It'll still fail, but it moved our old DB. // Our current observation is that closing the DB deletes the .shm file and also // checkpoints the WAL. XCTAssertFalse(db.createOrUpdate(MockFailingTable())) db.run("CREATE TABLE foo (bar TEXT)").value // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // But now it's been reopened, it's not the same -shm! let shmB = try! files.fileWrapper("foo.db-shm") let creationB = shmB.fileAttributes[NSFileCreationDate] as! NSDate let inodeB = (shmB.fileAttributes[NSFileSystemFileNumber] as! NSNumber).unsignedLongValue XCTAssertTrue(creationA.compare(creationB) != NSComparisonResult.OrderedDescending) XCTAssertNotEqual(inodeA, inodeB) XCTAssertTrue(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) } }
mpl-2.0
98b0ae33c165800ead73e56ae5047fa3
34.348315
97
0.624165
4.100391
false
false
false
false
Monnoroch/Cuckoo
Source/CuckooFunctions.swift
1
1529
// // CuckooFunctions.swift // Cuckoo // // Created by Tadeas Kriz on 13/01/16. // Copyright © 2016 Brightify. All rights reserved. // /// Starts the stubbing for the given mock. Can be used multiple times. public func stub<M: Mock>(_ mock: M, block: (M.Stubbing) -> Void) { block(mock.getStubbingProxy()) } /// Used in stubbing. Currently only returns passed function but this may change in the future so it is not recommended to omit it. public func when<F>(_ function: F) -> F { return function } /// Creates object used for verification of calls. public func verify<M: Mock>(_ mock: M, _ callMatcher: CallMatcher = times(1), file: StaticString = #file, line: UInt = #line) -> M.Verification { return mock.getVerificationProxy(callMatcher, sourceLocation: (file, line)) } /// Clears all invocations and stubs of mocks. public func reset<M: Mock>(_ mocks: M...) { mocks.forEach { mock in mock.manager.reset() } } /// Clears all stubs of mocks. public func clearStubs<M: Mock>(_ mocks: M...) { mocks.forEach { mock in mock.manager.clearStubs() } } /// Clears all invocations of mocks. public func clearInvocations<M: Mock>(_ mocks: M...) { mocks.forEach { mock in mock.manager.clearInvocations() } } /// Checks if there are no more uverified calls. public func verifyNoMoreInteractions<M: Mock>(_ mocks: M..., file: StaticString = #file, line: UInt = #line) { mocks.forEach { mock in mock.manager.verifyNoMoreInteractions((file, line)) } }
mit
bd4cd0bb35fe64f7121b2667622b38ab
29.56
145
0.670812
3.717762
false
false
false
false
scanf/semver-incrementer
Sources/TaskHelper.swift
1
646
import Foundation struct TaskHelper { let task: NSTask init(launchPath: String, args: [String]) { self.task = NSTask() self.task.launchPath = launchPath self.task.arguments = args } func performTask() -> NSString? { let pipe = NSPipe() task.standardOutput = pipe task.launch() task.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = NSString(data: data, encoding: NSUTF8StringEncoding) return output } func getReturn() -> Int32 { task.launch() task.waitUntilExit() return task.terminationStatus } }
apache-2.0
48f281dc1b422e955769c83f3bffcfdd
22.925926
71
0.634675
4.549296
false
false
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/Mosaic.swift
1
855
// // Mosaic.swift // Pods // // Created by Mohssen Fathi on 5/6/16. // // import UIKit struct MosaicUniforms: Uniforms { var intensity: Float = 0.5; } public class Mosaic: Filter { var uniforms = MosaicUniforms() @objc public var intensity: Float = 0.5 { didSet { clamp(&intensity, low: 0, high: 1) needsUpdate = true } } public init() { super.init(functionName: "mosaic") title = "Mosaic" properties = [Property(key: "intensity", title: "Intensity")] update() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func update() { if self.input == nil { return } uniforms.intensity = intensity * 50 updateUniforms(uniforms: uniforms) } }
mit
ba8bf59c3cf9429d558bba2689ea5a05
18.431818
69
0.555556
4.090909
false
false
false
false
3pillarlabs/ios-charts
Sources/Charts/model/GraphInputTable.swift
1
5691
// // GraphInputTable.swift // ChartsApp // // Created by Gil Eluard on 16/02/16. // Copyright © 2016 3PillarGlobal. All rights reserved. // import UIKit /// GraphInputTable plays the role of the data source for our graphs public class GraphInputTable: NSObject, GraphInputRowDelegate { /// Table name public var name = "" /// Array with all the column names public var columnNames: [String] = [] { didSet { delegate?.tableColumnsDidChange(table: self) } } /// Array with all the rows in our data source public var rows: [GraphInputRow] = [] { didSet { computeMinMax() computeMaxTotalPerColumn() delegate?.tableRowsDidChange(table: self) } } private(set) var min: Double = 0 private(set) var max: Double = 0 private(set) var total: Double = 0 private(set) var maxTotalPerColumn: Double = 0 /// Array with all the row names public var rowNames: [String] { return rows.map({$0.name}) } subscript(index: Int) -> (rowName: String, values:[CGFloat]) { let row = rows[index] return (row.name, row.values.map({CGFloat(($0 - min) / (max - min))})) } subscript(rowIndex: Int, columnIndex: Int) -> CGFloat { return CGFloat((rows[rowIndex].values[columnIndex] - min) / (max - min)) } weak var delegate: GraphInputTableDelegate? // MARK: - Business methods public convenience init(name: String) { self.init(name: name, columnNames:[]) } public init(name: String, columnNames:[String]) { super.init() self.name = name self.columnNames = columnNames computeMinMax() computeMaxTotalPerColumn() } /** Append a new column with the values specified in the rowValues array. - parameter columnName: add a custom name to the column - parameter rowValues: each array element is appended to its corresponding row by index */ public func addColumn(columnName: String, rowValues: [Double]) { guard rowValues.count == rows.count else { print("GraphInputTable[addColumn]: wrong number of values \(rowValues.count) (expected \(rows.count))") return } let delegate = self.delegate self.delegate = nil; for (index, row) in rows.enumerated() { row.values.append(rowValues[index]) } self.columnNames.append(columnName) computeMinMax() computeMaxTotalPerColumn() self.delegate = delegate delegate?.tableColumnsDidChange(table: self) } /** Remove a column at the specified index - parameter index: index of column that needs to be deleted */ public func removeColumnAtIndex(index: Int) { guard index < rows.count && index >= 0 else { print("GraphInputTable[removeColumn]: wrong index \(index) for an array of \(rows.count) elements") return } let delegate = self.delegate self.delegate = nil for (index, row) in rows.enumerated() { row.values.remove(at: index) } self.columnNames.remove(at: index) if (rows.count > 0) { computeMinMax() computeMaxTotalPerColumn() } else { min = 0 max = 0 maxTotalPerColumn = 0 } self.delegate = delegate delegate?.tableColumnsDidChange(table: self) } /** This will clean the entire data source */ public func removeAllColumns() { let delegate = self.delegate self.delegate = nil for row in rows { row.values.removeAll() } min = 0 max = 0 maxTotalPerColumn = 0 self.delegate = delegate self.columnNames.removeAll() } // MARK: - private methods private func computeMinMax() { var min: Double = .greatestFiniteMagnitude var max: Double = 0 var total: Double = 0 for row in rows { min = fmin(min, row.min) max = fmax(max, row.max) total += row.total } self.total = total self.min = min != .greatestFiniteMagnitude ? min : 0 self.max = max } private func computeMaxTotalPerColumn() { maxTotalPerColumn = 0 for (index, _) in columnNames.enumerated() { maxTotalPerColumn = fmax(maxTotalPerColumn, rows.reduce(0, {$0 + $1.values[index]})) } } func percentOfRowAtIndex(index: Int) -> CGFloat { let row = rows[index] return CGFloat(row.total/total) } func percentOfColumn(columnIndex: Int, rowIndex: Int) -> CGFloat { let value = rows[rowIndex].values[columnIndex] return CGFloat(value / total) } func normalizedValuesForColumn(index: Int) -> [CGFloat] { return (rows.map({ normalize(value: $0.values[index]) })) } func normalize(value: Double) -> CGFloat { return CGFloat(maxTotalPerColumn != 0 ? value / maxTotalPerColumn : 0) } // MARK: - GraphInputRowDelegate func rowValuesDidChange(row: GraphInputRow) { delegate?.tableValuesDidChange(table: self) } func rowTintColorDidChange(row: GraphInputRow) { if let index = rows.index(of: row) { delegate?.tableRowTintColorDidChange(table: self, rowIndex: index) } } }
mit
a9fdecfa06d32caf3b2d91b57ffce124
27.45
115
0.572408
4.694719
false
false
false
false
SuEric/SITV
SITV/AGSMapViewController.swift
1
15827
// // AGSMapViewController.swift // SITV // // Created by Eric García on 04/08/15. // Copyright (c) 2015 Eric García. All rights reserved. // import UIKit import ArcGIS import GoogleMaps class AGSMapViewController: AGSMapView, AGSMapViewLayerDelegate, AGSLocatorDelegate, AGSCalloutDelegate, AGSRouteTaskDelegate, UITableViewDataSource, UITableViewDelegate { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ var queue:NSOperationQueue! // Ejecuta el servicio web en background var access_token: NSString! // Access_token a obtener de la aplicación ArcGIS var showAllResults : Bool = true var firstGraphic : Bool = true var whichTable : Int! // OUTLETS DEL UIVIEW @IBOutlet weak var directionsLabel: UILabel! @IBOutlet weak var prevBtn: UIBarButtonItem! @IBOutlet weak var nextBtn: UIBarButtonItem! @IBOutlet weak var routeButton: UIButton! @IBOutlet weak var clearRouteButton: UIButton! @IBOutlet weak var originSearchBar: UISearchBar! @IBOutlet weak var destinationSearchBar: UISearchBar! @IBOutlet weak var originTableView: UITableView! @IBOutlet weak var destinationTableView: UITableView! // GOOGLE MAPS var lugares = [Int: [String]]() var lookupAddressResults: Dictionary<NSObject, AnyObject>! // origen var fetchedFormattedAddress: String! // origen var fetchedAddressLongitude: Double! // origen var fetchedAddressLatitude: Double! // origen var originCoordinate : CLLocationCoordinate2D! var destinationLookupAddressResults: Dictionary<NSObject, AnyObject>! // destino var destinationFetchedFormattedAddress: String! // destino var destinationFetchedAddressLongitude: Double! // destino var destinationFetchedAddressLatitude: Double! // destino var destinationCoordinate : CLLocationCoordinate2D! // ARCGIS var graphicLayer: AGSGraphicsLayer! // Layer de todos los gráficos // Elementos de rutas var routeTask: AGSRouteTask! var routeResult: AGSRouteResult! var currentDirectionGraphic: AGSDirectionGraphic! func placeAutocomplete(text: String, whichBar: Int) { let filter = GMSAutocompleteFilter() let topLeftCorner = CLLocationCoordinate2D(latitude: 18.490028574, longitude: -99.140625) let bottomRightCorner = CLLocationCoordinate2D(latitude: 20.0868885056, longitude: -97.0751953125) let bounds = GMSCoordinateBounds(coordinate: topLeftCorner, coordinate: bottomRightCorner) filter.type = GMSPlacesAutocompleteTypeFilter.NoFilter let placesClient = GMSPlacesClient() if !text.isEmpty { placesClient.autocompleteQuery(text, bounds: bounds, filter: filter, callback: { (results, error: NSError?) -> Void in if let error = error { print("Autocomplete error \(error)") } self.lugares = [Int: [String]]() var index = 0 for result in results! { if let result = result as? GMSAutocompletePrediction { self.lugares[index++] = [result.placeID, result.attributedFullText.string] } } if whichBar == 1 { self.destinationTableView.hidden = true; self.originTableView.hidden = false; self.originTableView.reloadData() } else { self.originTableView.hidden = true; self.destinationTableView.hidden = false; self.destinationTableView.reloadData() } }) } } // Al cargar el mapa func mapViewDidLoad(mapView: AGSMapView!) { mapView.locationDisplay.startDataSource() // Muestra ubicación actual } // Ejecución del web service func getAccessToken() { // Configuración del mensaje POST let url = NSURL(string: "https://www.arcgis.com/sharing/rest/oauth2/token/") let params = [ "client_id": "Bw3KiMdULPvUEStB", "client_secret": "742dbc21626b40b49b6425f136454b6a", "grant_type": "client_credentials" ] let jsonOp = AGSJSONRequestOperation(URL: url, queryParameters: params) jsonOp.target = self; jsonOp.action = "operation:didSucceedWithResponse:" jsonOp.errorAction = "operation:didFailWithError:" // Ejecuta en background queue = NSOperationQueue() self.queue.addOperation(jsonOp) } // Exito del web service func operation(op:NSOperation, didSucceedWithResponse json:NSDictionary) { access_token = json["access_token"] as! NSString // Obtiene el token del JSON print("Got token: \(access_token)") // Muestra el access_token self.queue.cancelAllOperations() // Deja de ejecutarla en background } // Error del web service func operation(op:NSOperation, didFailWithError error:NSError) { print("Error at web service: \(error)") self.queue.cancelAllOperations() // Deja de ejecutarla en background } // Función inicial func startFunc() { // Si no hay un layer if self.graphicLayer == nil { self.graphicLayer = AGSGraphicsLayer() // Layer que tendrá los resultados de geolocalización addMapLayer(self.graphicLayer, withName:"Results") // Agrega el layer // Crea un MarkerSymbol let pushpin = AGSPictureMarkerSymbol(imageNamed: "BluePushpin.png") pushpin.offset = CGPointMake(9, 16) pushpin.leaderPoint = CGPointMake(-9, 11) let renderer = AGSSimpleRenderer(symbol: pushpin) // Renderer con el marker self.graphicLayer.renderer = renderer // Asigna el renderer al layer } } // Consigue los Details de un Place (Google) func getPlaceDetails(placeID: String) { let placesClient = GMSPlacesClient() placesClient.lookUpPlaceID(placeID, callback: { (place: GMSPlace?, error: NSError?) -> Void in if let error = error { print("lookup place id query error: \(error.localizedDescription)") return } if let place = place { if self.whichTable == 1 { self.originCoordinate = place.coordinate } else { self.destinationCoordinate = place.coordinate } if self.originCoordinate != nil && self.destinationCoordinate != nil { self.startFunc(); self.routeButton.enabled = true } } else { UIAlertView(title: "Error", message: "No se pudo encontrar el lugar", delegate: nil, cancelButtonTitle: "OK").show() } }) } // Muestra la dirección i-esima func displayDirectionForIndex(index:Int) { self.graphicLayer.removeGraphic(self.currentDirectionGraphic) // Quitar la dirección anterior let directions = self.routeResult.directions as AGSDirectionSet // Obtener la dirección self.currentDirectionGraphic = directions.graphics[index] as! AGSDirectionGraphic // Asignar la dirección // Resaltar la dirección con otro symbol let cs = AGSCompositeSymbol() let sls1 = AGSSimpleLineSymbol() sls1.color = UIColor.whiteColor() sls1.style = .Solid sls1.width = 8 cs.addSymbol(sls1) let sls2 = AGSSimpleLineSymbol() sls2.color = UIColor.redColor() sls2.style = .Dash sls2.width = 4 cs.addSymbol(sls2) self.currentDirectionGraphic.symbol = cs self.graphicLayer.addGraphic(self.currentDirectionGraphic) self.directionsLabel.text = self.currentDirectionGraphic.text // Texto con dirección al label // Zoom a la dirección actual (1.3 de zoom) let env = self.currentDirectionGraphic.geometry.envelope.mutableCopy() as! AGSMutableEnvelope env.expandByFactor(1.3) self.zoomToEnvelope(env, animated: true) // Ver si se deshabilitar los botones if index >= self.routeResult.directions.graphics.count - 1 { self.nextBtn.enabled = false } else { self.nextBtn.enabled = true } if index > 0 { self.prevBtn.enabled = true } else { self.prevBtn.enabled = false } } // Traza ruta dado un destino func routeTo() { let params = AGSRouteTaskParameters() // Parametros del RouteTask // Ambos puntos se obtienen como Stops, y debe cambiarse // su sistema de latitud/longitud por el wgs84SpatialReference // Segundo punto let first_point = AGSPoint(x: originCoordinate.longitude, y: originCoordinate.latitude, spatialReference: AGSSpatialReference.wgs84SpatialReference()) // Primer punto let second_point = AGSPoint(x: destinationCoordinate.longitude, y: destinationCoordinate.latitude, spatialReference: AGSSpatialReference.wgs84SpatialReference()) // Si no hay un routeTask if self.routeTask == nil { let serviceURL = "http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World/solve?token=\(self.access_token)&stops=\(first_point.x),\(first_point.y);\(second_point.x),\(second_point.y)&directionsLanguage=es&f=json" print(serviceURL) self.routeTask = AGSRouteTask(URL: NSURL(string: serviceURL)) // RouteTask con el servicio self.routeTask.delegate = self // Delegate del routeTask } // Regresar toda la ruta params.returnRouteGraphics = true // Regresar direcciones de vueltas params.returnDirections = true // Evitar ordenamiento de stops params.findBestSequence = false params.preserveFirstStop = true params.preserveLastStop = true // ensure the graphics are returned in our maps spatial reference params.outSpatialReference = self.spatialReference params.ignoreInvalidLocations = false // Ignorar stops inválidos self.routeTask.solveWithParameters(params) // Ejecutar el servicio } // Ejecución correcta del routeTask func routeTask(routeTask: AGSRouteTask!, operation op: NSOperation!, didSolveWithResult routeTaskResult: AGSRouteTaskResult!) { self.directionsLabel.text = "Ruta calculada" // Texto del label self.routeButton.enabled = false self.clearRouteButton.enabled = true // Remover la ruta trazada, si hay una if self.routeResult != nil { self.graphicLayer.removeGraphic(self.routeResult.routeGraphic) } // Si hay resultados de rutas if routeTaskResult.routeResults != nil { // Se sabe que solo hay 1 ruta self.routeResult = routeTaskResult.routeResults[0] as? AGSRouteResult // Obtiene ruta [0] // Si no se ha trazado la ruta if self.routeResult != nil && self.routeResult.routeGraphic != nil { // Se mostrará la ruta con la línea siguiente let yellowLine = AGSSimpleLineSymbol(color: UIColor.orangeColor(), width: 8.0) self.routeResult.routeGraphic.symbol = yellowLine // Se agrega el graphic al layer self.graphicLayer.addGraphic(self.routeResult.routeGraphic) self.nextBtn.enabled = true // Enable del botón next para pasar las direcciones self.prevBtn.enabled = false self.currentDirectionGraphic = nil self.zoomToGeometry(self.routeResult.routeGraphic.geometry, withPadding: 100, animated: true) } } // No hubo rutas else { UIAlertView(title: "Sin rutas", message: "No se encontraron rutas", delegate: nil, cancelButtonTitle: "OK").show() } } // TableView DataSource and Delegate func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "autocompleteCell"; var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier) } cell?.textLabel?.text = lugares[indexPath.row]![1] return cell!; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lugares.count; } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let placeID = lugares[indexPath.row]![0]; if tableView == originTableView { whichTable = 1 self.originSearchBar.text = lugares[indexPath.row]![1] self.originSearchBar.resignFirstResponder() self.originTableView.hidden = true } else { whichTable = 2 self.destinationSearchBar.text = lugares[indexPath.row]![1] self.destinationSearchBar.resignFirstResponder() self.destinationTableView.hidden = true } self.getPlaceDetails(placeID) } // Botón consultar ruta @IBAction func routeButtonClicked(sender: AnyObject) { if originSearchBar.text == "" || destinationSearchBar.text == "" { UIAlertView(title: "Faltan campos", message: "Ingrese un origen y destino", delegate: nil, cancelButtonTitle: "OK").show() } else { self.graphicLayer.removeAllGraphics() self.routeTask = nil self.routeTo() // Trazar ruta, se pasa el AGSGeometry } } @IBAction func clearRouteButtonClicked(sender: AnyObject) { self.originSearchBar.text = "" self.destinationSearchBar.text = "" self.originCoordinate = nil self.destinationCoordinate = nil self.graphicLayer.removeAllGraphics() self.routeTask = nil self.clearRouteButton.enabled = false } // Botón prev @IBAction func prevBtnClicked(sender: AnyObject) { var index = 0 if self.currentDirectionGraphic != nil { if let currentIndex = (self.routeResult.directions.graphics as! [AGSDirectionGraphic]).indexOf(self.currentDirectionGraphic) { index = currentIndex - 1 } } self.displayDirectionForIndex(index) } // Botón next @IBAction func nextBtnClicked(sender: AnyObject) { var index = 0 if self.currentDirectionGraphic != nil { if let currentIndex = (self.routeResult.directions.graphics as! [AGSDirectionGraphic]).indexOf(self.currentDirectionGraphic) { index = currentIndex + 1 } } self.displayDirectionForIndex(index) } }
gpl-3.0
cfdec6097bcd0fb5e2ffd8d05e9af5ae
38.017284
246
0.614796
5.034087
false
false
false
false
renzifeng/ZFZhiHuDaily
ZFZhiHuDaily/Home/View/ZFHomeCell.swift
1
1289
// // ZFHomeCell.swift // ZFZhiHuDaily // // Created by 任子丰 on 16/1/7. // Copyright © 2016年 任子丰. All rights reserved. // import UIKit import Kingfisher class ZFHomeCell: UITableViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var rightImageView: UIImageView! @IBOutlet weak var imageWidthConstraint: NSLayoutConstraint! @IBOutlet weak var moreImageView: UIImageView! var news : ZFStories! { willSet { self.news = newValue } didSet { titleLabel.text = news.title rightImageView.kf_setImageWithURL(NSURL(string: news.images![0])!, placeholderImage: UIImage(named: "Image_Preview")) if news.multipic { moreImageView.hidden = false }else { moreImageView.hidden = true } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code dk_backgroundColorPicker = CELL_COLOR titleLabel.dk_textColorPicker = CELL_TITLE selectionStyle = .None } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
340c128f22da3a9fcf73995fce55d53d
25.541667
129
0.622449
4.649635
false
false
false
false
XQS6LB3A/LyricsX
LyricsX/Utility/CFExtension.swift
2
2298
// // CFExtension.swift // LyricsX - https://github.com/ddddxxx/LyricsX // // 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 https://mozilla.org/MPL/2.0/. // import Foundation import SwiftCF // MARK: - CFStringTokenizer extension NSString { var dominantLanguage: String? { return CFStringTokenizer.bestLanguage(for: .from(self))?.asSwift() } } extension CFStringTokenizer { func currentFuriganaAnnotation(in string: NSString) -> (NSString, NSRange)? { let range = currentTokenRange() let tokenStr = string.substring(with: range.asNS) guard tokenStr.unicodeScalars.contains(where: CharacterSet.kanji.contains), let latin = currentTokenAttribute(.latinTranscription)?.asNS(), let hiragana = latin.applyingTransform(.latinToHiragana, reverse: false), let (rangeToAnnotate, rangeInAnnotation) = rangeOfUncommonContent(tokenStr, hiragana) else { return nil } let annotation = String(hiragana[rangeInAnnotation]) as NSString var nsrangeToAnnotate = NSRange(rangeToAnnotate, in: tokenStr) nsrangeToAnnotate.location += range.location return (annotation, nsrangeToAnnotate) } } private func rangeOfUncommonContent(_ s1: String, _ s2: String) -> (Range<String.Index>, Range<String.Index>)? { guard s1 != s2, !s1.isEmpty, !s2.isEmpty else { return nil } var (l1, l2) = (s1.startIndex, s2.startIndex) while s1[l1] == s2[l2] { guard let nl1 = s1.index(l1, offsetBy: 1, limitedBy: s1.endIndex), let nl2 = s2.index(l2, offsetBy: 1, limitedBy: s2.endIndex) else { break } (l1, l2) = (nl1, nl2) } var (r1, r2) = (s1.endIndex, s2.endIndex) repeat { guard let nr1 = s1.index(r1, offsetBy: -1, limitedBy: s1.startIndex), let nr2 = s2.index(r2, offsetBy: -1, limitedBy: s2.startIndex) else { break } (r1, r2) = (nr1, nr2) } while s1[r1] == s2[r2] let range1 = (l1...r1).relative(to: s1.indices) let range2 = (l2...r2).relative(to: s2.indices) return (range1, range2) }
gpl-3.0
5d040cfa368e538c1043657261e84166
34.353846
112
0.630113
3.562791
false
false
false
false
filmhomage/swift_tutorial
swift_tutorial/Util/SWAlert.swift
1
6011
// // SWAlert.swift // swift_tutorial // // Created by JonghyunKim on 5/24/16. // Copyright © 2016 kokaru.com. All rights reserved. // import Foundation import UIKit class SWAlert : NSObject { static let sharedInstance = SWAlert() override init() { print("SWAlert init!") } func showOkAlert(title: String = "title", message: String = "message") { let alertController :UIAlertController = UIAlertController(title:title, message:message, preferredStyle: UIAlertControllerStyle.Alert) let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .Cancel, handler:{(action:UIAlertAction!) -> Void in }) alertController.addAction(okAction) UIApplication.topViewController()!.presentViewController(alertController, animated: true) { print("UIAlertController presentation!") } } func showOKCancelAlert(title: String = "title", message: String = "message", completion: (cancel: Bool) -> Void) { let alertController :UIAlertController = UIAlertController(title:title, message:message, preferredStyle: UIAlertControllerStyle.Alert) let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .Default, handler:{ (action:UIAlertAction!) -> Void in completion(cancel: false) }) let cancelAction: UIAlertAction = UIAlertAction(title: "cancel", style: .Cancel, handler:{(action:UIAlertAction!) -> Void in completion(cancel:true) }) alertController.addAction(okAction) alertController.addAction(cancelAction) UIApplication.topViewController()!.presentViewController(alertController, animated: true) { print("UIAlertController presentation!") } } func showChooseAlert(title: String = "title", message: String = "message", buttonTitleArray:[String?] = ["one", "two"], completion: (completion: String) -> Void) { let alertController :UIAlertController = UIAlertController(title:title, message:message, preferredStyle: UIAlertControllerStyle.Alert) for buttonTitle in buttonTitleArray { if buttonTitle != nil { let action = UIAlertAction(title: buttonTitle, style: .Default, handler:{(action:UIAlertAction!) -> Void in completion(completion: buttonTitle!) }) alertController.addAction(action) } } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler:{ (action:UIAlertAction!) -> Void in completion(completion: "Cancel") }) alertController.addAction(cancelAction) UIApplication.topViewController()!.presentViewController(alertController, animated: true) { print("UIAlertController presentation!") } } func showLoginAlert(title: String = "title", message: String = "message", completion:(completion: String) -> Void) { let alertController :UIAlertController = UIAlertController(title:title, message:message, preferredStyle: UIAlertControllerStyle.Alert) let loginAction = UIAlertAction(title: "Login", style: .Default) { (_) in let loginTextField = alertController.textFields![0] as UITextField let passwordTextField = alertController.textFields![1] as UITextField print("id : \(loginTextField.text) password : \(passwordTextField.text)") // login(loginTextField.text, passwordTextField.text) } loginAction.enabled = false let forgotPasswordAction = UIAlertAction(title: "Forgot Password", style: .Destructive) { (_) in } let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in } alertController.addTextFieldWithConfigurationHandler { (textField) in textField.placeholder = "Login" NSNotificationCenter.defaultCenter().addObserverForName(UITextFieldTextDidChangeNotification, object: textField, queue: NSOperationQueue.mainQueue()) { (notification) in loginAction.enabled = textField.text != "" } } alertController.addTextFieldWithConfigurationHandler { (textField) in textField.placeholder = "Password" textField.secureTextEntry = true } alertController.addAction(loginAction) alertController.addAction(forgotPasswordAction) alertController.addAction(cancelAction) UIApplication.topViewController()!.presentViewController(alertController, animated: true) { print("UIAlertController presentation!") } } }
mit
c8955a2dc99fef102d207cfba9722a34
44.530303
181
0.515141
6.900115
false
false
false
false
emilstahl/swift
test/SILGen/function_conversion_objc.swift
12
5780
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -verify | FileCheck %s import Foundation // REQUIRES: objc_interop // ==== Metatype to object conversions // CHECK-LABEL: sil hidden @_TF24function_conversion_objc20convMetatypeToObjectFFCSo8NSObjectMS0_T_ func convMetatypeToObject(f: NSObject -> NSObject.Type) { // CHECK: function_ref @_TTRXFo_oCSo8NSObject_dXMTS__XFo_oS__oPs9AnyObject__ // CHECK: partial_apply let _: NSObject -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oCSo8NSObject_dXMTS__XFo_oS__oPs9AnyObject__ : $@convention(thin) (@owned NSObject, @owned @callee_owned (@owned NSObject) -> @thick NSObject.Type) -> @owned AnyObject { // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSObject.Type to $@objc_metatype NSObject.Type // CHECK: objc_metatype_to_object {{.*}} : $@objc_metatype NSObject.Type to $AnyObject // CHECK: return @objc protocol NSBurrito {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc31convExistentialMetatypeToObjectFFPS_9NSBurrito_PMPS0__T_ func convExistentialMetatypeToObject(f: NSBurrito -> NSBurrito.Type) { // CHECK: function_ref @_TTRXFo_oP24function_conversion_objc9NSBurrito__dXPMTPS0___XFo_oPS0___oPs9AnyObject__ // CHECK: partial_apply let _: NSBurrito -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oP24function_conversion_objc9NSBurrito__dXPMTPS0___XFo_oPS0___oPs9AnyObject__ : $@convention(thin) (@owned NSBurrito, @owned @callee_owned (@owned NSBurrito) -> @thick NSBurrito.Type) -> @owned AnyObject // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSBurrito.Type to $@objc_metatype NSBurrito.Type // CHECK: objc_existential_metatype_to_object {{.*}} : $@objc_metatype NSBurrito.Type to $AnyObject // CHECK: return // CHECK-LABEL: sil hidden @_TF24function_conversion_objc28convProtocolMetatypeToObjectFFT_MPS_9NSBurrito_T_ func convProtocolMetatypeToObject(f: () -> NSBurrito.Protocol) { // CHECK: function_ref @_TTRXFo__dXMtP24function_conversion_objc9NSBurrito__XFo__oCSo8Protocol_ // CHECK: partial_apply let _: () -> Protocol = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dXMtP24function_conversion_objc9NSBurrito__XFo__oCSo8Protocol_ : $@convention(thin) (@owned @callee_owned () -> @thin NSBurrito.Protocol) -> @owned Protocol // CHECK: apply %0() : $@callee_owned () -> @thin NSBurrito.Protocol // CHECK: objc_protocol #NSBurrito : $Protocol // CHECK: strong_retain // CHECK: return // ==== Representation conversions // CHECK-LABEL: sil hidden @_TF24function_conversion_objc11funcToBlockFFT_T_bT_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @convention(block) () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> () // CHECK: return [[COPY]] func funcToBlock(x: () -> ()) -> @convention(block) () -> () { return x } // CHECK-LABEL: sil hidden @_TF24function_conversion_objc11blockToFuncFbT_T_FT_T_ : $@convention(thin) (@owned @convention(block) () -> ()) -> @owned @callee_owned () -> () // CHECK: [[COPIED:%.*]] = copy_block %0 // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFdCb__dT__XFo__dT__ // CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]]([[COPIED]]) // CHECK: return [[FUNC]] func blockToFunc(x: @convention(block) () -> ()) -> () -> () { return x } // ==== Representation change + function type conversion // CHECK-LABEL: sil hidden @_TF24function_conversion_objc22blockToFuncExistentialFbT_SiFT_P_ : $@convention(thin) (@owned @convention(block) () -> Int) -> @owned @callee_owned (@out protocol<>) -> () // CHECK: function_ref @_TTRXFdCb__dSi_XFo__dSi_ // CHECK: partial_apply // CHECK: function_ref @_TTRXFo__dSi_XFo__iP__ // CHECK: partial_apply // CHECK: return func blockToFuncExistential(x: @convention(block) () -> Int) -> () -> Any { return x } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb__dSi_XFo__dSi_ : $@convention(thin) (@owned @convention(block) () -> Int) -> Int // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSi_XFo__iP__ : $@convention(thin) (@out protocol<>, @owned @callee_owned () -> Int) -> () // C function pointer conversions class A : NSObject {} class B : A {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc18cFuncPtrConversionFcCS_1AT_cCS_1BT_ func cFuncPtrConversion(x: @convention(c) A -> ()) -> @convention(c) B -> () { // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return x } func cFuncPtr(a: A) {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc19cFuncDeclConversionFT_cCS_1BT_ func cFuncDeclConversion() -> @convention(c) B -> () { // CHECK: function_ref @_TToF24function_conversion_objc8cFuncPtrFCS_1AT_ : $@convention(c) (A) -> () // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return cFuncPtr } func cFuncPtrConversionUnsupported(x: @convention(c) (@convention(block) () -> ()) -> ()) -> @convention(c) (@convention(c) () -> ()) -> () { return x // expected-error{{C function pointer signature '@convention(c) (@convention(block) () -> ()) -> ()' is not compatible with expected type '@convention(c) (@convention(c) () -> ()) -> ()'}} }
apache-2.0
ebe57a743bc353f30f49a981f0ed7953
51.072072
275
0.646713
3.509411
false
false
false
false
BelledonneCommunications/linphone-iphone
UITests/Methods/IncomingOutgoingCallViewUITestsMethods.swift
1
5942
import XCTest import linphonesw class IncomingOutgoingCallViewUITestsMethods { let app = XCUIApplication() let manager = UITestsCoreManager.instance let appAccountAuthInfo: AuthInfo = UITestsCoreManager.instance.appAccountAuthInfo! let ghostAccount: UITestsRegisteredLinphoneCore = UITestsCoreManager.instance.ghostAccounts[0] func startIncomingCall() { XCTContext.runActivity(named: "Start Incoming Call") { _ in if (ghostAccount.callState != .Released) {ghostAccount.terminateCall()} app.representationWithElements.makeBackup(named: "call_end") ghostAccount.startCall(adress: manager.createAdress(authInfo: appAccountAuthInfo)) ghostAccount.waitForCallState(callState: .OutgoingRinging, timeout: 5) _ = app.callView.waitForExistence(timeout: 5) checkCallTime(element: app.callView.staticTexts["IO_call_view_duration"]) app.callView.images["IO_call_view_spinner"].representation.isAnimated(timeInterval: 0.5) //app.callView.representation.reMake() //app.statusBar.representation.withVariations(named: ["call_view"]).reMake() app.representationWithElements.mainView = app.callView app.representationWithElements.withElementVariations(mainView: [], statusBar: ["call_view"], tabBar: []).check() } } func startOutgoingCall() { XCTContext.runActivity(named: "Start Outgoing Call") { _ in if (ghostAccount.callState != .Released) {ghostAccount.terminateCall()} if (!app.dialerView.exists) { app.launch()} app.representationWithElements.makeBackup(named: "call_end") app.dialerView.textFields["adress_field"].fillTextField(ghostAccount.mAuthInfo.username) checkCallTime(element: app.callView.staticTexts["IO_call_view_duration"]) //app.callView.representation.withVariations(named: ["outgoing"]).reMake() //app.statusBar.representation.withVariations(named: ["call_view"]).reMake() app.representationWithElements.mainView = app.callView app.representationWithElements.withElementVariations(mainView: ["outgoing"], statusBar: ["call_view"], tabBar: []).check() ghostAccount.waitForCallState(callState: .IncomingReceived, timeout: 5) } } func endCall() { XCTContext.runActivity(named: "End Call (from remote)") { _ in if (ghostAccount.callState == .Released) {return} ghostAccount.terminateCall() ghostAccount.waitForCallState(callState: .Released, timeout: 5) app.representationWithElements.reloadBackup(named: "call_end").check() } } //expected format : "mm:ss" func checkCallTime(element: XCUIElement) { XCTContext.runActivity(named: "Check call time increment") { _ in let timerArray: [Int] = (0..<3).map{_ in sleep(1) return Int(element.label.split(separator: ":").last ?? "") ?? 0 } XCTAssert(Set(timerArray).count >= 2, "Call Time is not correctly incremented, less than 2 differents values are displayed in 3 seconds") XCTAssert(timerArray == timerArray.sorted(), "Call Time is not correctly incremented, it is not increasing") XCTAssert(timerArray.first! <= 3, "Call Time is not correctly initialized, it is more than 3 right after the start (found: \(timerArray.first!))") } } func toggleCallControls(buttonTag: String, parentView: XCUIElement) { XCTContext.runActivity(named: "Toggle call control Button : \"\(buttonTag)\"") { _ in app.representationWithElements.makeBackup(named: buttonTag) parentView.buttons["call_control_view_\(buttonTag)"].tap() app.representationWithElements.updateElementVariations(mainView: [buttonTag], statusBar: [], tabBar: []).check() parentView.buttons["call_control_view_\(buttonTag)"].tap() app.representationWithElements.reloadBackup(named: buttonTag).check() } } func noAnswerIncomingCall() { XCTContext.runActivity(named: "Let Incoming Call Ring Until Stop") { _ in XCTAssert(app.callView.waitForExistence(timeout: 5), "call already abort after less than 10 seconds ringing") XCTAssert(app.callView.waitForNonExistence(timeout: 30), "call still not abort after 30 seconds ringing") ghostAccount.waitForCallState(callState: .Released, timeout: 5) app.representationWithElements.reloadBackup(named: "call_end").check() } } func noAnswerOutgoingCall() { XCTContext.runActivity(named: "Check Outgoing Call Failed Popup Integrity And Close") { context in XCTAssert(app.callView.waitForExistence(timeout: 5), "call already abort after less than 10 seconds ringing") XCTAssert(app.callView.waitForNonExistence(timeout: 30), "call still not abort after 30 seconds ringing") ghostAccount.waitForCallState(callState: .Released, timeout: 5) app.callFailedView.representation.check() app.callFailedView.buttons["call_failed_error_view_action"].tap() app.representationWithElements.reloadBackup(named: "call_end").check() } } func cancelOutgoingCall() { XCTContext.runActivity(named: "Cancel Outgoing Call") { _ in app.callView.buttons["O_call_view_cancel"].tap() app.representationWithElements.reloadBackup(named: "call_end").check() ghostAccount.waitForCallState(callState: .Released, timeout: 5) } } func declineIncomingCall() { XCTContext.runActivity(named: "Decline Incoming Call") { _ in app.callView.buttons["I_call_view_decline"].tap() app.representationWithElements.reloadBackup(named: "call_end").check() ghostAccount.waitForCallState(callState: .Released, timeout: 5) } } func acceptIncomingCall() { XCTContext.runActivity(named: "Accept Incoming Call") { _ in app.callView.buttons["I_call_view_accept"].tap() checkCallTime(element: app.activeCallView.staticTexts["active_call_upper_section_duration"]) app.representationWithElements.mainView = app.activeCallView //app.activeCallView.representation.reMake() app.representationWithElements.check() ghostAccount.waitForCallState(callState: .StreamsRunning, timeout: 5) } } }
gpl-3.0
ec1b5789d34269ca38fedaa2f487c5ce
43.676692
150
0.739482
4.08947
false
false
false
false
katsumeshi/PhotoInfo
PhotoInfoTests/PhotoSpec.swift
1
5601
// // PhotoSpec.swift // photoinfo // // Created by Yuki Matsushita on 11/9/15. // Copyright © 2015 Yuki Matsushita. All rights reserved. // @testable import photoinfo import Quick import Nimble import Photos import ReactiveCocoa class PhotoSpec: QuickSpec { override func setUp() { continueAfterFailure = false } override func spec() { var photo:Photo! describe("Photo") { describe("Location") { context("is Nil") { beforeEach { class LocationNilMock : PHAsset { override var location: CLLocation? { return nil } } photo = Photo(LocationNilMock()) } it ("should be Nil") { expect(photo.location).to(beNil()) } it ("should have location error") { photo.place.startWithFailed { let code = LoadAssetError.Location.toError().code expect($0.code).to(equal(code)) } } } } describe("creationDate is Nil") { var photo:Photo! beforeEach { class DateNilMock : PHAsset { override var creationDate: NSDate? { return nil } } photo = Photo(DateNilMock()) } it ("should be equal timeIntervalSince1970: 0") { expect(photo.createdDate.timeIntervalSince1970) .to(equal(NSDate(timeIntervalSince1970: 0).timeIntervalSince1970)) } } describe("Image") { context("is empty asset") { var photo:Photo! beforeEach { let assetMock = PHAsset() photo = Photo(assetMock) } it ("should not be nil") { photo.image.startWithFailed { let code = LoadAssetError.Image.toError().code expect($0.code).to(equal(code)) } } } context("fetch first asset") { var photo:Photo! beforeEach { let assetMock = PHAsset.fetchAssetsWithMediaType(.Image, options: nil) .firstObject as! PHAsset photo = Photo(assetMock) } it ("should not be nil") { photo.image.startWithNext { expect($0).notTo(beNil()) } } } } describe("place") { let photos = PhotoLoader().photos context("geo tag is included") { it("should not be empty") { let expectation = self.expectationWithDescription("place fetch method") let locatedPhoto = photos.filter { $0.hasLocation }.first! locatedPhoto.place.startWithNext { expect($0.address).notTo(beEmpty()) expect($0.postalCode).notTo(beEmpty()) expectation.fulfill() } self.waitForExpectationsWithTimeout(10) { if let error = $0 { XCTFail(error.description) } } } } context("geo tag is not included") { it("should be faild with having error") { let expectation = self.expectationWithDescription("place fetch method") let notLocatedPhoto = photos.filter { !$0.hasLocation }.first! notLocatedPhoto.place.startWithFailed { expect($0).to(beAKindOf(NSError)) expectation.fulfill() } self.waitForExpectationsWithTimeout(1.0, handler: { if let error = $0 { XCTFail(error.description) } }) } } } describe("Property") { context("proper asset") { it("should not be empty") { let photo = PhotoLoader().photos.first! let expectation = self.expectationWithDescription("property fetch method") photo.property.startWithNext { expect($0).notTo(beEmpty()) expectation.fulfill() } self.waitForExpectationsWithTimeout(1.0, handler: { if let error = $0 { XCTFail(error.description) } }) } } } describe("Geo tag") { let photos = PhotoLoader().photos context("is nil having error") { let locatedPhoto = photos.filter { !$0.hasLocation }.first! locatedPhoto.requestAnnotation().startWithFailed { expect($0).to(beAKindOf(NSError)) } } context("is not nil") { let notLocatedPhoto:Photo = photos.filter { $0.hasLocation }.last! let expectation = self.expectationWithDescription("requestAnnotation Method") notLocatedPhoto.requestAnnotation().startWithNext{ expect($0.image).notTo(beNil()) expect($0.subtitle).notTo(beNil()) expect($0.title).notTo(beNil()) expect($0.coordinate).notTo(beNil()) expectation.fulfill() } self.waitForExpectationsWithTimeout(1.0, handler: { if let error = $0 { XCTFail(error.description) } }) } } } } }
mit
2f68d7c2ca531831390dbb4af071fc03
26.317073
87
0.486071
5.348615
false
false
false
false
Clean-Swift/CleanStore
CleanStore/Scenes/CreateOrder/CreateOrderInteractor.swift
1
3944
// // CreateOrderInteractor.swift // CleanStore // // Created by Raymond Law on 2/12/19. // Copyright (c) 2019 Clean Swift LLC. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol CreateOrderBusinessLogic { var shippingMethods: [String] { get } var orderToEdit: Order? { get } func formatExpirationDate(request: CreateOrder.FormatExpirationDate.Request) func createOrder(request: CreateOrder.CreateOrder.Request) func showOrderToEdit(request: CreateOrder.EditOrder.Request) func updateOrder(request: CreateOrder.UpdateOrder.Request) } protocol CreateOrderDataStore { var orderToEdit: Order? { get set } } class CreateOrderInteractor: CreateOrderBusinessLogic, CreateOrderDataStore { var presenter: CreateOrderPresentationLogic? var ordersWorker = OrdersWorker(ordersStore: OrdersMemStore()) var orderToEdit: Order? var shippingMethods = [ ShipmentMethod(speed: .Standard).toString(), ShipmentMethod(speed: .OneDay).toString(), ShipmentMethod(speed: .TwoDay).toString() ] // MARK: - Expiration date func formatExpirationDate(request: CreateOrder.FormatExpirationDate.Request) { let response = CreateOrder.FormatExpirationDate.Response(date: request.date) presenter?.presentExpirationDate(response: response) } // MARK: - Create order func createOrder(request: CreateOrder.CreateOrder.Request) { let orderToCreate = buildOrderFromOrderFormFields(request.orderFormFields) ordersWorker.createOrder(orderToCreate: orderToCreate) { (order: Order?) in self.orderToEdit = order let response = CreateOrder.CreateOrder.Response(order: order) self.presenter?.presentCreatedOrder(response: response) } } // MARK: - Edit order func showOrderToEdit(request: CreateOrder.EditOrder.Request) { if let orderToEdit = orderToEdit { let response = CreateOrder.EditOrder.Response(order: orderToEdit) presenter?.presentOrderToEdit(response: response) } } // MARK: - Update order func updateOrder(request: CreateOrder.UpdateOrder.Request) { let orderToUpdate = buildOrderFromOrderFormFields(request.orderFormFields) ordersWorker.updateOrder(orderToUpdate: orderToUpdate) { (order) in self.orderToEdit = order let response = CreateOrder.UpdateOrder.Response(order: order) self.presenter?.presentUpdatedOrder(response: response) } } // MARK: - Helper function private func buildOrderFromOrderFormFields(_ orderFormFields: CreateOrder.OrderFormFields) -> Order { let billingAddress = Address(street1: orderFormFields.billingAddressStreet1, street2: orderFormFields.billingAddressStreet2, city: orderFormFields.billingAddressCity, state: orderFormFields.billingAddressState, zip: orderFormFields.billingAddressZIP) let paymentMethod = PaymentMethod(creditCardNumber: orderFormFields.paymentMethodCreditCardNumber, expirationDate: orderFormFields.paymentMethodExpirationDate, cvv: orderFormFields.paymentMethodCVV) let shipmentAddress = Address(street1: orderFormFields.shipmentAddressStreet1, street2: orderFormFields.shipmentAddressStreet2, city: orderFormFields.shipmentAddressCity, state: orderFormFields.shipmentAddressState, zip: orderFormFields.shipmentAddressZIP) let shipmentMethod = ShipmentMethod(speed: ShipmentMethod.ShippingSpeed(rawValue: orderFormFields.shipmentMethodSpeed)!) return Order(firstName: orderFormFields.firstName, lastName: orderFormFields.lastName, phone: orderFormFields.phone, email: orderFormFields.email, billingAddress: billingAddress, paymentMethod: paymentMethod, shipmentAddress: shipmentAddress, shipmentMethod: shipmentMethod, id: orderFormFields.id, date: orderFormFields.date, total: orderFormFields.total) } }
mit
61ebeda33656556d9c776f20c05e3a24
38.049505
360
0.772566
4.746089
false
false
false
false
mownier/Umalahokan
Umalahokan/Source/UI/Drawer/DrawerContainerViewController.swift
1
3873
// // DrawerContainerViewController.swift // Umalahokan // // Created by Mounir Ybanez on 04/03/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class DrawerContainerController: UIViewController { lazy var gestureHelperView: UIView = { let view = UIView() view.backgroundColor = UIColor.clear return view }() private(set) var drawerMenuViewController: UIViewController! private(set) var drawerMenuInteractiveTransition = DrawerMenuInteractiveTransition() private(set) var drawerMenuTransitioning = DrawerMenuTransitioning() private(set) var edgePanGesture: UIScreenEdgePanGestureRecognizer! private(set) var currentContentId: String = "" var contentHandler: DrawerContainerContentHandlerProtocol? convenience init(drawerMenu: DrawerMenuProtocol) { self.init(nibName: nil, bundle: nil) let vc = drawerMenu.drawerMenuViewController vc.transitioningDelegate = drawerMenuTransitioning vc.modalPresentationStyle = .custom drawerMenu.drawerMenuInteractiveTransition = drawerMenuInteractiveTransition drawerMenuViewController = vc } override func loadView() { super.loadView() view.addSubview(gestureHelperView) edgePanGesture = UIScreenEdgePanGestureRecognizer() edgePanGesture.isEnabled = true edgePanGesture.cancelsTouchesInView = true edgePanGesture.delaysTouchesBegan = false edgePanGesture.delaysTouchesEnded = true edgePanGesture.minimumNumberOfTouches = 1 edgePanGesture.edges = .left edgePanGesture.addTarget(self, action: #selector(self.handleEdgePanGesture(_ :))) view.addGestureRecognizer(edgePanGesture) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var rect = CGRect.zero rect.size.width = 8 rect.origin.x = 0 rect.size.height = view.frame.height gestureHelperView.frame = rect view.bringSubview(toFront: gestureHelperView) } func changeContentUsing(_ content: DrawerContainerContentProtocol) { guard content.drawerContentId != currentContentId else { return } for subview in view.subviews { guard subview != gestureHelperView else { continue } subview.removeFromSuperview() } let viewController = content.drawerContentViewController.navigationController ?? content.drawerContentViewController viewController.view.frame.size = view.frame.size view.addSubview(viewController.view) addChildViewController(viewController) viewController.didMove(toParentViewController: self) currentContentId = content.drawerContentId content.hamburger = self } func handleEdgePanGesture(_ gesture: UIScreenEdgePanGestureRecognizer) { let translation = gesture.translation(in: view) let progress = drawerMenuInteractiveTransition.computeProgress(translation, viewBounds: view.bounds, direction: .right) drawerMenuInteractiveTransition.updateUsing(gesture.state, progress: progress) { [unowned self] in self.showMenu() } } } extension DrawerContainerController: DrawerContainerHamburger { var isMenuEnabled: Bool { return edgePanGesture.isEnabled } func showMenu() { guard isMenuEnabled else { return } drawerMenuTransitioning.interactiveTransition = drawerMenuInteractiveTransition present(drawerMenuViewController, animated: true, completion: nil) } func enableMenu(_ isEnabled: Bool) { edgePanGesture.isEnabled = isEnabled } }
mit
7549d58b06ace9ac71fc9f54e9d5d638
32.669565
127
0.679494
5.920489
false
false
false
false
victorwon/SwiftBus
Example/SwiftBus/ViewController.swift
1
6597
// // ViewController.swift // SwiftBus // // Created by Adam on 2015-08-29. // Copyright (c) 2017 Adam Boyd. All rights reserved. // import UIKit import SwiftBus class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func agencyListTouched(_ sender: AnyObject) { SwiftBus.shared.transitAgencies() { (agencies: [String: TransitAgency]) -> Void in let agenciesString = "Number of agencies loaded: \(agencies.count)" let agencyNamesString = agencies.map({_, agency in "\(agency.agencyTitle)"}) print("\n-----") print(agenciesString) print(agencyNamesString) self.showAlertControllerWithTitle(agenciesString, message: "\(agencyNamesString)") } } @IBAction func routesForAgencyTouched(_ sender: AnyObject) { //Alternative: //var agency = TransitAgency(agencyTag: "sf-muni") //agency.download({(success:Bool, agency:TransitAgency) -> Void in SwiftBus.shared.routes(forAgencyTag: "sf-muni") { routes in let agencyString = "Number of routes loaded for SF MUNI: \(routes.count)" let routeNamesString = routes.map({_, route in "\(route.routeTitle)"}) print("\n-----") print(agencyString) print(routeNamesString) self.showAlertControllerWithTitle(agencyString, message: "\(routeNamesString)") } } @IBAction func routeConfigurationTouched(_ sender: AnyObject) { //Alternative: //var route = TransitRoute(routeTag: "N", agencyTag: "sf-muni") //route.getRouteConfig({(success:Bool, route:TransitRoute) -> Void in SwiftBus.shared.configuration(forRouteTag: "5R", withAgencyTag: "sf-muni") { route in //If the route exists guard let route = route else { return } let routeCongigMessage = "Route config for route \(route.routeTitle)" let stops = Array(route.stops.values) let numberOfStopsMessage = "Number of stops on route in one direction: \(stops[0].count)" print("\n-----") print(routeCongigMessage) print(numberOfStopsMessage) self.showAlertControllerWithTitle(routeCongigMessage, message: numberOfStopsMessage) } } @IBAction func vehicleLocationsTouched(_ sender: AnyObject) { //Alternative: //var route = TransitRoute(routeTag: "N", agencyTag: "sf-muni") //route.getVehicleLocations({(success:Bool, vehicles:[TransitVehicle]) -> Void in SwiftBus.shared.vehicleLocations(forRouteTag: "N", forAgency: "sf-muni") { route in guard let route = route else { return } let vehicleTitleMessage = "\(route.vehiclesOnRoute.count) vehicles on route N Judah" let messageString = "Example vehicle:Vehcle ID: \(route.vehiclesOnRoute[0].vehicleId), \(route.vehiclesOnRoute[0].speedKmH) Km/h, \(route.vehiclesOnRoute[0].lat), \(route.vehiclesOnRoute[0].lon), seconds since report: \(route.vehiclesOnRoute[0].secondsSinceReport)" print("\n-----") print(vehicleTitleMessage) print(messageString) self.showAlertControllerWithTitle(vehicleTitleMessage, message: messageString) } } @IBAction func stationPredictionsTouched(_ sender: AnyObject) { SwiftBus.shared.stationPredictions(forStopTag: "5726", forRoutes: ["KT", "L", "M"], withAgencyTag: "sf-muni") { station in if let transitStation = station as TransitStation! { let lineTitles = "Prediction for lines: \(transitStation.routesAtStation.map({"\($0.routeTitle)"}))" let predictionStrings = "Predictions at stop \(transitStation.allPredictions.map({$0.predictionInMinutes}))" print("\n-----") print("Station: \(transitStation.stopTitle)") print(lineTitles) print(predictionStrings) self.showAlertControllerWithTitle(lineTitles, message: "\(predictionStrings)") } } } @IBAction func stopPredictionsTouched(_ sender: AnyObject) { //Alternative: //var route = TransitRoute(routeTag: "N", agencyTag: "sf-muni") //route.getStopPredictionsForStop("3909", completion: {(success:Bool, predictions:[String : [TransitPrediction]]) -> Void in SwiftBus.shared.stopPredictions(forStopTag: "3909", onRouteTag: "N", withAgencyTag: "sf-muni") { stop in //If the stop and route exists if let transitStop = stop as TransitStop! { let predictionStrings:[Int] = transitStop.allPredictions.map({$0.predictionInMinutes}) print("\n-----") print("Stop: \(transitStop.stopTitle)") print("Predictions at stop \(predictionStrings) mins") self.showAlertControllerWithTitle("Stop Predictions for stop \(transitStop.stopTitle)", message: "\(predictionStrings)") } } } @IBAction func multiPredictionsTouched(_ sender: Any) { SwiftBus.shared.stopPredictions(forStopTags: ["7252", "6721", "5631", "6985"], onRouteTags: ["N", "31", "43", "43"], inAgency: "sf-muni") { stops in var stopString = "" for stop in stops { stopString += "Stop \(stop.stopTitle) on route \(stop.routeTitle): \(stop.allPredictions.map({$0.predictionInMinutes}))\n\n" } print("\n-----") print("\(stopString)") self.showAlertControllerWithTitle("Multi Stop Predictions", message: "\(stopString)") } } func showAlertControllerWithTitle(_ title: String, message: String) { DispatchQueue.main.async { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
9a9ba19312a0124095183d04d37bac4a
39.975155
277
0.590723
4.865044
false
false
false
false
mac-cain13/R.swift
Sources/RswiftCore/Generators/PropertyListGenerator.swift
2
7237
// // PropertyListGenerator.swift // R.swift // // Created by Tom Lokhorst on 2018-07-07. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation struct PropertyListGenerator: ExternalOnlyStructGenerator { private let name: SwiftIdentifier private let plists: [PropertyList] private let toplevelKeysWhitelist: [String]? init(name: SwiftIdentifier, plists: [PropertyList], toplevelKeysWhitelist: [String]?) { self.name = name self.plists = plists self.toplevelKeysWhitelist = toplevelKeysWhitelist } func generatedStruct(at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Struct { guard let plist = plists.first else { return .empty } guard plists.all(where: { $0.url == plist.url }) else { let configs = plists.map { $0.buildConfigurationName } warn("Build configurations \(configs) use different \(name) files, this is not yet supported") return .empty } let contents: PropertyList.Contents if let whitelist = toplevelKeysWhitelist { contents = plist.contents.filter { (key, _) in whitelist.contains(key) } } else { contents = plist.contents } let qualifiedName = prefix + name return Struct( availables: [], comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(contents.count) properties."], accessModifier: externalAccessLevel, type: Type(module: .host, name: name), implements: [], typealiasses: [], properties: propertiesFromInfoPlist(contents: contents, path: [], at: externalAccessLevel, printWarnings: false), functions: [], structs: structsFromInfoPlist(contents: contents, path: [], at: externalAccessLevel), classes: [], os: [] ) } private func propertiesFromInfoPlist(contents duplicateContents: [String: Any], path: [String], at externalAccessLevel: AccessLevel, printWarnings: Bool) -> [Let] { let groupedContents = duplicateContents.grouped(bySwiftIdentifier: { $0.key }) // We do never print the warnings because this method is always called together with `structsFromInfoPlist` that will print the warning. // If we did print warnings they will be duplicate. let contents = Dictionary(uniqueKeysWithValues: groupedContents.uniques) return contents .compactMap { (key, value) -> Let? in switch value { case let value as Bool: return Let( comments: [], accessModifier: externalAccessLevel, isStatic: true, name: SwiftIdentifier(name: key), typeDefinition: .inferred(Type._Bool), value: "\(value)" ) case let value as String: return propertyFromInfoString(key: key, value: value, path: path, at: externalAccessLevel) default: return nil } } } private func propertyFromInfoString(key: String, value: String, path: [String], at externalAccessLevel: AccessLevel) -> Let { let steps = path.map { "\"\($0.escapedStringLiteral)\"" }.joined(separator: ", ") let isKey = key == "_key" let letValue: String = isKey ? "\"\(value.escapedStringLiteral)\"" : "infoPlistString(path: [\(steps)], key: \"\(key.escapedStringLiteral)\") ?? \"\(value.escapedStringLiteral)\"" return Let( comments: [], accessModifier: externalAccessLevel, isStatic: true, name: SwiftIdentifier(name: key), typeDefinition: .inferred(Type._String), value: letValue ) } private func structsFromInfoPlist(contents duplicateContents: [String: Any], path: [String], at externalAccessLevel: AccessLevel) -> [Struct] { let groupedContents = duplicateContents.grouped(bySwiftIdentifier: { $0.key }) groupedContents.printWarningsForDuplicatesAndEmpties(source: name.description, result: name.description) let contents = Dictionary(uniqueKeysWithValues: groupedContents.uniques) return contents .compactMap { (key, value) -> Struct? in var ps = path ps.append(key) switch value { case let duplicateArray as [String]: let groupedArray = duplicateArray.grouped(bySwiftIdentifier: { $0 }) groupedArray.printWarningsForDuplicatesAndEmpties(source: name.description, result: name.description) let array = groupedArray.uniques return Struct( availables: [], comments: [], accessModifier: externalAccessLevel, type: Type(module: .host, name: SwiftIdentifier(name: key)), implements: [], typealiasses: [], properties: array.map { item in propertyFromInfoString(key: item, value: item, path: ps, at: externalAccessLevel) }, functions: [], structs: [], classes: [], os: [] ) case var dict as [String: Any]: dict["_key"] = key return Struct( availables: [], comments: [], accessModifier: externalAccessLevel, type: Type(module: .host, name: SwiftIdentifier(name: key)), implements: [], typealiasses: [], properties: propertiesFromInfoPlist(contents: dict, path: ps, at: externalAccessLevel, printWarnings: false), functions: [], structs: structsFromInfoPlist(contents: dict, path: ps, at: externalAccessLevel), classes: [], os: [] ) case let dicts as [[String: Any]] where arrayOfDictionariesPrimaryKeys.keys.contains(key): return structForArrayOfDictionaries(key: key, dicts: dicts, path: path, at: externalAccessLevel) default: return nil } } } // For arrays of dictionaries we need a primary key. // This key will be used as a name for the struct in the generated code. private let arrayOfDictionariesPrimaryKeys: [String: String] = [ "UIWindowSceneSessionRoleExternalDisplay": "UISceneConfigurationName", "UIWindowSceneSessionRoleApplication": "UISceneConfigurationName", "UIApplicationShortcutItems": "UIApplicationShortcutItemType", "CFBundleDocumentTypes": "CFBundleTypeName", "CFBundleURLTypes": "CFBundleURLName" ] private func structForArrayOfDictionaries(key: String, dicts: [[String: Any]], path: [String], at externalAccessLevel: AccessLevel) -> Struct { let kvs = dicts.compactMap { dict -> (String, [String: Any])? in if let primaryKey = arrayOfDictionariesPrimaryKeys[key], let type = dict[primaryKey] as? String { return (type, dict) } return nil } var ps = path ps.append(key) let contents = Dictionary(kvs, uniquingKeysWith: { (l, _) in l }) return Struct( availables: [], comments: [], accessModifier: externalAccessLevel, type: Type(module: .host, name: SwiftIdentifier(name: key)), implements: [], typealiasses: [], properties: [], functions: [], structs: structsFromInfoPlist(contents: contents, path: ps, at: externalAccessLevel), classes: [], os: [] ) } }
mit
cea39de310cdc0e938aa82756f7af2b3
35.366834
166
0.642393
4.799072
false
false
false
false
Burning-Man-Earth/iBurn-iOS
iBurn/DateFormatter+iBurn.swift
1
2347
// // DateFormatter+iBurn.swift // iBurn // // Created by Chris Ballinger on 7/30/18. // Copyright © 2018 Burning Man Earth. All rights reserved. // import Foundation extension TimeZone { /// Gerlach time / PDT static let burningManTimeZone = TimeZone(abbreviation: "PDT")! } extension NSTimeZone { @objc public static var brc_burningManTimeZone: NSTimeZone { return TimeZone.burningManTimeZone as NSTimeZone } } extension DateFormatter { /** e.g. 2015-09-04 */ static let eventGroupDateFormatter: DateFormatter = { var df = DateFormatter() df.dateFormat = "yyyy-MM-dd" df.timeZone = TimeZone.burningManTimeZone return df }() /// e.g. "Monday" static let dayOfWeek: DateFormatter = { var df = DateFormatter() df.dateFormat = "EEEE" df.timeZone = TimeZone.burningManTimeZone return df }() /// e.g. 4:19 AM static let timeOnly: DateFormatter = { let df = DateFormatter() df.dateFormat = "h:mma" df.timeZone = TimeZone.burningManTimeZone return df }() /// e.g. Monday 8/29 4:19 AM static let annotationDateFormatter: DateFormatter = { let df = DateFormatter() df.dateFormat = "E' 'M/d' 'h:mma" df.timeZone = TimeZone.burningManTimeZone return df }() } extension DateComponentsFormatter { static let shortRelativeTimeFormatter: DateComponentsFormatter = { let formatter = DateComponentsFormatter() formatter.unitsStyle = .abbreviated formatter.allowedUnits = [ .hour, .minute ] return formatter }() } @objc public final class DateFormatters: NSObject { /** e.g. 2015-09-04 */ @objc public static var eventGroupDateFormatter: DateFormatter { return DateFormatter.eventGroupDateFormatter } /// e.g. "Monday" @objc public static var dayOfWeek: DateFormatter { return DateFormatter.dayOfWeek } /// e.g. 4:19 AM @objc public static var timeOnly: DateFormatter { return DateFormatter.timeOnly } @objc public static func stringForTimeInterval(_ interval: TimeInterval) -> String? { let formatter = DateComponentsFormatter.shortRelativeTimeFormatter return formatter.string(from: interval) } }
mpl-2.0
b0324748cd5d575ac0e8b379947d71f7
26.6
89
0.642796
4.627219
false
false
false
false
mtynior/SwiftyLogger
Source/LogLevel.swift
1
811
// // LogLevel.swift // SwiftyLogger // // Created by Michal Tynior on 24/10/2016. // Copyright © 2016 Michał Tynior. All rights reserved. // import Foundation public enum LogLevel: Int { case debug case verbose case info case warning case error case critical } extension LogLevel: CustomStringConvertible { public var description: String { let level: String switch(self) { case .debug: level = "Debug" case .verbose: level = "Verbose" case .info: level = "Info" case .warning: level = "Warning" case .error: level = "Error" case .critical: level = "Critical" } return level } }
mit
19507195ec9a5fe7c6120ad89d0ee6ad
16.586957
56
0.521632
4.469613
false
false
false
false
Sharelink/Bahamut
Bahamut/BahamutUIKit/UserGuide.swift
1
2974
// // UserGuide.swift // Bahamut // // Created by AlexChow on 15/12/2. // Copyright © 2015年 GStudio. All rights reserved. // import Foundation import UIKit //MARK: UserGuide class UserGuide:NSObject { fileprivate var viewController:UIViewController! fileprivate var guideImages:[UIImage]! fileprivate var userId:String! fileprivate var showingIndex:Int = 0 fileprivate var imgController:NoStatusBarViewController! fileprivate var imageView:UIImageView! fileprivate var isInited:Bool = false func initGuide<T:UIViewController>(_ controller:T,userId:String,guideImgs:[UIImage]) { viewController = controller guideImages = guideImgs self.userId = userId initImageViewController() isInited = true let className = T.description() firstTimeStoreKey = "showGuideMark:\(self.userId!)\(className)" } fileprivate var firstTimeStoreKey:String! fileprivate func initImageViewController() { imgController = NoStatusBarViewController() imgController.view.frame = (UIApplication.shared.keyWindow?.bounds)! imageView = UIImageView(frame: imgController.view.bounds) imgController.view.addSubview(imageView) self.imgController.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(UserGuide.onTapImage(_:)))) } func deInitUserGuide() { isInited = false self.viewController = nil self.imageView = nil self.imgController = nil self.guideImages = nil self.firstTimeStoreKey = nil } @objc func onTapImage(_:UITapGestureRecognizer) { showNextImage() } fileprivate func showNextImage() { self.showingIndex += 1 if showingIndex >= self.guideImages.count { self.viewController.dismiss(animated: false, completion: { self.deInitUserGuide() }) }else { self.imageView.image = self.guideImages[self.showingIndex] } } func showGuide() -> Bool { if isInited && self.guideImages != nil && self.guideImages.count > 0 { self.showingIndex = -1 self.viewController.present(imgController, animated: true, completion: { self.showNextImage() }) return true } return false } func showGuideControllerPresentFirstTime() -> Bool { if isInited && self.guideImages != nil && self.guideImages.count > 0 { let key = firstTimeStoreKey let showed = UserDefaults.standard.bool(forKey: key!) if !showed { UserDefaults.standard.set(true, forKey: key!) return showGuide() }else { deInitUserGuide() } } return false } }
mit
ae83a6a4fe133b5372267b92f99c23fe
27.567308
135
0.605857
5.087329
false
false
false
false
carabina/Butterfly
Example/Pods/Butterfly/Butterfly/ButterflyViewController.swift
1
7633
// // ButterflyViewController.swift // Butterfly // // Created by Zhijie Huang on 15/6/20. // // Copyright (c) 2015 Zhijie Huang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /// MARK: - Protocol of `ButterflyViewController protocol ButterflyViewControllerDelegate: class { func ButterflyViewControllerDidPressedSendButton(drawView: ButterflyDrawView?) } /// This is the viewController combined Butterfly modules. public class ButterflyViewController: UIViewController, ButterflyDrawViewDelegate, UITextViewDelegate { /// The image reported by users that will upload to server. internal var imageWillUpload: UIImage? /// The text reported by users that will upload to server. internal var textWillUpload: String? var topBar: ButterflyTopBar? var bottomBar: ButterflyBottomBar? var drawView: ButterflyDrawView? lazy var textView: ButterflyTextView = { let view = ButterflyTextView() return view }() weak var delegate: ButterflyViewControllerDelegate? var drawColor: UIColor? var drawLineWidth: Float? var imageView: UIImageView? var image: UIImage? var colors: [UIColor]? var textViewIsShowing: Bool? override public func viewDidLoad() { super.viewDidLoad() setup() self.view.backgroundColor = UIColor.clearColor() self.navigationController?.navigationBarHidden = true } /// Set up the view private func setup() { imageView = UIImageView(frame: UIScreen.mainScreen().bounds) imageView?.image = self.image imageView?.autoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin imageView?.contentMode = UIViewContentMode.Center self.view.addSubview(imageView!) drawView = ButterflyDrawView() drawView?.delegate = self self.view.addSubview(drawView!) topBar = ButterflyTopBar() self.view.addSubview(topBar!) bottomBar = ButterflyBottomBar() self.view.addSubview(bottomBar!) topBar?.sendButton?.addTarget(self, action: "sendButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) topBar?.cancelButton?.addTarget(self, action: "cancelButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) bottomBar?.colorChangedButton?.addTarget(self, action: "colorChangedButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) bottomBar?.descriptionButton?.addTarget(self, action: "inputDescriptionButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) bottomBar?.clearPathButton?.addTarget(self, action: "clearButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) textView.delegate = self view.addSubview(self.textView) } public func cancelButtonPressed(sender: UIButton?) { drawView?.enable() dismissViewControllerAnimated(false, completion: nil) } /// Note: Always access or upload `imageWillUpload` and `textWillUpload` only after send button has been pressed, otherwise, these two optional properties may be nil. /// After that, you can upload image and text manually and properly. public func sendButtonPressed(sender: UIButton?) { drawView?.enable() delegate?.ButterflyViewControllerDidPressedSendButton(drawView) imageWillUpload = ButterflyManager.sharedManager.takeAScreenshot() textWillUpload = textView.text if let textViewIsShowing = textView.isShowing { if textViewIsShowing == true { textView.hide() } } showAlertViewController() println(self.imageWillUpload) println(self.textWillUpload) } func showAlertViewController() { self.dismissViewControllerAnimated(false, completion: nil) let alert = UIAlertController(title: "Success", message: "Report Success", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)) self.presentingViewController?.presentViewController(alert, animated: true, completion: nil) } internal func colorChangedButtonPressed(sender: UIButton?) { drawView?.lineColor = UIColor.yellowColor() } internal func inputDescriptionButtonPressed(sender: UIButton?) { textView.show() drawView?.disable() } internal func clearButtonPressed(sender: UIButton?) { drawView?.clear() } // MARK: - ButterflyDrawViewDelegate func drawViewDidEndDrawingInView(drawView: ButterflyDrawView?) { topBar?.show() bottomBar?.show() } func drawViewDidStartDrawingInView(drawView: ButterflyDrawView?) { topBar?.hide() bottomBar?.hide() } /// MARK: - UITextViewDelegate /// /// Placeholder trick /// /// Changed if statements to compare tags rather than text. If the user deleted their text it was possible to also /// accidentally delete a portion of the place holder. This meant if the user re-entered the textView the following /// delegate method, `- textViewShouldBeginEditing` , it would not work as expected. /// /// http://stackoverflow.com/questions/1328638/placeholder-in-uitextview/7091503#7091503 /// DO NOT OVERRIDE THESE METHODS BELOW EXCEPTED YOU NEED INDEED. /// public func textViewShouldBeginEditing(textView: UITextView) -> Bool { if textView.tag == 0 { textView.text = ""; textView.textColor = UIColor.blackColor(); textView.tag = 1; } return true; } public func textViewDidEndEditing(textView: UITextView) { if count(textView.text) == 0 { textView.text = "Please enter your feedback." textView.textColor = UIColor.lightGrayColor() textView.tag = 0 } self.textView.hide() drawView?.enable() textWillUpload = textView.text } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } return true } /// MARK: - deinit deinit{ drawView?.delegate = nil } }
mit
c423c4b98e3c6e65f3a5bcde67308adf
35.874396
170
0.679156
5.271409
false
false
false
false
tomco/AlecrimCoreData
Source/Shared/AlecrimCoreData/Extensions/NSManagedObject+Extensions.swift
1
2205
// // NSManagedObject+Extensions.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 2014-06-24. // Copyright (c) 2014 Alecrim. All rights reserved. // import Foundation import CoreData // can be changed to nil or other suffix public var entityNameSuffix: NSString? = "Entity" // entity names cache private var entityNames = Dictionary<String, String>() extension NSManagedObject { public func inContext(context: Context) -> Self? { return self.inManagedObjectContext(context.managedObjectContext) } } extension NSManagedObject { private func inManagedObjectContext(otherManagedObjectContext: NSManagedObjectContext) -> Self? { if self.managedObjectContext == otherManagedObjectContext { return self } var error: NSError? = nil if self.objectID.temporaryID { if let moc = self.managedObjectContext { let success = moc.obtainPermanentIDsForObjects([self as NSManagedObject], error: &error) if !success { return nil } } else { return nil } } let objectInContext = otherManagedObjectContext.existingObjectWithID(self.objectID, error: &error) return unsafeBitCast(objectInContext, self.dynamicType) } } extension NSManagedObject { internal class var entityName: String { let className = NSStringFromClass(self) if let name = entityNames[className] { return name } else { var name: NSString = className let range = name.rangeOfString(".") if range.location != NSNotFound { name = name.substringFromIndex(range.location + 1) } if let suffix = entityNameSuffix { if !name.isEqualToString(suffix) && name.hasSuffix(suffix) { name = name.substringToIndex(name.length - suffix.length) } } entityNames[className] = name return name } } }
mit
f30b03d5b055c74995c760eb6d5d753b
26.222222
106
0.580045
5.404412
false
false
false
false
jangxyz/springy
springy-swift/springy/Node.swift
1
1087
// // node.swift // springy-swift // // Created by 김장환 on 1/11/15. // Copyright (c) 2015 김장환. All rights reserved. // import Foundation struct Node: Equatable { let id: String let data: [String:String] init(id:String, data:[String:String] = [String:String]()) { self.id = id self.data = data } init(id:String, data:[String:String]?) { self.id = id self.data = data ?? [String:String]() } init(id:Int, data:[String:String] = [String:String]()) { self.id = String(id) self.data = data } init(_ id:String, data:[String:String] = [String:String]()) { self.id = String(id) self.data = data } init(_ id:Int, data:[String:String] = [String:String]()) { self.id = String(id) self.data = data } func description() -> String { return "Node: #\(self.id):\(self.data)" } } func == (left: Node, right: Node) -> Bool { return left.id == right.id } func != (left: Node, right: Node) -> Bool { return !(left == right) }
mit
a0da3e6d14a180a416ea14014b0b1a00
21.395833
65
0.539535
3.257576
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Activity/CalendarViewController.swift
1
11352
import UIKit protocol CalendarViewControllerDelegate: AnyObject { func didCancel(calendar: CalendarViewController) func didSelect(calendar: CalendarViewController, startDate: Date?, endDate: Date?) } class CalendarViewController: UIViewController { private var calendarCollectionView: CalendarCollectionView! private var startDateLabel: UILabel! private var separatorDateLabel: UILabel! private var endDateLabel: UILabel! private var header: UIStackView! private let gradient = GradientView() private var startDate: Date? private var endDate: Date? weak var delegate: CalendarViewControllerDelegate? private lazy var formatter: DateFormatter = { let formatter = DateFormatter() formatter.setLocalizedDateFormatFromTemplate("MMM d, yyyy") return formatter }() private enum Constants { static let headerPadding: CGFloat = 16 static let endDateLabel = NSLocalizedString("End Date", comment: "Placeholder for the end date in calendar range selection") static let startDateLabel = NSLocalizedString("Start Date", comment: "Placeholder for the start date in calendar range selection") static let rangeSummaryAccessibilityLabel = NSLocalizedString( "Selected range: %1$@ to %2$@", comment: "Accessibility label for summary of currently selected range. %1$@ is the start date, %2$@ is " + "the end date.") static let singleDateRangeSummaryAccessibilityLabel = NSLocalizedString( "Selected range: %1$@ only", comment: "Accessibility label for summary of currently single date. %1$@ is the date") static let noRangeSelectedAccessibilityLabelPlaceholder = NSLocalizedString( "No date range selected", comment: "Accessibility label for no currently selected range.") } /// Creates a full screen year calendar controller /// /// - Parameters: /// - startDate: An optional Date representing the first selected date /// - endDate: An optional Date representing the end selected date init(startDate: Date? = nil, endDate: Date? = nil) { self.startDate = startDate self.endDate = endDate super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { super.init(coder: coder) } override func viewDidLoad() { title = NSLocalizedString("Choose date range", comment: "Title to choose date range in a calendar") // Configure Calendar let calendar = Calendar.current self.calendarCollectionView = CalendarCollectionView( calendar: calendar, style: .year, startDate: startDate, endDate: endDate ) // Configure headers and add the calendar to the view configureHeader() let stackView = UIStackView(arrangedSubviews: [ header, calendarCollectionView ]) stackView.axis = .vertical stackView.translatesAutoresizingMaskIntoConstraints = false stackView.setCustomSpacing(Constants.headerPadding, after: header) view.addSubview(stackView) view.pinSubviewToAllEdges(stackView, insets: UIEdgeInsets(top: Constants.headerPadding, left: 0, bottom: 0, right: 0)) view.backgroundColor = .basicBackground setupNavButtons() setUpGradient() calendarCollectionView.calDataSource.didSelect = { [weak self] startDate, endDate in self?.updateDates(startDate: startDate, endDate: endDate) } calendarCollectionView.scrollsToTop = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scrollToVisibleDate() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { _ in self.calendarCollectionView.reloadData(withAnchor: self.startDate ?? Date(), completionHandler: nil) }, completion: nil) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) setUpGradientColors() } private func setupNavButtons() { let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", comment: "Label for Done button"), style: .done, target: self, action: #selector(done)) navigationItem.setRightBarButton(doneButton, animated: false) navigationItem.setLeftBarButton(UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel)), animated: false) } private func updateDates(startDate: Date?, endDate: Date?) { self.startDate = startDate self.endDate = endDate updateLabels() } private func updateLabels() { guard let startDate = startDate else { resetLabels() return } startDateLabel.text = formatter.string(from: startDate) startDateLabel.textColor = .text startDateLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) if let endDate = endDate { endDateLabel.text = formatter.string(from: endDate) endDateLabel.textColor = .text endDateLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) separatorDateLabel.textColor = .text separatorDateLabel.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) } else { endDateLabel.text = Constants.endDateLabel endDateLabel.font = WPStyleGuide.fontForTextStyle(.title3) endDateLabel.textColor = .textSubtle separatorDateLabel.textColor = .textSubtle } header.accessibilityLabel = accessibilityLabelForRangeSummary(startDate: startDate, endDate: endDate) } private func configureHeader() { header = startEndDateHeader() resetLabels() } private func startEndDateHeader() -> UIStackView { let header = UIStackView(frame: .zero) header.distribution = .fill let startDate = UILabel() startDate.isAccessibilityElement = false startDateLabel = startDate startDate.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) if view.effectiveUserInterfaceLayoutDirection == .leftToRight { // swiftlint:disable:next inverse_text_alignment startDate.textAlignment = .right } else { // swiftlint:disable:next natural_text_alignment startDate.textAlignment = .left } header.addArrangedSubview(startDate) startDate.widthAnchor.constraint(equalTo: header.widthAnchor, multiplier: 0.47).isActive = true let separator = UILabel() separator.isAccessibilityElement = false separatorDateLabel = separator separator.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) separator.textAlignment = .center header.addArrangedSubview(separator) separator.widthAnchor.constraint(equalTo: header.widthAnchor, multiplier: 0.06).isActive = true let endDate = UILabel() endDate.isAccessibilityElement = false endDateLabel = endDate endDate.font = WPStyleGuide.fontForTextStyle(.title3, fontWeight: .semibold) if view.effectiveUserInterfaceLayoutDirection == .leftToRight { // swiftlint:disable:next natural_text_alignment endDate.textAlignment = .left } else { // swiftlint:disable:next inverse_text_alignment endDate.textAlignment = .right } header.addArrangedSubview(endDate) endDate.widthAnchor.constraint(equalTo: header.widthAnchor, multiplier: 0.47).isActive = true header.isAccessibilityElement = true header.accessibilityTraits = [.header, .summaryElement] return header } private func scrollToVisibleDate() { if calendarCollectionView.frame.height == 0 { calendarCollectionView.superview?.layoutIfNeeded() } if let startDate = startDate { calendarCollectionView.scrollToDate(startDate, animateScroll: true, preferredScrollPosition: .centeredVertically, extraAddedOffset: -(self.calendarCollectionView.frame.height / 2)) } else { calendarCollectionView.setContentOffset(CGPoint( x: 0, y: calendarCollectionView.contentSize.height - calendarCollectionView.frame.size.height ), animated: false) } } private func resetLabels() { startDateLabel.text = Constants.startDateLabel separatorDateLabel.text = "-" endDateLabel.text = Constants.endDateLabel [startDateLabel, separatorDateLabel, endDateLabel].forEach { label in label?.textColor = .textSubtle label?.font = WPStyleGuide.fontForTextStyle(.title3) } header.accessibilityLabel = accessibilityLabelForRangeSummary(startDate: nil, endDate: nil) } private func accessibilityLabelForRangeSummary(startDate: Date?, endDate: Date?) -> String { switch (startDate, endDate) { case (nil, _): return Constants.noRangeSelectedAccessibilityLabelPlaceholder case (.some(let startDate), nil): let startDateString = formatter.string(from: startDate) return String.localizedStringWithFormat(Constants.singleDateRangeSummaryAccessibilityLabel, startDateString) case (.some(let startDate), .some(let endDate)): let startDateString = formatter.string(from: startDate) let endDateString = formatter.string(from: endDate) return String.localizedStringWithFormat(Constants.rangeSummaryAccessibilityLabel, startDateString, endDateString) } } private func setUpGradient() { gradient.isUserInteractionEnabled = false gradient.translatesAutoresizingMaskIntoConstraints = false view.addSubview(gradient) NSLayoutConstraint.activate([ gradient.heightAnchor.constraint(equalToConstant: 50), gradient.topAnchor.constraint(equalTo: calendarCollectionView.topAnchor), gradient.leadingAnchor.constraint(equalTo: calendarCollectionView.leadingAnchor), gradient.trailingAnchor.constraint(equalTo: calendarCollectionView.trailingAnchor) ]) setUpGradientColors() } private func setUpGradientColors() { gradient.fromColor = .basicBackground gradient.toColor = UIColor.basicBackground.withAlphaComponent(0) } @objc private func done() { delegate?.didSelect(calendar: self, startDate: startDate, endDate: endDate) } @objc private func cancel() { delegate?.didCancel(calendar: self) } }
gpl-2.0
e1f54d8ab4a8ea19baddb8893e29f106
39.398577
161
0.662438
5.860609
false
false
false
false
TechnologySpeaks/smile-for-life
smile-for-life/SQLiteExtensionQueries.swift
1
4858
// // SQLiteExtensionQueries.swift // smile-for-life // // Created by Lisa Swanson on 8/21/16. // Copyright © 2016 Technology Speaks. All rights reserved. // import Foundation extension SQLiteDatabase { func getNameFromUsers(_ name: String) -> User { let user = User() let querySql = "SELECT * FROM Users WHERE name = ?;" guard let queryStatement = try? prepareStatement(querySql) else { return user } defer { sqlite3_finalize(queryStatement) } // guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else { // return (0, "None") } guard sqlite3_bind_text(queryStatement, 1, name, -1, nil) == SQLITE_OK else { return user } guard sqlite3_step(queryStatement) == SQLITE_ROW else { return user } user.id = sqlite3_column_int(queryStatement, 0) let queryResultCol1 = sqlite3_column_text(queryStatement, 1) user.name = String(cString: queryResultCol1!) return user } // MARK: Removal func getCalendarOralEvents(_ id: Int32) -> [GetOralEventsQuery] { var oralEventsCollection = [GetOralEventsQuery]() let querySql = "select * from OralEvents where created > strftime('%Y', '2016') and userId = ? order by datetime(created) asc;" guard let queryStatement = try? prepareStatement(querySql) else { return [] } defer { sqlite3_finalize(queryStatement) } guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else { return [] } while sqlite3_step(queryStatement) == SQLITE_ROW { //let id = sqlite3_column_int(queryStatement, 0) let queryResultCol1 = sqlite3_column_text(queryStatement, 1) let queryResultCol2 = sqlite3_column_text(queryStatement, 2) let getOralEventQuery = GetOralEventsQuery(headerSectionName: String(cString: queryResultCol1!), oralEventType: String(cString: queryResultCol2!)) oralEventsCollection.append(getOralEventQuery) } return oralEventsCollection } // ********************************************** // func getUserCalendarOralEvents(id: Int32) -> [OralEventGroups] { // var oralEventsCollection = [OralEventGroups]() // let querySql = "select * from OralEvents where created > strftime('%Y', '2016') and userId = ?;" // guard let queryStatement = try? prepareStatement(querySql) else { // return [] // } // // defer { // sqlite3_finalize(queryStatement) // } // // guard sqlite3_bind_int(queryStatement, 1, id) == SQLITE_OK else { // return [] // } // // while sqlite3_step(queryStatement) == SQLITE_ROW { // // let oralEventGroup = OralEventGroups() // let oralHygieneEvent: OralHygieneEvent // // oralEventGroup.id = sqlite3_column_int(queryStatement, 0) // let queryResultCol1 = sqlite3_column_text(queryStatement, 1) // oralEventGroup.headerSectionName = String.fromCString(UnsafePointer<CChar>(queryResultCol1))! // let queryResultCol2 = sqlite3_column_text(queryStatement, 2) // oralHygieneEvent.eventName = String.fromCString(UnsafePointer<CChar>(queryResultCol2))! // oralHygieneEvent.sortingIndex = "" // oralHygieneEvent.timeLabel = "" // print("%%%%%%%%") // print(oralHygieneEvent.eventName) // print(oralHygieneEvent) //// let test = Mirror(reflecting: oralEventGroup.oralHygieneEvents) // print(Mirror(reflecting: oralEventGroup.oralHygieneEvents).subjectType) //// print(test.subjectType) // oralEventGroup.oralHygieneEvents.append(oralHygieneEvent) // print(oralEventGroup.oralHygieneEvents) // oralEventsCollection.append(oralEventGroup) // } // return oralEventsCollection // // } // func getCountFromUsers() -> (Int32) { // let querySql = "SELECT count(*) from Users;" // guard let queryStatement = try? prepareStatement(querySql) else { // return (0) // } // // defer { // sqlite3_finalize(queryStatement) // } // // guard sqlite3_step(queryStatement) == SQLITE_ROW else { // return (0) // } // // let id = sqlite3_column_int(queryStatement, 0) // // return (id: id) // } func getAvailableCalendarsFromUsers() -> [User] { var arrayOfCalendar = [User]() let querySql = "SELECT * from Users;" guard let queryStatement = try? prepareStatement(querySql) else { return [] } defer { sqlite3_finalize(queryStatement) } while sqlite3_step(queryStatement) == SQLITE_ROW { let user = User() user.id = sqlite3_column_int(queryStatement, 0) let queryResultCol1 = sqlite3_column_text(queryStatement, 1) user.name = String(cString: queryResultCol1!) arrayOfCalendar.append(user) } return arrayOfCalendar } }
mit
45dac90deaf8fb2cf4d0c884dcfb3c02
28.436364
152
0.63846
4.0475
false
false
false
false
Fahrni/PastryKit
PastryTest/ViewController.swift
1
2541
// // ViewController.swift // PastryTest // // Created by Rob Fahrni on 3/22/15. // Copyright (c) 2015 Robert R. Fahrni. All rights reserved. // import UIKit //import PastryKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var goButton: UIButton! @IBOutlet weak var actionSegmentedControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func goButtonHandler(sender: AnyObject) { let pk = PastryKit() switch (self.actionSegmentedControl.selectedSegmentIndex) { case 0: pk.thoughtByDay(NSDate(), completionHandler:{ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); case 1: pk.thoughtByDay(NSDate(), previous:5, completionHandler:{ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); case 2: pk.thoughtByDay(NSDate(), next:5, completionHandler:{ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); case 3: pk.thoughtByDay(NSDate(), to:NSDate(), completionHandler:{ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); case 4: self.showPastryBaker(); case 5: pk.allThoughts({ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); default: pk.thoughtByDay(NSDate(), completionHandler:{ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); } } private func showPastryBaker() { let pastryKit = PastryKit(); pastryKit.thoughtsByBaker("mike-monteiro", completionHandler:{ (pasteries, error) in if nil != error { print(error) } if nil != pasteries { print(pasteries) } }); } }
mit
c98d9520e868cc29ad9fac7f5e29eee2
31.164557
92
0.553719
4.767355
false
false
false
false
liuxuan30/ios-charts
ChartsDemo-iOS/Swift/Demos/PieChartViewController.swift
3
5160
// // PieChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // #if canImport(UIKit) import UIKit #endif import Charts class PieChartViewController: DemoBaseViewController { @IBOutlet var chartView: PieChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Pie Chart" self.options = [.toggleValues, .toggleXValues, .togglePercent, .toggleHole, .toggleIcons, .animateX, .animateY, .animateXY, .spin, .drawCenter, .saveToGallery, .toggleData] self.setup(pieChartView: chartView) chartView.delegate = self let l = chartView.legend l.horizontalAlignment = .right l.verticalAlignment = .top l.orientation = .vertical l.xEntrySpace = 7 l.yEntrySpace = 0 l.yOffset = 0 // chartView.legend = l // entry label styling chartView.entryLabelColor = .white chartView.entryLabelFont = .systemFont(ofSize: 12, weight: .light) sliderX.value = 4 sliderY.value = 100 self.slidersValueChanged(nil) chartView.animate(xAxisDuration: 1.4, easingOption: .easeOutBack) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } func setDataCount(_ count: Int, range: UInt32) { let entries = (0..<count).map { (i) -> PieChartDataEntry in // IMPORTANT: In a PieChart, no values (Entry) should have the same xIndex (even if from different DataSets), since no values can be drawn above each other. return PieChartDataEntry(value: Double(arc4random_uniform(range) + range / 5), label: parties[i % parties.count], icon: #imageLiteral(resourceName: "icon")) } let set = PieChartDataSet(entries: entries, label: "Election Results") set.drawIconsEnabled = false set.sliceSpace = 2 set.colors = ChartColorTemplates.vordiplom() + ChartColorTemplates.joyful() + ChartColorTemplates.colorful() + ChartColorTemplates.liberty() + ChartColorTemplates.pastel() + [UIColor(red: 51/255, green: 181/255, blue: 229/255, alpha: 1)] let data = PieChartData(dataSet: set) let pFormatter = NumberFormatter() pFormatter.numberStyle = .percent pFormatter.maximumFractionDigits = 1 pFormatter.multiplier = 1 pFormatter.percentSymbol = " %" data.setValueFormatter(DefaultValueFormatter(formatter: pFormatter)) data.setValueFont(.systemFont(ofSize: 11, weight: .light)) data.setValueTextColor(.white) chartView.data = data chartView.highlightValues(nil) } override func optionTapped(_ option: Option) { switch option { case .toggleXValues: chartView.drawEntryLabelsEnabled = !chartView.drawEntryLabelsEnabled chartView.setNeedsDisplay() case .togglePercent: chartView.usePercentValuesEnabled = !chartView.usePercentValuesEnabled chartView.setNeedsDisplay() case .toggleHole: chartView.drawHoleEnabled = !chartView.drawHoleEnabled chartView.setNeedsDisplay() case .drawCenter: chartView.drawCenterTextEnabled = !chartView.drawCenterTextEnabled chartView.setNeedsDisplay() case .animateX: chartView.animate(xAxisDuration: 1.4) case .animateY: chartView.animate(yAxisDuration: 1.4) case .animateXY: chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4) case .spin: chartView.spin(duration: 2, fromAngle: chartView.rotationAngle, toAngle: chartView.rotationAngle + 360, easingOption: .easeInCubic) default: handleOption(option, forChartView: chartView) } } // MARK: - Actions @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
apache-2.0
99f1b56daa7d09d1768f1341d5600259
32.283871
168
0.560574
5.44773
false
false
false
false
cam-hop/RxSwiftFlux
RxSwiftFluxDemo/RxSwiftFluxDemo/Controller/SubcriberViewController.swift
2
1966
// // ViewController.swift // DemoApp // // Created by DUONG VANHOP on 2017/06/14. // Copyright © 2017年 DUONG VANHOP. All rights reserved. // import UIKit import RxSwiftFlux class SubcriberViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var refreshControl = UIRefreshControl() private let subcriberDataSource = SubcriberDataSource() let subcriberStore = SubcriberStore.shared override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. configureUI() observeStore() observeUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func configureUI() { view.backgroundColor = UIColor.lightGray navigationItem.title = "Subcribers" tableView.addSubview(refreshControl) subcriberDataSource.register(tableView: tableView) } private func observeStore() { } private func observeUI() { ActionCreator.invoke(action: SubcriberAction.Fetch()) let rx_refreshControler = refreshControl.rx.controlEvent(.valueChanged) rx_refreshControler .map ({ _ in !self.refreshControl.isRefreshing }) .filter({ $0 == false }) .subscribe(onNext: { [unowned self] _ in self.refreshControl.beginRefreshing() ActionCreator.invoke(action: SubcriberAction.Fetch()) }) .addDisposableTo(rx_disposeBag) rx_refreshControler .map ({ _ in self.refreshControl.isRefreshing }) .filter({ $0 == true }) .subscribe(onNext: { _ in self.refreshControl.endRefreshing() }) .addDisposableTo(rx_disposeBag) } }
mit
1564dab7ddbe2ccfce7f1dd383faa003
25.173333
80
0.612328
5.234667
false
false
false
false
AlexanderTar/LASwift
Sources/VectorArithmetic.swift
1
14161
// Vector.swift // // Copyright (c) 2017 Alexander Taraymovich <[email protected]> // All rights reserved. // // This software may be modified and distributed under the terms // of the BSD license. See the LICENSE file for details. import Darwin import Accelerate // MARK: - Arithmetic operations on two vectors /// Perform vector addition. /// /// Alternatively, `plus(a, b)` can be executed with `a + b`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: elementwise vector sum of a and b public func plus(_ a: Vector, _ b: Vector) -> Vector { return vectorVectorOperation(vDSP_vaddD, a, b) } /// Perform vector addition. /// /// Alternatively, `a + b` can be executed with `plus(a, b)`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: elementwise vector sum of a and b public func + (_ a: Vector, _ b: Vector) -> Vector { return plus(a, b) } /// Perform vector substraction. /// /// Alternatively, `minus(a, b)` can be executed with `a - b`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: elementwise vector difference of a and b public func minus(_ a: Vector, _ b: Vector) -> Vector { return vectorVectorOperation(vDSP_vsubD, b, a) } /// Perform vector substraction. /// /// Alternatively, `a - b` can be executed with `minus(a, b)`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: elementwise vector difference of a and b public func - (_ a: Vector, _ b: Vector) -> Vector { return minus(a, b) } /// Perform vector multiplication. /// /// Alternatively, `times(a, b)` can be executed with `a .* b`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: elementwise vector product of a and b public func times(_ a: Vector, _ b: Vector) -> Vector { return vectorVectorOperation(vDSP_vmulD, a, b) } /// Perform vector multiplication. /// /// Alternatively, `a .* b` can be executed with `times(a, b)`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: elementwise vector product of a and b public func .* (_ a: Vector, _ b: Vector) -> Vector { return times(a, b) } /// Perform vector right division. /// /// Alternatively, `rdivide(a, b)` can be executed with `a ./ b`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: result of elementwise division of a by b public func rdivide(_ a: Vector, _ b: Vector) -> Vector { return vectorVectorOperation(vDSP_vdivD, b, a) } /// Perform vector right division. /// /// Alternatively, `a ./ b` can be executed with `rdivide(a, b)`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: result of elementwise division of a by b public func ./ (_ a: Vector, _ b: Vector) -> Vector { return rdivide(a, b) } /// Perform vector left division. /// /// Alternatively, `ldivide(a, b)` can be executed with `a ./. b`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: result of elementwise division of b by a public func ldivide(_ a: Vector, _ b: Vector) -> Vector { return vectorVectorOperation(vDSP_vdivD, a, b) } /// Perform vector left division. /// /// Alternatively, `a ./. b` can be executed with `ldivide(a, b)`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: result of elementwise division of b by a public func ./. (_ a: Vector, _ b: Vector) -> Vector { return ldivide(a, b) } // MARK: - Dot product operations on two vectors /// Perform vector dot product operation. /// /// Alternatively, `dot(a, b)` can be executed with `a * b`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: dot product of a and b public func dot(_ a: Vector, _ b: Vector) -> Double { precondition(a.count == b.count, "Vectors must have equal lenghts") var c: Double = 0.0 vDSP_dotprD(a, 1, b, 1, &c, vDSP_Length(a.count)) return c } /// Perform vector dot product operation. /// /// Alternatively, `a * b` can be executed with `dot(a, b)`. /// /// - Parameters /// - a: left vector /// - b: right vector /// - Returns: dot product of a and b public func * (_ a: Vector, _ b: Vector) -> Double { return dot(a, b) } // MARK: - Arithmetic operations on vector and scalar /// Perform vector and scalar addition. /// /// Scalar value expands to vector dimension /// and elementwise vector addition is performed. /// /// Alternatively, `plus(a, b)` can be executed with `a + b`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: elementwise sum of vector a and scalar b public func plus(_ a: Vector, _ b: Double) -> Vector { return vectorScalarOperation(vDSP_vsaddD, a, b) } /// Perform vector and scalar addition. /// /// Scalar value expands to vector dimension /// and elementwise vector addition is performed. /// /// Alternatively, `a + b` can be executed with `plus(a, b)`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: elementwise sum of vector a and scalar b public func + (_ a: Vector, _ b: Double) -> Vector { return plus(a, b) } /// Perform scalar and vector addition. /// /// Scalar value expands to vector dimension /// and elementwise vector addition is performed. /// /// Alternatively, `plus(a, b)` can be executed with `a + b`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: elementwise sum of scalar a and vector b public func plus(_ a: Double, _ b: Vector) -> Vector { return plus(b, a) } /// Perform scalar and vector addition. /// /// Scalar value expands to vector dimension /// and elementwise vector addition is performed. /// /// Alternatively, `a + b` can be executed with `plus(a, b)`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: elementwise sum of scalar a and vector b public func + (_ a: Double, _ b: Vector) -> Vector { return plus(a, b) } /// Perform vector and scalar substraction. /// /// Scalar value expands to vector dimension /// and elementwise vector substraction is performed. /// /// Alternatively, `minus(a, b)` can be executed with `a - b`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: elementwise difference of vector a and scalar b public func minus(_ a: Vector, _ b: Double) -> Vector { return vectorScalarOperation(vDSP_vsaddD, a, -b) } /// Perform vector and scalar substraction. /// /// Scalar value expands to vector dimension /// and elementwise vector substraction is performed. /// /// Alternatively, `a - b` can be executed with `minus(a, b)`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: elementwise difference of vector a and scalar b public func - (_ a: Vector, _ b: Double) -> Vector { return minus(a, b) } /// Perform scalar and vector substraction. /// /// Scalar value expands to vector dimension /// and elementwise vector addition is performed. /// /// Alternatively, `minus(a, b)` can be executed with `a - b`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: elementwise difference of scalar a and vector b public func minus(_ a: Double, _ b: Vector) -> Vector { return uminus(minus(b, a)) } /// Perform scalar and vector substraction. /// /// Scalar value expands to vector dimension /// and elementwise vector addition is performed. /// /// Alternatively, `a - b` can be executed with `minus(a, b)`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: elementwise difference of scalar a and vector b public func - (_ a: Double, _ b: Vector) -> Vector { return minus(a, b) } /// Perform vector and scalar multiplication. /// /// Scalar value expands to vector dimension /// and elementwise vector multiplication is performed. /// /// Alternatively, `times(a, b)` can be executed with `a .* b`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: elementwise product of vector a and scalar b public func times(_ a: Vector, _ b: Double) -> Vector { return vectorScalarOperation(vDSP_vsmulD, a, b) } /// Perform vector and scalar multiplication. /// /// Scalar value expands to vector dimension /// and elementwise vector multiplication is performed. /// /// Alternatively, `a .* b` can be executed with `times(a, b)`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: elementwise product of vector a and scalar b public func .* (_ a: Vector, _ b: Double) -> Vector { return times(a, b) } /// Perform scalar and vector multiplication. /// /// Scalar value expands to vector dimension /// and elementwise vector multiplication is performed. /// /// Alternatively, `times(a, b)` can be executed with `a .* b`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: elementwise product of scalar a and vector b public func times(_ a: Double, _ b: Vector) -> Vector { return times(b, a) } /// Perform scalar and vector multiplication. /// /// Scalar value expands to vector dimension /// and elementwise vector multiplication is performed. /// /// Alternatively, `a .* b` can be executed with `times(a, b)`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: elementwise product of scalar a and vector b public func .* (_ a: Double, _ b: Vector) -> Vector { return times(a, b) } /// Perform vector and scalar right division. /// /// Scalar value expands to vector dimension /// and elementwise vector right division is performed. /// /// Alternatively, `rdivide(a, b)` can be executed with `a ./ b`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: result of elementwise division of vector a by scalar b public func rdivide(_ a: Vector, _ b: Double) -> Vector { return vectorScalarOperation(vDSP_vsdivD, a, b) } /// Perform vector and scalar right division. /// /// Scalar value expands to vector dimension /// and elementwise vector right division is performed. /// /// Alternatively, `a ./ b` can be executed with `rdivide(a, b)`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: result of elementwise division of vector a by scalar b public func ./ (_ a: Vector, _ b: Double) -> Vector { return rdivide(a, b) } /// Perform scalar and vector right division. /// /// Scalar value expands to vector dimension /// and elementwise vector right division is performed. /// /// Alternatively, `rdivide(a, b)` can be executed with `a ./ b`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: result of elementwise division of scalar a by vector b public func rdivide(_ a: Double, _ b: Vector) -> Vector { let c = Vector(repeating: a, count: b.count) return rdivide(c, b) } /// Perform scalar and vector right division. /// /// Scalar value expands to vector dimension /// and elementwise vector right division is performed. /// /// Alternatively, `a ./ b` can be executed with `rdivide(a, b)`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: result of elementwise division of scalar a by vector b public func ./ (_ a: Double, _ b: Vector) -> Vector { return rdivide(a, b) } /// Perform vector and scalar left division. /// /// Scalar value expands to vector dimension /// and elementwise vector left division is performed. /// /// Alternatively, `ldivide(a, b)` can be executed with `a ./. b`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: result of elementwise division of scalar b by vector a public func ldivide(_ a: Vector, _ b: Double) -> Vector { return rdivide(b, a) } /// Perform vector and scalar left division. /// /// Scalar value expands to vector dimension /// and elementwise vector left division is performed. /// /// Alternatively, `a ./. b` can be executed with `ldivide(a, b)`. /// /// - Parameters /// - a: vector /// - b: scalar /// - Returns: result of elementwise division of scalar b by vector a public func ./. (_ a: Vector, _ b: Double) -> Vector { return ldivide(a, b) } /// Perform scalar and vector left division. /// /// Scalar value expands to vector dimension /// and elementwise vector left division is performed. /// /// Alternatively, `ldivide(a, b)` can be executed with `a ./. b`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: result of elementwise division of vector b by scalar a public func ldivide(_ a: Double, _ b: Vector) -> Vector { return rdivide(b, a) } /// Perform scalar and vector left division. /// /// Scalar value expands to vector dimension /// and elementwise vector left division is performed. /// /// Alternatively, `a ./. b` can be executed with `ldivide(a, b)`. /// /// - Parameters /// - a: scalar /// - b: vector /// - Returns: result of elementwise division of vector b by scalar a public func ./. (_ a: Double, _ b: Vector) -> Vector { return ldivide(a, b) } // MARK: - Sign operations on vector /// Absolute value of vector. /// /// - Parameters /// - a: vector /// - Returns: vector of absolute values of elements of vector a public func abs(_ a: Vector) -> Vector { return unaryVectorOperation(vDSP_vabsD, a) } /// Negation of vector. /// /// Alternatively, `uminus(a)` can be executed with `-a`. /// /// - Parameters /// - a: vector /// - Returns: vector of negated values of elements of vector a public func uminus(_ a: Vector) -> Vector { return unaryVectorOperation(vDSP_vnegD, a) } /// Negation of vector. /// /// Alternatively, `-a` can be executed with `uminus(a)`. /// /// - Parameters /// - a: vector /// - Returns: vector of negated values of elements of vector a public prefix func - (_ a: Vector) -> Vector { return uminus(a) } /// Threshold function on vector. /// /// - Parameters /// - a: vector /// - Returns: vector with values less than certain value set to 0 /// and keeps the value otherwise public func thr(_ a: Vector, _ t: Double) -> Vector { var b = zeros(a.count) var t = t vDSP_vthrD(a, 1, &t, &b, 1, vDSP_Length(a.count)) return b }
bsd-3-clause
8446a56ae9bbe909a4755264cd866b90
26.766667
71
0.629405
3.642233
false
false
false
false
dadalar/DDSpiderChart
DDSpiderChart/Classes/DDSpiderChartView.swift
1
6004
// // DDSpiderChartView.swift // DDSpiderChart // // Created by dadalar on 05/01/2017. // Copyright (c) 2017 dadalar. All rights reserved. // import UIKit @IBDesignable open class DDSpiderChartView: UIView { public var axes: [DrawableString] = [] { didSet { // When categories change, data sets should be cleaned views.forEach { $0.removeFromSuperview() } views = [] } } var views: [DDSpiderChartDataSetView] = [] // DDSpiderChartDataSetView's currently being presented @IBInspectable public var color: UIColor = .gray { didSet { setNeedsDisplay() } } @IBInspectable public var circleCount: Int = 10 { didSet { views.forEach { $0.radius = circleRadius $0.setNeedsDisplay() } } } @IBInspectable public var circleGap: CGFloat = 10 { didSet { views.forEach { $0.radius = circleRadius $0.setNeedsDisplay() } } } @IBInspectable public var endLineCircles: Bool = true { didSet { setNeedsDisplay() } } @discardableResult public func addDataSet(values: [Float], color: UIColor, animated: Bool = true) -> UIView? { guard values.count == axes.count else { return nil } let view = DDSpiderChartDataSetView(radius: circleRadius, values: values, color: color) view.frame = bounds view.autoresizingMask = [.flexibleHeight, .flexibleWidth] view.backgroundColor = .clear views.append(view) addSubview(view) if animated { view.alpha = 0 view.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 5.0, options: [], animations: { view.alpha = 1.0 view.transform = CGAffineTransform.identity }, completion: nil) } return view } public func removeDataSetView(_ view: UIView) { guard let index = views.index(where: { $0 === view }) else { return } views.remove(at: index) view.removeFromSuperview() } } // MARK: Drawing methods extension DDSpiderChartView { override open func draw(_ rect: CGRect) { let center = CGPoint(x: rect.width/2, y: rect.height/2) // Draw circles let circlesToDraw = endLineCircles ? circleCount : circleCount + 1 for i in 1...circlesToDraw { let radius = CGFloat(i) * circleGap let circlePath = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(2 * Float.pi), clockwise: true) let color = (i % 2 == 0 || i == circlesToDraw) ? self.color : self.color.withAlphaComponent(0.5) color.set() circlePath.stroke() } // Draw each data set for (index, axis) in axes.enumerated() { // Draw line let angle = CGFloat(-Float.pi / 2) - CGFloat(index) * CGFloat(2 * Float.pi) / CGFloat(axes.count) self.color.set() let linePath = UIBezierPath() linePath.move(to: center) let x = center.x + (circleRadius + circleGap) * cos(angle) let y = center.y + (circleRadius + circleGap) * sin(angle) linePath.addLine(to: CGPoint(x: x, y: y)) linePath.stroke() var circleCenter = CGPoint(x: center.x + (circleRadius) * cos(angle), y: center.y + (circleRadius) * sin(angle)) if endLineCircles { // Draw circle at the end the line circleCenter = CGPoint(x: center.x + (circleRadius + circleGap * 3/2) * cos(angle), y: center.y + (circleRadius + circleGap * 3/2) * sin(angle)) let circlePath = UIBezierPath(arcCenter: circleCenter, radius: circleGap/2, startAngle: 0, endAngle: CGFloat(2 * Float.pi), clockwise: true) circlePath.stroke() } // Draw axes label let isOnTop = sin(angle) < 0 // we should draw text on top of the circle when circle is on the upper half. (and vice versa) let isOnLeft = cos(angle) < 0 // we should draw text on left of the circle when circle is on the left half. (and vice versa) let categoryStringSize = axis.size() let categoryStringPadding = circleGap/2 + 5 if endLineCircles { let categoryStringOrigin = CGPoint(x: circleCenter.x - categoryStringSize.width/2, y: circleCenter.y+(isOnTop ? (-(categoryStringSize.height+categoryStringPadding)) : (categoryStringPadding))) axis.drawDrawable(with: .init(origin: categoryStringOrigin, size: categoryStringSize)) } else { let categoryStringOrigin = CGPoint(x: circleCenter.x-(index == 0 ? categoryStringSize.width/2 : (isOnLeft ? categoryStringSize.width+categoryStringPadding : -categoryStringPadding)), y: circleCenter.y+(isOnTop ? (-(categoryStringSize.height+categoryStringPadding)) : (categoryStringPadding))) axis.drawDrawable(with: .init(origin: categoryStringOrigin, size: categoryStringSize)) } } } } // MARK: Computational properties & helper methods extension DDSpiderChartView { fileprivate var circleRadius: CGFloat { return CGFloat(circleCount) * circleGap } override open var intrinsicContentSize: CGSize { let len = 2 * circleRadius + 100 // +100 for text return .init(width: len, height: len) } override open func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() axes = ["Axis 1", "Axis 2", "Axis 3", "Axis 4", "Axis 5"] _ = addDataSet(values: [0.7, 0.5, 0.6, 0.9, 1.0], color: .white) } }
mit
be8af10c61f9cc497d827fa4b206eb65
39.026667
308
0.588941
4.600766
false
false
false
false
TheInfiniteKind/duckduckgo-iOS
DuckDuckGo/SettingsViewController.swift
1
4889
// // SettingsViewController.swift // DuckDuckGo // // Created by Mia Alexiou on 30/01/2017. // Copyright © 2017 DuckDuckGo. All rights reserved. // import UIKit import MessageUI import Core class SettingsViewController: UITableViewController { @IBOutlet weak var omniFireOpensNewTabExperimentToggle: UISwitch! @IBOutlet weak var safeSearchToggle: UISwitch! @IBOutlet weak var regionFilterText: UILabel! @IBOutlet weak var dateFilterText: UILabel! @IBOutlet weak var versionText: UILabel! private lazy var versionProvider = Version() fileprivate lazy var groupData = GroupDataStore() override func viewDidLoad() { super.viewDidLoad() configureSafeSearchToggle() configureVersionText() configureOmniFireExperiment() } private func configureSafeSearchToggle() { safeSearchToggle.isOn = groupData.safeSearchEnabled } private func configureVersionText() { versionText.text = versionProvider.localized() } private func configureOmniFireExperiment() { omniFireOpensNewTabExperimentToggle.isOn = groupData.omniFireOpensNewTab } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) configureRegionFilter() configureDateFilter() } private func configureRegionFilter() { regionFilterText.text = currentRegionSelection().name } private func configureDateFilter() { dateFilterText.text = UserText.forDateFilter(currentDateFilter()) } @IBAction func onDonePressed(_ sender: Any) { dismiss(animated: true, completion: nil) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 && indexPath.row == 0 { launchOnboardingFlow() } if indexPath.section == 3 && indexPath.row == 0 { sendFeedback() } tableView.deselectRow(at: indexPath, animated: true) } private func launchOnboardingFlow() { let controller = OnboardingViewController.loadFromStoryboard() controller.modalTransitionStyle = .flipHorizontal present(controller, animated: true, completion: nil) } private func sendFeedback() { let appVersion = versionProvider.localized() ?? "" let device = UIDevice.current.deviceType.displayName let osName = UIDevice.current.systemName let osVersion = UIDevice.current.systemVersion let feedback = FeedbackEmail(appVersion: appVersion, device: device, osName: osName, osVersion: osVersion) guard let mail = MFMailComposeViewController.create() else { return } mail.mailComposeDelegate = self mail.setToRecipients([feedback.mailTo]) mail.setSubject(feedback.subject) mail.setMessageBody(feedback.body, isHTML: false) present(mail, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let controller = segue.destination as? RegionSelectionViewController { controller.delegate = self } if let controller = segue.destination as? DateFilterSelectionViewController { controller.delegate = self } } @IBAction func onOmniFireOpensNewTabToggled(_ sender: UISwitch) { groupData.omniFireOpensNewTab = sender.isOn } @IBAction func onSafeSearchToggled(_ sender: UISwitch) { groupData.safeSearchEnabled = sender.isOn } fileprivate func currentRegionFilter() -> RegionFilter { return RegionFilter.forKey(groupData.regionFilter) } fileprivate func currentDateFilter() -> DateFilter { return DateFilter.forKey(groupData.dateFilter) } } extension SettingsViewController: RegionSelectionDelegate { func currentRegionSelection() -> RegionFilter { return currentRegionFilter() } func onRegionSelected(region: RegionFilter) { groupData.regionFilter = region.filter } } extension SettingsViewController: DateFilterSelectionDelegate { func currentDateFilterSelection() -> DateFilter { return currentDateFilter() } func onDateFilterSelected(dateFilter: DateFilter) { let value = (dateFilter == .any) ? nil : dateFilter.rawValue groupData.dateFilter = value } } extension SettingsViewController: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } } extension MFMailComposeViewController { static func create() -> MFMailComposeViewController? { return MFMailComposeViewController() } }
apache-2.0
45d9ecbd7142a45b90f08e4a396e06d7
30.947712
133
0.686375
5.347921
false
true
false
false
samodom/TestableUIKit
TestableUIKit/UIResponder/UIView/UITableView/UITableViewReloadSectionIndexTitlesSpy.swift
1
1961
// // UITableViewReloadSectionIndexTitlesSpy.swift // TestableUIKit // // Created by Sam Odom on 2/22/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import FoundationSwagger import TestSwagger public extension UITableView { private static let reloadSectionIndexTitlesCalledString = UUIDKeyString() private static let reloadSectionIndexTitlesCalledKey = ObjectAssociationKey(reloadSectionIndexTitlesCalledString) private static let reloadSectionIndexTitlesCalledReference = SpyEvidenceReference(key: reloadSectionIndexTitlesCalledKey) /// Spy controller for ensuring a table view has had `reloadSectionIndexTitles` called on it. public enum ReloadSectionIndexTitlesSpyController: SpyController { public static let rootSpyableClass: AnyClass = UITableView.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(UITableView.reloadSectionIndexTitles), spy: #selector(UITableView.spy_reloadSectionIndexTitles) ) ] as Set public static let evidence = [reloadSectionIndexTitlesCalledReference] as Set public static let forwardsInvocations = true } /// Spy method that replaces the true implementation of `reloadSectionIndexTitles` public func spy_reloadSectionIndexTitles() { reloadSectionIndexTitlesCalled = true spy_reloadSectionIndexTitles() } /// Indicates whether the `reloadSectionIndexTitles` method has been called on this object. public final var reloadSectionIndexTitlesCalled: Bool { get { return loadEvidence(with: UITableView.reloadSectionIndexTitlesCalledReference) as? Bool ?? false } set { saveEvidence(true, with: UITableView.reloadSectionIndexTitlesCalledReference) } } }
mit
c0b8be43b512b5a0351106fe98bef391
34.636364
108
0.717347
6.343042
false
false
false
false
con-beo-vang/Spendy
Spendy/View Controllers/RootTabBarController.swift
1
1379
// // RootTabBarController.swift // Spendy // // Created by Harley Trung on 9/17/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit import SwiftSpinner class RootTabBarController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. SwiftSpinner.hide() // print("RootTabBarController:viewDidLoad") dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { // Call with true to reset data DataManager.setupDefaultData(false) } // Replace the Settings placeholder controller // Load Settings storyboard's initial controller let storyboard = UIStoryboard(name: "Settings", bundle: nil) let settingsController = storyboard.instantiateInitialViewController() as! UINavigationController if var tabControllers = self.viewControllers { assert(tabControllers[2] is SettingsViewController, "Expecting the 3rd tab is SettingsController") tabControllers[2] = settingsController self.setViewControllers(tabControllers, animated: true) } else { print("Error hooking up Settings tab", terminator: "") } } override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { if item.title == "Add" { tabBar.hidden = true } } }
mit
156e65dcc032a0ca0657d45dad95f6f9
28.340426
104
0.700508
4.788194
false
false
false
false
stuart-grey/shinobicharts-style-guide
case-studies/StyleGuru/StyleGuru/sparklines/SparkData.swift
1
2289
// // Copyright 2015 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation struct HealthSpark { let date: NSDate let flights: Int let steps: Int let walkingDistance: Double let cyclingDistance: Double } extension HealthSpark { private init?(dict: [String : AnyObject]) { if let date = dict["date"] as? NSDate, let flights = dict["flights"] as? Int, let steps = dict["steps"] as? Int, let walkingDistance = dict["walkingDistance"] as? Double, let cyclingDistance = dict["cyclingDistance"] as? Double { self.init(date: date, flights: flights, steps: steps, walkingDistance: walkingDistance, cyclingDistance: cyclingDistance) } else { return nil } } } extension HealthSpark { static func loadDataFromPlistNamed(name: String) -> [HealthSpark]? { if let path = NSBundle.mainBundle().pathForResource(name, ofType: "plist"), let array = NSArray(contentsOfFile: path) as? [[String: AnyObject]] { return array.map { HealthSpark(dict: $0)! } } return .None } static func loadDataFromDefaultPlist() -> [HealthSpark]? { return HealthSpark.loadDataFromPlistNamed("healthspark") } } extension HealthSpark { func flightsDataPoint() -> SChartData { return generateDataPoint(flights) } func stepsDataPoint() -> SChartData { return generateDataPoint(steps) } func walkingDistanceDataPoint() -> SChartData { return generateDataPoint(walkingDistance) } func cyclingDistanceDataPoint() -> SChartData { return generateDataPoint(cyclingDistance) } private func generateDataPoint(yValue: AnyObject) -> SChartData { let dp = SChartDataPoint() dp.xValue = date dp.yValue = yValue return dp } }
apache-2.0
1e0e32f86e3fb69a02158ec044f5468e
27.6125
80
0.695937
4.393474
false
false
false
false
roecrew/AudioKit
AudioKit/Common/MIDI/Sequencer/AKMusicTrack.swift
2
11297
// // AKMusicTrack.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation /// Wrapper for internal Apple MusicTrack public class AKMusicTrack { // MARK: - Properties /// The representation of Apple's underlying music track public var internalMusicTrack: MusicTrack = nil private var name: String = "Unnamed" /// Sequencer this music track is part of public var sequencer = AKSequencer() /// Pointer to the Music Track public var trackPointer: UnsafeMutablePointer<MusicTrack> /// Total duration of the music track public var length: MusicTimeStamp { var size: UInt32 = 0 var lengthFromMusicTimeStamp = MusicTimeStamp(0) MusicTrackGetProperty(internalMusicTrack, kSequenceTrackProperty_TrackLength, &lengthFromMusicTimeStamp, &size) return lengthFromMusicTimeStamp } // MARK: - Initialization /// Initialize with nothing /// /// - parameter musicTrack: An Apple Music Track /// public init() { trackPointer = UnsafeMutablePointer<MusicTrack>(internalMusicTrack) } /// Initialize with a music track /// /// - parameter musicTrack: An Apple Music Track /// public convenience init(musicTrack: MusicTrack, name: String = "Unnamed") { self.init() self.name = name internalMusicTrack = musicTrack trackPointer = UnsafeMutablePointer<MusicTrack>(internalMusicTrack) let data = [UInt8](name.utf8) var metaEvent = MIDIMetaEvent() metaEvent.metaEventType = 3 // track or sequence name metaEvent.dataLength = UInt32(data.count) withUnsafeMutablePointer(&metaEvent.data, { ptr in for i in 0 ..< data.count { ptr[i] = data[i] } }) let result = MusicTrackNewMetaEvent(internalMusicTrack, MusicTimeStamp(0), &metaEvent) if result != 0 { print("Unable to name Track") } } /// Initialize with a music track and the AKSequence /// /// - parameter musicTrack: An Apple Music Track /// public convenience init(musicTrack: MusicTrack, sequencer: AKSequencer) { self.init() internalMusicTrack = musicTrack trackPointer = UnsafeMutablePointer<MusicTrack>(internalMusicTrack) self.sequencer = sequencer } /// Set the Node Output /// /// - parameter node: Apple AUNode for output /// public func setNodeOutput(node: AUNode) { MusicTrackSetDestNode(internalMusicTrack, node) } /// Set loop info /// /// - parameter duration: How long the loop will last, from the end of the track backwards /// - paramter numberOfLoops: how many times to loop. 0 is infinte /// public func setLoopInfo(duration: AKDuration, numberOfLoops: Int) { let size: UInt32 = UInt32(sizeof(MusicTrackLoopInfo)) let loopDuration = duration.musicTimeStamp var loopInfo = MusicTrackLoopInfo(loopDuration: loopDuration, numberOfLoops: Int32(numberOfLoops)) MusicTrackSetProperty(internalMusicTrack, kSequenceTrackProperty_LoopInfo, &loopInfo, size) } /// Set length /// If any of your notes are longer than the new length, this will truncate those notes /// This will truncate your sequence if you shorten it - so make a copy if you plan on doing that. /// /// - parameter duration: How long the loop will last, from the end of the track backwards /// public func setLength(duration: AKDuration) { let size: UInt32 = 0 var len = duration.musicTimeStamp var tmpSeq: MusicSequence = nil var seqPtr: UnsafeMutablePointer<MusicSequence> var tmpTrack: MusicTrack = nil seqPtr = UnsafeMutablePointer<MusicSequence>(tmpSeq) NewMusicSequence(&tmpSeq) MusicTrackGetSequence(internalMusicTrack, seqPtr) MusicSequenceNewTrack(tmpSeq, &tmpTrack) MusicTrackSetProperty(tmpTrack, kSequenceTrackProperty_TrackLength, &len, size) if !isEmpty { MusicTrackCopyInsert(internalMusicTrack, 0, len, tmpTrack, 0) clear() MusicTrackSetProperty(internalMusicTrack, kSequenceTrackProperty_TrackLength, &len, size) MusicTrackCopyInsert(tmpTrack, 0, len, internalMusicTrack, 0) MusicSequenceDisposeTrack(tmpSeq, tmpTrack) DisposeMusicSequence(tmpSeq) //now to clean up any notes that are too long var iterator: MusicEventIterator = nil NewMusicEventIterator(internalMusicTrack, &iterator) var eventTime = MusicTimeStamp(0) var eventType = MusicEventType() var eventData: UnsafePointer<Void> = nil var eventDataSize: UInt32 = 0 var hasNextEvent: DarwinBoolean = false MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) while(hasNextEvent) { MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize) if eventType == kMusicEventType_MIDINoteMessage { let data = UnsafePointer<MIDINoteMessage>(eventData) let channel = data.memory.channel let note = data.memory.note let velocity = data.memory.velocity let dur = data.memory.duration if eventTime + dur > duration.beats { var newNote = MIDINoteMessage(channel: channel, note: note, velocity: velocity, releaseVelocity: 0, duration: Float32(duration.beats - eventTime)) MusicEventIteratorSetEventInfo(iterator, eventType, &newNote) } } MusicEventIteratorNextEvent(iterator) MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) } DisposeMusicEventIterator(iterator) } else { MusicTrackSetProperty(internalMusicTrack, kSequenceTrackProperty_TrackLength, &len, size) } } /// A less destructive and simpler way to set the length /// /// - parameter duration: How long the loop will last, from the end of the track backwards /// public func setLengthSoft(duration: AKDuration) { let size: UInt32 = 0 var len = duration.musicTimeStamp MusicTrackSetProperty(internalMusicTrack, kSequenceTrackProperty_TrackLength, &len, size) } /// Clear all events from the track public func clear() { clearMetaEvents() if !isEmpty { MusicTrackClear(internalMusicTrack, 0, length) } } func clearMetaEvents(){ var iterator: MusicEventIterator = nil NewMusicEventIterator(internalMusicTrack, &iterator) var eventTime = MusicTimeStamp(0) var eventType = MusicEventType() var eventData: UnsafePointer<Void> = nil var eventDataSize: UInt32 = 0 var hasNextEvent: DarwinBoolean = false MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) while(hasNextEvent) { MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize) if eventType == 5 { MusicEventIteratorDeleteEvent(iterator) } MusicEventIteratorNextEvent(iterator) MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) } } public var isEmpty : Bool{ var outBool = true var iterator: MusicEventIterator = nil NewMusicEventIterator(internalMusicTrack, &iterator) var eventTime = MusicTimeStamp(0) var eventType = MusicEventType() var eventData: UnsafePointer<Void> = nil var eventDataSize: UInt32 = 0 var hasNextEvent: DarwinBoolean = false MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) while(hasNextEvent) { MusicEventIteratorGetEventInfo(iterator, &eventTime, &eventType, &eventData, &eventDataSize) outBool = false //print("time is \(eventTime) - type is \(eventType)") //print("data is \(eventData)") MusicEventIteratorNextEvent(iterator) MusicEventIteratorHasCurrentEvent(iterator, &hasNextEvent) } return outBool } /// Clear some events from the track /// /// - Parameters: /// - start: Start of the range to clear, in beats /// - duration: Duration of the range to clear, in beats /// public func clearRange(start start: AKDuration, duration: AKDuration) { if !isEmpty { MusicTrackClear(internalMusicTrack, start.beats, duration.beats) } } /// Add Note to sequence /// /// - Parameters: /// - noteNumber: The midi note number to insert /// - velocity: The velocity to insert note at /// - position: Where in the sequence to start the note (expressed in beats) /// - duration: How long to hold the note (would be better if they let us just use noteOffs...oh well) /// - channel: MIDI channel for this note /// public func add(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, position: AKDuration, duration: AKDuration, channel: MIDIChannel = 0) { var noteMessage = MIDINoteMessage( channel: UInt8(channel), note: UInt8(noteNumber), velocity: UInt8(velocity), releaseVelocity: 0, duration: Float32(duration.beats)) MusicTrackNewMIDINoteEvent(internalMusicTrack, position.musicTimeStamp, &noteMessage) } /// Add Controller change to sequence /// /// - Parameters: /// - controller: The midi controller to insert /// - value: The velocity to insert note at /// - position: Where in the sequence to start the note (expressed in beats) /// - channel: MIDI channel for this note /// public func addController(controller: Int, value: Int, position: AKDuration, channel: MIDIChannel = 0) { var controlMessage = MIDIChannelMessage(status: UInt8(11 << 4) | UInt8((channel) & 0xf), data1: UInt8(controller), data2: UInt8(value), reserved: 0) MusicTrackNewMIDIChannelEvent(internalMusicTrack, position.musicTimeStamp, &controlMessage) } /// Set the MIDI Ouput /// /// - parameter endpoint: MIDI Endpoint Port /// public func setMIDIOutput(endpoint: MIDIEndpointRef) { MusicTrackSetDestMIDIEndpoint(internalMusicTrack, endpoint) } /// Debug by showing the track pointer. public func debug() { CAShow(trackPointer) } }
mit
cf4484232d789ba57c261270e2b2b048
36.779264
170
0.616678
5.338374
false
false
false
false
jlainog/Messages
Messages/Messages/ChatViewController.swift
1
5033
// // ChatViewController.swift // Messages // // Created by Stephany Lara Jimenez on 3/8/17. // Copyright © 2017 JLainoG. All rights reserved. // import UIKit import Firebase import JSQMessagesViewController final class ChatViewController: JSQMessagesViewController { // MARK: Variable Definitions private var messages: [Message] = [] lazy var outgoingBubbleImageView: JSQMessagesBubbleImage = self.setupOutgoingBubble() lazy var incomingBubbleImageView: JSQMessagesBubbleImage = self.setupIncomingBubble() var user: User! var channel: Channel! { didSet { title = channel.name } } // MARK: DataSource & Delegate override func viewDidLoad() { super.viewDidLoad() self.senderId = user.identifier self.senderDisplayName = user.name collectionView!.collectionViewLayout.incomingAvatarViewSize = CGSize.zero collectionView!.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero configureObserver() } //TODO - Handle nils func configureObserver() { ChatFacade.observeMessages(byListingLast: 25, channelId: channel.id!) { [weak self] message in self?.messages.append(message) JSQSystemSoundPlayer.jsq_playMessageReceivedAlert() self?.finishReceivingMessage() } } private func setupOutgoingBubble() -> JSQMessagesBubbleImage { let bubbleImageFactory = JSQMessagesBubbleImageFactory() return bubbleImageFactory!.outgoingMessagesBubbleImage(with: UIColor.jsq_messageBubbleBlue()) } private func setupIncomingBubble() -> JSQMessagesBubbleImage { let bubbleImageFactory = JSQMessagesBubbleImageFactory() return bubbleImageFactory!.incomingMessagesBubbleImage(with: UIColor.jsq_messageBubbleLightGray()) } override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { addMessage(withId: self.senderId, name: self.senderDisplayName, text: text) JSQSystemSoundPlayer.jsq_playMessageSentSound() finishSendingMessage() } override func didPressAccessoryButton(_ sender: UIButton!) { let refreshAlert = UIAlertController(title: "Function not yet implemented", message: "This functionality is not yet implemented in the application.", preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(refreshAlert, animated: true, completion: nil) } deinit { ChatFacade.removeAllObservers() } // MARK: Private Function private func addMessage(withId id: String, name: String, text: String) { let message = Message(userId: id, userName: name, message: text) ChatFacade.createMessage(channelId: (channel.id!), message: message) } // MARK: CollectionView Functions override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { return messages[indexPath.item] } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat { return 15 } override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { let message = messages[indexPath.item] if message.userId == senderId { return outgoingBubbleImageView } else { return incomingBubbleImageView } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = super.collectionView(collectionView, cellForItemAt: indexPath) as! JSQMessagesCollectionViewCell let message = messages[indexPath.item] if message.userId == senderId { cell.textView?.textColor = UIColor.white } else { cell.textView?.textColor = UIColor.blue } return cell } override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { let message = messages[indexPath.item] guard let senderDisplayName = message.senderDisplayName() else { return nil } return NSAttributedString(string: senderDisplayName) } }
mit
cd8c296c451b8c1f133abf1419c888f0
37.121212
214
0.678259
5.976247
false
false
false
false
modocache/swift
test/DebugInfo/return.swift
2
992
// RUN: %target-swift-frontend %s -g -emit-ir -o - | %FileCheck %s class X { init (i : Int64) { x = i } var x : Int64 } // CHECK: define {{.*}}ifelseexpr public func ifelseexpr() -> Int64 { var x = X(i:0) // CHECK: [[META:%.*]] = call %swift.type* @_TMaC6return1X() // CHECK: [[X:%.*]] = call %C6return1X* @_TFC6return1XCfT1iVs5Int64_S0_( // CHECK-SAME: i64 0, %swift.type* [[META]]) // CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) if true { x.x += 1 } else { x.x -= 1 } // CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) // CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) // CHECK-SAME: , !dbg ![[RELEASE:.*]] // The ret instruction should be in the same scope as the return expression. // CHECK: ret{{.*}}, !dbg ![[RELEASE]] return x.x // CHECK: ![[RELEASE]] = !DILocation(line: [[@LINE]], column: 3 }
apache-2.0
aef32fd2b75f21eec7473347e510fd21
34.428571
81
0.544355
2.934911
false
false
false
false
maxim-pervushin/HyperHabit
HyperHabit/HyperHabit/Data/ReportsByDateDataSource.swift
1
1836
// // Created by Maxim Pervushin on 19/11/15. // Copyright (c) 2015 Maxim Pervushin. All rights reserved. // import Foundation class ReportsByDateDataSource: DataSource { var date = NSDate() { didSet { changesObserver?.observableChanged(self) } } var hasPreviousDate: Bool { return date.dateComponent != NSDate(timeIntervalSince1970: 0).dateComponent } var hasNextDate: Bool { return date.dateComponent != NSDate().dateComponent } func previousDate() { date = date.dateByAddingDays(-1) } func nextDate() { date = date.dateByAddingDays(1) } var reports: [Report] { let habits = dataProvider.habits var reports = dataProvider.reportsForDate(date) for habit in habits { var createReport = true for report in reports { // TODO: Find better solution if report.habitName == habit.name && report.habitDefinition == habit.definition { createReport = false break; } } if createReport { reports.append(Report(habit: habit, repeatsDone: 0, date: date)) } } return reports.sort({ $0.habitName > $1.habitName }) } var completedReports: [Report] { return reports.filter { return $0.completed } } var incompletedReports: [Report] { return reports.filter { return !$0.completed } } func saveReport(report: Report) -> Bool { dataProvider.saveReport(report) let otherReports = reports.filter({ $0 != report }) for otherReport in otherReports { dataProvider.saveReport(otherReport) } return true } }
mit
b8783b43cfd6a4b5d0b3d9b17f9cedd4
24.859155
97
0.564815
4.768831
false
false
false
false
autonaviapi/navigation_swiftDemo
AMapDemoSwift/NaviViewController.swift
1
10891
// // NaviViewController.swift // AMapDemoSwift // // Created by 王菲 on 15-2-6. // Copyright (c) 2015年 autonavi. All rights reserved. // import UIKit class NaviViewController: UIViewController ,MAMapViewDelegate,AMapNaviManagerDelegate,AMapNaviViewControllerDelegate,IFlySpeechSynthesizerDelegate{ var annotations: NSArray? var calRouteSuccess: Bool? var polyline: MAPolyline? var startPoint: AMapNaviPoint? var endPoint: AMapNaviPoint? var mapView: MAMapView? var iFlySpeechSynthesizer: IFlySpeechSynthesizer? var naviManager: AMapNaviManager? var naviViewController: AMapNaviViewController? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. navigationController?.toolbar.barStyle = UIBarStyle.Black navigationController?.toolbar.translucent = true navigationController?.setToolbarHidden(false, animated: true); initToolBar() configMapView() initNaviManager() initAnnotations() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { startPoint = AMapNaviPoint.locationWithLatitude(39.989614, longitude: 116.481763); endPoint = AMapNaviPoint.locationWithLatitude(39.983456, longitude: 116.315495) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } func configSubViews() { var startPointLabel = UILabel(frame: CGRectMake(0, 100, 320, 20)) startPointLabel.textAlignment = NSTextAlignment.Center startPointLabel.font = UIFont.systemFontOfSize(14) let startLatitude = startPoint?.latitude.description let startLongitude = startPoint?.longitude.description startPointLabel.text = "起点:" + startLatitude! + "," + startLongitude! view.addSubview(startPointLabel) var endPointLabel = UILabel(frame: CGRectMake(0, 130, 320, 20)) endPointLabel.textAlignment = NSTextAlignment.Center endPointLabel.font = UIFont.systemFontOfSize(14) let endLatitude = endPoint?.latitude.description let endLongitude = endPoint?.longitude.description endPointLabel.text = "终点:" + endLatitude! + "," + endLongitude! view.addSubview(endPointLabel) var startBtn = UIButton.buttonWithType(UIButtonType.Custom) as UIButton startBtn.layer.borderColor = UIColor.lightGrayColor().CGColor startBtn.layer.borderWidth = 0.5 startBtn.layer.cornerRadius = 5 startBtn.frame = CGRectMake(60, 160, 200, 30) startBtn.setTitle("模拟导航", forState: UIControlState.Normal) startBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) startBtn.titleLabel?.font = UIFont.systemFontOfSize(14.0) startBtn.addTarget(self, action: "startSimuNavi", forControlEvents: UIControlEvents.TouchUpInside) view.addSubview(startBtn) } func initAnnotations(){ let star = MAPointAnnotation() star.coordinate = CLLocationCoordinate2DMake(39.989614,116.481763) star.title = "Start" mapView!.addAnnotation(star) let end = MAPointAnnotation() end.coordinate = CLLocationCoordinate2DMake(39.983456, 116.315495) end.title = "End" mapView!.addAnnotation(end) annotations = [star,end] } func initToolBar() { let flexbleItem : UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let calcroute: UIBarButtonItem = UIBarButtonItem(title: "路径规划", style: UIBarButtonItemStyle.Bordered, target: self, action: "calculateRoute") let simunavi: UIBarButtonItem = UIBarButtonItem(title: "模拟导航", style: UIBarButtonItemStyle.Bordered, target: self, action: "startSimuNavi") setToolbarItems([flexbleItem,calcroute,flexbleItem,simunavi,flexbleItem], animated: false) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configMapView(){ mapView = MAMapView(frame: self.view.bounds) mapView!.delegate = self view.insertSubview(mapView!, atIndex: 0) if calRouteSuccess == true { mapView!.addOverlay(polyline) } if(annotations?.count > 0){ mapView!.addAnnotations(annotations) } } func initIFlySpeech(){ iFlySpeechSynthesizer = IFlySpeechSynthesizer.sharedInstance() as? IFlySpeechSynthesizer iFlySpeechSynthesizer?.delegate = self } func initNaviManager(){ if (naviManager == nil) { naviManager = AMapNaviManager() naviManager?.delegate = self } } func initNaviViewController(){ if(naviViewController == nil){ naviViewController = AMapNaviViewController(mapView: mapView!, delegate: self) } } // 模拟导航 func startSimuNavi() { if (calRouteSuccess == true) { initNaviViewController() naviManager?.presentNaviViewController(naviViewController!, animated: true) } else { var alert = UIAlertView(title: "请先进行路线规划", message: nil, delegate: nil, cancelButtonTitle: "确定") alert.show() } } // 路径规划 func calculateRoute(){ var startPoints = [AMapNaviPoint]() var endPoints = [AMapNaviPoint]() startPoints.append(startPoint!) endPoints.append(endPoint!) var count1 = startPoints.count // 步行路径规划 // naviManager?.calculateWalkRouteWithStartPoints(startPoints, endPoints: endPoints) // 驾车路径规划 naviManager?.calculateDriveRouteWithStartPoints(startPoints, endPoints: endPoints, wayPoints: nil, drivingStrategy: AMapNaviDrivingStrategy.Default) } // 展示规划路径 func showRouteWithNaviRoute(naviRoute: AMapNaviRoute) { if polyline != nil { mapView!.removeOverlay(polyline!) polyline = nil } let coordianteCount: Int = naviRoute.routeCoordinates.count var coordinates: [CLLocationCoordinate2D] = [] for var i = 0; i < coordianteCount; i++ { var aCoordinate: AMapNaviPoint = naviRoute.routeCoordinates[i] as AMapNaviPoint coordinates.append(CLLocationCoordinate2DMake(Double(aCoordinate.latitude), Double(aCoordinate.longitude))) } polyline = MAPolyline(coordinates:&coordinates, count: UInt(coordianteCount)) mapView!.addOverlay(polyline) } // MAMapViewDelegate func mapView(mapView: MAMapView!, viewForOverlay overlay: MAOverlay!) -> MAOverlayView! { if overlay.isKindOfClass(MAPolyline) { let polylineView: MAPolylineView = MAPolylineView(overlay: overlay) polylineView.lineWidth = 5.0 polylineView.strokeColor = UIColor.redColor() return polylineView } return nil } func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! { if annotation.isKindOfClass(MAPointAnnotation) { let annotationIdentifier = "annotationIdentifier" var poiAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier) as? MAPinAnnotationView if poiAnnotationView == nil { poiAnnotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier) } poiAnnotationView!.animatesDrop = true poiAnnotationView!.canShowCallout = true return poiAnnotationView; } return nil } // AMapNaviManagerDelegate // 算路成功回调 func naviManagerOnCalculateRouteSuccess(naviManager: AMapNaviManager!) { println("success") showRouteWithNaviRoute(naviManager.naviRoute); calRouteSuccess = true } // 展示导航视图回调 func naviManager(naviManager: AMapNaviManager!, didPresentNaviViewController naviViewController: UIViewController!) { println("success") initIFlySpeech() naviManager.startEmulatorNavi() } // 导航播报信息回调 func naviManager(naviManager: AMapNaviManager!, playNaviSoundString soundString: String!, soundStringType: AMapNaviSoundType) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),{ self.iFlySpeechSynthesizer?.startSpeaking(soundString) println("start speak"); }); } // AMapNaviViewControllerDelegate // 导航界面关闭按钮点击的回调 func naviViewControllerCloseButtonClicked(naviViewController: AMapNaviViewController!) { iFlySpeechSynthesizer?.stopSpeaking() iFlySpeechSynthesizer?.delegate = nil iFlySpeechSynthesizer = nil naviManager?.stopNavi() naviManager?.dismissNaviViewControllerAnimated(true) configMapView() } // 导航界面更多按钮点击的回调 func naviViewControllerMoreButtonClicked(naviViewController: AMapNaviViewController!) { if naviViewController.viewShowMode == AMapNaviViewShowMode.CarNorthDirection { naviViewController.viewShowMode = AMapNaviViewShowMode.MapNorthDirection } else { naviViewController.viewShowMode = AMapNaviViewShowMode.CarNorthDirection } } // 导航界面转向指示View点击的回调 func naviViewControllerTurnIndicatorViewTapped(naviViewController: AMapNaviViewController!){ naviManager?.readNaviInfoManual() } // IFlySpeechSynthesizerDelegate func onCompleted(error: IFlySpeechError!) { println("IFly error\(error)") } }
mit
e4a64e38c055f7de8878b93f00392d1f
31.009009
156
0.628671
5.548673
false
false
false
false
mathsandphysics/Steps
Steps/Steps/BaseCore/JLHBaseUI/JLHPopover/PopoverAnimator.swift
1
3104
// // PopoverAnimator.swift // Steps // // Created by mathsandphysics on 2017/1/20. // Copyright © 2017年 Utopia. All rights reserved. // import UIKit class PopoverAnimator: NSObject { /** 标识present状态 */ var isPresented = false var presentFrame = CGRect.zero var animationDuration = 0.5 var closure : ((_ isPresented : Bool) -> ())? } // MARK: - 自定义转场代理人 extension PopoverAnimator : UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let presentation = JLHPopoverPresentationController(presentedViewController: presented, presenting: presenting) presentation.presentedFrame = presentFrame return presentation } // MARK: - 实现弹出动画的对象 func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = true closure!(isPresented) return self } // MARK: - 实现消失动画的对象 func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresented = false closure!(isPresented) return self } } // MARK: - 转场动画弹出和消失的方法 extension PopoverAnimator : UIViewControllerAnimatedTransitioning { // MARK: - 动画执行时间 func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return animationDuration } // MARK: - 通过转场上下文获取弹出的view和消失的view func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { isPresented ? presentedAnimation(using: transitionContext) : dismissAnimation(using: transitionContext) } } extension PopoverAnimator { func presentedAnimation(using transitionContext: UIViewControllerContextTransitioning) { let presentedView = transitionContext.view(forKey: .to)! transitionContext.containerView.addSubview(presentedView) presentedView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0) presentedView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0) UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { presentedView.transform = CGAffineTransform.identity }) { (_) in transitionContext.completeTransition(true) } } func dismissAnimation(using transitionContext: UIViewControllerContextTransitioning) { let dismissView = transitionContext.view(forKey: .from)! UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { dismissView.transform = CGAffineTransform(scaleX: 1.0, y: 0.0001) }) { (_) in dismissView.removeFromSuperview() transitionContext.completeTransition(true) } } }
apache-2.0
38401a38ad43f9c2f21dfcf43fdf8bab
37.115385
170
0.716112
5.609434
false
false
false
false
tellowkrinkle/Sword
Sources/Sword/Types/Channel.swift
1
6576
// // Channel.swift // Sword // // Created by Alejandro Alonso // Copyright © 2017 Alejandro Alonso. All rights reserved. // import Foundation /// Generic Channel structure public protocol Channel { // MARK: Properties /// Parent class weak var sword: Sword? { get } /// The id of the channel var id: ChannelID { get } /// Indicates what type of channel this is var type: ChannelType { get } } public extension Channel { // MARK: Functions /// Deletes the current channel, whether it be a DMChannel or GuildChannel func delete(then completion: @escaping (Channel?, RequestError?) -> () = {_ in}) { self.sword?.deleteChannel(self.id, then: completion) } } /// Used to distinguish channels that are pure text base and voice channels public protocol TextChannel: Channel { // MARK: Properties /// The last message's id var lastMessageId: MessageID? { get } } public extension TextChannel { // MARK: Functions /** Adds a reaction (unicode or custom emoji) to message - parameter reaction: Unicode or custom emoji reaction - parameter messageId: Message to add reaction to */ func addReaction(_ reaction: String, to messageId: MessageID, then completion: @escaping (RequestError?) -> () = {_ in}) { self.sword?.addReaction(reaction, to: messageId, in: self.id, then: completion) } /** Deletes a message from this channel - parameter messageId: Message to delete */ func deleteMessage(_ messageId: MessageID, then completion: @escaping (RequestError?) -> () = {_ in}) { self.sword?.deleteMessage(messageId, from: self.id, then: completion) } /** Bulk deletes messages - parameter messages: Array of message ids to delete */ func deleteMessages(_ messages: [MessageID], then completion: @escaping (RequestError?) -> () = {_ in}) { self.sword?.deleteMessages(messages, from: self.id, then: completion) } /** Deletes a reaction from message by user - parameter reaction: Unicode or custom emoji to delete - parameter messageId: Message to delete reaction from - parameter userId: If nil, deletes bot's reaction from, else delete a reaction from user */ func deleteReaction(_ reaction: String, from messageId: MessageID, by userId: UserID? = nil, then completion: @escaping (RequestError?) -> () = {_ in}) { self.sword?.deleteReaction(reaction, from: messageId, by: userId, in: self.id, then: completion) } /** Edits a message's content - parameter messageId: Message to edit - parameter content: Text to change message to */ func editMessage(_ messageId: MessageID, with options: [String: Any], then completion: @escaping (Message?, RequestError?) -> () = {_ in}) { self.sword?.editMessage(messageId, with: options, in: self.id, then: completion) } /** Gets a message from this channel - parameter messageId: Id of message you want to get **/ func getMessage(_ messageId: MessageID, then completion: @escaping (Message?, RequestError?) -> ()) { self.sword?.getMessage(messageId, from: self.id, then: completion) } /** Gets an array of messages from this channel #### Option Params #### - **around**: Message Id to get messages around - **before**: Message Id to get messages before this one - **after**: Message Id to get messages after this one - **limit**: Number of how many messages you want to get (1-100) - parameter options: Dictionary containing optional options regarding how many messages, or when to get them **/ func getMessages(with options: [String: Any]? = nil, then completion: @escaping ([Message]?, RequestError?) -> ()) { self.sword?.getMessages(from: self.id, with: options, then: completion) } /** Gets an array of users who used reaction from message - parameter reaction: Unicode or custom emoji to get - parameter messageId: Message to get reaction users from */ func getReaction(_ reaction: String, from messageId: MessageID, then completion: @escaping ([User]?, RequestError?) -> ()) { self.sword?.getReaction(reaction, from: messageId, in: self.id, then: completion) } /// Get Pinned messages for this channel func getPinnedMessages(then completion: @escaping ([Message]?, RequestError?) -> () = {_ in}) { self.sword?.getPinnedMessages(from: self.id, then: completion) } /** Pins a message to this channel - parameter messageId: Message to pin */ func pin(_ messageId: MessageID, then completion: @escaping (RequestError?) -> () = {_ in}) { self.sword?.pin(messageId, in: self.id, then: completion) } /** Sends a message to channel - parameter message: String to send as message */ func send(_ message: String, then completion: @escaping (Message?, RequestError?) -> () = {_ in}) { self.sword?.send(message, to: self.id, then: completion) } /** Sends a message to channel - parameter message: Dictionary containing info on message to send */ func send(_ message: [String: Any], then completion: @escaping (Message?, RequestError?) -> () = {_ in}) { self.sword?.send(message, to: self.id, then: completion) } /** Sends a message to channel - parameter message: Embed to send as message */ func send(_ message: Embed, then completion: @escaping (Message?, RequestError?) -> () = {_ in}) { self.sword?.send(message, to: self.id, then: completion) } /** Unpins a pinned message from this channel - parameter messageId: Pinned message to unpin */ func unpin(_ messageId: MessageID, then completion: @escaping (RequestError?) -> () = {_ in}) { self.sword?.unpin(messageId, from: self.id, then: completion) } } /// Distinguishes Guild channels over dm type channels public protocol GuildChannel: Channel { // MARK: Properties /// Guild this channel belongs to weak var guild: Guild? { get } /// Name of the channel var name: String? { get } /// Collection of overwrites mapped by `OverwriteID` var permissionOverwrites: [OverwriteID: Overwrite] { get } /// Position the channel is in guild var position: Int? { get } } /// Used to indicate the type of channel public enum ChannelType: Int { /// This is a regular Guild Text Channel (`GuildChannel`) case guildText /// This is a 1 on 1 DM with a user (`DMChannel`) case dm /// This is the famous Guild Voice Channel (`GuildChannel`) case guildVoice /// This is a Group DM Channel (`GroupChannel`) case groupDM /// This is an unreleased Guild Category Channel case guildCategory }
mit
78914142d600053cd2e002e7e6dc5fba
28.352679
155
0.674981
4.233741
false
false
false
false
anyflow/Jonsnow
Jonsnow/Model/Message.swift
1
1636
// // Chat.swift // Jonsnow // // Created by Park Hyunjeong on 1/17/16. // Copyright © 2016 Anyflow. All rights reserved. // import Foundation import ObjectMapper import Realm import RealmSwift class Message: Object, Mappable { var id: String? var channelId: String? var creatorId: String? var text: String? var createDate: NSDate? var unreadCount: Int? required convenience init?(_ map: Map) { self.init() } func mapping(map: Map) { id <- map["id"] channelId <- map["channelId"] creatorId <- map["creatorId"] text <- map["text"] unreadCount <- map["unreadCount"] let transform = TransformOf<NSDate, Int>(fromJSON: { (value: Int?) -> NSDate? in guard let value = value else { return nil } return NSDate(timeIntervalSince1970: (Double)(value / 1000)) }, toJSON: { (value: NSDate?) -> Int? in guard let value = value else { return 0 } return (Int)(value.timeIntervalSince1970 * 1000) }) createDate <- (map["createDate"], transform) } override var description: String { return "\n" + "id : \(id)\n" + "channelId : \(channelId)" + "creatorId : \(creatorId)\n" + "text : \(text)\n" + "createDate : \(createDate)" + "unreadCount : \(unreadCount)" } } extension NSDate { func dateStringWithFormat(format: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format return dateFormatter.stringFromDate(self) } }
apache-2.0
6b0366d4c5619359e375c1dc518f52b2
23.787879
88
0.576758
3.997555
false
false
false
false