How can I get out of this process of what looks like losing everything unsaved in sublime? - sublimetext2

I have lots of open documents in sublime, many of them not saved
I was experimenting with keyboard shortcuts I thought I had created one for sorting tabs, but I hit the wrong one, something along the lines of ctrl-alt-shift-s
And it seems to be doing a close all
So I now have a situation of sublime with a load of unsaved documents and a window that looks like
and if I hit OK then it asks about the next file (so presumably I lose that one). Though that one might not be important, many of them are defunitely untitled and important. Others titled but perhaps not saved.
I can't see a way of getting out of this process without potentially losing all my unsaved files (or updates to saved ones).
What do you suggest?
Further to Hugo's input that it's a JSON, i'd be interested in reading it in a JSON editor / JSON reader.
But I get this error
So maybe it's not a totally valid json? I will try to find out what character is there..
If I try some NodeJS to read the file, I still get an issue
/*
http://stackoverflow.com/questions/14432165/uncaught-syntaxerror-unexpected-token-with-json-parse
// preserve newlines, etc - use valid JSON
s = s.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
s = s.replace(/[\u0000-\u0019]+/g,"");
var o = JSON.parse(s);
*/
var fs = require('fs');
fs.readFile('./auto1.json', 'utf8', function (err, data) {
if (err) throw err; // we'll not consider error handling for now
var str=data;
str = str.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f")
.replace(/[\u0000-\u001F]+/g,"");
var obj = JSON.parse(data);
});
and I get output
C:\crp\abba>node a.js
undefined:1273
"contents": "\nhtt...
SyntaxError: Unexpected token
at Object.parse (native)
at C:\crp\abba\a.js:36:20
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:380:3)
C:\crp\abba>
I'll have to try out smaller parts of the file and try to find the part of the json that is causing the issue. And i'll try sublime on another computer and load the files onto that 'cos sublime is apparently more lenient when reading(and creating!) a json than javascript is.

Sublime stores the contents of unsaved files inside some json files located at:
C:\Users\<USER>\AppData\Roaming\Sublime Text 2\Settings
First thing, create a backup of these files, then try to copy these files to the same folder in another computer (or to another account in the same computer) and then open sublime.

Related

Dart / flutter: download or read the contents of a Google Drive file

I have a public (anyone with the link can view) file on my Google Drive and I want to use the content of it in my Android app.
From what I could gather so far, I need the fileID, the OAuth token and the client ID - these I already got. But I can't figure out what is the exact methodology of authorising the app or fetching the file.
EDIT:
Simply reading it using file.readAsLines didn't work:
final file = new File(dogListTxt);
Future<List<String>> dogLinks = file.readAsLines();
return dogLinks;
The dogLinks variable isn't filled with any data, but I get no error messages.
The other method I tried was following this example but this is a web based application with explicit authorization request (and for some reason I was never able to import the dart:html library).
The best solution would be if it could be done seamlessly, as I would store the content in a List at the application launch, and re-read on manual refresh button press.
I found several old solutions here, but the methods described in those doesn't seem to work anymore (from 4-5 years ago).
Is there a good step-by-step tutorial about integrating the Drive API in a flutter application written in dart?
I had quite a bit of trouble with this, it seems much harder than it should be. Also this is for TXT files only. You need to use files.export() for other files.
First you need to get a list fo files.
ga.FileList textFileList = await drive.files.list(q: "'root' in parents");
Then you need to get those files based on ID (This is for TXT Files)
ga.Media response = await drive.files.get(filedId, downloadOptions: ga.DownloadOptions.FullMedia);
Next is the messy part, you need to convert your Media object stream into a File and then read the text from it. ( #Google, please make this easier.)
List<int> dataStore = [];
response.stream.listen((data) {
print("DataReceived: ${data.length}");
dataStore.insertAll(dataStore.length, data);
}, onDone: () async {
Directory tempDir = await getTemporaryDirectory(); //Get temp folder using Path Provider
String tempPath = tempDir.path; //Get path to that location
File file = File('$tempPath/test'); //Create a dummy file
await file.writeAsBytes(dataStore); //Write to that file from the datastore you created from the Media stream
String content = file.readAsStringSync(); // Read String from the file
print(content); //Finally you have your text
print("Task Done");
}, onError: (error) {
print("Some Error");
});
There currently is no good step-by-step tutorial, but using https://developers.google.com/drive/api/v3/manage-downloads as a reference guide for what methods to use in Dart/Flutter via https://pub.dev/packages/googleapis: to download or read the contents of a Google Drive file, you should be using googleapis/Drive v3, or specifically, the methods from the FilesResourceApi class.
drive.files.export(), if this is a Google document
/// Exports a Google Doc to the requested MIME type and returns the exported content. Please note that the exported content is limited to 10MB.
drive.files.get(), if this something else, a non-Gdoc file
/// Gets a file's metadata or content by ID.
Simplified example:
var drive = new DriveApi(http_client);
drive.files.get(fileId).then((file) {
// returns file
});
However, what I discovered was that this Dart-GoogleAPIs library seemed to be missing a method equivalent to executeMediaAndDownloadTo(outputStream). In the original Google Drive API v3, this method adds the alt=media URL parameter to the underlying HTTP request. Otherwise, you'll get the error, which is what I saw:
403, message: Export requires alt=media to download the exported
content.
And I wasn't able to find another way to insert that URL parameter into the current request (maybe someone else knows?). So as an alternative, you'll have to resort to implementing your own Dart API to do the same thing, as hinted by what this OP did over here https://github.com/dart-lang/googleapis/issues/78: CustomDriveApi
So you'll either:
do it through Dart with your own HttpClient implementation and try to closely follow the REST flow from Dart-GoogleAPIs, but remembering to include the alt=media
or implement and integrate your own native-Android/iOS code and use the original SDK's convenient executeMediaAndDownloadTo(outputStream)
(note, I didn't test googleapis/Drive v2, but a quick examination of the same methods looks like they are missing the same thing)
I wrote this function to get file content of a file using its file id. This is the simplest method I found to do it.
Future<String> _getFileContent(String fileId) async {
var response = await driveApi.files.get(fileId, downloadOptions: DownloadOptions.fullMedia);
if (response is! Media) throw Exception("invalid response");
return await utf8.decodeStream(response.stream);
}
Example usage:
// save file to app data folder with 150 "hello world"s
var content = utf8.encode("hello world" * 150);
driveApi.files
.create(File(name: fileName, parents: [appDataFolder]),
uploadMedia: Media(Stream.value(content), content.length))
.then((value) {
Log().i("finished uploading file ${value.id}");
var id = value.id;
if (id != null) {
// after successful upload, read the recently uploaded file content
_getFileContent(id).then((value) => Log().i("got content is $value"));
}
});

How to parse json newline delimited in Angular 2

I am writing an Angular 2 app (built with angular cli), and trying to use AWS Polly text-to-speech API.
According to the API you can request audio output as well as "Speech Marks" which can describe word timing, visemes, etc. The audio is delivered as "mp3" format, and the speech marks as "application/x-json-stream", which I understand as a "new line" delimited JSON. It cannot be parsed with JSON.parse() due to the new lines. I have yet been unable to read/parse this data. I have looked at several libs that are for "json streaming" but they are all built for node.js and won't work with Angular 2. My code is as follows...
onClick() {
AWS.config.region = 'us-west-2';
AWS.config.accessKeyId = 'xxxxx';
AWS.config.secretAccessKey = 'yyyyy';
let polly = new AWS.Polly();
var params = {
OutputFormat: 'json',
Text: 'Hello world',
VoiceId: 'Joanna',
SpeechMarkTypes:['viseme']
};
polly.synthesizeSpeech(params, (err, data) => {
if (err) {
console.log(err, err.stack);
} else {
var uInt8Array = new Uint8Array(data.AudioStream);
var arrayBuffer = uInt8Array.buffer;
var blob = new Blob([arrayBuffer]);
var url = URL.createObjectURL(blob);
this.audio.src = url;
this.audio.play(); // works fine
// speech marks info displays "application/x-json-stream"
console.log(data.ContentType);
}
});
Strangely enough Chrome browser knows how to read this data and displays it in the response.
Any help would be greatly appreciated.
I had the same problem. I saved the file so I could then read it line by line, accessing the JSON objects when I need to highlight words being read. Mind you this is probably not the most effective way, but an easy way to move on and get working on the fun stuff.
I am trying out different ways to work with Polly, will update answer if I find a better way
You can do it with:
https://www.npmjs.com/package/ndjson-parse
That worked for me.
But I can't play audio, I tried your code it says
DOMException: Failed to load because no supported source was found.

JSON.parse(dt) doesn't work at all, give all the errors it can imagine

I have this code at server side (nodejs):
socket.on('data', function(dt){
var rdata = dt;
var msg = JSON.parse(rdata);
broadcast(msg);
});
Also I tried this way: var msg = JSON.parse(dt);
dt gets either:
{"chat":"hey","nickname":"nick_name"} OR
'{"chat":"hey","nickname":"nick_name"}'
Also I have this at the client side (AS3), tried both:
var msg = JSON.stringify({nickname: nname.text, chat: input_txt.text}); OR
var msg = "'" + JSON.stringify({nickname: nname.text, chat: input_txt.text}) + "'";
That is what console gives:
undefined:1
{"chat":"hey","nickname":"nick_name"}
^
SyntaxError: Unexpected token
DEBUG: Program node app exited with code 8
Also in some other situations, it gives all kinds of messages.
Just have no idea what is going on.
BTW, also tried JSONStream, still doesn't work.
What kind of socket exactly are you using? If you are using a websocket you might have already received an object as a response (I think most frameworks do so). If you are using plain net.socket you might be receiving a buffer or the data in chunks and not all at once. This seems like an appropriate fix for that situation:
var buffer;
socket.setEncoding('utf8');
socket.on('data', function(data) {
buffer += data;
});
socket.on('end', function() {
var object = JSON.parse(buffer);
});
Unexpected token at the end of data string, is some ghost symbol that is not a white space. trim() doesn't work, so to substring the last symbor works. This is AS3 symbol, so we have to keep it. First you save this symbol in the new variable. the you erase this symbol from the line. After that you can parse the string. work with it.
undefined:1
{"chat":"hey","nickname":"nick_name"}
^
SyntaxError: Unexpected token
DEBUG: Program node app exited with code 8
When you finish working with it, stringify the object, then add ghost symbol to the end and send over the socket. Without this symbol AS3 will not parse the data.
I don't know why is that, but that works for me.

Phonegap file writer is not working, cannot truncate file content

I am using phonegap file reading functionality, once i read the content and i will do some functionality with that content, once that over i am calling file truncate functionality. In that i can't truncate any value. Help me to fix this issue.
removeFileContent();
function removeFileContent(){
console.log("Inside remove file content");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFileTruncate, onProcessFailure);
};
function gotFileTruncate(fileSystem){
console.log("Inside get file path for remove content");
/** Function to get file path */
filePath = getFilePath(device.platform);
console.log("Device File Path to remove content-->"+this.filePath);
fileSystem.root.getFile(filePath, null, gotFileEntryTruncate, onProcessFailure);
}
function gotFileEntryTruncate(fileEntry){
globals.raiseLog("Inside file to truncate call");
globals.raiseLog("File Name-->"+fileEntry.name);
fileEntry.createWriter(gotFileWriter, onProcessFailure);
}
function gotFileWriter(writer){
globals.raiseLog("Inside file writer to truncate file content");
globals.raiseLog("Content length-->"+writer.length);
//writer.truncate(10);
writer.onwriteend = function(evt) {
writer.truncate(0);
writer.onwriteend = function(evt) {
};
};
writer.write("");
globals.raiseLog("Content length after truncate-->"+writer.length);
}
In the above gotFileWriter() if i check for writer.length its still showing some count. I dont know how come we can check the file gets empty. I having some text inside that file. Need to clear the file when i finish the reading of the file. I am calling removeFileContent() after i finish the reading functionality. Kindly help.
The way your code is written you may get a false positive that the file still has contents in it. Move your:
globals.raiseLog("Content length after truncate-->"+writer.length);
into your onwriteend function as the write call is async and may not finish before your log is printed.

Flash Builder will not read local JSON file . .

So I've tried to build a small utility to view the contents of a JSON file in an easy-to-understand manner (for non-tech people).
I have Googled far and wide, high and low, but every example that shows how to consume a JSON file in Flash Builder uses the HTTP service, pointing to a file on the web.
Here I am, sitting in front of my MacBook, wondering why I can't make this work. In the documentation I've found (sort of relating to this issue), they always show Windows examples, and they seem to work fine:
C://me/projects/json/my_json.json
Perhaps I'm completely missing the obvious, but is this possible on a Mac as well?
I've tried
file:///Users/me/projects/json/my_json.json
That doesn't work. I've tried some "resolve to path" syntax, but the HTTP service does not seem to allow for anything but file paths in quotes.
Would anyone be able to pint me in the right direction?
Use the File API. It's really easy, here's a quick code sample:
// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;
// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);
// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");
// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);
// Select event handler
private function onSelect(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
// Cast to File
var selectedFile:File = e.currentTarget as File;
readFile(selectedFile);
}
private function onCancel(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
}
private function readFile(file:File):void
{
// Read file
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.READ);
var contents:String = fs.readUTFBytes(selectedFile.size);
fs.close()
// Parse your JSON for display or whatever you need it for
parseJSON(contents);
}
You hinted at this in your post about examples being for Windows and you being on a Mac but I'll state it explicitly here: you should always use the File API because it is cross platform. This code will work equally well on Windows and Mac.