How can I use CFBinaryHeap in Swift? - swift

I searched and could not find an example of using a CFBinaryHeap from Swift code so I am posting my example as the answer below.

Here is an example that uses a CFBinaryHeap to store Foo structs from Swift, sorted by an integer property.
struct Foo {
var x : Int = 0
}
var callbacks = CFBinaryHeapCallBacks()
// <Foo> comparator
callbacks.compare = { (a,b,unused) in
let afoo : Foo = UnsafePointer<Foo>(a).memory
let bfoo : Foo = UnsafePointer<Foo>(b).memory
if ( afoo.x == bfoo.x ) { return CFComparisonResult.CompareEqualTo }
if ( afoo.x > bfoo.x ) { return CFComparisonResult.CompareGreaterThan }
return CFComparisonResult.CompareLessThan
}
let callbackPointer = UnsafeMutablePointer<CFBinaryHeapCallBacks>.alloc(1)
callbackPointer.initialize(callbacks)
var bh = CFBinaryHeapCreate(nil, 0, callbackPointer, nil)
var fooPointer : UnsafeMutablePointer<Foo>!
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 42))
CFBinaryHeapAddValue(bh, fooPointer)
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 99))
CFBinaryHeapAddValue(bh, fooPointer)
fooPointer = UnsafeMutablePointer<Foo>.alloc(1)
fooPointer.initialize(Foo(x: 2))
CFBinaryHeapAddValue(bh, fooPointer)
var got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 2
CFBinaryHeapRemoveMinimumValue(bh)
got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 42
CFBinaryHeapRemoveMinimumValue(bh)
got = UnsafePointer<Foo>(CFBinaryHeapGetMinimum(bh))
got.memory.x // 99
CFBinaryHeapRemoveMinimumValue(bh)

Related

How to Convert JS Password Strength Meter to Swift

I'm trying to convert this javascript password score function to swift, so I can use the same logic on mobile as we do on web. Here is the JS fiddle with the code to test:
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /\d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /\W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "Strong";
if (score > 60)
return "Good";
if (score >= 30)
return "Weak";
return "";
}
I'm having an issue in converting this part:
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
I've tried to create a dictionary to store the character as key and then increment the value with each occurrences of that key, but it's not working as expected.
let string = "Testing22!"
var score = 0
var dictionary = [String.Element: Int]()
for x in string {
let value = dictionary[x] ?? 0
dictionary[x] = value + 1
score += 5 / value
}
print(dictionary) //["s": 1, "T": 1, "g": 1, "2": 2, "n": 1, "i": 1, "!": 1, "t": 1, "e": 1]
print(score)
I'm also not sure of the most efficient way to handle the regex checks for the bonus points section.
I'd port it over to swift like this, I'm sure there are some improvements to be made, but thats a quick conversion:
func scorePassword(_ inputString: String?) -> Double {
var score: Double = 0
guard let string = inputString, !string.isEmpty else { return score }
// award every unique letter until 5 repetitions
let countedSet = NSCountedSet()
for x in string {
countedSet.add(x)
score += 5.0 / Double(countedSet.count(for: x))
}
// bonus points for mixing it up
let variations = [
"^(?=.*[0-9]).*$",
"^(?=.*[a-z]).*$",
"^(?=.*[A-Z]).*$",
"^(?=.*\\W).*$"
]
var variationCount: Double = 0
for check in variations {
print(string.testRegex(check))
variationCount += string.testRegex(check) ? 1 : 0
}
score += (variationCount - 1) * 10
return floor(score)
}
func checkPassStrength(_ inputString: String?) -> String {
let score = scorePassword(inputString)
if score > 80 {
return "Strong"
} else if score > 60 {
return "Good"
} else if score > 30 {
return "Weak"
}
return ""
}
extension String {
func testRegex(_ regex: String) -> Bool {
let test = NSPredicate(format: "SELF MATCHES %#", regex)
return test.evaluate(with: self)
}
}
You can run js code inside Swift and get the result from it, so you can share code between platforms.
let jsSource = """
function scorePassword(pass) {
var score = 0;
if (!pass)
return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i<pass.length; i++) {
letters[pass[i]] = (letters[pass[i]] || 0) + 1;
score += 5.0 / letters[pass[i]];
}
// bonus points for mixing it up
var variations = {
digits: /d/.test(pass),
lower: /[a-z]/.test(pass),
upper: /[A-Z]/.test(pass),
nonWords: /W/.test(pass),
}
variationCount = 0;
for (var check in variations) {
variationCount += (variations[check] == true) ? 1 : 0;
}
score += (variationCount - 1) * 10;
return parseInt(score);
}
function checkPassStrength(pass) {
var score = scorePassword(pass);
if (score > 80)
return "Strong";
if (score > 60)
return "Good";
if (score >= 30)
return "Weak";
return "";
}
"""
let context = JSContext()
context?.evaluateScript(jsSource)
let testFunction = context?.objectForKeyedSubscript("scorePassword")
let result = testFunction?.call(withArguments: ["1234"])
print("js result : " , result )
Note; I edited the part "digits: /\d/.test(pass)" to "digits: /d/.test(pass)"

VSCode language extension with hierarchical Outline, DocumentSymbol

I'm trying to get outline working with a custom language in VScode. I have the below code but I feel like it is slow because of the way I find a range in class. Are there better ways to find the range and assign children. I've thought about just keeping track of the depth of the brackets and assigning all functions/methods/classes in higher depths into the last item of previous depth.
It was based off of this answer.
class JSLDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
public provideDocumentSymbols(document: vscode.TextDocument,
token: vscode.CancellationToken): Thenable<vscode.DocumentSymbol[]> {
return new Promise((resolve, reject) => {
var symbols: vscode.DocumentSymbol[] = [];
var depth = 0;
for (var i = 0; i < document.lineCount; i++) {
var line = document.lineAt(i);
var txt = line.text;
var ltxt = txt.toLowerCase();
let open_brackets = ltxt.match(/\(/g) || [];
let close_brackets = ltxt.match(/\)/g) || [];
// console.log(ltxt)
// console.log(open_brackets, close_brackets)
//console.log(i, open_brackets.length, close_brackets.length)
depth += open_brackets.length - close_brackets.length;
//console.log(depth);
if (ltxt.includes("define class(")) {
let sname = txt.trim().substr(14, txt.trim().length - 16); //this is hard coded right now but it's kind of working
let detail = "ARGS:x, y returns z";
let start_pos = new vscode.Position(i, 0);
let n_bracket = 1;
let i_char = 0;
//let children: vscode.DocumentSymbol[] = []
let ds = new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Class, line.range, line.range);
for(var i_line = i; n_bracket > 0; i_line++){
let class_line = document.lineAt(i_line);
let mtxt = class_line.text;
let ic;
if(i == i_line) ic = 16;
else ic = 0;
for(i_char = ic; i_char < mtxt.length; i_char++){
if(mtxt[i_char] === "(") n_bracket++;
else if(mtxt[i_char] === ")") n_bracket--;
if(n_bracket === 0) break
}
if (/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i.test(mtxt)) {
let result = mtxt.match(/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let mname = result[1].trim();
let m_details = ""
if(result.length == 3){
m_details = result[2].trim();
}
ds.children.push(new vscode.DocumentSymbol(mname, m_details, vscode.SymbolKind.Method, class_line.range, class_line.range));
}
if(n_bracket === 0) break
}
let end_pos = new vscode.Position(i_line, i_char);
let rng = new vscode.Range(start_pos, end_pos);
ds.range = rng;
//ds.children = children;
symbols.push(ds);
}
else if (/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/.test(ltxt)) {
let result = txt.match(/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let sname = result[1].trim();
let detail = "";
if(result.length == 3){
detail = "(" + result[2].trim() + ")";
}
symbols.push(new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Function, line.range, line.range));
}
}
resolve(symbols);
});
}
}

"Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions"

I really need help with refactoring or breaking up code to smaller pieces. My Xcode can't even build project because it's too complicated.
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
I can't break up into smaller pieces because I have to assign results of UITextField to that function to push it to BackEnd. Code is too messy.
/* That's where I'm assigning values to Bools and selections */
#objc func handleSaveMZHD()
var NalichieTehPasportBol: Bool = false
if NalichieTehPasportResponse.text == "Да"{
NalichieTehPasportBol = true
} else if NalichieTehPasportResponse.text == "Нет"{
NalichieTehPasportBol = false
}
var NalichieElektroLambiBol: Bool = false
if (ElektroLampiResponse.text == "Да"){
NalichieElektroLambiBol = true
} else if ElektroLampiResponse.text == "Нет"{
NalichieElektroLambiBol = false
}
var NalichieLiftaBol: Bool = false
if NalichieLiftaResponse.text == "Да"{
NalichieElektroLambiBol = true
} else if NalichieLiftaResponse.text == "Нет"{
NalichieElektroLambiBol = false
}
var AktTehObsledSelection: Int = 0
if AktTehnObsledovaniyaResponse.text == "аварийный"{
AktTehObsledSelection = 1
} else if self.AktTehnObsledovaniyaResponse.text == "Не аварийный"{
AktTehObsledSelection = 2
}
var BalansPrinadlejnostiSel: Int = 0
if BalansPrinadlejResponse.text == "Государственная Собственность" {
BalansPrinadlejnostiSel = 1
} else if BalansPrinadlejResponse.text == "Частная Собственность" {
BalansPrinadlejnostiSel = 2
}
var OblicovkaSel: String = ""
if OblicovkaResponse.text == "Монолит"{
OblicovkaSel = "monolith"
}else if OblicovkaResponse.text == "Кирпич"{
OblicovkaSel = "brick"
}else if OblicovkaResponse.text == "Блоки"{
OblicovkaSel = "blocks"
}else if OblicovkaResponse.text == "Облицовка"{
OblicovkaSel = "facing"
}
/* That's function itself to push all that information to BackEnd */
updaTeRecord(o_model: "property.building", id: 207, attrs: [
"street": ulicaResponse.text,
"parking_area": PlowadParkingaResponse.text,
"builded_at": GodPostroikiResponse.text,
"all_size": Int(ObwayaPlowadDomaResponse.text!),
"land_size": Int(ObwayaPlowadUchastkaResponse.text!),
"apartment_amount": Int(KolvoKvartirResponse.text!),
"porch_amount": Int(KolvoPodezdovResponse.text!),
"level_amount": KolvoEtajeiResponse.text,
"is_tech_passport" : NalichieTehPasportBol,
"entrance_state": SostoyaniePodezdResponse.text,
"entrance_energy_saving_lamps": NalichieElektroLambiBol,
"entrance_windows_count": KolvoOkonResponse.text,
"entrance_windows_material": MaterialOkonResponse.text,
"lift_provided": NalichieLiftaBol,
"conclusion_of_technical_inspection": AktTehObsledSelection,
"lift_amount": Int(KolvoLiftovResponse.text!),
"lift_installed_at": DataUstanovkiLiftaResponse.text,
"lift_lifetime": SrokEkspluatLiftaResponse.text,
"lift_last_checked": DataPoslObslLiftaResponse.text,
"lift_company": ObslujOrganizaciyaResponse.text,
"lift_payment_method": TipOplatiLiftaResponse.text,
"power_consumption": PotreblyaemayaMownostResponse.text,
"registration_of_condominium": RegestraciyaKondominimumaResponse.text,
"date_of_condominium": DataRegestraciyaKondominimumaResponse.text,
"inventory_number": InvertarniiNomerResponse.text,
"cadastral_number": KadastroviiNomerResponse.text,
"date_of_the_last_overhaul": PosledniiKapitalniiRemontResponse.text,
"energy_efficiency": KlassEnergoResponse.text,
"house_balance": BalansPrinadlejnostiSel,
"definition_isystem": InformacionnayaSystemaResponse.text,
"ip_address_isystem": InformacionnayaIPadressResponse.text,
"last_energy_audit_at": EnergoAudiotResponse.text,
"number_of_sections": KolvoSekciiResponse.text,
"service_life_of_the_building": SrokSlujbZdaniyaResponse.text,
"depreciation": IznosMZHDResponse.text,
"house_walls": OblicovkaSel
]) { (result) in
print(result)
}
Try splitting your call to updaTeRecord(o_model:id:attrs:completion:) like this:
let myAttributes: [String: Any] = [
"street": ulicaResponse.text,
"parking_area": PlowadParkingaResponse.text,
"builded_at": GodPostroikiResponse.text,
//...
"service_life_of_the_building": SrokSlujbZdaniyaResponse.text,
"depreciation": IznosMZHDResponse.text,
"house_walls": OblicovkaSel
]
updaTeRecord(o_model: "property.building", id: 207, attrs: myAttributes) { (result) in
print(result)
}
Or this may work more stable (compile without similar issues) in most cases:
var myAttributes: [String: Any] = [:]
myAttributes["street"] = ulicaResponse.text
myAttributes["parking_area"] = PlowadParkingaResponse.text
myAttributes["builded_at"] = GodPostroikiResponse.text
//...
myAttributes["service_life_of_the_building"] = SrokSlujbZdaniyaResponse.text
myAttributes["depreciation"] = IznosMZHDResponse.text
myAttributes["house_walls"] = OblicovkaSel
updaTeRecord(o_model: "property.building", id: 207, attrs: myAttributes) { (result) in
print(result)
}

Connect-Four Game in Scala

I have to make a connect-four game using scala. I have attached the code but everytime the game runs and gets to row 3 it just continues to change the second rows entry instead of going to the next row. Any help would be appreciated. I found this code on another thread on here and couldn't figure out how to get it to work:
// makes the board
val table = Array.fill(9,8)('-')
var i = 0;
while(i < 8){
table(8)(i) = (i+'0').toChar
i = i+1;
}
// prints starting board
def printBoard(table: Array[Array[Char]]) {
table.foreach( x => println(x.mkString(" ")))
}
//player 1 moves
def playerMove1(){
val move = readInt
var currentRow1 = 7
while (currentRow1 >= 0)
if (table(currentRow1)(move) != ('-')) {
currentRow1 = (currentRow1-1)
table(currentRow1)(move) = ('X')
return (player2)}
} else {
table(currentRow1)(move) = ('X')
return (player2)
}
}
//player 2 moves
def playerMove2(){
val move = readInt
var currentRow2 = 7
while (currentRow2 >= 0)
if (table(currentRow2)(move) != ('-')) {
currentRow2 = (currentRow2-1)
table(currentRow2)(move) = ('O')
return (player1)}
} else {
table(currentRow2)(move) = ('O')
return (player1)
}
}
//player 1
def player1(){
printBoard(table)
println("Player 1 it is your turn. Choose a column 0-7")
playerMove1()
}
//player 2
def player2(){
printBoard(table)
println("Player 2 it is your turn. Choose a column 0-7")
playerMove2()
}
for (turn <- 1 to 32){
player1
player2
}
I've tried to make your code readable and compiling and also tried to fix some logic.
However, I've never worked with Scala so this is just a first sketch where you might want to continue ...
Some functions can be merged and the currentRow needed a fix. See here:
object ConnectFour{
val table = Array.fill(9,8)('-')
val currentRow = Array.fill(8)(8)
def main(args: Array[String]) {
var i = 0;
while(i < 8) {
table(8)(i) = (i+'0').toChar
i = i+1;
}
player(1)
}
def printBoard(table: Array[Array[Char]]) {
table.foreach( x => println(x.mkString(" ")))
}
def player(playerNr : Int){
printBoard(table)
println("Player " + playerNr + " it is your turn. Choose a column 0-7")
var column = readAndVerifyInt
var nextUser = 1 : Int
var symbol = 'O' : Char
if(playerNr == 1) {
symbol = 'X'
nextUser = 2
}
var curR = currentRow(column)
while (curR >= 0) {
if (table(curR)(column) != ('-')) {
curR = curR-1
currentRow(column) = curR
}
table(curR)(column) = symbol
player(nextUser)
}
}
def readAndVerifyInt() : Int = {
var column = readInt
if (column >= 0 && column <= 7) {
return column
} else {
println(" > Please try again")
return readAndVerifyInt
}
}
}

Swift iOS application not saving all object Parse

My problem is adding new numbers to the array field in users. all the code seems to work but i have the problem with saveAll function. All the names are correct, as i've checked on several different occasions.
func taskAllocation(){
var query = PFUser.query()
var objectQuery:[PFUser] = [PFUser]()
query.whereKey("Year", equalTo: yearTextField.text.toInt())
query.whereKey("Class", equalTo: classTextField.text.toInt())
query.whereKey("Keystage", equalTo: keystageTextField.text.toInt())
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error != nil {
println(error)
} else {
if objects.isEmpty {
println("empty query")
}
else {
for object in objects as [PFUser] {
var test:[Int] = object["taskIDs"] as [Int]
test.append(self.getIndex)
println(test)
object["taskIDs"] = test
object["tasksCompleted"] = "hello"
objectQuery.append(object)
}//For
println(objectQuery.count)
if objectQuery.count != 0{
println("Success!!!")
println(objectQuery)
PFUser.saveAllInBackground(objectQuery)
}
}
}
}
This below is stored in the println(objectQuery) as you can see the taskIDs have been appended and the tasksCompleted contains the string. Which leads me to believe that there is a problem with the saveallinbackground function.
[<PFUser: 0x155f6510, objectId: W6TrPQwCQ7, localId: (null)> {
Class = 2;
Forename = "Joe ";
Keystage = 2;
Surname = Freeston;
Year = 4;
admin = false;
completedTaskIDs = (
);
taskIDs = (
0,
2,
4,
5,
6,
46
);
tasksCompleted = hello;
tasksCorrect = 0;
userType = Student;
username = jfreeston;
}, <PFUser: 0x1569b7a0, objectId: slLd1KBIaM, localId: (null)> {
Class = 2;
Forename = "Camilla ";
Keystage = 2;
Surname = Linhart;
Year = 4;
admin = false;
completedTaskIDs = (
);
taskIDs = (
0,
46
);
tasksCompleted = hello;
tasksCorrect = 0;
userType = Student;
username = clinhart;
}]
Not sure if anyone has more knowledge of the parse api, mainly how the saveall/saveallinbackground functions work maybe.
To save all in background as a user I would first create a PFUser variable, like
var NewUser = PFUser.currentUser
Then to save in background
newUser.saveInBackgroundWithBlock {
(success:Bool, error: NSError!) -> Void in {
}
Then you can put if-statements and stuff within those brackets to do what you need it to when successful. like:
if(success) {
performSegueWithIdentifier("YourSegue", sender: nil)
}