what does the err_list means returned by pycurl.curlmulti.infor_read()? - pycurl

m = pycurl.CurlMulti()
for request_param in request_params:
c = pycurl.Curl()
c.setopt(pycurl.ENCODING, 'gzip')
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.TIMEOUT, int(os.environ['timeout']))
c.setopt(pycurl.CONNECTTIMEOUT, int(os.environ['timeout']))
c.setopt(pycurl.FORBID_REUSE, 1)
c.setopt(pycurl.FRESH_CONNECT, 1)
c.setopt(pycurl.NOSIGNAL, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.setopt(pycurl.URL, request_param['url'])
buffer = BytesIO()
c.setopt(c.WRITEFUNCTION, buffer.write)
m.add_handle(c)
while num_handlers:
ret = m.select(1.0)
if ret == -1 or ret == -2:
continue
while 1:
ret, num_handlers = m.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM: break
while 1:
num_q, ok_list, err_list = m.info_read()
for c, errno, errmsg in err_list:
if "Resolving timed out after" in errmsg or "Could not resolve host" in errmsg:
print("blabla")
My question:after call the info_read(),we get an err_list. What kind of handles will be put into this list? Will it be defined as an error one once any one of the resources in the requested URL request failed?

Related

How can I access what the user passes in the command to use it the command error handler? discord.py

How can I access what the user passes in the command user so I can use it the user.error handler?
here's what I've tried and didn't work:
#commands.command(aliases= ["info"])
async def user(self, ctx, *, member: discord.Member=None):
colors = [0xad1457, 0xe67e22, 0x992d22, 0x607d8b, 0x7289da, 0x71368a, 0x11806a]
if member == None:
embed = discord.Embed(color = random.choice(colors))
embed.add_field(name = "**Joined Discord**:", value = "`" + ctx.author.created_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.add_field(name = "**Joined Server:**", value = "`" + ctx.author.joined_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.set_footer(text = f"{ctx.author.name}")
embed.set_image(url = f"{ctx.author.avatar_url}")
await ctx.send(embed = embed)
else:
embed = discord.Embed(color = random.choice(colors))
embed.add_field(name = "**Joined Discord**:", value = "`" + member.created_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.add_field(name = "**Joined Server:**", value = "`" + member.joined_at.strftime("%d/%m/%Y %I:%M") + "`")
embed.set_footer(text = f"{member.name}")
embed.set_image(url = f"{member.avatar_url}")
await ctx.send(embed = embed)
#user.error
async def user_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"**Wrong format. Use {ctx.prefix}user <user>**")
elif isinstance(error, commands.MemberNotFound):
await ctx.send(f"**🙄 - {ctx.author.name}**, I can't find {member.id} in the server.")
else:
raise error
so I want to access what the user passes in the command so I can use it in the command handler.
and another question, how can I make the aliases doesn't need the prefix to run the command
example: in my code above I have info as aliases, I want if the user typed info(without the prefix) the bot will answer.
You can get the passed arguments and keyword arguments with ctx.args and ctx.kwargs.
EDIT:
#user.error
async def user_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"**Wrong format. Use {ctx.prefix}user <user>**")
elif isinstance(error, commands.MemberNotFound):
await ctx.send(f"**🙄 - {ctx.author.name}**, I can't find a member with {error.argument} in the server.")
else:
raise error

[RabbitMQ][AMQP] Failing to get and read single message with amqp_basic_get and amqp_read_message

I want to setup a consumer with amqp to read from a specific queue. Some googling pointed out that this can be done with amqp_basic_get, and looking into the documentation, the actual message is retrieved with amqp_read_message. I also found this example which I tried to follow for implementing the basic_get. Nevertheless, I am failing to get and read a message from a specific queue.
My scenario is like this: I have two programs that communicate by publishing and consuming from the rabbitmq server. In each, a connection is declared, with two channels, one meant for consuming, and one for publishing. The flow of information is like this: program A gets the current time and publishes to rabbitmq. Upon receiving this message, program B gets its own time, packages its time and the received time in a message that it publishes to rabbitmq. Program A should consume this message. However, I cannot succeed in reading from the namedQueue.
Program A (in c++, and uses the amqp.c) is implemented as follows:
... after creating the connection
//Create channels
amqp_channel_open_ok_t *res = amqp_channel_open(conn, channelIDPub);
assert(res != NULL);
amqp_channel_open_ok_t *res2 = amqp_channel_open(conn, channelIDSub);
assert(res2 != NULL);
//Declare exchange
exchange = "exchangeName";
exchangetype = "direct";
amqp_exchange_declare(conn, channelIDPub, amqp_cstring_bytes(exchange.c_str()),
amqp_cstring_bytes(exchangetype.c_str()), 0, 0, 0, 0,
amqp_empty_table);
...
throw_on_amqp_error(amqp_get_rpc_reply(conn), printText.c_str());
//Bind the exchange to the queue
const char* qname = "namedQueue";
amqp_bytes_t queue = amqp_bytes_malloc_dup(amqp_cstring_bytes(qname));
amqp_queue_declare_ok_t *r = amqp_queue_declare(
conn, channelIDSub, queue, 0, 0, 0, 0, amqp_empty_table);
throw_on_amqp_error(amqp_get_rpc_reply(conn), "Declaring queue");
if (queue.bytes == NULL) {
fprintf(stderr, "Out of memory while copying queue name");
return;
}
amqp_queue_bind(conn, channelIDSub, queue, amqp_cstring_bytes(exchange.c_str()),
amqp_cstring_bytes(queueBindingKey.c_str()), amqp_empty_table);
throw_on_amqp_error(amqp_get_rpc_reply(conn), "Binding queue");
amqp_basic_consume(conn, channelIDSub, queue, amqp_empty_bytes, 0, 0, 1,
amqp_empty_table);
throw_on_amqp_error(amqp_get_rpc_reply(conn), "Consuming");
// ...
// In order to get a message from rabbitmq
amqp_rpc_reply_t res, res2;
amqp_message_t message;
amqp_boolean_t no_ack = false;
amqp_maybe_release_buffers(conn);
printf("were here, with queue name %s, on channel %d\n", queueName, channelIDSub);
amqp_time_t deadline;
struct timeval timeout = { 1 , 0 };//same timeout used in consume(json)
int time_rc = amqp_time_from_now(&deadline, &timeout);
assert(time_rc == AMQP_STATUS_OK);
do {
res = amqp_basic_get(conn, channelIDSub, amqp_cstring_bytes("namedQueue"), no_ack);
} while (res.reply_type == AMQP_RESPONSE_NORMAL &&
res.reply.id == AMQP_BASIC_GET_EMPTY_METHOD
&& amqp_time_has_past(deadline) == AMQP_STATUS_OK);
if (AMQP_RESPONSE_NORMAL != res.reply_type || AMQP_BASIC_GET_OK_METHOD != res.reply.id)
{
printf("amqp_basic_get error codes amqp_response_normal %d, amqp_basic_get_ok_method %d\n", res.reply_type, res.reply.id);
return false;
}
res2 = amqp_read_message(conn,channelID,&message,0);
printf("error %s\n", amqp_error_string2(res2.library_error));
printf("5:reply type %d\n", res2.reply_type);
if (AMQP_RESPONSE_NORMAL != res2.reply_type) {
printf("6:reply type %d\n", res2.reply_type);
return false;
}
payload = std::string(reinterpret_cast< char const * >(message.body.bytes), message.body.len);
printf("then were here\n %s", payload.c_str());
amqp_destroy_message(&message);
Program B (in python) is as follows
#!/usr/bin/env python3
import pika
import json
from datetime import datetime, timezone
import time
import threading
cosimTime = 0.0
newData = False
lock = threading.Lock()
thread_stop = False
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
connectionPublish = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channelConsume = connection.channel()
channelPublish = connectionPublish.channel()
print("Declaring exchange")
channelConsume.exchange_declare(exchange='exchangeName', exchange_type='direct')
channelPublish.exchange_declare(exchange='exchangeName', exchange_type='direct')
print("Creating queue")
result = channelConsume.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
result2 = channelPublish.queue_declare(queue='namedQueue', exclusive=False, auto_delete=False)
channelConsume.queue_bind(exchange='exchangeName', queue=queue_name,
routing_key='fromB')
channelPublish.queue_bind(exchange='exchangeName', queue="namedQueue",
routing_key='toB')
print(' [*] Waiting for logs. To exit press CTRL+C')
def callbackConsume(ch, method, properties, body):
global newData, cosimTime
print("\nReceived [x] %r" % body)
#cosimTime = datetime.datetime.strptime(body, "%Y-%m-%dT%H:%M:%S.%f%z")
with lock:
newData = True
cosimTime = body.decode()
cosimTime = json.loads(cosimTime)
#print(cosimTime)
def publishRtime():
global newData
while not thread_stop:
if newData:
#if True:
with lock:
newData = False
msg = {}
msg['rtime'] = datetime.now(timezone.utc).astimezone().isoformat(timespec='milliseconds')
msg['cosimtime'] = cosimTime["simAtTime"]
print("\nSending [y] %s" % str(msg))
channelPublish.basic_publish(exchange='exchangeName',
routing_key='toB',
body=json.dumps(msg))
#time.sleep(1)
channelConsume.basic_consume(
queue=queue_name, on_message_callback=callbackConsume, auto_ack=True)
try:
thread = threading.Thread(target = publishRtime)
thread.start()
channelConsume.start_consuming()
except KeyboardInterrupt:
print("Exiting...")
channelConsume.stop_consuming()
thread_stop = True
connection.close()
What program A outputs is:
amqp_basic_get error codes amqp_response_normal 1, amqp_basic_get_ok_method 3932232
which is the code for AMQP_BASIC_GET_EMPTY_METHOD.
Program B gets the data, and publishes continuously.
If I slightly modify B to just publish all the time a specific string, then it seems that the amqp_basic_get returns successfully, however then it fails at amqp_read_message with the code AMQP_RESPONSE_LIBRARY_EXCEPTION.
Any idea how to get this to work, what I am missing the setup?
The issue was in the queue_declare where the auto_delete parameter was not matching on both sides.

How to assert an element is present after a click in Hound?

I'm using Hound as webdriver framework for leveraging Selenium in Elixir. I'm testing facebook account creation. After I fill out a negative test (firstname = Roberto, lastname = asdlkfj;)I click submit and I am trying to get an error for not having a correct last name. The problem is Hound isn't waiting for the element to be displayed and returns an element not found error. How can I handle this and have the test wait until the element is loaded? Here's my code:
test "Last name with random characters" do
counter = :rand.uniform(100)
navigate_to "https://www.facebook.com"
first_name = find_element(:name, "firstname")
fill_field(first_name, "Jorge")
last_name = find_element(:name, "lastname")
fill_field(last_name, "asdfja;lsdf")
email_input = "robbie#{counter}#gmail.com"
email = find_element(:name, "reg_email__")
fill_field(email, email_input)
confirm_email = find_element(:name, "reg_email_confirmation__")
fill_field(confirm_email, email_input)
password_input = "123456Test"
password = find_element(:name, "reg_passwd__")
fill_field(password, password_input)
#Birthday
birth_month = find_element(:css, "#month > option:nth-child(5)")
birth_day = find_element(:css, "#day > option:nth-child(25)")
birth_year = find_element(:css, "#year > option:nth-child(22)")
click(birth_month)
click(birth_day)
click(birth_year)
#gender
select_gender = find_element(:css, "#u_0_s > span:nth-child(2)")
click(select_gender)
sign_up_button = find_element(:name, "websubmit")
click(sign_up_button)
search = find_element(:id, "#reg_error_inner")
# found = element_displayed?("#reg_error_inner")
IO.puts(search)
# assert found == true
# :timer.sleep(10000)
end```
Use search_element instead of find_element. search_element will return {:ok, element} on success and {:error, error} on failure. If you just want to assert the element exists, then you can:
assert {:ok, _} = search_element(:id, "#reg_error_inner")
If you want to also have it in a variable for further processing, then:
assert {:ok, element} = search_element(:id, "#reg_error_inner")
If you want to convert it to a boolean, then:
match?({:ok, _}, search_element(:id, "#reg_error_inner"))

AutoIt - How to read pdf document properties

I'm trying to read PDF' page size eg.height X weight. Page size can be found in
File -> Properties -> Page Size
I used the code below to fetch the property value:
$path = FileOpenDialog("Select a file to read attributes",#ScriptDir,"All (*.*)")
$prop = _GetExtProperty($path,-1)
_ArrayDisplay($prop,"Property Array")
Func _GetExtProperty($sPath, $iProp)
Local $iExist, $sFile, $sDir, $oShellApp, $oDir, $oFile, $aProperty, $sProperty
$iExist = FileExists($sPath)
If $iExist = 0 Then
SetError(1)
Return 0
Else
$sFile = StringTrimLeft($sPath, StringInStr($sPath, "\", 0, -1))
$sDir = StringTrimRight($sPath, (StringLen($sPath) - StringInStr($sPath, "\", 0, -1)))
$oShellApp = ObjCreate ("shell.application")
$oDir = $oShellApp.NameSpace ($sDir)
$oFile = $oDir.Parsename ($sFile)
If $iProp = -1 Then
Local $aProperty[35]
For $i = 0 To 34
$aProperty[$i] = $oDir.GetDetailsOf ($oFile, $i)
Next
Return $aProperty
Else
$sProperty = $oDir.GetDetailsOf ($oFile, $iProp)
If $sProperty = "" Then
Return 0
Else
Return $sProperty
EndIf
EndIf
EndIf
EndFunc ;==>_GetExtProperty
By using above code i managed to get file size in MB, Created date , Modified date, Location and so on, but not Page Size. Appreciated, if anyone could advice how I can get page size. Any reference, advice or sample code is highly appreciated.
Nearly the same, but maybe it helps.
#include <Array.au3>
;===============================================================================
; Function Name.....: _FileGetProperty
; Description.......: Returns a property or all properties for a file.
; Version...........: 1.0.2
; Change Date.......: 2008-07-28
; AutoIt Version....: 3.2.12.1
;
; Parameter(s)......: $S_PATH - String containing the file path to return the property from.
; $S_PROPERTY - [optional] String containing the name of the property to return. (default = "")
; Requirements(s)...: None
; Return Value(s)...: Success: Returns a string containing the property value.
; If $S_PROPERTY is empty, an two-dimensional array is returned:
; $av_array[0][0] = Number of properties.
; $av_array[1][0] = 1st property name.
; $as_array[1][1] = 1st property value.
; $av_array[n][0] = nth property name.
; $as_array[n][1] = nth property value.
; Failure: Returns 0 and sets #error to:
; 1 = The folder $S_PATH does not exist.
; 2 = The property $S_PROPERTY does not exist or the array could not be created.
; 3 = Unable to create the "Shell.Application" object $objShell.
;
; Author(s).........: - Simucal <Simucal#gmail.com>
; - Modified by: Sean Hart <autoit#hartmail.ca>
; - Modified by: teh_hahn <sPiTsHiT#gmx.de>
; Company...........: None
; URL...............: None
; Note(s)...........: None
;===============================================================================
Global $re = _FileGetProperty(#ScriptDir & '\1Tutorial - AutoItWiki1.pdf')
If #error Then MsgBox(16, 'ERROR', 'Error: ' & #error & #CRLF & '1 = The folder $S_PATH does not exist.' & #CRLF & _
'2 = The property $S_PROPERTY does not exist or the array could not be created.' & #CRLF & _
'3 = Unable to create the "Shell.Application" object $objShell.')
_ArrayDisplay($re)
Func _FileGetProperty(Const $S_PATH, Const $S_PROPERTY = "")
If Not FileExists($S_PATH) Then Return SetError(1, 0, 0)
Local Const $S_FILE = StringTrimLeft($S_PATH, StringInStr($S_PATH, "\", 0, -1))
Local Const $S_DIR = StringTrimRight($S_PATH, StringLen($S_FILE) + 1)
Local Const $objShell = ObjCreate("Shell.Application")
If #error Then Return SetError(3, 0, 0)
Local Const $objFolder = $objShell.NameSpace($S_DIR)
Local Const $objFolderItem = $objFolder.Parsename($S_FILE)
If $S_PROPERTY Then
For $i = 0 To 99
If $objFolder.GetDetailsOf($objFolder.Items, $i) = $S_PROPERTY Then Return $objFolder.GetDetailsOf($objFolderItem, $i)
Next
Return SetError(2, 0, 0)
EndIf
Local $av_ret[1][2] = [[1]]
For $i = 0 To 99
If $objFolder.GetDetailsOf($objFolder.Items, $i) Then
ReDim $av_ret[$av_ret[0][0] + 1][2]
$av_ret[$av_ret[0][0]][0] = $objFolder.GetDetailsOf($objFolder.Items, $i)
$av_ret[$av_ret[0][0]][1] = $objFolder.GetDetailsOf($objFolderItem, $i)
$av_ret[0][0] += 1
EndIf
Next
If Not $av_ret[1][0] Then Return SetError(2, 0, 0)
$av_ret[0][0] -= 1
Return $av_ret
EndFunc ;==>_FileGetProperty

change a clipper code to bypass authentication of a old program

Hi a friend of mine asked me to recover a password of a program written in clipper back in 1994. I got myself a decompiler (Valkyrie 5) and decompiled the EXE-file. I located a procedure called USERLOGIN. The problem is that i dont know how to program in clipper. I would be very thankfull if someone could edit the procedure so it won't ask for authentication anymore.
#include "common.ch"
#include "inkey.ch"
********************************
Function USERLOGON
Local Local1:= -1, Local2:= .F., Local3, Local4, Local5:= 3, ;
Local6:= 3, Local7:= 7, Local8:= 41, Local9, Local10, Local11, ;
Local12, Local13, Local14, Local15
Local3:= 1
Local9:= {}
Local13:= setcursor()
If (!netuse(diskname() + ":" + dirname() + "\" + "sinusr.dbf", ;
"users"))
Return Local1
EndIf
dbSetFilter({ || users->valid })
Local14:= box(Local5, Local6, Local7, Local8, Nil, ;
coltonum("GR+/B"))
Do While (!Local2)
Local10:= Space(12)
Local11:= Space(10)
setcursor(1)
If (!Empty(n_shellver()))
Local10:= padr(nnetwhoami(), 12)
EndIf
wininfo(Local14, #Local5, #Local6, #Local7, #Local8)
# Local5 + 1, Local6 + 5 Say "User............." Color "GR+/B"
SetPos(Row(), Col() + 1)
AAdd(Local9, __Get({ |_1| IIf(ISNIL(_1), Local10, Local10:= ;
_1) }, "cUName", "#K!", Nil, Nil):display())
# Local5 + 2, Local6 + 5 Say "Password........." Color "GR+/B"
SetPos(Row(), Col() + 1)
AAdd(Local9, __Get({ |_1| IIf(ISNIL(_1), Local11, Local11:= ;
_1) }, "cUPass", "#K!", Nil, Nil):display())
Local9[2]:reader({ |_1| gt_grpassw(_1) })
wreadmodal(Local9, 0)
Local11:= Local9[2]:cargo()
Local9:= {}
If (LastKey() == K_ESC .OR. !winisinuse(Local14))
If (winisinuse(Local14))
winclose(Local14)
EndIf
Return Local1
EndIf
Local10:= alltrim(Local10)
Local12:= {}
Locate For Local10 == alltrim(users->emri)
Do While (Found())
AAdd(Local12, users->id)
Continue
EndDo
For Local4:= 1 To Len(Local12)
If ((Local15:= upass(Local12[Local4])) != Nil)
If (alltrim(Local11) == Local15)
Local2:= .T.
Exit
EndIf
EndIf
Next
EndDo
If (users->id != Local12[Local4])
users->(dbGoTop())
Locate For Local12[Local4] == users->id
If (!Found())
msg("Fatal error in user's file !", 3)
Return -1
EndIf
EndIf
For Local4:= 1 To MaxCol()
winchgpos(0, 3)
Next
boxc(Local14)
setcursor(Local13)
If (users->in)
tone(500, 10)
Local4:= al_box("User " + Trim(users->emri) + ;
" is already IN;" + "Do You Want to Jump In ?", 2, ;
{" Yes ", " No "}, 2, "WARNING")
If (Local4 == 1)
msg("More than One User with the same Name might cause Trouble !", ;
3)
Else
Close
Return -1
EndIf
ElseIf (netrlock())
Replace users->in With .T.
Unlock
dbcommit()
Else
Close
Return -1
EndIf
Static148[1]:= users->id
Static148[2]:= alltrim(users->emri)
Static148[3]:= alltrim(users->dirpriv)
Static148[4]:= users->gjuha1
Static148[5]:= users->gjuha2
Static148[6]:= alltrim(users->emriiplote)
Local1:= Static148[1]
Close
Return Local1
* EOF
This is partially guesswork, but here's my interpretation:
Read the user's password from the console into Local9[2]:
# Local5 + 2, Local6 + 5 Say "Password........." Color "GR+/B"
...
Local9[2]:reader({ |_1| gt_grpassw(_1) })
wreadmodal(Local9, 0)
Put the password into Local11:
Local11:= Local9[2]:cargo()
Fetch all user ids into Local12 via Local10:
Locate For Local10 == alltrim(users->emri)
Do While (Found())
AAdd(Local12, users->id)
Continue
EndDo
Get each user's password into Local15, and if the password's present and matches the password in Local11, verify the user:
For Local4:= 1 To Len(Local12)
If ((Local15:= upass(Local12[Local4])) != Nil)
If (alltrim(Local11) == Local15)
Local2:= .T.
Exit
EndIf
EndIf
Next
The fix
Just remove the password check code. Not being certain about the purpose of all the rest of the code, I'd recommend leaving it alone. I've preserved the retrieval of the user's password, as maybe there's a good reason not to log in a user who has no password at all (perhaps that's how an account is disabled. The last block above could be changed to this:
For Local4:= 1 To Len(Local12)
If ((Local15:= upass(Local12[Local4])) != Nil)
Local2:= .T.
EndIf
Next