I'm trying fileinput to read some compressed files, and I tried the following three methods, however, none of them really works.
file=os.join.path(path+filename)
for i,line in enumerate(fileinput([file], openhook=gzip.open)):
for i,line in enumerate(fileinput.input(openhook=fileinput.hook_compressed(file1,'r'))):
for i,line in enumerate(fileinput.FileInput(openhook=fileinput.hook_compressed(file1,'r'))):
For the first command, errors are like:
'module' object is not callable
For the third command, errors like:
Traceback (most recent call last):
File "read_file.py", line 15, in <module>
for i,line in enumerate(fileinput.input(openhook=fileinput.hook_compressed(file1,'r'))):
File "/share/lib/python2.6/fileinput.py", line 103, in input
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
File "/share/lib/python2.6/fileinput.py", line 230, in __init__
raise ValueError("FileInput openhook must be callable")
ValueError: FileInput openhook must be callable
I don't understand why openhook cannot be callable here?
Can anyone help me with this?
thx
You should pass in the function object as the hook parameter, not call the function.
for i, line in enumerate(fileinput.input(openhook=fileinput.hook_compressed)):
sys.stdout.write("%-6i %s" % (i, line))
In more detail, if function is a function object (something somebody declared with def or lambda), then
variable = function()
calls the function, and stores the result in variable. When instead you say
variable = function
you assign (a reference to) the function object to variable, so that you now can use
variable()
as effectively a synonym for
function()
This usage is relatively rare otherwise, but definitely the norm for hook variables (and indeed, the whole point of hook variables - they offer a "hook" where you can place your own function inside the flow of another class or function. They are alse known as callbacks, if this term should be more familiar).
Related
await message.channel.send("please input the radius of the circle")
alg(int(message.content()))
await message.channel.send(alg)
every time I input a number after the first message I get the below error.
File "main.py", line 138, in on_message
alg(int(message.content()))
TypeError: 'str' object is not callable```
Message.content is an attribute, not a method - means it shouldn't be called (remove the parenthesis)
int(message.content)
I have a class which has BaseScheduler as an attribute, nothing fancy, no frameworks etc.
class MyClass(object):
def __init__(self, ...):
...
self.Scheduler = BackgroundScheduler()
...
Later on I define methods that a) schedule jobs based on a schedule definition passed as kwargs, and b) handle the jobs when they are triggered:
def _schedule_Events(self, *args, **kwargs):
try:
Schedule_Def = kwargs.copy()
Schedule_Def['func'] = self._handle_scheduled_Event
job = self.Scheduler.add_job(**Schedule_Def)
self.Scheduled_Events.append(job)
except Exception as e:
self.Logger.exception('%s: exception in schedule_Events, details: %s' %(self.Name, e))
def _handle_scheduled_Event(self, Event_Action):
""" Callback function for scheduled jobs """
try:
.... do stuff ....
However, adding jobs with _schedule_Events fails with:
File "/usr/local/lib/python3.4/dist-packages/apscheduler/util.py", line 381, in check_callable_args
', '.join(unsatisfied_args))
ValueError: The following arguments have not been supplied: Event_Action
The reason is apparently that the 'func' argument must be globally callable, ie. not within a class instance scope. I also don't see how using a 'textual reference' as described in the documentation will help.
If I replace the 'func' callable with a function defined at the module level then it works, but I need to make it call a method within my instance object. Any ideas how to make this work ? Custom trigger ? Wrapping APS Scheduler inside another class and pass the callback ? Other ideas ?
Many thanks in advance.
A plugin defines a function named HLMarks():
hi Marks term=reverse ctermfg=0 ctermbg=40 guibg=Grey40
function! HLMarks(group)
call clearmatches()
let index = char2nr('a')
while index < char2nr('z')
call matchadd( a:group, '\%'.line( "'".nr2char(index)).'l')
let index = index + 1
endwhile
endfunction
I want the HLMarks() function to run automatically every time vim opens a file.
It works when I call the function manually:
:call HLMarks("Marks")
Adding this line to the end of the plugin didn't do anything:
call HLMarks("Marks")
Calling the function from vimrc got this error:
E117: Unknown function: HLMarks
How to automatically call the HLMarks("Marks") function when a file is opened?
The plugin is described on http://www.vim.org/scripts/script.php?script_id=3394
and down loaded from http://www.vim.org/scripts/download_script.php?src_id=21611
The plugin's markHL.vim file is in my ~/.vim/plugin/ directory.
The ":function" command lists:
function HLMarks(group)
The solution is to add this line to vimrc:
autocmd BufReadPost * call HLMarks("Marks")
Details are at https://groups.google.com/forum/#!topic/vim_use/i2HWD_9V-28
If you define the function in .vimrc then:
function! yourFunc()
" ...
endfunction
call yourFunc()
simply adding the call yourFunc() after the definition will work.
Is there a way to put a argument into a method in batch script? I know I can do that in java programming.
Example #1 (Java)
public class Test {
public static void main (String [] args) {
Test t1=new Test();
System.out.print(t1.method1(false));
}
public int method1 (boolean val1) {
if (val1==false) {
return 0;}
else {
return 1;}
}
}
I want to have something like this so when the method runs, depending on the argument, the method will produce varying results.
Example #2 (Batch - partial pseudocode)
:method1
::With an argument a1 (by default a1=1)
if %a1%==1 echo Option #1
if %a1%==2 echo Option #2
So when I call method1, depending on the argument, I could have two results.
Is there a way to do that? Or suggestions on how one method can have different results? Thanx
Try the inline help for the call built-in statement.
C:\>call /?
Calls one batch program from another.
CALL [drive:][path]filename [batch-parameters]
batch-parameters Specifies any command-line information required by the
batch program.
If Command Extensions are enabled CALL changes as follows:
CALL command now accepts labels as the target of the CALL. The syntax
is:
CALL :label arguments
A new batch file context is created with the specified arguments and
control is passed to the statement after the label specified. You must
"exit" twice by reaching the end of the batch script file twice. The
first time you read the end, control will return to just after the CALL
statement. The second time will exit the batch script. Type GOTO /?
for a description of the GOTO :EOF extension that will allow you to
"return" from a batch script.
<continutes>
I'm trying to save the outputs of a model (written in fortran 77) in netCDF4 format. I'm using gfortran. Since I'm a fresher in fortran, I wrote a simple code in which I create dummy variables and add it to my test netcdf file emulating dimensions,variables and attributes of the model. It works perfectly.
I proceeded to the next step knowing that my code works. Well, the thing is that the very same code does not work and I cannot find out why. The model code is old and "organized" in one single .for file. Interestingly enough, the main code was written as a subroutine. The basic structure of the program is:
implicit real*8(a-h,o-z)
character dummy*80
...
call main(delt,npl)
end
subroutine main(delt, npl)
*variable declarations*
...
end
My approach was to create the netcdf file outside the "main" subroutine. It works and the netcdf file was created. Inside "main" I define dimensions and variable (since they're based on the data generated inside the subroutine). The code works like a charm when I add only the dimensions:
Setting dimensions
nc_status = nf_def_dim(ncid,'parcel_id', ntot, prcl_dimid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
nc_status = nf_def_dim(ncid, 'time', icomp, time_dimid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
End define mode.
nc_status = nf_enddef(ncid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
Close the file
nc_status = nf_close(ncid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
The nc file generated has the right dimensions with the right size. The problem comes when I try to add the variables:
Dimensions
nc_status = nf_def_dim(ncid,'parcel_id', ntot, prcl_dimid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
nc_status = nf_def_dim(ncid, 'time', icomp, time_dimid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
dimids(1) = prcl_dimid
dimids(2) = time_dimid
Variables
**nc_status = nf_def_var(ncid, 'latitude', NF_FLOAT, 2, dimids,
+ lat_varid)**
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
End define mode.
nc_status = nf_enddef(ncid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
Close the file
nc_status = nf_close(ncid)
if (nc_status .ne. nf_noerr) call handle_err(nc_status)
I get the following error from the bold-font part of the code.
Error: NetCDF: Not a valid data type or _FillValue type mismatch
First, this code (exactly like that) works when I create my simple fortran file with dummy values. Second, no fillvalue was defined by me. And third, NF_FLOAT is a valid data type according to UNIDATA website.
I've also tried to create the whole netcdf4 inside the "main" subroutine but I get the same error. I've used all my imagination trying to figure out what is happening and, apparently, no one else had the same problem (or at least did not mention it online...). But I'm a beginner in fortran and everything is possible.
All the best and sorry if it is a stupid question for you. It hasnt been stupid for me at all!