Amazon MTurk: can't delete HIT in state 'Reviewable' - amazon-web-services

I am using the script offered here to delete deployed HITs from the Amazon Mechanical Turk platform. However, I am getting the following exception by the mturk client:
An error occurred (RequestError) when calling the DeleteHIT operation: This HIT is currently in the state 'Reviewable'. This operation can be called with a status of: Reviewing, Reviewable (1574723552282 s)
To me, the error msg itself seems to be wrong. Does anybody have an explanation for this behaviour?

Try somethng like this maybe, I found this somewhere and it can solve your problem,
# if hit is reviewable and has assignments, approve assignments
if status == 'Reviewable':
assignments = mturk.list_assignments_for_hit(HITId=hit['HITId'], AssignmentStatuses=['Submitted'])
if assignments['NumResults'] > 0:
for assign in assignments['Assignments']:
mturk.approve_assignment(AssignmentId=assign['AssignmentId'])
try:
mturk.delete_hit(HITId=hit['HITId'])
except:
print('Not deleted')

Related

How to handle exceptions with stripe

I am trying to integrate stripe with my django project, so I try to create a PaymentIntent and if a network communication with stripe failed I will try to do like this:
try:
intent = stripe.PaymentIntent.create(
amount=100,
currency='usd'
)
return JsonResponse({
'clientSecret': intent['client_secret']
})
except stripe.error.CardError as e:
pass
except stripe.error.RateLimitError as e:
pass
except stripe.error.InvalidRequestError as e:
pass
except stripe.error.AuthenticationError as e:
pass
except stripe.error.APIConnectionError as e:
try:
intent_cancel = stripe.PaymentIntent.cancel(
intent['id']
)
except Exception as e:
# (If an exception is raised this means that the PaymentIntent was not created, I am right ?)
# I redirect the user to the payment page and inform him
# that a network problem has occurred and ask him to repeat his request
pass
except stripe.error.StripeError as e:
pass
except Exception as e:
pass
My questions are:
1 Is my way of handling the exception right ?
2 Can I apply this logic to the other exception ?
3 In the documentation they say that we should use an idempotency_key to retry the failed requests, how can I implement this ? and what about if I retry the failed request and it fails again, what should I do ?
You have 2 Stripe API requests in the same try block. This means if one succeeds but the other fails due to a connection error you'll treat both as failed. A better flow would be to only have one API operation per try/catch block.
You also have a request to cancel a hardcoded PaymentIntent after your code returns a JSON object. Since the return isn't conditional this is likely dead code.
The cancel logic in the case of a connection error doesn't make sense here. You should only hit this path if the connection failed and the intent wasn't created, so trying to cancel the non-existent PaymentIntent will likely result in yet another error. Instead you should introduce retry logic here. Luckily stripe-python has this built in specifically for network errors: https://github.com/stripe/stripe-python#configuring-automatic-retries
Once all retries have failed, you should probably log that somewhere and inform your user that a problem occurred and that they should try again later.
As for idempotency keys, the Stripe docs have a primer on that here: https://stripe.com/docs/api/idempotent_requests?lang=python

Python urllib3 Error Handling

I'm fairly new to Python and would like some guidance on how to deal with authentication errors with urrlib3 on Python 2.7. My current use case is using SNAPI to auto create ServiceNow tickets. To do this I have the following snippet of code to use my username/password and get a token to log in.
r = session.post(auth_url, json=login_data, verify=False)
web_token = r.text
This is working fine but I want a cleaner way of notifying myself if there is an error within the code. If the username/password is incorrect, I get this back from the SN web server.
{
"error": "Authentication failure"
}
Originally I was going to use a try/exception but it seems like that wouldn't work very well in this case since the code is working correctly, it's just not the input I was expecting. So my second thought was doing something along the lines of:
if r.text does not contain "error"
then continue on my doe
else send an email telling me the error code
Before writing the code for that, I wanted to see if this is the best method for this type of error handling or if I should be going down another route.
Thanks,
Eric
I spoke with a friend and he recommended the following method which seems to work very well and is a lot cleaner than doing an if/match statement.
try:
r = session.post(auth_url, json=login_data, verify=False)
web_token = r.text
r.raise_for_status()
except Exception as e:
print(e)

How to delete cases in PM?

I am trying to delete cases in PM but I am not able to using the API
http://wiki.processmaker.com/3.1/REST_API_Cases#Delete_Case:DELETE.2Fcases.2F.7Bapp_uid.7D
I have tried this API but it gives me an error like:
[GuzzleHttp\Exception\ClientException]
Client error: `DELETE http://processmaker.app:32768/api/1.0/workflow/cases/50492041658e1dfca544ad3002222462` resulted in a `400 Bad Request` response:
{"error":{"code":400,"message":"Bad Request: You can't delete the case because it's not in Draft status and was already (truncated...)
Yes, I even tried cancelling the case but still the same error
The error you are receiving is because you cannot delete a case once it has left the status of DRAFT. That means, once a case is submitted to the next task, it is considered in the status of TODO.
So, once a case has transitioned to the status of TODO, you may only Cancel a case, not delete it.
You can find more information relating to that here: http://wiki.processmaker.com/3.1/user_guide#Cancel
Don't forget to make sure that the user you are making the rest api call as has the right permissions to be able to cancel/delete the case as well.
To cancel a case through the rest api, take a look at this link: http://wiki.processmaker.com/3.1/REST_API_Cases#Cancel_Case:PUT.2Fcases.2F.7Bapp_uid.7D.2Fcancel
I hope that helps!

Can Amazon Simple Workflow (SWF) be made to work with jRuby?

For uninteresting reasons, I have to use jRuby on a particular project where we also want to use Amazon Simple Workflow (SWF). I don't have a choice in the jRuby department, so please don't say "use MRI".
The first problem I ran into is that jRuby doesn't support forking and SWF activity workers love to fork. After hacking through the SWF ruby libraries, I was able to figure out how to attach a logger and also figure out how to prevent forking, which was tremendously helpful:
AWS::Flow::ActivityWorker.new(
swf.client, domain,"my_tasklist", MyActivities
) do |options|
options.logger= Logger.new("logs/swf_logger.log")
options.use_forking = false
end
This prevented forking, but now I'm hitting more exceptions deep in the SWF source code having to do with Fibers and the context not existing:
Error in the poller, exception:
AWS::Flow::Core::NoContextException: AWS::Flow::Core::NoContextException stacktrace:
"aws-flow-2.4.0/lib/aws/flow/implementation.rb:38:in 'task'",
"aws-flow-2.4.0/lib/aws/decider/task_poller.rb:292:in 'respond_activity_task_failed'",
"aws-flow-2.4.0/lib/aws/decider/task_poller.rb:204:in 'respond_activity_task_failed_with_retry'",
"aws-flow-2.4.0/lib/aws/decider/task_poller.rb:335:in 'process_single_task'",
"aws-flow-2.4.0/lib/aws/decider/task_poller.rb:388:in 'poll_and_process_single_task'",
"aws-flow-2.4.0/lib/aws/decider/worker.rb:447:in 'run_once'",
"aws-flow-2.4.0/lib/aws/decider/worker.rb:419:in 'start'",
"org/jruby/RubyKernel.java:1501:in `loop'",
"aws-flow-2.4.0/lib/aws/decider/worker.rb:417:in 'start'",
"/Users/trcull/dev/etl/flow/etl_runner.rb:28:in 'start_workers'"
This is the SWF code at that line:
# #param [Future] future
# Unused; defaults to **nil**.
#
# #param block
# The block of code to be executed when the task is run.
#
# #raise [NoContextException]
# If the current fiber does not respond to `Fiber.__context__`.
#
# #return [Future]
# The tasks result, which is a {Future}.
#
def task(future = nil, &block)
fiber = ::Fiber.current
raise NoContextException unless fiber.respond_to? :__context__
context = fiber.__context__
t = Task.new(nil, &block)
task_context = TaskContext.new(:parent => context.get_closest_containing_scope, :task => t)
context << t
t.result
end
I fear this is another flavor of the same forking problem and also fear that I'm facing a long road of slogging through SWF source code and working around problems until I finally hit a wall I can't work around.
So, my question is, has anyone actually gotten jRuby and SWF to work together? If so, is there a list of steps and workarounds somewhere I can be pointed to? Googling for "SWF and jRuby" hasn't turned up anything so far and I'm already 1 1/2 days into this task.
I think the issue might be that aws-flow-ruby doesn't support Ruby 2.0. I found this PDF dated Jan 22, 2015.
1.2.1
Tested Ruby Runtimes The AWS Flow Framework for Ruby has been tested
with the official Ruby 1.9 runtime, also known as YARV. Other versions
of the Ruby runtime may work, but are unsupported.
I have a partial answer to my own question. The answer to "Can SWF be made to work on jRuby" is "Yes...ish."
I was, indeed, able to get a workflow working end-to-end (and even make calls to a database via JDBC, the original reason I had to do this). So, that's the "yes" part of the answer. Yes, SWF can be made to work on jRuby.
Here's the "ish" part of the answer.
The stack trace I posted above is the result of SWF trying to raise an ActivityTaskFailedException due to a problem in some of my activity code. That part is my fault. What's not my fault is that the superclass of ActivityTaskFailedException has this code in it:
def initialize(reason = "Something went wrong in Flow",
details = "But this indicates that it got corrupted getting out")
super(reason)
#reason = reason
#details = details
details = details.message if details.is_a? Exception
self.set_backtrace(details)
end
When your activity throws an exception, the "details" variable you see above is filled with a String. MRI is perfectly happy to take a String as an argument to set_backtrace(), but jRuby is not, and jRuby throws an exception saying that "details" must be an Array of Strings. This exception blows through all the nice error catching logic of the SWF library and into this code that's trying to do incompatible things with the Fiber library. That code then throws a follow-on exception and kills the activity worker thread entirely.
So, you can run SWF on jRuby as long as your activity and workflow code never, ever throws exceptions because otherwise those exceptions will kill your worker threads (which is not the intended behavior of SWF workers). What they are designed to do instead is communicate the exception back to SWF in a nice, trackable, recoverable fashion. But, the SWF code that does the communicating back to SWF has, itself, code that's incompatible with jRuby.
To get past this problem, I monkey-patched AWS::Flow::FlowException like so:
def initialize(reason = "Something went wrong in Flow",
details = "But this indicates that it got corrupted getting out")
super(reason)
#reason = reason
#details = details
details = details.message if details.is_a? Exception
details = [details] if details.is_a? String
self.set_backtrace(details)
end
Hope that helps someone in the same situation as me.
I'm using JFlow, it lets you start SWF flow activity workers with JRuby.

Sharing through Facebook SDK I am getting the following error in iphone app?Can you suggest me what mistake might me I made?

While I am trying to share something through facebook SDK I am getting error like
"Error Domain=facebookErrDomain Code=10000 "The operation couldn’t be completed. (facebookErrDomain error 10000.)" UserInfo=0xd1700a0 {error={ code = 12; message = "(#12) username is deprecated for versions v2.0 and higher"; type = OAuthException; }}".
Can any one help me which kind of error will be? Thanks in advance
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.0
there is a clear explanation of the facebook error code in the link given above
according to that your error means: login status or access token has expired, been revoked, or is otherwise invalid - Handle expired access tokens (unless subcode is present)