Is there any way to generate "Random date value" to test a "date picker" in the "angualr 4 web application" using "Protractor".
You need to write your own function which will return random date.
findRandomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
this.findRandomDate(new Date(2012, 0, 1), new Date());
Related
I am currently writing a flutter app which includes displaying the weekly schedule of a class. I also have to calculate the attendance of each student. To do that, I need the number of time each subject are taught in any given month and I am stumped as I can't think of a way to do that.
I have the weekly schedule of the class and I stored it in Firestore. It is formatted as below,
{Day: 1 , Major: 'EcE', Subject: 'Communication', Year: 5, Period: 1, ...}
Screenshot of a timetable entry
where Day refers to Monday, Tuesday, ...
It appears in the app like this.
My problem is, to track and calculate the attendance of students, I have to know how many times each subjects are taught in a month but I dont think multiplying said times in a week by 4 is viable since days in a month are dynamic. But I don't know how to work with a calendar programmatically so I am currently out of ideas. Any hints and suggestions are appreciated. The suggestions can be in either dart or node js since I can both implement in client side or cloud functions. Thanks a lot.
P.S - I haven't provide any code for now but please ask me for clarifications and I will provide the related codes. I just didn't want to bloat the post.
If I understood your question correctly all you need is to count the number of each weekday occurrence in a given month.
Here you go, in both js and dart:
JS:
var dtNow = new Date(); // replace this for the month/date of your choosing
var dtFirst = new Date(dtNow.getFullYear(), dtNow.getMonth(), 1); // first date in a month
var dtLast = new Date(dtNow.getFullYear(), dtNow.getMonth() + 1, 0); // last date in a month
// we need to keep track of weekday occurrence in a month, a map looks suitable for this
var dayOccurrence = {
"Monday" : 0,
"Tuesday" : 0,
"Wednesday" : 0,
"Thursday" : 0,
"Friday" : 0,
"Saturday" : 0,
"Sunday" : 0
}
var dtLoop = new Date(dtFirst); // temporary date, used for looping
while(dtLoop <= dtLast){
// getDay() method returns the day of the week, from 0(Sunday) to 6(Saturday)
switch(dtLoop.getDay()) {
case 0:
dayOccurrence.Sunday++; break;
case 1:
dayOccurrence.Monday++; break;
case 2:
dayOccurrence.Tuesday++; break;
case 3:
dayOccurrence.Wednesday++; break;
case 4:
dayOccurrence.Thursday++; break;
case 5:
dayOccurrence.Friday++; break;
case 6:
dayOccurrence.Saturday++; break;
default:
console.log("this should not happen");
}
dtLoop.setDate(dtLoop.getDate() + 1);
}
// log the results
var keys = Object.keys(dayOccurrence);
keys.forEach(key=>{
console.log(key + ' : ' + dayOccurrence[key]);
});
And here is the same thing in dart:
void main() {
DateTime dtNow = new DateTime.now(); // replace this for the month/date of your choosing
DateTime dtFirst = new DateTime(dtNow.year, dtNow.month, 1); // first date in a month
DateTime dtLast = new DateTime(dtNow.year, dtNow.month + 1, 0); // last date in a month
// we need to keep track of weekday occurrence in a month, a map looks suitable for this
Map<String, int> dayOccurrence = {
'Monday' : 0,
'Tuesday' : 0,
'Wednesday' : 0,
'Thursday' : 0,
'Friday' : 0,
'Saturday' : 0,
'Sunday' : 0
};
DateTime dtLoop = DateTime(dtFirst.year, dtFirst.month, dtFirst.day);
while(DateTime(dtLoop.year, dtLoop.month, dtLoop.day) != dtLast.add(new Duration(days: 1))){
// weekday is the day of the week, from 1(Monday) to 7(Sunday)
switch(dtLoop.weekday) {
case 1:
dayOccurrence['Monday']++; break;
case 2:
dayOccurrence['Tuesday']++; break;
case 3:
dayOccurrence['Wednesday']++; break;
case 4:
dayOccurrence['Thursday']++; break;
case 5:
dayOccurrence['Friday']++; break;
case 6:
dayOccurrence['Saturday']++; break;
case 7:
dayOccurrence['Sunday']++; break;
default:
print("this should not happen");
}
dtLoop = dtLoop.add(new Duration(days: 1));
}
// log the results
dayOccurrence.forEach((k,v) => print('$k : $v'));
}
I would like to know what could be the best way to obtain the starting date values for each month based on the date range.
For example: If I am given a year range of 2015-11-10 and 2018-01-15(format YYYY-mm-dd). Then I would like to extract following dates:
2015-12-01
2016-01-01
.
.
2018-01-01
You can try to use this flow for generating the first day of each month in the provided date range.
Overall flow
Step 1 Configuration: Start
Step 2 Configuration: Configure Date Range
Provide the start and end dates as configuration parameters via this step.
Step 3 Configuration: Generate First Dates For Months
This uses a Groovy script, which is provided below
Groovy script
flowFile = session.get();
if(!flowFile)
return;
DATE_FORMAT = 'yyyy-MM-dd';
startDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("start_date"));
endDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("end_date"));
allFirstDates = "";
Calendar calendar = Calendar.getInstance();
Set firstDaysOfMonths = new LinkedHashSet();
for (int i = 0; i <= endDate-startDate; i++) {
calendar.setTime(startDate.plus(i));
calendar.set(Calendar.DAY_OF_MONTH, 1);
firstDayOfMonth = calendar.getTime();
if (firstDayOfMonth.compareTo(startDate) >= 0) {
firstDaysOfMonths.add(calendar.getTime().format(DATE_FORMAT));
}
}
firstDaysOfMonths.each {
firstDayOfMonth -> allFirstDates = allFirstDates + firstDayOfMonth + "\n";
}
flowFile = session.putAttribute(flowFile,"all_first_dates", allFirstDates );
session.transfer(flowFile,REL_SUCCESS)
Step 4 Configuration: View Result
Output of run:
When the flow is run, the attribute all_first_dates will be populated with the first dates of each month in the date range.
I have AFL which is working fine for crude oil. out of 10 trades, 8 trades are targets hitting. I have code for place orders auto trades. the auto trade code is working fine with other AFL codes but the problem is in below algorithm the BUY and SELL Boolean value is not giving to IF condition. But IIF(Buy .... conditions are working fine.
My main question is why BUY Sell True or false is not working in the last status in AFL. Kindly help me to resolve this.
_SECTION_BEGIN("T+4 day ");
Title = " ..:: duy ::.. - Filter of Stock " + " " + FullName() + " " + Date( ) ;
// 4-Day-Range Switch
prev=AMA2(C,1,0);
d=IIf(C>Ref(Max(Max(H,Ref(H,-20)),Max(Ref(H,-10),Ref(H,-15))),-1),Min(Min(L,Ref(L,-20)),Min(Ref(L,-10),Ref(L,-15))),
IIf(C<Ref(Min(Min(L,Ref(L,-20)),Min(Ref(L,-10),Ref(L,-15))),-1),Max(Max(H,Ref(H,-20)),Max(Ref(H,-10),Ref(H,-15))),PREV));
a=Cross(Close,d);
b=Cross(d,Close);
state=IIf(BarsSince(a)<BarsSince(b),1,0);
s=state>Ref(state,-1);
ss=state<Ref(state,-1);
sss=state==Ref(state,-1);
col=IIf(state == 1 ,51,IIf(state ==0,4,1));
Plot(C,"",Col,128);
Buy=s;
Sell=ss;
PlotShapes( shapeUpArrow * s ,6,0,L);
PlotShapes( shapeDownArrow *ss ,4,0,H);
dist = 0.8*ATR(10);
dist1 = 2*ATR(10);
for( i = 0; i < BarCount; i++ )
{
if( Buy )
{
PlotText( "\nBuy:" + L[ i ] + "\nT= " + (L*1.005) + "\nSL= " + (L*0.9975), i, L[ i ]-dist, colorGreen, colorWhite );
}
if( Sell )
{
PlotText( "Sell:" + H[ i ] + "\nT= " + (H*0.995) + "\nSL= " + (H*1.0025), i, H[ i ]+dist1, colorRed, colorWhite );
}
}
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
if ( LastValue(Buy)==1)
{
quantity=2;
orderId=placeOrderFuture("MCX", "FUTCOM", ChartSymbol, "BUY", "INTRADAY", "MARKET", quantity, 0, defaultTriggerPrice(), "19-APR-2018", defaultStrategyId(), defaultComments());
//orderId = placeOrderUsingParams(tradeType, AT_ORDER_TYPE, AT_QUANTITY, buyPrice, defaultTriggerPrice(), 1);
}
if ( LastValue(Sell) == 1 )
{
quantity=2;
orderId=placeOrderFuture("MCX", "FUTCOM", ChartSymbol, "SELL", "INTRADAY", "MARKET", quantity, 0, defaultTriggerPrice(), "19-APR-2018", defaultStrategyId(), defaultComments());
//orderId = placeOrderUsingParams("SELL", AT_ORDER_TYPE, AT_QUANTITY, sellPrice, defaultTriggerPrice(), 1);
}
LastValue documentation
With if statements, you need to specify a specific bar. And according to the documentation, LastValue may look into the future. I can't say for sure what's happening with your code, but the loops/if/switch can be tricky. This tutorial Looping in Amibroker might give you some insights into how they work.
You may try SelectedValue instead. If you haven't got any bars selected, it automatically defaults to the last bar. I use this for my realtime trading.
bi = SelectedValue(BarIndex());
if(Buy[bi])
{
...
}
On an unrelated note, your text plots aren't going to plot unfiltered signals, put your ExRem code under your initial Buy and Sell conditions.
I have a database table
TABLE subject_loads
id (int)
subject_name (varchar)
time_start (time)
time_end (time)
time_diff (decimal)
When I save it on database, it will first check whether the time is not conflicting from the other time already inputed. If it's okay, then compute the time_start and time_end to give me a difference between the two.
Example, 7:30 AM - 8:30 AM is already in database, when i input 8:00 AM - 9:00 AM it will say "conflicting with the other time". Only I can input before 7:30 AM or after 8:30 AM that doesn't overlap from 7:30 AM - 8:30 AM.
Can someone help on how to do this?
First you need to check if overlapping values (compared to new value) already exist. You will do that with:
$query = $this->db->get_where('subject_loads', array('time_start >= ' => $time_start, 'time_end <= ' => $time_end));
if((int)$query->num_rows() > 0)
{
//similar values exist
}
else
{
//you are free to insert values
}
Second part of issue:
$hm1 = "2:12 AM";
$hm2 = "4:41 PM";
$e = conv($hm2) - conv($hm1);
echo $e;
function conv($time)
{
$expl_time = explode(' ', $time);
$t = explode(":", $expl_time[0]);
if ($expl_time[1] == 'PM' || $expl_time[1] == 'pm')
{
$t[0] += 12;
}
return ($t[0] + round($t[1]/60, 1, PHP_ROUND_HALF_UP));
}
I want to record a data processing time in esper and I choose Bollinger Band as example. In Bollinger Band, there is called Moving Average (MA). that MA obtained from the result of calculate the stock price average. In this case, I set win:length(20). So, the MA can be obtained from the result of calculate the stock price average from 20 events that exists in the data window view. The following is code that i created.
public class BollingerBand {
static double startTime, finishTime;
public static void main (String [] args){
Configuration configuration = new Configuration();
configuration.addEventType("Stock", Stock.class);
EPServiceProvider epService = EPServiceProviderManager.getDefaultProvider(configuration);
AdapterInputSource source = new AdapterInputSource("BollingerBand.csv");
EPStatement statement = epService.getEPAdministrator().createEPL("insert into Aggregation " +
"select prevcount(symbol), symbol, avg(price) as SimpleMovingAverage, stddev(price) as StandardDeviation, " +
"last(price) as price, last(timestamp) as date from Stock.std:groupwin(symbol).win:length(20)" +
" group by symbol having count(*) >=20");
statement.addListener(new UpdateListener() {
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
// TODO Auto-generated method stub
//System.out.println("Event Receive : "+newEvents[0].getUnderlying());
startTime = System.currentTimeMillis();
System.out.println("\nStart time : " + startTime + " miliseconds\n");
}
});
EPStatement statement2 = epService.getEPAdministrator().createEPL("select symbol, " +
"SimpleMovingAverage + 2*StandardDeviation as UpperBand," +
"SimpleMovingAverage as MiddleBand," +
"SimpleMovingAverage - 2*StandardDeviation as LowerBand," +
"price," +
"4*StandardDeviation/SimpleMovingAverage as Bandwidth," +
"(price - (SimpleMovingAverage - (2 * StandardDeviation))) / ((SimpleMovingAverage + " +
"(2 * StandardDeviation)) - (SimpleMovingAverage - (2 * StandardDeviation))) as PercentB," +
"date from Aggregation");
statement2.addListener(new UpdateListener() {
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
// TODO Auto-generated method stub
//System.out.println("Event Receive : "+newEvents[0].getUnderlying());
finishTime = System.currentTimeMillis();
System.out.println("Start time : " + startTime + " miliseconds");
System.out.println("Finish time : " + finishTime + " miliseconds");
System.out.println("Processing time : " + (finishTime-startTime) + " miliseconds");
}
});
(new CSVInputAdapter(epService, source, "Stock")).start();
}
}
From the above code, time will be recorded if the average has calculated. But what i need is I want the time is recorded when the 20th event and next event enter to data window view. It's as the start time and finish time obtained from bollinger band calculation result. My question is how to record time of the 20th event and in the same time next event enter to the window view data. please help
The CSV adapter doesn't provide a callback when events are sent. You could easily change its code however. Or you could use a different CSV reader and send the events via runtime API.
Maybe have some sort of TickCounter in which there's a map that takes a key value pair of (item_count and timestamp). You update this in your second UpdateListener and of course you can always lookup the item of key 20.
By the way, I've used your Bollinger Band Calculation but using Storm and the EsperBolt. Blogged about it here:
http://chanchal.wordpress.com/2014/07/08/using-esperbolt-and-storm-to-calculate-bollinger-bands/