let $d := doc('/test/a-false.json')
return ($d, if ($d/a) then 'false is true' else 'false is false')
The result:
{"a":false}
false is true
Really?
StackOverflow's robot was not contented with the above, so I will add some meaningless text that you don't have to read, even though I think the above is more than adequate at describing the problem. Long live our mechanical overlords.
In your example $d/a is a boolean node, a MarkLogic extension, part of the set of node types added to represent JSON in XDM.
The EBV of such a node is true if it exists. Which might be surprising for a boolean node with the value false. What you see here is the answer to the question: "Does such a node exists?" For the question "Is its value false?," use fn:data().
Relevant expressions:
let $d := fn:doc('/test/a-false.json')
return (
$d,
$d/a,
fn:data($d/a),
if ( $d/a ) then 'false exists' else 'false does not exist',
if ( fn:data($d/a) ) then 'false is true' else 'false is not true'
)
Result:
{"a":false}
fn:doc("/test/a-false.json")/boolean-node("a")
false
false exists
false is not true
Related
i am currently trying to find whether the high price(column 'high') is the highest among 1 and -1 periods away, if so then it would return True in my new added column called 'high_peak'. This is what i've managed but the output returns everything False. Can someone help me out please? im a new learner which just started to learn python, so if there could be some elaboration along the lines would be much appreciated :D
Here's what i did:
SPX = pd.read_csv(r'D:\Users\jimmyli\Downloads\SP_SPX, 1D.csv', index_col = 'time')
def peak(x):
for i in range(len(x)):
if x[i] > x[i+1] and x[i] > x[i-1]:
return True
else:
return False
SPX['high_peak'] = peak(SPX['high'])
print(SPX)
And here's what came out:
open high low high_peak
time
2009/9/14 1040.15 1049.74 1035.00 False
2009/9/15 1049.03 1056.04 1043.42 False
2009/9/16 1053.99 1068.76 1052.87 False
2009/9/17 1067.87 1074.77 1061.20 False
2009/9/18 1066.60 1071.52 1064.27 False
... ... ... ...
2022/2/14 4412.61 4426.22 4364.84 False
2022/2/15 4429.28 4472.77 4429.28 False
2022/2/16 4455.75 4489.55 4429.68 False
2022/2/17 4456.06 4456.06 4373.81 False
2022/2/18 4384.57 4394.60 4327.22 False
[3132 rows x 4 columns]
As you can see, there's an error at the operation because the high price #2009/9/17 should have returned True at 'high_peak' column
I have seen this issue many times happening to many people (here). I am still struggling trying to validate whether what my dictionary captures from a JSON is "None" or not but I still get the following error.
This code is supposed to call a CURL looking for the 'closed' value in the 'status' key until it finds it (or 10 times). When payment is done by means of a QR code, status changes from opened to closed.
status = (my_dict['elements'][0]['status'])
TypeError: 'NoneType' object is not subscriptable
Any clue of what am I doing wrong and how can I fix it?
Also, if I run the part of the script that calls the JSON standalone, it executes smoothly everytime. Is it anything in the code that could be affecting the CURL execution?
By the way, I have started programming 1 week ago so please excuse me if I mix concepts or say something that lacks of common sense.
I have tried to validate the IF with "is not" instead of "!=" and also with "None" instead of "".
def show_qr():
reference_json = reference.replace(' ','%20') #replaces "space" with %20 for CURL assembly
url = "https://api.mercadopago.com/merchant_orders?external_reference=" + reference_json #CURL URL concatenate
headers = CaseInsensitiveDict()
headers["Authorization"] = "Bearer MY_TOKEN"
pygame.init()
ventana = pygame.display.set_mode(window_resolution,pygame.FULLSCREEN) #screen settings
producto = pygame.image.load("qrcode001.png") #Qr image load
producto = pygame.transform.scale(producto, [640,480]) #Qr size
trials = 0 #sets while loop variable start value
status = "undefined" #defines "status" variable
while status != "closed" and trials<10: #to repeat the loop until "status" value = "closed"
ventana.blit(producto, (448,192)) #QR code position setting
pygame.display.update() #
response = requests.request("GET", url, headers=headers) #makes CURL GET
lag = 0.5 #creates an incremental 0.5 seconds everytime return value is None
sleep(lag) #
json_data = (response.text) #Captures JSON response as text
my_dict = json.loads(json_data) #creates a dictionary with JSON data
if json_data != "": #Checks if json_data is None
status = (my_dict['elements'][0]['status']) #If json_data is not none, asigns 'status' key to "status" variable
else:
lag = lag + 0.5 #increments lag
trials = trials + 1 #increments loop variable
sleep (5) #time to avoid being banned from server.
print (trials)
From your original encountered error, it's not clear what the issue is. The problem is that basically any part of that statement can result in a TypeError being raised as the evaluated part is a None. For example, given my_dict['elements'][0]['status'] this can fail if my_dict is None, or also if my_dict['elements'] is None.
I would try inserting breakpoints to better assist with debugging the cause. another solution that might help would be to wrap each part of the statement in a try-catch block as below:
my_dict = None
try:
elements = my_dict['elements']
except TypeError as e:
print('It possible that my_dict maybe None.')
print('Error:', e)
else:
try:
ele = elements[0]
except TypeError as e:
print('It possible that elements maybe None.')
print('Error:', e)
else:
try:
status = ele['status']
except TypeError as e:
print('It possible that first element maybe None.')
print('Error:', e)
else:
print('Got the status successfully:', status)
Can someone please explain me what I am doing wrong. I don't understand the behaviour of the ifelse function in R. I expected that the ifelse function would return the whole list ids_match. However, these are the results I get with RStudio Version 1.3.1093 in the Console Window:
cond1 = FALSE
cond2 = FALSE
cond3 = TRUE
ids_match = list(1, 2, 3)
ifelse(cond1 & cond2 & cond3, ids_match[1], ids_match)
[[1]]
[1] 1
ifelse(TRUE, ids_match[1], ids_match)
[[1]]
[1] 1
ifelse(FALSE, ids_match[1], ids_match)
[[1]]
[1] 1
ifelse(FALSE, "TRUE", "FALSE")
[1] "FALSE"
ifelse(TRUE, "TRUE", "FALSE")
[1] "TRUE"`
According to ?ifelse:
Usage: ifelse(test, yes, no)
Description:
‘ifelse’ returns a value with the same shape as ‘test’ which is
filled with elements selected from either ‘yes’ or ‘no’ depending
on whether the element of ‘test’ is ‘TRUE’ or ‘FALSE’.
Now, since (cond1 & cond2 & cond3) is a single boolean variable (i.e. length(cond1 & cond2 & cond3) == 1), your response will also have length of 1.
Also see related discussion here.
Please help as soon as possible...
Write a MIPS assembly language program that prompts the user to input two strings (each should be no longer than 50 characters including the null terminator). Your program should determine whether the second string is a substring of the first. If it is, then your program should print out the first index in which the second string appears in the first. For example, if the first string is “Hello World” and the second string is “lo”, then the program should print out 3, i.e. the starting index of “lo” in “Hello World.” If the second string is not contained in the first string, then your program should print out -1.
To be able to understand what you have to implement at assembly level, the first thing you should do, is understanding the high-level algorithm. Why?
It's easier for you to see all the cases and edge-cases in time!
To look back at what have I been trying to do again? in the middle of programming the Assembly version.
To quickly see which variables you (certainly) need.
I wrote following program (forgive me, python has been a while for me):
def is_in_string_1(string, substring):
"""
aaba: a, b, ab, ba, aba (last one will fail)
"""
length = len(string)
sublength = len(substring)
if (sublength == 0):
return True
j = 0
for i in range(0, length):
if string[i] != substring[j]:
j = 0
else:
j += 1
if j == sublength:
return True
return False
def is_in_string_2(string, substring):
"""
aaba: a, b, ab, ba, aba
"""
length = len(string)
sublength = len(substring)
for i in range(0, length + 1 - sublength): # string: aabc; substring: c; length: 4; sublength: 1; indexes: 0,1,2,3;
is_substring = True
for j in range(0, sublength): # for the sake of the algorithm, no slicing here
if string[i+j] != substring[j]:
is_substring = False
break
if is_substring:
return True
return False
stringTuples = [
("aaa", "aa"),
("aaa", "aaa"),
("aaa", "aab"),
("abc", "bc"),
("abc", "a"),
("abc", "abc"),
("aaa", ""),
("aaa", "b")
]
for stringTuple in stringTuples:
print(
stringTuple[0],
stringTuple[1],
':',
is_in_string_1(stringTuple[0], stringTuple[1]),
is_in_string_2(stringTuple[0], stringTuple[1]),
sep='\t'
)
I first thought I could optimize the standard solution (is_in_string_2), leaving out the second for-loop (is_in_string_1), but after some thinking I already found out it would fail (the edge-case wasn't even in any of my test-data!) - so I left it as an example for how important it is that you use a correct algorithm.
The program produces the following output:
aaa aa : True True
aaa aaa : True True
aaa aab : False False
abc bc : True True
abc a : True True
abc abc : True True
aaa : True True
aaa b : False False
aaba aba : False True
Notice how all output was correct, except for the last line, where the first algorithm is wrong.
Before you continue:
You have to make your own len() function in MIPS; note that all string are (if I remember correctly) null terminated, so you'll have to count all non-null characters of a string, or in other words, count how many characters precede the null-terminator.
You should use j, $ra and jr calls to go to a "function" or subroutines. (Search)
While in one, you can call other functions using the stack. (Search)
For this data
https://jqplay.org/s/onlU9ghjn1
I can not figure out the correct syntax to do something like
.gcp_price_list | ."CP-COMPUTEENGINE-OS" |
(
if ( .[].cores == "shared" ) then
.[].cores = 0.5
end
)
Seems I need the else part but I'm not sure what to put there. If I do:
.gcp_price_list | ."CP-COMPUTEENGINE-OS" |
(
if ( .[].cores == "shared" ) then
.[].cores = 0.5
else .[].cores = .[].cores end
)
There is still "shared" in the result, i.e.
"win": {
"low": 0.02,
"high": 0.04,
"cores": "shared",
"percore": true
}
Inputs get replicated into the result, which is not what I want.
Related, but I don't find them very helpful, questions
JQ If then Else
How do I update a single value in a json document using jq?
My practical alternative is "replaced all" with a text editor,
but I will leave this question here in case there is an elegant solution.
It looks as though you want:
.gcp_price_list
| ."CP-COMPUTEENGINE-OS"
| map_values(
if .cores == "shared"
then .cores = 0.5
else . end )
In any case, be careful when using expressions such as .[].cores as arguments of if, then, or else, because they produce a stream of results.
In future, please follow the MCVE guidelines.
Postscript
If you want to edit the JSON document, you would use |= like so:
.gcp_price_list."CP-COMPUTEENGINE-OS" |=
map_values(
if ( .cores == "shared" ) then
.cores = 0.5
else . end
)