Set default value depending on actual time INFOPATH - datetime

I'm trying to set a default value in a DropDown box depending on the current time. (substring-after(now(), "T"))
To be more specific, I would like my DropDown box to have as default value
"AM" if the current time is between 06:00:01 and 12:00:00.
"PM" if the current time is between 12:00:01 and 18:00:00.
"NIGHT" if the current time is between 18:00:01 and 06:00:00.
I tried with "Rules" and "Set default value" but can't figure out a solution.
Thanks for help!

go get the hours and seconds number and put it fields.
A - hours
B - seconds
A >= 6 and B > 0 OR A =< 12 and B = 0 ---> AM
if A >= 12 and B > 0 OR A =< 18 and B = 0 ---> PM
if A >= 18 and B > 0 OR A =< 6 and B = 0 ---> NIGHT

I found a way, I put hours in a field (I don't think it's absolutely necessary but it's more clear for the formula after) then I set the default value for the formula of the DropDown Box as :
concat(substring("AM", 1, (field4 < 12) * string-length("AM")), substring("PM", 1, (not(field4 < 12)) * string-length("PM")))
field4 is the field when I extract the current hour of the day with that formula:
substring-before((substring-after(now(), "T")), ":")
You will find usefull tips here for this application:
http://blogs.msdn.com/b/infopath/archive/2006/11/27/conditional-default-values.aspx

Related

Constraint issue with pyomo involving a scalar

working on an economic optimization problem with pyomo, I would like to add a constraint to prevent the product of the commodity quantity and its price to go below zero (<0), avoiding a negative revenue. It appears that all the data are in a dataframe and I can't setup a constraint like:
def positive_revenue(model, t)
return model.P * model.C >=0
model.positive_rev = Constraint(model.T, rule=positive_revenue)
The system returns the error that the price is a scalar and it cannot process it. Indeed the price is set as such in the model:
model.T = Set(doc='quarter of year', initialize=df.quarter.tolist(), ordered=True)
model.P = Param(initialize=df.price.tolist(), doc='Price for each quarter')
##while the commodity is:
model.C = Var(model.T, domain=NonNegativeReals)
I just would like to apply that for each timestep (quarter of hour here) that:
price(t) * model.C(t) >=0
Can someone help me to spot the issue ? Thanks
Here are more information:
df dataframe:
df time_stamp price Status imbalance
quarter
0 2021-01-01 00:00:00 64.84 Final 16
1 2021-01-01 00:15:00 13.96 Final 38
2 2021-01-01 00:30:00 12.40 Final 46
index = quarter from 0 till 35049, so it is ok
Here is the df.info()
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 time_stamp 35040 non-null datetime64[ns]
1 price 35040 non-null float64
2 Status 35040 non-null object
3 imbalance 35040 non-null int64
I modified the to_list() > to_dict() in model.T but still facing the same issue:
KeyError: "Cannot treat the scalar component 'P' as an indexed component" at the time model.T is defined in the model parameter, set and variables.
Here is the constraint where the system issues the error:
def revenue_positive(model,t):
for t in model.T:
return (model.C[t] * model.P[t]) >= 0
model.positive_revenue = Constraint(model.T,rule=revenue_positive)
Can't figure it out...any idea ?
UPDATE
Model works after dropping an unfortunate 'quarter' column somewhere...after I renamed the index as quarter.
It runs but i still get negative revenues, so the constraints seems not working at present, here is how it is written:
def revenue_positive(model,t):
for t in model.T:
return (model.C[t] * model.P[t]) >= 0
model.positive_revenue = Constraint(model.T,rule=revenue_positive)
What am I missing here ? Thanks for help, just beginning
Welcome to the site.
The problem you appear to be having is that you are not building your model parameter model.P as an indexed component. I believe you likely want it to be indexed by your set model.T.
When you make indexed params in pyomo you need to initialize it with some key:value pairing, like a python dictionary. You can make that from your data frame by re-indexing your data frame so that the quarter labels are the index values.
Caution: The construction you have for model.T and this assume there are no duplicates in the quarter names.
If you have duplicates (or get a warning) then you'll need to do something else. If the quarter labels are unique you can do this:
import pandas as pd
import pyomo.environ as pyo
df = pd.DataFrame({'qtr':['Q5', 'Q6', 'Q7'], 'price':[12.80, 11.50, 8.12]})
df.set_index('qtr', inplace=True)
print(df)
m = pyo.ConcreteModel()
m.T = pyo.Set(initialize=df.index.to_list())
m.price = pyo.Param(m.T, initialize=df['price'].to_dict())
m.pprint()
which should get you:
price
qtr
Q5 12.80
Q6 11.50
Q7 8.12
1 Set Declarations
T : Size=1, Index=None, Ordered=Insertion
Key : Dimen : Domain : Size : Members
None : 1 : Any : 3 : {'Q5', 'Q6', 'Q7'}
1 Param Declarations
price : Size=3, Index=T, Domain=Any, Default=None, Mutable=False
Key : Value
Q5 : 12.8
Q6 : 11.5
Q7 : 8.12
2 Declarations: T price
edit for clarity...
NOTE:
The first argument when you create a pyomo parameter is the indexing set. If this is not provided, pyomo assumes that it is a scalar. You are missing the set as shown in my example and highlighted with arrow here: :)
|
|
|
V
m.price = pyo.Param(m.T, initialize=df['price'].to_dict())
Also note, you will need to initialize model.P with a dictionary as I have in the example, not a list.

Gnuplot: data normalization

I have several time-based datasets which are of very different scale, e. g.
[set 1]
2010-01-01 10
2010-02-01 12
2010-03-01 13
2010-04-01 19
…
[set 2]
2010-01-01 920
2010-02-01 997
2010-03-01 1010
2010-04-01 1043
…
I'd like to plot the relative growth of both since 2010-01-01. To put both curves on the same graph I have to normalize them. So I basically need to pick the first Y value and use it as a weight:
plot "./set1" using 1:($2/10), "./set2" using 1:($2/920)
But I want to do it automatically instead of hard-coding 10 and 920 as dividers. I don't even need the max value of the second column, I just want to pick the first value or, better, a value for a given date.
So my question: is there a way to parametrize the value of a given column which corresponds a given value of the given X column (X is a time axis)? Something like
plot "./set1" using 1:($2/$2($1="2010-01-01")), "./set2" using 1:($2/$2($1="2010-01-01"))
where $2($1="2010-01-01") is the feature I'm looking for.
Picking the first value is quite easy. Simply remember its value and divide all data values by it:
ref = 0
plot "./set1" using 1:(ref = ($0 == 0 ? $2 : ref), $2/ref),\
"./set2" using 1:(ref = ($0 == 0 ? $2 : ref), $2/ref)
Using the value at a given date is more involved:
Using an external tool (awk)
ref1 = system('awk ''$1 == "2010-01-01" { print $2; exit; }'' set1')
ref2 = system('awk ''$1 == "2010-01-01" { print $2; exit; }'' set1')
plot "./set1" using 1:($2/ref1), "./set1" using 1:($2/ref2)
Using gnuplot
You can use gnuplot's stats command to pick the desired value, but you must pay attention to do all time settings only after that:
a) String comparison
stats "./set1" using (strcol(1) eq "2010-01-01" ? $2 : 1/0)
ref1 = STATS_max
...
set timefmt ...
set xdata time
...
plot ...
b) Compare the actual time value (works like this only since version 5.0):
reftime = strptime("%Y-%m-%d", "2010-01-01")
stats "./set1" using (timecolumn(1, "%Y-%m-%d") == reftime ? $2 : 1/0)
ref1 = STATS_max
...
set timefmt ...
set xdata time
...
plot ...

How to restrict order open to a certain time and close it in another certain time with Interactive Brokers API

Using Interactive Brokers API, I would like to restrict order open to a certain time for example not before 09:35, I would also like to close the position at about 5 minutes before the end of the day.I tried to use an if statment with Sys.time() but I didn't work and in addition it is not elegant..How can I fix the error or use another method to full fill my need ?
Hour<-as.integer(format(Sys.time(), "%H"))
Minute<-as.integer(format(Sys.time(), "%M"))
print(lastValue)
library(IBrokers)
options("scipen"=4)
myconid = 3
twsobj = twsConnect(myconid)
Sys.sleep(2)
myorderid = as.integer(reqIds(twsobj))
print(myorderid)
Sys.sleep(2)
if(lastValue>0.5 && Hour > 16 && Minute > 35 ){
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid ,"BUY",1,"MKT"))
print("IT WAS A BUY ORDER")
Sys.sleep(10)
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid + 1 ,"SELL",1,"MKT"))
} else{
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid , "SELL" , 1 , "MKT"))
print("IT WAS A SELL ORDER")
Sys.sleep(10)
placeOrder(twsobj,Contract=twsSTK("SPY"),Order=twsOrder(myorderid + 1 , "BUY" ,1, "MKT"))
}
Every broker has a facility to specify the good after time (GAT). It should be as simple as setting this field in the R interface. In the CRAN IBrokers docs it says the field
goodAfterTime Trades Good After Time: YYYYMMDD hh:mm:ss or ""
Here's the order properties API info at IB
https://www.interactivebrokers.com/en/software/api/apiguide/java/order.htm
The trade's "Good After Time," format
"YYYYMMDD hh:mm:ss (optional time zone)"
Note, MKT orders will be filled practically instantly. A LMT order may take some time.

Classic ASP - Subtracting numbers but keep leading zeros

I was wondering if someone could help me out.
I have a number, it could be 004 or 010 ... I would like to subtract it by 1 and keep the leading zero.
Everytime i try to subtract, it always takes away the leading zero.
for instance
004 - 1
This always ends up as just
3
But i would like it to be
003
Having said that if i have 010 and i subtract 1 i would like it to be 009
Any help would be greatly appreciated.
Cheers,
Do your calculations with integers then change to a string to display them. then concatenate "0" or "00" where needed eg
c = a - b
displayvalue = cstr(c)
if c < 100 then
displayvalue = "0" & cstr(c)
end if
if c < 10 then
displayvalue = "00" & cstr(c)
end if
Continue doing the math as you are but include some padding 0's using the Right and String functions.
Dim a, b
a = 003
b = 1
Right(String(3,"0") + cstr(a-b), 3)

Number pattern for checkboxes in asp.net?

I have a database table which contanis a field name Province bits and it adds up the count of the pattern like:
AB-1
BC-2
CD-4
DE-8
EF-16.... and so on.
Now in the table entry I have a value-13(Province bit), which implies checkboxes against entry AB,CD,DE(adds up to 13)should be checked.
I am not able to get the logic behind the same, how can check only those checkboxes whose sum adds up to the entry in the table?
You need to check to see if the value is in the bitwise total.
if( interestedInValue & totalValue == interestedInValue)
{
// this value is in the total, check the box
}
Documentation on & http://msdn.microsoft.com/en-us/library/sbf85k1c(v=vs.71).aspx
e.g. 13 = 1 + 4 + 8
13 & 1 == 1 // true
13 & 2 == 2 // false
13 & 4 == 4 // true
13 & 8 == 8 // true
13 & 16 == 16 // false
EDIT: for more clarification
ab.Checked = 1 && ProvinceBit == 1 // checkbox AB
bc.Checked = 2 && ProvinceBit == 2 // checkbox BC
...
The field is using bit flags.
13 is 1101 binary.
So convert the value to bits and assign one bit to each checkbox.
By converting your number to a string, you can convert to an array or just iterate through the string. A bit brute force, but will give you what you need.
var value = 13
string binary = Convert.ToString(value, 2);
//binary = "1101"

Resources