I've tried the following
url=[http://upload.wikimedia.org/wikipedia/pt/c/ce/Who_Killed_the_Electric_Car.jpg];
filename = [teste.jpg]
urlwrite (url, filename)
By doing these steps, the image in this link will be written under "teste.jpg" filename
In other hand, if I try:
url=[http://upload.wikimedia.org/wikipedia/pt/c/ce/ererr.jpg];
filename = [teste.jpg]
urlwrite (url, filename)
Matlab prompt will return :
??? Error using ==> urlwrite at 140 Error downloading URL. Your
network connection may be down or your proxy settings improperly
configured.
So, how can I make matlab to check if the image exists?
If you use output arguments, the error will be suppressed. See URLWRITE documentation.
[filestr,status] = urlwrite(_) stores the file path in variable filestr, and suppresses the display of error messages, using any of
the input arguments in the previous syntaxes. When the operation is
successful, status is 1. Otherwise, status is 0.
Related
Following is the code I have used :-
require(realpath(dirname(__FILE__).'/../../../email/apps/common/framework/YiiBase.php'));
$config = require(realpath(dirname(__FILE__).'/../../../email/apps/customer/config/main.php'));
Yii::createWebApplication($config);
var_dump(Yii::app()->User->id);
i am getting following error:-
Message: include(): Failed opening 'Yii.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear')
Filename: framework/YiiBase.php
Line Number: 428
Be kind write full absolute path for the script that executes the code and location of the files YiiBase.php and main.php.
Solution from the creator of Yii says:
require_once('path/to/yii.php');
Yii::createWebApplication($config);
// you can access Yii::app() now as usual
$session = Yii::app()->session;
//....use session as you wish
My file that can help you start is:
// change the following paths if necessary
$yii=dirname(__FILE__).'/../yii/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($yii);
Yii::createWebApplication($config);
NOTE
Its is not recommended you use YiiBase. Use either yii or yiilite. YiiBase serves as base class and is not intended to be used directly (to the best of my kowledge). Also check paths if they real point to the file!
I am working on porting a project in Windows over to OSX. I have overcome issues with VBA for OSX Word 2011 not allowing you to send POSTs to a server and have figured out how to return a string result from an external script. Now I have to insert an image in my Word file from a URL that is built using the return of my external script.
The current attempt is as follows, and works in Windows but crashes Word in OSX:
Selection.InlineShapes.AddPicture FileName:=File_Name, _
LinkToFile:=False, SaveWithDocument:=True
After doing some research, it looks like MS may have disabled this functionality in OSX as a "security risk". I still need to make it work. Does anybody know of a way within VBA for Office 2011 to make this work, or barring that a workaround? I am trying to avoid writing the image file to the disk if possible.
UPDATE: I have created a Python script for getting the image file from a URL, but I still do not know how to get this image from the Python script into VBA, and from there into the Word document at the location of the cursor. The important bits of the script are below. The image is read in as a PIL object and I can show it using img.show() just fine, but I am not sure what filetype this is or how to get VBA to accept it.
# Import the required libraries
from urllib2 import urlopen, URLError
from cStringIO import StringIO
from PIL import Image
# Send request to the server and receive response, with error handling!
try:
# Read the response and print to a file
result = StringIO(urlopen(args.webAddr + args.filename).read())
img = Image.open(result)
img.show()
except URLError, e:
if hasattr(e, 'reason'): # URL error case
# a tuple containing error code and text error message
print 'Error: Failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # HTTP error case
# HTTP error code, see section 10 of RFC 2616 for details
print 'Error: The server could not fulfill the request.'
print 'Error code: ', e.code
Note that in the above, args.webAddr and args.filename are passed to the script using the argparse library. This script works, and will show the image file that I expect. Any ideas on how to get that image into Word 2011 for OSX and insert it under the cursor?
Thanks a lot!
Edit: updated the link to the project since migrating to github.
Old question, but no answer, and I see the same crash here when the image is at an http URL. I think you can use the following workaround
Sub insertIncludePictureAndUnlink()
' Put your URL in here...
Const theImageURL As String = ""
Dim f As Word.Field
Dim r As Word.Range
Set f = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldIncludePicture, Text:=Chr(34) & theImageURL & Chr(34), PreserveFormatting:=False)
Set r = f.Result
f.Unlink
Set f = Nothing
' should have an inlineshape in r
Debug.Print r.InlineShapes.Count
' so now you can do whatever you need, e.g....
r.Copy
Set r = Nothing
End Sub
I have gone through quite a few questions that have been posted which appear to be related, but not entirely the same issue that I am having:
I am using python's ftplib module along with zipfile to download a zip file from ftp in binary format. However, for some reason, the downloaded zip file appears to be in ascii.
I have ensured that a leading / does not exist in the path of the file I am downloading (to match the zip specifications).
outFile = zipfile.ZipFile(local_file_path, 'w')
myftp.retrbinary('RETR %s' %i, outFile.write(i)) #i - target file path on ftp server
This code fails giving me the following error:
st = os.stat(filename)
OSError: [Errno 2] No such file or directory: //$i
I tried adding the 'b' option for binary, but zipfile doesn't seem to like it:
outFile = zipfile.ZipFile(local_file_path, 'wb')
This raises error:
RuntimeError: ZipFile() requires mode "r", "w", or "a"
I am using python v2.6.
What am I doing wrong and how to fix it?
According to python doc (http://docs.python.org/2/library/ftplib.html) seems retrbinary takes a callback as second parameter:
>>> ftp.retrbinary('RETR README', open('README', 'wb').write)
'226 Transfer complete.'
>>> ftp.quit()
Documentation says:
FTP.retrbinary(command, callback[, maxblocksize[, rest]])
Retrieve a file in binary transfer mode. command should be an
appropriate RETR command: 'RETR filename'. The callback function is
called for each block of data received, with a single string argument
giving the data block. [...]
In your example it should be outfile.write (instead of outfile.write(i)).
>>> ftp.retrbinary('RETR %s' % i, outFile.write)
I'm porting a large VBA project over from Windows to the new Mac Word 2011. It's actually going very well...almost all of the code is working.
My code needs to call scripts on my server. On Windows, I call the system function InternetOpenUrl to call a script and InternetReadFile to read the results returned by the script. For example, I call a script like:
"http://www.mysite.com/cgi-bin/myscript.pl?param1=Hello¶m2=World
and it returns a string like "Success"
What's the best way to do the equivalent on the Mac? Is using Applescript (via the vba MacScript function) the answer? I do that to display the file chooser dialog, but I can't find what the applescript to call an online script would look like. Or is there a better/faster way to do this?
Thanks in advance,
gary
You can try the URL Access Scripting library, which is a front-end for curl, or go to the script via a browser and reading the text through there.
I recently figured this out for making a call to a server to convert a user-defined LaTeX string to an image of the equation. The call is made through VBA via the MacScript command as:
command = "do shell script """ & pyPath & "python " & getURLpath & "getURL.py --formula '" _
& Latex_Str & "' --fontsize " & Font_Size & " " & WebAdd & """"
result = MacScript(command)
Which looks ugly, but this is just building the command do shell script /usr/bin/python {path to script}/getURL.py --formula '{LaTeX formula string}' --fontsize {int} {myurl} and passing it to the command. My Python script then uses argparse to parse the arguments sent to it, and urllib and urllib2 to handle sending the request to the server. The MacScript command read the stdout of my Python script and returns it as a string to result.
This guide on urllib2 should help you get the Python script up and running.
EDIT: Sorry, my answer was incomplete last time. The Python script I used to finish the job is below.
# Import the required libraries
from urllib import urlencode
from urllib2 import Request, urlopen, URLError, ProxyHandler, build_opener, install_opener
import argparse
# Set up our argument parser
parser = argparse.ArgumentParser(description='Sends LaTeX string to web server and returns meta data used by LaTeX in Word project')
parser.add_argument('webAddr', type=str, help='Web address of LaTeX in Word server')
parser.add_argument('--formula', metavar='FRML', type=str, help='A LaTeX formula string')
parser.add_argument('--fontsize', metavar='SIZE', type=int, default=10, help='Integer representing font size (can be 10, 11, or 12. Default 10)')
parser.add_argument('--proxServ', metavar='SERV', type=str, help='Web address of proxy server, i.e. http://proxy.server.com:80')
parser.add_argument('--proxType', metavar='TYPE', type=str, default='http', help='Type of proxy server, i.e. http')
# Get the arguments from the parser
args = parser.parse_args()
# Define formula string if input
if args.formula:
values = {'formula': str(args.fontsize) + '.' + args.formula} # generate formula from args
else:
values = {}
# Define proxy settings if proxy server is input.
if args.proxServ: # set up the proxy server support
proxySupport = ProxyHandler({args.proxType: args.proxServ})
opener = build_opener(proxySupport)
install_opener(opener)
# Set up the data object
data = urlencode(values)
data = data.encode('utf-8')
# Send request to the server and receive response, with error handling!
try:
req = Request(args.webAddr, data)
# Read the response and print to a file
response = urlopen(req)
print response.read()
except URLError, e:
if hasattr(e, 'reason'): # URL error case
# a tuple containing error code and text error message
print 'Error: Failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # HTTP error case
# HTTP error code, see section 10 of RFC 2616 for details
print 'Error: The server could not fulfill the request.'
print 'Error code: ', e.code
If I am running a long R script from the command line (R --slave script.R), then how can I get it to give line numbers at errors?
I don't want to add debug commands to the script if at all possible; I just want R to behave like most other scripting languages.
This won't give you the line number, but it will tell you where the failure happens in the call stack which is very helpful:
traceback()
[Edit:] When running a script from the command line you will have to skip one or two calls, see traceback() for interactive and non-interactive R sessions
I'm not aware of another way to do this without the usual debugging suspects:
debug()
browser()
options(error=recover) [followed by options(error = NULL) to revert it]
You might want to look at this related post.
[Edit:] Sorry...just saw that you're running this from the command line. In that case I would suggest working with the options(error) functionality. Here's a simple example:
options(error = quote({dump.frames(to.file=TRUE); q()}))
You can create as elaborate a script as you want on an error condition, so you should just decide what information you need for debugging.
Otherwise, if there are specific areas you're concerned about (e.g. connecting to a database), then wrap them in a tryCatch() function.
Doing options(error=traceback) provides a little more information about the content of the lines leading up to the error. It causes a traceback to appear if there is an error, and for some errors it has the line number, prefixed by #. But it's hit or miss, many errors won't get line numbers.
Support for this will be forthcoming in R 2.10 and later. Duncan Murdoch just posted to r-devel on Sep 10 2009 about findLineNum and setBreapoint:
I've just added a couple of functions to R-devel to help with
debugging. findLineNum() finds which line of which function
corresponds to a particular line of source code; setBreakpoint() takes
the output of findLineNum, and calls trace() to set a breakpoint
there.
These rely on having source reference debug information in the code.
This is the default for code read by source(), but not for packages.
To get the source references in package code, set the environment
variable R_KEEP_PKG_SOURCE=yes, or within R, set
options(keep.source.pkgs=TRUE), then install the package from source
code. Read ?findLineNum for details on how to tell it to search
within packages, rather than limiting the search to the global
environment.
For example,
x <- " f <- function(a, b) {
if (a > b) {
a
} else {
b
}
}"
eval(parse(text=x)) # Normally you'd use source() to read a file...
findLineNum("<text>#3") # <text> is a dummy filename used by
parse(text=)
This will print
f step 2,3,2 in <environment: R_GlobalEnv>
and you can use
setBreakpoint("<text>#3")
to set a breakpoint there.
There are still some limitations (and probably bugs) in the code; I'll
be fixing thos
You do it by setting
options(show.error.locations = TRUE)
I just wonder why this setting is not a default in R? It should be, as it is in every other language.
Specifying the global R option for handling non-catastrophic errors worked for me, along with a customized workflow for retaining info about the error and examining this info after the failure. I am currently running R version 3.4.1.
Below, I've included a description of the workflow that worked for me, as well as some code I used to set the global error handling option in R.
As I have it configured, the error handling also creates an RData file containing all objects in working memory at the time of the error. This dump can be read back into R using load() and then the various environments as they existed at the time of the error can be inspected interactively using debugger(errorDump).
I will note that I was able to get line numbers in the traceback() output from any custom functions within the stack, but only if I used the keep.source=TRUE option when calling source() for any custom functions used in my script. Without this option, setting the global error handling option as below sent the full output of the traceback() to an error log named error.log, but line numbers were not available.
Here's the general steps I took in my workflow and how I was able to access the memory dump and error log after a non-interactive R failure.
I put the following at the top of the main script I was calling from the command line. This sets the global error handling option for the R session. My main script was called myMainScript.R. The various lines in the code have comments after them describing what they do. Basically, with this option, when R encounters an error that triggers stop(), it will create an RData (*.rda) dump file of working memory across all active environments in the directory ~/myUsername/directoryForDump and will also write an error log named error.log with some useful information to the same directory. You can modify this snippet to add other handling on error (e.g., add a timestamp to the dump file and error log filenames, etc.).
options(error = quote({
setwd('~/myUsername/directoryForDump'); # Set working directory where you want the dump to go, since dump.frames() doesn't seem to accept absolute file paths.
dump.frames("errorDump", to.file=TRUE, include.GlobalEnv=TRUE); # First dump to file; this dump is not accessible by the R session.
sink(file="error.log"); # Specify sink file to redirect all output.
dump.frames(); # Dump again to be able to retrieve error message and write to error log; this dump is accessible by the R session since not dumped to file.
cat(attr(last.dump,"error.message")); # Print error message to file, along with simplified stack trace.
cat('\nTraceback:');
cat('\n');
traceback(2); # Print full traceback of function calls with all parameters. The 2 passed to traceback omits the outermost two function calls.
sink();
q()}))
Make sure that from the main script and any subsequent function calls, anytime a function is sourced, the option keep.source=TRUE is used. That is, to source a function, you would use source('~/path/to/myFunction.R', keep.source=TRUE). This is required for the traceback() output to contain line numbers. It looks like you may also be able to set this option globally using options( keep.source=TRUE ), but I have not tested this to see if it works. If you don't need line numbers, you can omit this option.
From the terminal (outside R), call the main script in batch mode using Rscript myMainScript.R. This starts a new non-interactive R session and runs the script myMainScript.R. The code snippet given in step 1 that has been placed at the top of myMainScript.R sets the error handling option for the non-interactive R session.
Encounter an error somewhere within the execution of myMainScript.R. This may be in the main script itself, or nested several functions deep. When the error is encountered, handling will be performed as specified in step 1, and the R session will terminate.
An RData dump file named errorDump.rda and and error log named error.log are created in the directory specified by '~/myUsername/directoryForDump' in the global error handling option setting.
At your leisure, inspect error.log to review information about the error, including the error message itself and the full stack trace leading to the error. Here's an example of the log that's generated on error; note the numbers after the # character are the line numbers of the error at various points in the call stack:
Error in callNonExistFunc() : could not find function "callNonExistFunc"
Calls: test_multi_commodity_flow_cmd -> getExtendedConfigDF -> extendConfigDF
Traceback:
3: extendConfigDF(info_df, data_dir = user_dir, dlevel = dlevel) at test_multi_commodity_flow.R#304
2: getExtendedConfigDF(config_file_path, out_dir, dlevel) at test_multi_commodity_flow.R#352
1: test_multi_commodity_flow_cmd(config_file_path = config_file_path,
spot_file_path = spot_file_path, forward_file_path = forward_file_path,
data_dir = "../", user_dir = "Output", sim_type = "spot",
sim_scheme = "shape", sim_gran = "hourly", sim_adjust = "raw",
nsim = 5, start_date = "2017-07-01", end_date = "2017-12-31",
compute_averages = opt$compute_averages, compute_shapes = opt$compute_shapes,
overwrite = opt$overwrite, nmonths = opt$nmonths, forward_regime = opt$fregime,
ltfv_ratio = opt$ltfv_ratio, method = opt$method, dlevel = 0)
At your leisure, you may load errorDump.rda into an interactive R session using load('~/path/to/errorDump.rda'). Once loaded, call debugger(errorDump) to browse all R objects in memory in any of the active environments. See the R help on debugger() for more info.
This workflow is enormously helpful when running R in some type of production environment where you have non-interactive R sessions being initiated at the command line and you want information retained about unexpected errors. The ability to dump memory to a file you can use to inspect working memory at the time of the error, along with having the line numbers of the error in the call stack, facilitate speedy post-mortem debugging of what caused the error.
First, options(show.error.locations = TRUE) and then traceback(). The error line number will be displayed after #