hi guys I have some logic problem in my code (adonet entity framework)
here's the pseudocode
i = 0
while i < 5
using transactionreadcommited
{
var getuser = (from a in mydb.users where userid.equals(1) select a).firstordefault
try {
getuser.moneyBalance -= 10;
//error here
some command here causing expected error so it goes to catch ;
db.savechanges()
transaction.complete()
}catch{
i = i + 1
}
}
end while
the problem is,:
I get a new user in new transaction every time it retries in the while loop
User's initial money balance is 100.I minus 10, so it becomes 90
but if some command fails, it will exit the transaction and retry -
in the 2nd loop, User's money becomes initial 90 - 10 = 80. shouldn't it revert back to 100, since I recreate a new transaction, and have not committed the first loop ?
Related
SCRIPT ERROR: #sessionmanager/server/host_lock.lua:25: attempt to compare number with nil
[script:sessionmanage]> handler (#sessionmanager/server/host_lock.lua:25)
the script:
-- whitelist c2s events
RegisterServerEvent('hostingSession')
RegisterServerEvent('hostedSession')
-- event handler for pre-session 'acquire'
local currentHosting
local hostReleaseCallbacks = {}
-- TODO: add a timeout for the hosting lock to be held
-- TODO: add checks for 'fraudulent' conflict cases of hosting attempts (typically whenever the host can not be reached)
AddEventHandler('hostingSession', function()
-- if the lock is currently held, tell the client to await further instruction
if currentHosting then
TriggerClientEvent('sessionHostResult', source, 'wait')
-- register a callback for when the lock is freed
table.insert(hostReleaseCallbacks, function()
TriggerClientEvent('sessionHostResult', source, 'free')
end)
return
end
-- if the current host was last contacted less than a second ago
if GetHostId() >= 1 then
if GetPlayerLastMsg(GetHostId()) < 1000 then
TriggerClientEvent('sessionHostResult', source, 'conflict')
return
end
end
hostReleaseCallbacks = {}
currentHosting = source
TriggerClientEvent('sessionHostResult', source, 'go')
-- set a timeout of 5 seconds
SetTimeout(5000, function()
if not currentHosting then
return
end
currentHosting = nil
for _, cb in ipairs(hostReleaseCallbacks) do
cb()
end
end)
end)
AddEventHandler('hostedSession', function()
-- check if the client is the original locker
if currentHosting ~= source then
-- TODO: drop client as they're clearly lying
print(currentHosting, '~=', source)
return
end
-- free the host lock (call callbacks and remove the lock value)
for _, cb in ipairs(hostReleaseCallbacks) do
cb()
end
currentHosting = nil
end)
EnableEnhancedHostSupport(true)
i tried searching on google but i didnt found anything
correct the block:
if GetHostId() >= 1 then
if GetPlayerLastMsg(GetHostId()) < 1000 then
TriggerClientEvent('sessionHostResult', source, 'conflict')
return
end
end
here you need to check for nil or not allow nil when comparing numbers:
local HostId = GetHostId() or 0
if HostId >= 1 then
if GetPlayerLastMsg(HostId) < 1000 then
TriggerClientEvent('sessionHostResult', source, 'conflict')
return
end
end
I have googled this a lot and I can only find answers that relate to conditions within the loop being met. I want this loop to run infinitely (Hence while 1==1) and I'm testing it at the moment by just leaving it running in Thonny. It runs for variable lengths of time and then just stops. It doesn't exit the program or stop running, it just behaves as if it's waiting for something but there's nothing that I can see that it's waiting for. The shell doesn't report any errors or report that it has stopped running, it simply stops printing the string in the fourth line print statement.
I am very new to python and Linux and I have no idea how to debug this problem or where to look for the stopping point. Even running it in debug mode doesn't render any helpful information. Has anyone got any suggestions please?
The only other thing that I have tried outside of what I have said is I have tried running it on a fresh install of Raspberry Pi OS on three different Raspberry Pi 4 Model B computers. It behaves exactly the same on all of them.
while 1==1:
time.sleep(1)
cnt = 1
print('One = One loop ' + str(datetime.today()) + ' CNT: ' + str(cnt))
while Decimal(target_temperature()) - Decimal(0.3) >= Decimal(actual_temperature()) and switch_state() == 'currently not running':
print('Before heating loop ' + str(datetime.today()))
try:
if cnt == 1:
if Decimal(target_temperature()) - Decimal(0.3) >= Decimal(actual_temperature()) and switch_state() == 'currently not running':
print('First heating loop ' + str(datetime.today()))
requests.get('http://192.168.1.167/4/on')
log_db('On', str(target_temperature()), str(actual_temperature()))
time.sleep(225)
requests.get('http://192.168.1.167/4/off')
log_db('Off', str(target_temperature()), str(actual_temperature()))
time.sleep(300)
cnt = cnt + 1
if(cnt != 1):
if Decimal(target_temperature()) - Decimal(0.3) >= Decimal(actual_temperature()) and switch_state() == 'currently not running':
print('Second heating loop ' + str(datetime.today()))
requests.get('http://192.168.1.167/4/on')
log_db('On', str(target_temperature()), str(actual_temperature()))
time.sleep(180)
requests.get('http://192.168.1.167/4/off')
log_db('Off', str(target_temperature()), str(actual_temperature()))
time.sleep(300)
except Exception as e:
print(e)
Bearing in mind i don't know anything about python i will try to help.
1 - The first thing i would do is put the whole program in a try catch block. That wasy if anything bad happens you should be told about it
try:
<all your code>
except Exception as e2:
print('The whole thing errored' + e2)
2 - The delays are in seconds? For testing i would change every sleep to (30) so you can see what is going on without getting too bored waiting, when you have it working then change the times back.
3 - I would add some more print('got here!') like where you have if(cnt == 1) add else print('first loop wasnt 1 it was ' + cnt)
4 - try and make the code easier for you to read, when it gets actually run it will be so optimized that it wont bear any relation to what you write. So write it in a way that is easiest for you
5 - You turn it on and then off, but if the off failed it would never be turned off, you should assume that it will go badly and that will be the day you get a big bill. Try and stop it if an error occurs by adding another check if actualTemp > targetTemp then turn it off?
6 - the http request might take ages, specify a time in seconds you are prepared to wait like , timeout=60
try:
while 1==1:
try:
time.sleep(30)
targetTemp = Decimal(target_temperature())
actualTemp = Decimal(actual_temperature())
switchState = switch_state()
print('Doing it at ' + str(datetime.now()) + ' target ' + str(targetTemp) + ' actual ' + str(actualTemp) + ' switch ' + switchState)
if targetTemp - Decimal(0.3) >= actualTemp and switchState == 'currently not running'
print('too cold turning it for a bit!')
requests.get('http://192.168.1.167/4/on', timeout=60)
log_db('On', targetTemp , actualTemp)
else if actualTemp > targetTemp and switchState != 'currently not running'
print('too hot turning it off!')
requests.get('http://192.168.1.167/4/off', timeout=60)
log_db('Off', targetTemp , actualTemp)
else
print('Not doing anything!')
except Exception as e1:
print('Loop errored -> ' + e1)
except Exception as e2:
print('Whole thing errored -> ' + e2)
Thanks Billy the Kid. You were right. Sometimes the devices that the loop uses via HTTPRequests just don't reapond (the two functions use HTTPRequests) and sometimes they create errors that aren't caught in the loop. Putting the whole thing in a try/catch oddly did identify that. Problem solved.
The Java docs say the following:
Emit the last value from this Flux only if there were no new values emitted during the time window provided by a publisher for that particular last value.
However I found the above description confusing. I read in gitter chat that its similar to debounce in RxJava. Can someone please illustrate it with an example? I could not find this anywhere after doing a thorough search.
sampleTimeout lets you associate a companion Flux X' to each incoming value x in the source. If X' completes before the next value is emitted in the source, then value x is emitted. If not, x is dropped.
The same processing is applied to subsequent values.
Think of it as splitting the original sequence into windows delimited by the start and completion of each companion flux. If two windows overlap, the value that triggered the first one is dropped.
On the other side, you have sample(Duration) which only deals with a single companion Flux. It splits the sequence into windows that are contiguous, at a regular time period, and drops all but the last element emitted during a particular window.
(edit): about your use case
If I understand correctly, it looks like you have a processing of varying length that you want to schedule periodically, but you also don't want to consider values for which processing takes more than one period?
If so, it sounds like you want to 1) isolate your processing in its own thread using publishOn and 2) simply need sample(Duration) for the second part of the requirement (the delay allocated to a task is not changing).
Something like this:
List<Long> passed =
//regular scheduling:
Flux.interval(Duration.ofMillis(200))
//this is only to show that processing is indeed started regularly
.elapsed()
//this is to isolate the blocking processing
.publishOn(Schedulers.elastic())
//blocking processing itself
.map(tuple -> {
long l = tuple.getT2();
int sleep = l % 2 == 0 || l % 5 == 0 ? 100 : 210;
System.out.println(tuple.getT1() + "ms later - " + tuple.getT2() + ": sleeping for " + sleep + "ms");
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
return l;
})
//this is where we say "drop if too long"
.sample(Duration.ofMillis(200))
//the rest is to make it finite and print the processed values that passed
.take(10)
.collectList()
.block();
System.out.println(passed);
Which outputs:
205ms later - 0: sleeping for 100ms
201ms later - 1: sleeping for 210ms
200ms later - 2: sleeping for 100ms
199ms later - 3: sleeping for 210ms
201ms later - 4: sleeping for 100ms
200ms later - 5: sleeping for 100ms
201ms later - 6: sleeping for 100ms
196ms later - 7: sleeping for 210ms
204ms later - 8: sleeping for 100ms
198ms later - 9: sleeping for 210ms
201ms later - 10: sleeping for 100ms
196ms later - 11: sleeping for 210ms
200ms later - 12: sleeping for 100ms
202ms later - 13: sleeping for 210ms
202ms later - 14: sleeping for 100ms
200ms later - 15: sleeping for 100ms
[0, 2, 4, 5, 6, 8, 10, 12, 14, 15]
So the blocking processing is triggered approximately every 200ms, and only values that where processed within 200ms are kept.
I have a VB6 client application, which creates 1 or more (upto 4) sockets and connects to one or more TCP servers.
The client is supposed to continuously send requests to the server and wait for the server to respond for a certain responseTime. If the response does not arrive in the "responseTime", the client should send the next request on one of the sockets.
What is best way to make the client wait till the response arrives on the socket?
I do the following to have the client wait for the response/data to arrive: (Here the dataProcessed flag is set to True by the helper function invoked from the dataArrival() routine. This flag indicates that a response has been received and processed.
*Do While ((Timer < SentRequestTime) + responseTimeout) And (dataProcessed = False))
'DoEvents OR Sleep
Sleep 50
End If
Loop*
If I use "DoEvents" in the while loop, the application works fine for a while but later even though the response comes back to TCP layer (which I have examined through wireshark), the application does not get the DataArrival event.
If I use "sleep", the dataArrival event does not get delivered during the while loop, but arrives as soon as the loop is over. Using sleep makes the application non responsive.
What is the best way to have a single threaded VB6 socket client application to send a request, "wait for the data " to arrive for a certain time and then move on to the next request?
I would forget about both DoEvents() and Sleep() here. Those are tools of last resort, and nearly no program should contain either one. You need to "think 4th dimensionally" i.e. "Trust the Events, Luke!" This ain't your daddy's QBasic.
Here's a simulation where four Command buttons act as the servers, i.e. you click them manually as they become enabled. Two Timer controls are used here because we need to simulate processing time and transmission delay.
Option Explicit
'Use 4 Command buttons to simulate TCP sockets making server
'requests and getting back responses. Each "send" must get
'a response within RESPONSE_TIME_MS or be counted as a "miss."
'A new request is sent in either case.
Private Const PROCESS_TIME_MS As Long = 2000
Private Const PROCESS_TICKS As Long = PROCESS_TIME_MS \ 10
Private Const PROCESS_TICK_MS As Long = PROCESS_TIME_MS \ PROCESS_TICKS
Private Const RESPONSE_TIME_MS As Long = 4000
Private Const RESPONSE_TICKS As Long = RESPONSE_TIME_MS \ 10
Private Const RESPONSE_TICK_MS As Long = RESPONSE_TIME_MS \ RESPONSE_TICKS
Private ProcessCountdowns(0 To 3)
Private ResponseCountdowns(0 To 3)
Private Misses(0 To 3)
Private Sub SendRequest(ByVal Socket As Integer)
ResponseCountdowns(Socket) = RESPONSE_TICKS
cmdResponse(Socket).Enabled = True
End Sub
Private Sub cmdResponse_Click(Index As Integer)
'This is a "DataArrival" event.
'Process the response, then send a new request:
cmdResponse(Index).Enabled = False
ResponseCountdowns(Index) = 0
ProcessCountdowns(Index) = PROCESS_TICKS
End Sub
Private Sub Form_Load()
Dim Socket As Integer
For Socket = 0 To 3
SendRequest Socket
Next
tmrProcess.Interval = PROCESS_TICK_MS
tmrProcess.Enabled = True
tmrResponse.Interval = RESPONSE_TICK_MS
tmrResponse.Enabled = True
End Sub
Private Sub tmrProcess_Timer()
'This just simulates delay involved in processing responses and
'then sending new ones.
Dim Socket As Integer
For Socket = 0 To 3
If ProcessCountdowns(Socket) > 0 Then
ProcessCountdowns(Socket) = ProcessCountdowns(Socket) - 1
If ProcessCountdowns(Socket) <= 0 Then
SendRequest Socket
End If
End If
Next
End Sub
Private Sub tmrResponse_Timer()
Dim Socket As Integer
For Socket = 0 To 3
If ResponseCountdowns(Socket) > 0 Then
ResponseCountdowns(Socket) = ResponseCountdowns(Socket) - 1
If ResponseCountdowns(Socket) <= 0 Then
Misses(Socket) = Misses(Socket) + 1
lblMisses(Socket).Caption = CStr(Misses(Socket))
SendRequest Socket
End If
End If
Next
End Sub
Running the simulation requires two control arrays: one of 4 Command buttons and one of 4 Labels. Then it becomes a game of "Whack a Mole."
Pretty routine stuff actually, and the main reason we have Timer controls in the first place.
I'm using ASP code and AspEmail component to send emails to our clinets, but I have some problmes...
I have more then 1000 email address that I need to send them an email, becuase of my SMTP provider limitation, I can't add them all as BCC in one email but I need to send each email seperatly, therefor looping on +1000 times witch takes forever and fires the server timeout error.
I need to send those emails about 20 times a day.
This is my script:
on error resume next
msg = "SOME TEXT HERE"
Set Mail = Server.CreateObject("Persits.MailSender")
Mail.Host = "SMPT.HOST.ADDRESS"
Mail.Port = 25
Mail.CharSet = "UTF-8"
Mail.ContentTransferEncoding = "Quoted-Printable"
Mail.From = "noreply#mydomain.co.il"
MailSubject = "email subject"
Mail.Subject = Mail.EncodeHeader(MailSubject, "utf-8")
Mail.Body = msg
Mail.IsHTML = True
zBcc = split(zBcc, ";") '1000 emails here
for i=0 to Ubound(zBcc)
zBcc(i) = trim(zBcc(i))
if len(zBcc(i))>0 then
if inStr(zBcc(i), " ")>0 then
else
if (Mail.ValidateAddress(zBcc(i)) = 0) then
Mail.Reset()
Mail.AddAddress zBcc(i)
Mail.Send
end if
end if
end if
next
set Mail=nothing
why dont you do it using a pagination type logic i.e.
limit by 100,
loop thru that batch,
once that has completed,
reload the page with the next offset in mind like send-email.asp?offset=100, send-email.asp?offset=200, etc.
use that offset value to get next batch
repeat process until end of recordset.
At least you have less chance of it timing out altho you can increase it: server.ScriptTimeout = 180
First of all I'd maximize the number of BCC's per cycle. Let's say you can email 50 BCC's in one go; you should: especially when you need this page about 20 times a day.
Anyway. Before you start; maximize the scripttimeout
Server.ScriptTimeout = 2147483647