Error when acquiring a lock in julia 1.5.2 - multithreading

I am following the documentation to acquire a lock on a variable but it fails:
a = 0
lock(a) do
a += 1
end
Error message:
ERROR: MethodError: no method matching lock(::var"#3#4", ::Int64)
Closest candidates are:
lock(::Any, ::Base.GenericCondition) at condition.jl:78
lock(::Any, ::Base.AbstractLock) at lock.jl:158
lock(::Any, ::WeakKeyDict) at weakkeydict.jl:76
Stacktrace:
[1] top-level scope at REPL[3]:1
The error message is clear but why would the code provided in the documentation fail. Moreover, not sure where to look for the detailed documentation about the lock function.

OK, I figured it out:
a = 0
l = ReentrantLock()
lock(l) do
global a # Needed if using REPL
a += 1
end

Related

Angr can't solve the googlectf beginner problem

I am a student studying angr, first time.
I'm watching the code in this url.
https://github.com/Dvd848/CTFs/blob/master/2020_GoogleCTF/Beginner.md
import angr
import claripy
FLAG_LEN = 15
STDIN_FD = 0
base_addr = 0x100000 # To match addresses to Ghidra
proj = angr.Project("./a.out", main_opts={'base_addr': base_addr})
flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(FLAG_LEN)]
flag = claripy.Concat( *flag_chars + [claripy.BVV(b'\n')]) # Add \n for scanf() to accept the input
state = proj.factory.full_init_state(
args=['./a.out'],
add_options=angr.options.unicorn,
stdin=flag,
)
# Add constraints that all characters are printable
for k in flag_chars:
state.solver.add(k >= ord('!'))
state.solver.add(k <= ord('~'))
simgr = proj.factory.simulation_manager(state)
find_addr = 0x101124 # SUCCESS
avoid_addr = 0x10110d # FAILURE
simgr.explore(find=find_addr, avoid=avoid_addr)
if (len(simgr.found) > 0):
for found in simgr.found:
print(found.posix.dumps(STDIN_FD))
https://github.com/google/google-ctf/tree/master/2020/quals/reversing-beginner/attachments
Which is the answer of googlectf beginner.
But, the above code does not work. It doesn't give me the answer.
I want to know why the code is not working.
When I execute this code, the output was empty.
I run the code with python3 in Ubuntu 20.04 in wsl2
Thank you.
I believe this script isn't printing anything because angr fails to find a solution and then exits. You can prove this by appending the following to your script:
else:
raise Exception('Could not find the solution')
If the exception raises, a valid solution was not found.
In terms of why it doesn't work, this code looks like copy & paste from a few different sources, and so it's fairly convoluted.
For example, the way the flag symbol is passed to stdin is not ideal. By default, stdin is a SimPackets, so it's best to keep it that way.
The following script solves the challenge, I have commented it to help you understand. You will notice that changing stdin=angr.SimPackets(name='stdin', content=[(flag, 15)]) to stdin=flag will cause the script to fail, due to the reason mentioned above.
import angr
import claripy
base = 0x400000 # Default angr base
project = angr.Project("./a.out")
flag = claripy.BVS("flag", 15 * 8) # length is expected in bits here
initial_state = project.factory.full_init_state(
stdin=angr.SimPackets(name='stdin', content=[(flag, 15)]), # provide symbol and length (in bytes)
add_options ={
angr.options.SYMBOL_FILL_UNCONSTRAINED_MEMORY,
angr.options.SYMBOL_FILL_UNCONSTRAINED_REGISTERS
}
)
# constrain flag to common alphanumeric / punctuation characters
[initial_state.solver.add(byte >= 0x20, byte <= 0x7f) for byte in flag.chop(8)]
sim = project.factory.simgr(initial_state)
sim.explore(
find=lambda s: b"SUCCESS" in s.posix.dumps(1), # search for a state with this result
avoid=lambda s: b"FAILURE" in s.posix.dumps(1) # states that meet this constraint will be added to the avoid stash
)
if sim.found:
solution_state = sim.found[0]
print(f"[+] Success! Solution is: {solution_state.posix.dumps(0)}") # dump whatever was sent to stdin to reach this state
else:
raise Exception('Could not find the solution') # Tell us if angr failed to find a solution state
A bit of Trivia - there are actually multiple 'solutions' that the program would accept, I guess the CTF flag server only accepts one though.
❯ echo -ne 'CTF{\x00\xe0MD\x17\xd1\x93\x1b\x00n)' | ./a.out
Flag: SUCCESS

Problem with billing_agreement.cancel(). ('cancel() missing 1 required positional argument: 'attributes')

SDK/Library version: 1.13.1
Environment: Sandbox
PayPal-Debug-ID values: None
Language, the language version, and OS: Python, Ubuntu
Issue description:
I'm getting the following error when I try to cancel a billing agreement.
The error:
TypeError: cancel() missing 1 required positional argument: 'attributes'
My code:
billing_agreement = BillingAgreement.find(billing_id)
if billing_agreement.cancel():
print(billing_agreement)
else:
flash('We are having some difficulties canceling your subscription, please try again later.', 'fails')
return redirect(url_for('settings.settingspage'))
I'm getting the error because I need something in the attribute's value but I don't know what should I assign to the variable.
GitHub issue: https://github.com/paypal/PayPal-Python-SDK/issues/297
After some digging and looking at the documentation samples I found a sample about the cancel option and what I needed to assign to the attribute value was a cancel_note.
The code:
cancel_note = {"note": "Canceling the agreement"}
user = Users.query.filter_by(id=ID).first()
billing_id = Subscriptions.query.filter_by(email=user.email).filter_by(active=1).first().order_id
billing_agreement = BillingAgreement.find(billing_id)
if billing_agreement.cancel(cancel_note):
flash('Subscription canceled with success.', 'success')
return redirect(url_for('settings.settingspage'))
else:
flash('We are having some difficulties canceling your subscription, please try again later.', 'fails')
return redirect(url_for('settings.settingspage'))
The documentation sample

Show expected and actual values for assertion failures

When writing assertions for my tests, the assertion failures don't provide enough information without needing to open an IDE and start debugging.
For example, I have some code that uses the 'assert' library:
import * as assert from 'assert'
// some code
assert(someObject.getValue() === 0)
I just get
AssertionError [ERR_ASSERTION]: false == true
+ expected - actual
-false
+true
This error message isn't really meaningful. As a workaround, I added it in the message in the assertion:
assert(someObject.getValue() === 0,
'\nActual: ' + someObject.getValue() +
'\nExpected: ' + 0)
Is there a better, cleaner way to just show the expected & actual values without overriding the message on every assertion? I also tried to create an assert wrapper, but I wasn't able to extract the actual and expected values from the expression.
EDIT: assert.strictEqual resolves this issue for equalities only. But as soon as any other operator is included, then we have the same issue (e.g. assert(someObject.getValue() > 0)
Any advice would be appreciated.
Thanks!
You can use assert.strictEqual(actual, expected[, message]) to get actual/expected error messages without the need of the third message argument:
assert.strictEqual(someObject.getValue(), 0)
You'd get an error message such as:
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 0
Hopefully that helps!

ZADD Redis error

I am implementing a targeted search using Redis
Below the function for indexing ads
def index_ad(conn,id,locations,content,type,value):
pipeline = conn.pipeline(True)
for location in locations:
pipeline.sadd('idx:req:'+location,id)
words = tokenize(content)
for word in words:
pipeline.zadd('idx:'+word,id,0)
rvalue = TO_ECPM[type](1000,AVERAGE_PER_1K.get(type,1),value)
pipeline.hset('type:',id,type)
pipeline.zadd('idx:ad:value:',id,rvalue)
pipeline.zadd('ad:base_value:',id,value)
pipeline.sadd('terms:'+id,*list(words))
pipeline.execute()
I get the following error:
Command # 3 (ZADD idx:look 0 1) of pipeline caused error: WRONGTYPE Operation against a key holding the wrong kind of value

What's the correct way to check sql found condition in ILE RPG?

When working with embedded SQL in RPG, you often end up with a cursor and a dow-loop for processing all rows in your result. The condition in the loop is somehow dependent on SQLCOD and/or SQLSTT, some globally available variables in an SQLRPGLE-program?
But what is the correct way of checking these values? Some suggest SQLCOD = 0 others not (SQLCOD = +100 or SQLSTT = '02000'). One fails on all warnings, the other does not fail on some errors, so I'm not content.
To illustrate what I do with some code:
Pmain B
D PI
Dmy_ds E DS extname(SOME_TABLE)
D qualified
/free
exec sql
DECLARE cur CURSOR FOR
SELECT *
FROM some_table;
exec sql
OPEN cur;
exec sql
FETCH cur
INTO :my_ds;
dow sql_found();
exec sql
FETCH cur
INTO :my_ds;
enddo;
exec sql
CLOSE cur;
/end-free
Pmain E
Psql_found B
D PI N
/free
// insert return statement here...
/end-free
Psql_found E
I'm looking for the correct return statement here, that will make me go through all rows if no error occurs and lets me leave when an error occurs. Bonus points for some decent way to check for errors.
SQLSTATE is better, and recommended by IBM.
From IBM's InfoCenter SQL Messages and Codes Reference: SQLCODE and SQLSTATE concepts
SQLSTATE is the preferred standard return code.
SQLSTATE is 5 characters, with the first two bytes identifying a class of conditions.
'00' = Unqualified Successful Completion
'01' = Warning
'02' = No Data
Anything else is an error. I generally only check for '00'.
Simple. Easy. More portable.
Using SQLCODE often involves lists of codes which are, IMHO, less than developer friendly.
Example:
Personally, I generally include definitions and code like this:
D xSQLState# s * inz( %addr(SQLState) )
D xSQLState ds 5 based(xSQLState#)
D xSQLState2 2a
D
D Success_On_SQL C const('00')
D Warning_On_SQL C const('01')
D NoData_On_SQL C const('02')
Then after any SQL operation, I generally check
if xSQLState2 <> Success_On_Sql;
someflag = true;
endif;
The best practice is to process the SQLCODEs you expect (as part of the expected processing) and to add exception code to handle the ones you don't. One implementation:
dow 1=1; // forever
exec sql
FETCH cur
INTO :my_ds;
// normal exit
if sqlstt = SQL_NODATA;
SFLEND = *on;
leave;
endif;
// can't CAST a value
if sqlstt = SQL_CAST; // CAST error
... tell user there's an error and read another
iter;
endif;
// decimal data error
if sqlstt = SQL_DDE;
tell user to call IT and stop reading
leave;
endif;
// whoops! not expected at all. Dump for post-mortem
if sqlstt <> SQL_NORMAL;
... tell user to call IT and stop reading
dump(a);
leave;
endif;
// test for end of loop
// filled subfile page?
enddo; // forever
With this type of implementation you have to intentionally leave the loop; whether you've filled a subfile page, loaded the highest element in an array or hit an error. I'm not sure there is a single, generic implementation that will handle all circumstances. Sometimes you might want to leave the read loop if you have a record lock and sometimes you want to issue a message and try again (for example).
I did some more searching on the topic and found something on IBM's site (quote):
The SQLCODE is also set by the database manager after each SQL
statement is executed as follows:
- If SQLCODE = 0 and SQLWARN0 is blank, execution was successful.
- If SQLCODE = 100, no data was found. For example, a FETCH
statement returned no data, because the cursor was positioned
after the last row of the result table.
- If SQLCODE > 0 and not = 100, execution was successful with a
warning.
- If SQLCODE = 0 and SQLWARN0 = 'W', execution was successful
with a warning.
- If SQLCODE < 0, execution was not successful.
Which would lead me to an sql_found() like this:
Pfound_sql B
D PI N
/free
return (SQLCOD >= 0) and (SQLCOD<>100);
/end-free
Pfound_sql E
That should take care of the End of Data condition and fail on all errors. I'm not sure if there are some warnings that I should take care of (don't want to get trapped in an endless loop, if there is a warning that leads to not reading).

Resources