Why can't I directly assign to object properties using multiple return values from a method? - groovy

Based on this question I've coded the following which throws a compilation time error:
Here is the code:
43. Currency currency = new Currency()
44. (currency.rate_one, currency.time_one) = getDateAndRate()
My method with two return values:
def getDateAndRate(){
Date date = new Date()
double rate = getRate();
return [rate, date]
}
Error thrown
expecting '}', found ',' # line 44, column 26.
(currency.rate_one, currency.time_one) = getDateAndRate()
^

Try this instead
def (rate, time) = getDateAndRate()
currency.rate_one = rate
currency.time_one = time

There is a trick I learned only recently myself and that is to combine multiple assignment and with:
with (currency) {
(rate_one, time_one) = getDateAndTime()
}

Related

Argument to dynamic structure reference must evaluate to a valid field name (helperBluetoothChannelClassification)

Hi im doing a bluetooth project using bluetooth toolbox in matlab, and encountered a problem. So I have been following one of the example from https://www.mathworks.com/help/bluetooth/ug/noncollaborative-bluetooth-le-coexistence-with-wlan-signal-interference.html this error occurred.
ble_wlan_interference
Argument to dynamic structure reference must evaluate to a valid field
name.
Error in helperBluetoothChannelClassification (line 102)
obj.(varargin{idx}) = varargin{idx+1};
Error in ble_wlan_interference (line 58)
classifierObj = helperBluetoothChannelClassification(centralNode,peripheralNode,PERThreshold=50);
At line 102 of helperBluetoothChannelClassification.m is as follows,
methods
% Constructor
function obj = helperBluetoothChannelClassification(varargin)
% Set name-value pairs
for idx = 1:2:nargin
obj.(varargin{idx}) = varargin{idx+1};
end
At line 58 of main code is as follows,
%enable channel classification
enableChannelClassification = true;
if enableChannelClassification
classifierObj = helperBluetoothChannelClassification(centralNode,peripheralNode,PERThreshold=50);
classifyFcn = #(varargin) classifierObj.classifyChannels;
userData = []; % User data needed to be passed to the callback function
callAt = 0; % Absolute simulation time, in seconds
periodicity = 125e-3; % In seconds
scheduleAction(networkSimulator,classifyFcn,userData,callAt,periodicity); % Schedule channel classification
end
I think the centralNode and peripheralNode parameter is not recognizable in helperBluetoothChannelClassification function, but don't know what is a problem.. Thanks :)

Jupyter Notebook HOw can i assign a default value to datepicker and sort the time within the selected date?

I can try to set condition some data that is within the time picker in the datepicker. I got two problem
MY code was
def show_filter_date(start ,end):
print(start_dater.value)
print(end_dater.value)
time_df = (id_one[(id_one['_source.timestampstring']>pd.to_datetime(start))&(id_one['_source.timestampstring']<pd.to_datetime(end))])
#print(time_df.head(20))
# time_df = (id_one[(id_one['_source.timestampstring']>pd.to_datetime(start_dater.value))&(id_one['_source.timestampstring']<pd.to_datetime(end_dater.value))])
time_df.head(20)
layout = widgets.Layout(width='auto', height='40px')
start_dater = widgets.DatePicker(description='Pick a Start Date',disabled=False)
end_dater = widgets.DatePicker(description='Pick an End Date',disabled=False )
#display(widgets.HBox((start_dater, end_dater)))
#display(start_dater)
#display(end_dater)
#id_one.head()
#combine_date = widgets.HBox((start = start_dater, end = end_dater))
#country_selector = widgets.Dropdown(
interact(show_filter_date,start = start_dater , end = end_dater)
everytime i run the code it show Error
"Invalid comparison between dtype=datetime64[ns] and NoneType"
I have tried to assign default value like
start_dater = widgets.DatePicker(description='Pick a Start Date',disabled=False, year = 2020 ,month = 12, day = 1)
but it won't change to 2020/12/01
So, how can I get a value other than null?
I fail in interact for the datepicker in which
A) print(time_df.head(20))
B)
time_df = (id_one[(id_one['_source.timestampstring']>pd.to_datetime(start_dater.value))&(id_one['_source.timestampstring']<pd.to_datetime(end_dater.value))])
time_df.head(20)
Only (A) can be "interact" or "refresh" when I pick a day but not (B)
And for Question 2, when I put time_df.head(20) in the NEXT CELL it does work tho.......
But what i want is to show the result like in time_df
I would appreciate if any help
the id_one is something like
Index _source.hdrrId _source.hdrfId _source.hdrType \
199 1300 1234 1
_source.timestampstring
199 2020-11-06 09:36:04.800
Thanks!
Jeff
I replicated your first error with
id_one = pd.DataFrame(pd.date_range('20200101','20200202'), columns = ['_source.timestampstring'])
This is because you did not set a default value for the DatePicker. The value is None by default hence the error. Here is the fix (value argument is the default value):
start_dater = widgets.DatePicker(description='Pick a Start Date',disabled=False, value = datetime.date(2020,1,1))
end_dater = widgets.DatePicker(description='Pick an End Date',disabled=False, value = datetime.date(2020,2,1))
I cannot replicate your second error. My guess is you put print before the time_df = statement. You need to put the print after the line that calculates time_df

Python list add variables in rows

im trying to add variables to a list that i created. Got a result from a session.execute.
i´ve done this:
def machine_id(session, machine_serial):
stmt_raw = '''
SELECT
id
FROM
machine
WHERE
machine.serial = :machine_serial_arg
'''
utc_now = datetime.datetime.utcnow()
utc_now_iso = pytz.utc.localize(utc_now).isoformat()
utc_start = datetime.datetime.utcnow() - datetime.timedelta(days = 30)
utc_start_iso = pytz.utc.localize(utc_start).isoformat()
stmt_args = {
'machine_serial_arg': machine_serial,
}
stmt = text(stmt_raw).columns(
#ts_insert = ISODateTime
)
result = session.execute(stmt, stmt_args)
ts = utc_now_iso
ts_start = utc_start_iso
ID = []
for row in result:
ID.append({
'id': row[0],
'ts': ts,
'ts_start': ts_start,
})
return ID
In trying to get the result over api like this:
def form_response(response, session):
result_machine_id = machine_id(session, machine_serial)
if not result_machine_id:
response['Error'] = 'Seriennummer nicht vorhanden/gefunden'
return
response['id_timerange'] = result_machine_id
Output looks fine.
{
"id_timerange": [
{
"id": 1,
"ts": "2020-08-13T08:32:25.835055+00:00",
"ts_start": "2020-07-14T08:32:25.835089+00:00"
}
]
}
Now i only want the id from it as a parameter for another function. Problem is i think its not a list. I cant select the first element. result_machine_id[0] result is like the posted Output. I think in my first function i only add ts & ts_start to the first row? Is it possible to add emtpy rows and then add 'ts':ts as value?
Help would be nice
If I have understood your question correctly ...
Your output looks like dict. so access its id_timerange key which gives you a list. Access the first element which gives you another dict. On this dict you have an id key:
result_machine_id["id_timerange"][0]["id"]

NIFI: Generating dates between two dates using ExecuteScript processor

I am currently trying to get list of all dates in a flowfile between the two dates specified using ExecuteScript. But I am somehow getting empty attribute.
Following is my Groovy code of ExecuteScript for the specified startdate and enddate variable specified:
flowFile = session.get();
if(!flowFile)
return;
DATE_FORMAT = 'dd-MM-yyyy';
startDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("startdate"));
endDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("enddate"));
allDates = "";
Calendar calendar = Calendar.getInstance();
Set allDates = new LinkedHashSet();
numbers = TimeUnit.MILLISECONDS.toDays(Math.abs(endDate - startDate))
for (int i = 1; i <= numbers; i++) {
calendar.setTime( startDate );
calendar.add( Calendar.DATE, i );
}
days.each {
day -> allDates = allDates + day + "\n";
}
flowFile = session.putAttribute(flowFile,"allDates", allDates );
session.transfer(flowFile,REL_SUCCESS)
On my outgoing queue I find the attribute allDates is empty String
What is going wrong with my code?
you have some problems in your code
for example the variable allDates declared twice i two different scopes:
global (without type or def)
allDates = "";
and local (with type)
Set allDates = new LinkedHashSet();
after that it's hard to predict which one is used
and actually code could be easier in groovy:
def DATE_FORMAT = 'dd-MM-yyyy';
def startDate = Date.parse(DATE_FORMAT, '01-11-1970');
def endDate = Date.parse(DATE_FORMAT, '09-11-1970');
def allDates = ""
for (def d = startDate; d<=endDate; d++){
allDates+=d.format(DATE_FORMAT)+"\n"
}
println allDates
note that this is runable code so you can use groovyconsole or any IDE to debug it before integrating into nifi
of cause you have to wrap it with flow file handling before using in nifi

inbuilt parser in Python for handling dates like : 05/May/2010:12:01:15 +0000

In a logfile, I have my date and time recorded in the format :
[05/May/2010:12:01:15 +0000]
I am trying to extract only the time from the above in Python3.x. I was mainly looking for a inbuilt parser in Python3.x. I ran into different formats except for this. I came up with a solution in JAVA using the below code and I am looking for something similar in Python3.x. Is there one ? Or do I have to write my own parser for extracting the date,time out of this ? Here is the JAVA code of what I wanted :
//field[3] contains "[25/May/2015:23:11:15 +0000]"
String timeStamp = fields[3].substring(1,fields[3].length()).split(" ")[0];
SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.US);
Date d = null;
try {
d = df.parse(timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Time :"+ d.getTime());// Prints 23:11:15
You can use time.strptime() to parse it into a time.struct_time object:
import time
your_field = "[25/May/2015:23:11:15 +0000]"
parsed = time.strptime(your_field, "[%d/%b/%Y:%H:%M:%S %z]")
# NOTE: %z depends on implementation, you might need to remove the timezone info
# before parsing your date/time with `time.strptime()`.
# print time:
print(time.strftime("%H:%M:%S", parsed))
# prints: 23:11:15
But if you just want to get the time you don't need to parse it just to build it again, instead you can just substring it out:
your_field = "[25/May/2015:23:11:15 +0000]"
your_time = your_field.split(":", 1)[1].split(" ", 1)[0]
# print time:
print(your_time)
# prints: 23:11:15
Here is a solution using datetime.strptime:
from datetime import datetime
field3 = '[25/May/2015:23:11:15 +0000]'
result = datetime.strptime(field3, '[%d/%b/%Y:%H:%M:%S %z]')
print(result.strftime("%H:%M:%S"))
Output
23:11:15

Resources