Get separate data from Firebase in Swift - xcode

I can't get data and write to String variable.
When I do:
myRootRef.observeEventType(.ChildAdded, withBlock: {
snapshot in
print(snapshot.value.objectForKey("02-03-2016"))
})
I get all this records (in type - AnyObject):
Optional({
TD = {
Entry = 44;
Name = Tedd;
Potential = 32;
StopLoss = 77;
};
})
But I need "Entry", "Name", "Potential", "StopLoss" - put to variables, and after put to textfield...
Help please to understand, how I can do it.
I can't find solution already more 4 hours....
Thanks.

You are trying to print a value associated with a key. ( a key:value pair)
The key you are specifying is "02-03-2016" and that key doesn't seem to exist.
Assuming your structure is
Entry = 44;
Name = Tedd;
Potential = 32;
StopLoss = 77;
Then your keys are Entry, Name, Potential and StopLoss
print(snapshot.value.objectForKey("Entry")
would print
44

Related

office script - range find - return row or array to power automate

I have been trying several different ways to write an office script to search for a value in a cell and return the row or rows to power automate.
I believe I need to use range.find in order to make use of the "completematch: true" option.
However, I have also tried a filter and a foreach loop to find rows which include the text I am searching for.
I'm after a hint as to which method might be best?
essentially trying to:-
power automate - pass text parameter to the script
Scripts search for a match in excel business spreadsheet
the script finds match(s)
Script passes back the row(s) to powerautomate as an array
this is what I have so far: essentially it just finds the row number in which the matching result is found. This seems to work better to avoid partial matched (as happened with the filter method )
any pointers, most welcome
function main(workbook: ExcelScript.Workbook, siteNameToFilter: string) {
let activeSheet = workbook.getActiveWorksheet();
let range = activeSheet.getUsedRange();
let values = range.getValues();
/**
* This script searches for the next instance of the text "Fino" on the current worksheet.
*/
// Get the next cell that contains "Fino".
let findCell = range.find("Fino", {
completeMatch: true, /* Don't match if the cell text only contains "fino" as part of another string. */
matchCase: false,
searchDirection: ExcelScript.SearchDirection.forward /* Start at the beginning of the range and go to later columns and rows. */
});
// Set focus on the found cell.
findCell.select();
// Remove the "TK" text value from the cell, as well as any formatting that may have been added.
//tkCell.clear(ExcelScript.ClearApplyTo.all);
let row = findCell.getRow().getUsedRange();
let ur = findCell.getUsedRange();
console.log(row);
}
I think Find may only be returning the first match. It sounds like you want all matches with the siteName. To do this, you'd either want to filter the range or loop through it.
Here's an example that loops through the range and adds the values from the rows containing the site name to an array. After the loop's completed, the array containing the values is returning by the function:
function main(workbook: ExcelScript.Workbook, siteNameToFilter: string) {
let activeSheet = workbook.getActiveWorksheet();
let range = activeSheet.getUsedRange()
let values = range.getValues() as string[][];
let rowCount = range.getRowCount()
let colCount = range.getColumnCount()
let colIndex = range.getColumnIndex()
let rowsArr: string[][][] = []
for (let i = 0; i < rowCount; i++) {
for (let j = 0; j < colCount; j++) {
if (values[i][j] === siteNameToFilter) {
rowsArr.push(activeSheet.getRangeByIndexes(i, colIndex, 1, colCount).getValues() as string[][])
}
}
}
return rowsArr
}

Google AppMaker: Fetch a MAX value

I am not able to fetch a max value from a number field in AppMaker. The field is filled with unique integers from 1 and up. In SQL I would have asked like this:
SET #tKey = (SELECT MAX(ID) FROM GiftCard);
In AppMaker I have done the following (with a bit help from other contributors in this forum) until now, and it returns tKey = "NaN":
var tKey = google.script.run.MaxID();
function MaxID() {
var ID_START_FROM = 11000;
var lock = LockService.getScriptLock();
lock.waitLock(3000);
var query = app.models.GiftCard.newQuery();
query.sorting.ID._descending();
query.limit = 1;
var records = query.run();
var next_id = records.length > 0 ? records[0].ID : ID_START_FROM;
lock.releaseLock();
return next_id;
}
There is also a maxValue() function in AppMaker. However, it seems not to work in that way I use it. If maxvalue() is better to use, please show :-)
It seems that you are looking in direction of auto incremented fields. The right way to achieve it would be using Cloud SQL database. MySQL will give you more flexibility with configuring your ids:
ALTER TABLE GiftCard AUTO_INCREMENT = 11000;
In case you strongly want to stick to Drive Tables you can try to fix your script as follow:
google.script.run
.withSuccessHandler(function(maxId) {
var tKey = maxId;
})
.withFailureHandler(function(error) {
// TODO: handle error
})
.MaxID();
As a side note I would also recommend to set your ID in onBeforeCreate model event as an extra security layer instead of passing it to client and reading back since it can be modified by malicious user.
You can try using Math.max(). Take into consideration the example below:
function getMax() {
var query = app.models.GiftCard.newQuery();
var allRecords = query.run();
allIds = [];
for( var i=0; i<allRecords.length;i++){
allIds.push(allRecords[i].ID);
}
var maxId = Math.max.apply(null, allIds);
return maxId;
}
Hope it helps!
Thank you for examples! The Math.max returned an undefined value. Since this simple case is a "big" issue, I will solve this in another way. This value is meant as a starting value for a sequence only. An SQL base is better yes!

when provided a value, looking to have the row number of the cell where that value resides

Please take a look at the following googleapps script code. the spreadsheet it references has 4 values in it. in a2 is the value "Two". I want that when I run this code, i receive an email with "2" in the subject line. I seem to keep on receiving a "4". Any ideas?
function rowofspecificvalue(){
var sheet = SpreadsheetApp.openById("1rMUrZFie94RLFDKaWVBPsQ-jebL8wNA6qsZWivMBDTk").getActiveSheet();
var data = sheet.getRange("a1:a4").getValues();
for(var i = 0; i<data.length;i++){
if(data[i][1] == "Two"){
Logger.log((i+1))
return i+1;
}
} MailApp.sendEmail ("fake_email#gmail.com", i, "");
}
Thanks!
Write
MailApp.sendEmail("fake_email#gmail.com", i-2, "")
and you will "2" have in subject. Second argument of MailApp.sendEmail() function set up subject of email.

Android: Connecting buttons to the java file through a for loop

I'm trying to create a chess game for Android and would like to avoid having to declare every button when they are all named so similarly. I tried to generate all of the A + Num button using this for loop.
int RowNum ;
for (RowNum = 1; RowNum < 8; RowNum++) {
String Position = "A" + RowNum;
Button Position = (Button)findViewById(R.id.Position);
}
But I have an error: Variable 'Position' is already defined in the scope.
I would really appreciate if someone could explain to me the best way to go about doing this.
Thanks in advance.
R.Id.A1, R.id.A2, etc. are identifiers and each of them is mapped to a single integer during compilation of R class. Thus, you cannot manipulate the 'R.id.sth' as a string because it will not compile properly.
A way to solve that is search for the string in resources dynamically with a code like this:
Button[] buttons=new Button[8];
for(int RowNum=0; RowNum<8; RowNum++) {
String buttonID = "A"+(RowNum+1);
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[RowNum] = ((Button) findViewById(resID));
}
Alternatively, to avoid the time overhead of dynamic search you can add a resource array:
int[] butIds = {R.id.A1, R.id.A2,...};
Button[] buttons= new Button[8];
for(int RowNum=0; RowNum<8, RowNum++) {
buttons[RowNum]= ((Button) findViewById(butIds[RowNum]));
}
You can even store the resource array in XML form and retrieve it as a TypedArray.
You called your String and Button object both Position. Give them different names, e.g.
for (int RowNum = 1; RowNum < 8; RowNum++) {
String currentPosition = "A" + RowNum;
//Why doesn this not use the Position (now 'currentPosition' variable)?
Button currentButton = (Button)findViewById(R.id.Position);
}
Semantically I still don't get that piece of code because Position is not used within the argument of findViewById, to which you pass a static variable R.id.Position.

Can I override a Lua table's return value for itself?

Is it possible for a table, when referenced without a key, to return a particular value rather than a reference to itself?
Let's say I have the following table:
local person = {
name = "Kapulani",
level = 100,
age = 30,
}
In Lua, I can quite easily refer to "person.name", "person.level", or "person.age" and get the values as expected. However, I have certain cases where I may want to just reference "person" and, instead of getting "table: " I'd like to return the value of "person.name" instead.
In other words, I'd like person.x (or person[x]) to return the appropriate entry from the table, but person without a key to return the value of person.name (or person["name"]). Is there a mechanism for this that I haven't been able to find?
I have had no success with metatables, since __index will only apply to cases where the key does not exist. If I put "person" into a separate table, I can come up with:
local true_person = {
... -- as above
}
local env_mt = {
__index = function(t, k)
if k == 'person' then
return true_person
end
end
}
local env = setmetatable( {}, env_mt )
This lets me use __index to do some special handling, except there's no discernable way for me to tell, from __index(), whether I'm getting a request for env.person (where I'd want to return true_person.name) or env.person[key] (where I'd want to return true_person as a table, so that 'key' can be accessed appropriately).
Any thoughts? I can approach this differently, but hoping I can approach this along these lines.
You can do it when the table is being used as a string by setting the __tostring metatable entry:
$ cat st.lua
local person = {
name = "Kapulani",
level = 100,
age = 30,
}
print(person)
print(person.name)
print(person.age)
setmetatable(person, {__tostring = function(t) return t.name end})
print(person)
$ lua st.lua
lua st.lua
table: 0x1e8478e0
Kapulani
30
Kapulani
I am not sure that what you are asking for is a good idea because it flies in the face of compositionality. Usually one would expect the following two programs to do the same thing but you want them to behave differently
print(person.name)
local p = person
print( p.name )
Its also not very clear how assignment would work. person.age = 10 should change the age but person = otherPerson should change the reference to the perrson, not the age.
If you don't care about compositionality and are onyl reading data, then a more direct way to solve the problem is to have a query function that receives the fields encoded in a string
query("person.age") -- 17
query("person.name") -- "hugomg"
query("person") -- 17; query gets to default to whatever it wants.
To keep the syntax more lightweight you can omit the optional parenthesis
q"person.age"
q"person"
Or you can extend the __index metamethod on the global table, _G
setmetattable(_G, { __index = function(self, key) return query(key) end })
print ( person_age ) -- You will need to use "_" instead of "." for the
-- query to be a valid identifier.

Resources