I am writing an app which compares a sign on time to a block of times and then takes the number of sectors and then returns a duty limit.
For example, a sign on at 0035 for two sectors returns a duty limit of 1030.
This works OK in my Playground but brings up several compiler errors when transferred to Xcode.
Starting with "Operators are only allowed at global scope".
Can anyone point me in the right direction?
This is my code so far:
let dateMaker = NSDateFormatter()
dateMaker.dateFormat = "HHmm"
let FTL1 = dateMaker.dateFromString("0800")!
let FTL2 = dateMaker.dateFromString("1259")!
let FTL3 = dateMaker.dateFromString("1300")!
let FTL4 = dateMaker.dateFromString("1759")!
let FTL5 = dateMaker.dateFromString("1800")!
let FTL6 = dateMaker.dateFromString("2159")!
let FTL7 = dateMaker.dateFromString("2200")!
let FTL8 = dateMaker.dateFromString("2359")!
let FTL9 = dateMaker.dateFromString("0000")!
let FTL10 = dateMaker.dateFromString("0759")!
let SO = dateMaker.dateFromString("0035")
var sect = 2
func <(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.compare(rhs) == .OrderedAscending
}
func >(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.compare(rhs) == .OrderedDescending
}
if SO! == FTL1 || SO! == FTL2 || SO! > FTL1 && SO! < FTL2 {
if sect == 1 {
let FTL = "1400"
}
if sect == 2 {
let FTL = "1315"
}
if sect == 3 {
let FTL = "1230"
}
}
if SO! == FTL3 || SO! == FTL4 || SO! > FTL3 && SO! < FTL4 {
if sect == 1 {
let FTL = "1300"
}
if sect == 2 {
let FTL = "1215"
}
if sect == 3 {
let FTL = "1130"
}
}
if SO! == FTL5 || SO! == FTL6 || SO! > FTL5 && SO! < FTL6 {
if sect == 1 {
let FTL = "1200"
}
if sect == 2 {
let FTL = "1115"
}
if sect == 3 {
let FTL = "1030"
}
}
if SO! == FTL7 || SO! == FTL8 || SO! > FTL7 && SO! < FTL8 {
if sect == 1 {
let FTL = "1100"
}
if sect == 2 {
let FTL = "1030"
}
if sect == 3 {
let FTL = "0930"
}
}
if SO! == FTL9 || SO! == FTL10 || SO! > FTL9 && SO! < FTL10 {
if sect == 1 {
let FTL = "1100"
}
if sect == 2 {
let FTL = "1030"
}
if sect == 3 {
let FTL = "0930"
}
}
you should write code out of class
class NewObject {
}
func >(lhs: NSDate, rhs: NSDate) -> Bool
{
return lhs.compare(rhs) == .OrderedDescending
}
Related
var colRange = getRange("Sheet1!G2:G200")
logger.log(colRange)
logger.log(colRange[0])
for(var i = 0; i < colRange.length; i++) {
if(activeCell.getColumn() == 7 && activeCell.getRow() == colRange[i] && ss.getActiveSheet().getName()=="Sheet1") {
newValue=e.value;
oldValue=e.oldValue;
if(!e.value) {
activeCell.setValue("");
}
else {
if (!e.oldValue) {
activeCell.setValue(newValue);
}
else {
activeCell.setValue(oldValue+', '+newValue);
}
}
}
}
Could anybody help with the for loop. Need it to check every row of column G to allow multiple drop down selections. If I replace colRange[i] with the specific row it does work. I assume I need to loop through each range G2, G3, G4, etc
Please explain what you are trying to
It's hard to figure out what you are trying to accomplish with you code but this is my best guess
function onEdit(e) {
const sh = e.range.getSheet();
if (e.range.columnStart == 7 && e.range.rowStart > 1 && sh.getName() == "Sheet1") {
if (!e.value) {
e.range.setValue("");//doesn't make sense it's already null
} else if (!e.oldValue) {
e.range.setValue(e.value);
} else {
e.range.setValue(oldValue + ', ' + newValue);
}
}
}
Any suggestions on how to improve the following code to make it more Functional Programming oriented. Specifically how to remove the MutableList which signifies historical states. There are two data classes: Bank, which represents a riverbank (number of missionaries and number of cannibals currently on the bank) and BankState which represents a historical state of the two banks (the source bank, target bank and boatAtSource - a boolean which indicates whether the boat is currently at the source or target bank). overloaded operator function plus adds missionaries and cannibals to a riverbank and function minus removes them from a riverbank. The boat function is the one which carries the most heft. You can call the following algorithm from fun main (app.kt) as such:
app.kt
fun main(args:Array<String>) {
val source:Bank = Bank(3,3)
val target:Bank = Bank()
source boat target
}
Bank.kt
data class Bank(val missionaries:Int=0,val cannibals:Int=0)
data class BankState(val sourceTarget:Pair<Bank,Bank>,val boatAtSource:Boolean)
operator fun Bank.plus(b:Pair<Int,Int>):Bank = Bank(this.missionaries+b.first,this.cannibals+b.second)
operator fun Bank.minus(b:Pair<Int,Int>):Bank = Bank(this.missionaries-b.first,this.cannibals-b.second)
infix fun Bank.boat(target:Bank):List<BankState> {
val begin = Pair(this,target)
val history = mutableListOf<BankState>(BankState(begin,true))
boat(begin,true,this.missionaries,this.cannibals,history)
return history
}
fun boat(sourceTarget:Pair<Bank,Bank>,
boatAtSource:Boolean,
totalMissionaries:Int,
totalCannibals:Int,
history:MutableList<BankState>):Boolean {
if(sourceTarget.first.cannibals+sourceTarget.second.cannibals==totalCannibals &&
sourceTarget.first.missionaries + sourceTarget.second.missionaries==totalMissionaries &&
sourceTarget.first.cannibals>=0 &&
sourceTarget.first.missionaries>=0 &&
sourceTarget.second.cannibals>=0 &&
sourceTarget.second.missionaries>=0 &&
(sourceTarget.first.missionaries==0 || sourceTarget.first.missionaries>=sourceTarget.first.cannibals) &&
(sourceTarget.second.missionaries==0 || sourceTarget.second.missionaries >= sourceTarget.second.cannibals)) {
if(sourceTarget.second.missionaries==totalMissionaries &&
sourceTarget.second.cannibals==totalCannibals) {
history.forEach(::println)
return true
} else {
val deltas = listOf(Pair(0,1),Pair(1,1),Pair(1,0),Pair(2,0),Pair(0,2))
val comparator = object : Comparator<Pair<Pair<Boolean,Int>,Pair<Bank,Bank>>> {
override fun compare(arg1:Pair<Pair<Boolean,Int>,Pair<Bank,Bank>>,arg2:Pair<Pair<Boolean,Int>,Pair<Bank,Bank>>):Int {
if(arg1.first.first && arg2.first.first) {
return if(arg1.first.second<arg2.first.second) -1 else if(arg1.first.second>arg2.first.second) 1 else 0
} else if(arg1.first.first){
return 1
} else if(arg2.first.first) {
return -1
}
return 0
}
}
val result = deltas.map{
checkNext(it.first,it.second,totalMissionaries,totalCannibals,history,sourceTarget,boatAtSource)
}.maxWith(comparator)
if(result?.first?.first!=null && result.first.first) {
history.add(BankState(result.second,!boatAtSource))
return true;
}
}
}
return false
}
fun checkNext(missionariesDelta:Int,
cannibalsDelta:Int,
totalMissionaries:Int,
totalCannibals:Int,
history:MutableList<BankState>,
sourceTarget:Pair<Bank,Bank>,
boatAtSource:Boolean):Pair<Pair<Boolean,Int>,Pair<Bank,Bank>> {
val nextSrcTgt = if(boatAtSource) Pair(sourceTarget.first-Pair(missionariesDelta,cannibalsDelta),sourceTarget.second+Pair(missionariesDelta,cannibalsDelta))
else Pair(sourceTarget.first+Pair(missionariesDelta,cannibalsDelta),sourceTarget.second-Pair(missionariesDelta,cannibalsDelta))
val bankState:BankState = BankState(nextSrcTgt,!boatAtSource)
if(!history.contains(bankState)) {
history.add(bankState)
val combo2:Boolean = boat(nextSrcTgt,!boatAtSource,totalMissionaries,totalCannibals,history)
val combo2Depth = history.size
history.remove(bankState)
return Pair(Pair(combo2,combo2Depth),nextSrcTgt)
} else {
return Pair(Pair(false,0),nextSrcTgt)
}
}
In my Android app, I am trying to sort Bus route tags in order 1, 2, 3..etc.
For that I am using this
Collections.sort(directions, Comparator { lhs, rhs ->
var obj1 = lhs.short_names.firstOrNull() ?: ""
var obj2 = rhs.short_names.firstOrNull() ?: ""
if (obj1 === obj2) {
obj1 = lhs.headsigns.firstOrNull() ?: ""
obj2 = rhs.headsigns.firstOrNull() ?: ""
if (obj1 === obj2) {
return#Comparator 0
}
obj1.compareTo(obj2)
} else {
obj1.compareTo(obj2)
}
The issue I am having is this sorts them, but will run into the issue of
1, 2, 3, 30, 31, 4, 5
How should I change this to get the correct ordering.
If you need just a simple number comparison you can do it like that.
directions.sortWith(Comparator { lhs, rhs ->
val i1 = lhs.toInt()
val i2 = rhs.toInt()
when {
i1 < i2 -> -1
i1 > i2 -> 1
else -> 0
}
})
As hotkey pointed out the code above can be replaced with almost identical implementation that looks much simplier.
directions.sortBy { it.toInt() }
The general version of this algorithm is called alphanum sorting and described in details here. I made a Kotlin port of this algorithm, which you can use. It's more complicated than what you need, but it will solve your problem.
class AlphanumComparator : Comparator<String> {
override fun compare(s1: String, s2: String): Int {
var thisMarker = 0
var thatMarker = 0
val s1Length = s1.length
val s2Length = s2.length
while (thisMarker < s1Length && thatMarker < s2Length) {
val thisChunk = getChunk(s1, s1Length, thisMarker)
thisMarker += thisChunk.length
val thatChunk = getChunk(s2, s2Length, thatMarker)
thatMarker += thatChunk.length
// If both chunks contain numeric characters, sort them numerically.
var result: Int
if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
// Simple chunk comparison by length.
val thisChunkLength = thisChunk.length
result = thisChunkLength - thatChunk.length
// If equal, the first different number counts.
if (result == 0) {
for (i in 0..thisChunkLength - 1) {
result = thisChunk[i] - thatChunk[i]
if (result != 0) {
return result
}
}
}
} else {
result = thisChunk.compareTo(thatChunk)
}
if (result != 0) {
return result
}
}
return s1Length - s2Length
}
private fun getChunk(string: String, length: Int, marker: Int): String {
var current = marker
val chunk = StringBuilder()
var c = string[current]
chunk.append(c)
current++
if (isDigit(c)) {
while (current < length) {
c = string[current]
if (!isDigit(c)) {
break
}
chunk.append(c)
current++
}
} else {
while (current < length) {
c = string[current]
if (isDigit(c)) {
break
}
chunk.append(c)
current++
}
}
return chunk.toString()
}
private fun isDigit(ch: Char): Boolean {
return '0' <= ch && ch <= '9'
}
}
To use this Comparator just call
directions.sortWith(AlphanumComparator())
If you don't need it to be coded in Kotlin you can just take an original Java version on Dave Koelle's page. And the Kotlin version of the algorithm can be also found on GitHub.
Hi I'm currently trying to create a program that moves the cursor from a given point to another in one smooth randomised motion. I currently have created the following using CoreGraphics, which works but the mouse movement gets very choppy. Any ideas on how to fix this? Much appreciated. I call the following at the start of my Mac OS X Application inside applicationDidFinishLaunching:
var pos = NSEvent.mouseLocation()
pos.y = NSScreen.mainScreen()!.frame.height - pos.y
moveMouse(CGPoint(x:200,y:200), from: pos)
And these are the functions I've created:
func transMouse(point:CGPoint) {
let move = CGEventCreateMouseEvent(nil, CGEventType.MouseMoved, point, CGMouseButton.Left)
CGEventPost(CGEventTapLocation.CGHIDEventTap, move)
}
func moveMouseOne(direction:Character, _ currentPos:CGPoint) -> CGPoint {
var newPos = currentPos
if direction == "r" {
newPos.x = currentPos.x + 1
} else if direction == "l" {
newPos.x = currentPos.x - 1
} else if direction == "u" {
newPos.y = currentPos.y - 1
} else if direction == "d" {
newPos.y = currentPos.y + 1
}
transMouse(newPos)
return newPos
}
func moveMouse(to:CGPoint, from:CGPoint) -> CGPoint {
let dx:Int = Int(to.x - from.x)
let dy:Int = Int(to.y - from.y)
var moves = Array<Character>()
if dx > 0 {
for _ in 0..<dx {
moves.append("r")
}
} else {
for _ in 0..<(-dx) {
moves.append("l")
}
}
if dy > 0 {
for _ in 0..<dy {
moves.append("d")
}
} else {
for _ in 0..<(-dy) {
moves.append("u")
}
}
var pos = from
let delay:Double = 0.0008
let startTime = DISPATCH_TIME_NOW
for var i = 0; i < moves.count; ++i {
let time = dispatch_time(startTime, Int64(delay * Double(i) * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
let count = moves.count
let random = Int(arc4random_uniform(UInt32(count)))
pos = self.moveMouseOne(moves[random], pos)
if random == count - 1 {
moves.popLast()
} else {
moves[random] = moves.popLast()!
}
}
}
return to
}
I really recommend using Core Animation for something like this, will save you a lot of time and effort.
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreAnimation_guide/Introduction/Introduction.html
I recently received some excellent advice for writing some jquery functionality. I am trying to turn it into a pluggin.
this is the code that I got from stackOverflow#micha at this link
https://stackoverflow.com/a/8820946/729820
$('#DischargeDateTimeMask').keypress(function (e) {
var regex = ["[0-1]",
"[0-2]",
":",
"[0-5]",
"[0-9]",
"(\\s)",
"(A|P)",
"M"],
string = $(this).val() + keyboard(e),
b = true;
for (var i = 0; i < string.length; i++) {
if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
b = false;
}
}
return b;
});
function keyboard(a) { var b = a.charCode ? a.charCode : a.keyCode ? a.keyCode : 0; if (b == 8 || b == 9 || b == 13 || b == 35 || b == 36 || b == 37 || b == 39 || b == 46) { if ($.browser.mozilla) { if (a.charCode == 0 && a.keyCode == b) { return true } } } return String.fromCharCode(b) }
I personally attempt to turn it into a pluggin like so...
(function ($) {
$.fn.simpleTimeMask = function () {
$(this).keypress(function (e) {
debugger;
var regex = ["[0-2]",
"[0-4]",
":",
"[0-6]",
"[0-9]",
"(A|P)",
"M"],
string = $(this).val() + keyboard(e),
b = true;
for (var i = 0; i < string.length; i++) {
if (!new RegExp("^" + regex[i] + "$").test(string[i])) {
b = false;
}
}
return b;
});
}
(function ($) {
var methods = {
keyboard: function (a) {
//THIS
var b = a.charCode ? a.charCode : a.keyCode ? a.keyCode : 0; if (b == 8 || b == 9 || b == 13 || b == 35 || b == 36 || b == 37 || b == 39 || b == 46) { if ($.browser.mozilla) { if (a.charCode == 0 && a.keyCode == b) { return true } } } return String.fromCharCode(b)
}
}
});
function keyboard(a) { var b = a.charCode ? a.charCode : a.keyCode ? a.keyCode : 0; if (b == 8 || b == 9 || b == 13 || b == 35 || b == 36 || b == 37 || b == 39 || b == 46) { if ($.browser.mozilla) { if (a.charCode == 0 && a.keyCode == b) { return true } } } return String.fromCharCode(b) }
})(jQuery);
Notice how I have two functions that attempt to do the same thing. One I think would be a function that would be called by a user of this pluggin, the other would be used internally. Anyway, I got this thing all compiled and I attempted to add it to my project, but as expected, it did not work. What would be your recommendations for building this pluggin?