Im new Firefox addon programming.
I want set default file browse location with firefox addon sdk.
Thank you so much.
open scratchpad copy and paste this:
const nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["#mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
var startDir = FileUtils.File('C:\\');
fp.displayDirectory = startDir;
fp.init(window, "Dialog Title", nsIFilePicker.modeOpen);
fp.appendFilters(nsIFilePicker.filterAll | nsIFilePicker.filterText);
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
var file = fp.file;
// Get the path as string. Note that you usually won't
// need to work with the string paths.
var path = fp.file.path;
// work with returned nsILocalFile...
}
if thats what you want let me know, then ill put it in a default location
Related
I have a scenario where after reading the file, it needs the value inside that file to be replaced.
We have this script from our JMeter where we based our script from. (Please refer to the code below)
def file = new File('C:/Peak2020/China/${__time(YMMdd)}-085644-336_000101-plant 8956.xml')
def newConfig = file.text.replace('596791365558876095', '000101')
file.text = newConfig
def newConfig2 = file.text.replace('C6D-CN-NBB2829A', 'C7D-CN-NBB$4568792B')
file.text = newConfig2
def sku = file.text.replace('323094-01', '45903-01')
file.text = sku
I tried doing it in the Neoload, using the replace() but it's not working. It does copy the file from sourcefolder to destinationfolder but the value was not changed. (Please refer to the code below)
var file = new java.io.BufferedReader(new java.io.FileReader("C:\\Peak2020\\China\\testSource1.xml"));
var line = file.readLine();
var id = line.replace(new RegExp("596791365558876095", "12345678"), "");
var destFile = line;
var writer = new java.io.FileWriter("C:\\Peak2020\\Teemp\\TestDestination3.xml",true);
writer.write(destFile);
writer.close();
Does anyone knows what right javascript code to use? Thank you.
String is immutable in Javascript and Java you are replacing it in
var id = line.replace(new RegExp("596791365558876095", "12345678"), "");
but then you use the var line again for the new variable.
var destFile = line;
it should be
var destFile = id;
because replace will return a new string with the replaced value.
I need to create an api where user will provide indesign file and I need to extract text from it.
Basically it can be done this way:
from win32com.client import Dispatch
app = Dispatch('InDesign.Application.CS6')
doc = app.Open(r"d:\text.indd")
contents = ""
for story in doc.stories: contents += story.contents + "\n"
f = open(r"d:\text.txt", "w", encoding="utf8")
f.write(contents)
f.close()
doc.Close()
But perhaps there can be glitches with special symbols. I believe it makes sense to use the native Javascript Extendscript for this task. Something like this:
var doc = app.open(File("d:/text.indd"));
var stories = doc.stories.everyItem().getElements();
var contents = "";
for (var i=0; i<stories.length; i++) contents += stories[i].contents + "\n";
var file = File("d:/text.txt");
file.open("w");
file.write(contents);
file.close();
doc.close();
How to get a unique temporary file path using Swift/Cocoa on OS X?
Cocoa does not seem to provide a function for this, only NSTemporaryDirectory() which returns the path of the temporary directory. Using the BSD mktemp function requires a mutable C-string as argument.
Apple has been trying to move away from path-as-string and into NSURL. Here's one way:
Swift 3:
let directory = NSTemporaryDirectory()
let fileName = NSUUID().uuidString
// This returns a URL? even though it is an NSURL class method
let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])
Swift 2:
let directory = NSTemporaryDirectory()
let fileName = NSUUID().UUIDString
let fullURL = NSURL.fileURLWithPathComponents([directory, fileName])
Here is a possible method to use mkstemp() from Swift 3 and later. URL methods
are used to convert between URL instances and C strings representing the file system path:
// The template string:
let template = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("file.XXXXXX") as NSURL
// Fill buffer with a C string representing the local file system path.
var buffer = [Int8](repeating: 0, count: Int(PATH_MAX))
template.getFileSystemRepresentation(&buffer, maxLength: buffer.count)
// Create unique file name (and open file):
let fd = mkstemp(&buffer)
if fd != -1 {
// Create URL from file system string:
let url = URL(fileURLWithFileSystemRepresentation: buffer, isDirectory: false, relativeTo: nil)
print(url.path)
} else {
print("Error: " + String(cString: strerror(errno)))
}
Older code for Swift 2:
// The template string:
let template = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("file.XXXXXX")
// Fill buffer with a C string representing the local file system path.
var buffer = [Int8](count: Int(PATH_MAX), repeatedValue: 0)
template.getFileSystemRepresentation(&buffer, maxLength: buffer.count)
// Create unique file name (and open file):
let fd = mkstemp(&buffer)
if fd != -1 {
// Create URL from file system string:
let url = NSURL(fileURLWithFileSystemRepresentation: buffer, isDirectory: false, relativeToURL: nil)
print(url.path!)
} else {
print("Error: " + String(strerror(errno)))
}
Although NSTemporaryDirectory() does indeed return a temporary directory path for the current user, the documentation includes the following caveat:
See the FileManager method url(for:in:appropriateFor:create:) for the preferred means of finding the correct temporary directory.
Following that link, we are presented with the following:
You can use this method to create a new temporary directory. To do so, specify FileManager.SearchPathDirectory.itemReplacementDirectory for the directory parameter, userDomainMask for the domain parameter, and a URL for the url parameter which determines the volume of the returned URL.
For example, the following code results in a new temporary directory with a path in the form of /private/var/folders/d0/h37cw8ns3h1bfr_2gnwq2yyc0000gn/T/TemporaryItems/Untitled/:
let desktop = URL(fileURLWithPath: "/Users/jappleseed/Desktop/")
do {
let temporaryDirectory = try FileManager.default.url(
for: .itemReplacementDirectory,
in: .userDomainMask,
appropriateFor: desktop,
create: true
)
print(temporaryDirectory)
} catch {
// Handle the error.
}
(Note the the create parameter is ignored when creating a temporary directory.)
So what exactly is the difference between these two approaches? Well, here's what I get when I call the two different methods from the Swift REPL:
1> import Foundation
2> NSTemporaryDirectory()
$R0: String = "/var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/"
3> let desktop = URL(fileURLWithPath: "/Users/chris/Desktop/")
desktop: URL = "file:///Users/chris/Desktop/"
4> let temporaryDirectory = try FileManager.default.url(
5. for: .itemReplacementDirectory,
6. in: .userDomainMask,
7. appropriateFor: desktop,
8. create: true
9. )
temporaryDirectory: URL = "file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20repl_swift)/"
It appears that NSTemporaryDirectory() will always return the temporary directory path for the current user whereas FileManager's url(for:appropriateFor:create) will return a new temporary subdirectory each time it is called. For example, here are the directories returned by consecutive calls to url(for:in:appropriateFor:create:) from the Swift REPL:
file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20repl_swift)/
file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20repl_swift%202)/
file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20repl_swift%203)/
And here are the directories returned by consecutive calls to the same method from a Swift Playground:
file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20Xcode)/
file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20Xcode%202)/
file:///var/folders/n_/0_9q7d2d1ls5v9kx599y_tj00000gn/T/TemporaryItems/(A%20Document%20Being%20Saved%20By%20Xcode%203)/
The NSHipster article on temporary files seems to suggest that the FileManager method url(for:in:appropriateFor:create:) is intended to be used when staging a file to be moved to a more permanent location (such as the user's desktop in the example above), but I don't see why it couldn't also be used to simply get a unique subdirectory that will automatically be removed when you're done with it and where you shouldn't have to worry about files getting accidentally clobbered by other processes writing to the same temporary directory.
A Swift 3 one-liner inspired by the UUID based Swift 2 answer:
let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(UUID().uuidString)
FileManager extension in Swift to get a temporary file URL. You can pass your own file name and extension, if needed.
public extension FileManager {
func temporaryFileURL(fileName: String = UUID().uuidString) -> URL? {
return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(fileName)
}
}
Usage:
let tempURL = FileManager.default.temporaryFileURL()
let tempJPG = FileManager.default.temporaryFileURL(fileName: "temp.jpg")
Use a GUID (Globally Unique Identifier):
let directory :NSString = "directory"
let randomName = NSProcessInfo().globallyUniqueString
let path = directory.stringByAppendingPathComponent(randomName)
directory/3B635E49-813A-4324-B4B8-56279B42BEAB-36687-0002D962615DAE5F
I like the idea of this article: NSTemporary​Directory - NSHipster
This uses the NSTemporaryDirectory() for the temporary folder and ProcessInfo.processInfo.globallyUniqueString to generate a unique string.
Swift 4:
func uniqueTempFolderURL() -> URL
{
let folderName = ProcessInfo.processInfo.globallyUniqueString
return URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true).appendingPathComponent(folderName)
}
Swift3
I came here looking for something like boost::filesystem::unique_path()
So I made this extension to the URL class.
extension URL {
func appendingUniquePathComponent(pathExtension: String? = nil) -> URL {
var pathComponent = UUID().uuidString
if let pathExtension = pathExtension {
pathComponent += ".\(pathExtension)"
}
return appendingPathComponent(pathComponent)
}
}
Usage:
let url0 = URL(fileURLWithPath: "/tmp/some/dir")
let url1 = url0.appendingUniquePathComponent(pathExtension: "jpg")
print("url1: \(url1)")
// url1: file:///tmp/some/dir/936324FF-EEDB-410E-AD09-E24D5EB4A24F.jpg
The code below for file with no-extension brings up a dialog shown below listing applications that can be used to open the file. This behavior is seen only from Windows-8. And the applications listed in the dialog are taken from HKEY_LOCAL_MACHINE\SOFTWARE\Classes*\OpenWithList. Is there anyway to suppress this dialog and get a behavior similar to old platforms?
-Karthik
SHELLEXECUTEINFO shinfo;
unsigned long mask = SEE_MASK_FLAG_NO_UI;
memset(&shinfo,0,sizeof(shinfo));
shinfo.cbSize = sizeof(shinfo);
shinfo.fMask = SEE_MASK_FLAG_DDEWAIT | mask;
shinfo.hwnd = NULL;
shinfo.lpVerb = "open";
shinfo.lpFile = prog;
shinfo.lpParameters = NULL;
shinfo.lpDirectory = 0;
shinfo.fMask = SEE_MASK_FLAG_NO_UI;
shinfo.nShow = SW_SHOWDEFAULT;
rc = ShellExecuteEx(&shinfo);
I'd suspect there is no default action associated with open on Windows 8 for files without an extension. I confirmed this using your code (a Delphi version of it, anyway) on Windows 7.
Running the code with shinfo.lpverb set to 'open' caused ShellExecuteEx to return FALSE, and GetLastError did indeed return ERROR_NO_ASSOCIATION. However, changing lpVerb to NULL (nil in Delphi) instead displayed the standard Win7 Open With dialog, just like your code does on Windows 8.
Here's a modified version of your code for testing:
SHELLEXECUTEINFO shinfo;
memset(&shinfo, 0, sizeof(shinfo));
shinfo.cbSize = sizeof(shinfo);
shinfo.fMask = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
shinfo.lpVerb = NULL;
shinfo.lpFile = prog;
shinfo.hwnd = NULL;
shinfo.lpParameters = NULL;
shinfo.lpDirectory = 0;
shinfo.nShow = SW_SHOWDEFAULT;
rc = ShellExecuteEx(&shinfo);
Here's my test Delphi code for comparison (a quite literal translation of your C++ code):
var
shInfo: TShellExecuteInfo;
FillChar(shInfo, SizeOf(shInfo), 0); // Same result as memset()
shInfo.cbSize := SizeOf(shInfo);
shInfo.fMask := SEE_MASK_FLAG_NO_UI or SEE_MASK_FLAG_DDEWAIT;
shInfo.Wnd := 0;
shInfo.lpVerb := nil; // Also tested with 'open'
shInfo.lpDirectory := 'D:\TempFiles'; // Path to my no-extension file
shInfo.lpFile := 'datafile'; // My test file with no ext
shInfo.nShow := SW_SHOWDEFAULT;
if not ShellExecuteEx(#shInfo) then
ShowMessage(SysErrorMessage(GetLastError)); // Readable error message
A quick change to your code to replace "open" with NULL as the lpVerb should confirm.
You can also confirm my suspicion fairly easily by right-clicking a file with no extension in Win8's Explorer, and checking the bold default action at the top of the context menu. If there is no bold option, or if it's anything but open, my suspicions are correct.
I'm working on a Windows batch script that creates a directory/file listing of a complete hard disk for archival/cataloging purposes, using only command line-tools (and open-source/free tools). For each of the entries in the listing I wanted to list the filename, directory where it resides in, the filesize, date a,nd time of the file, and the md5 sum. I have been able to create somewhat a working starting point, but I'm hitting a wall since I'm not sure if it is even possible using the command-line tools in Windows. The command "dir /s /a:-d /o:-d /t:c" gives me a nice overview, but I would like this overview displayed (or saved to) a comma-delimited format. So my questions are:
Can I create a csv file with all the fields I mentioned above, with the standard command-line tools (and a m5 freeware tool for the md5 sums)
Do you know of a better way, or is there a dead simple disk cataloging command-line tool I missed?
Thanks in advance for any tips!
You can use dir /s /a:-d /o:-d /t:c > slam.txt
Then the content of this slam.txt, can be processed by WScript in windows, making a CSV file ...
If you need a WScript ex, I can provide one ?
I know this not an CSV example - but it should be complex enough for pattern inspiration :)
and remember this fil is saved as .js
var what2lookfor = '<rect ';
var forReading = 1, forWriting = 2, forAppending = 8, jx = 0, ix = 0;
var triStateUseDefault = -2, triStateTrue = -1, triStateFalse = 0;
var thisRecord="", validFileTypes="js,xml,txt,php,xsl,css,htm,html" , akkum = "";
var fileArray = [];
var FSO = new ActiveXObject("Scripting.FileSystemObject");
var objFiles = FSO.GetFolder("F:\\xps1710\\jscript\\");
var objFileControl = new Enumerator(objFiles.files);
for (; !objFileControl.atEnd(); objFileControl.moveNext()) {
objFile = FSO.GetFile(objFileControl.item());
var ext = objFile.Name.split(".");
if (validFileTypes.indexOf(ext[1]) > 1) {
fileArray[ix] = "F:\\xps1710\\jscript\\" + objFile.Name;
ix++;
}
}
for (zx = 0 ; zx < ix ; zx++ ) {
var file2Traverse = FSO.OpenTextFile(fileArray[zx], forReading, triStateUseDefault );
while (!file2Traverse.AtEndOfStream) {
thisRecord = file2Traverse.ReadLine();
if (thisRecord.indexOf(what2lookfor) > 1 ) {
akkum = akkum + fileArray[zx] + '::' + thisRecord + '\n';
break;
}
}
}
WScript.Echo(akkum);