I know that we can print to the console in dart using the print() statement.
I want to know if it is possible to read data from console. I did a search and also looked in the dart:io package, but couldn't find any reference.
Thanks
You can use StringInputStream to read from stdin like this
#import("dart:io");
main() {
var stream = new StringInputStream(stdin);
stream.onLine = () {
var line = stream.readLine();
if (line != null) {
print(line);
}
};
}
also if you're developing a console application then checkout the Options class to parse command line arguments
final args = new Options().arguments;
Related
From a basic standpoint what I am trying to do is get a list of keys (key names) from session storage.
The way I am trying to do this is by calling the JsRuntime.InvokeAsync method to:
Get the number of keys in session storage, and
loop thought the number of items in session storage and get the key name.
public async Task<List<string>> GetKeysAsync()
{
var dataToReturn = new List<string>();
var storageLength = await JsRuntime.InvokeAsync<string>("sessionStorage.length");
if (int.TryParse(storageLength, out var slength))
{
for (var i = 1; i <= slength; i++)
{
dataToReturn.Add(await JsRuntime.InvokeAsync<string>($"sessionStorage.key({i})"));
}
}
return dataToReturn;
}
When calling the JsRuntime.InvokeAsync($"sessionStorage.length")) or JsRuntime.InvokeAsync($"sessionStorage.key(0)")) I am getting an error "The value 'sessionStorage.length' is not a function." or The value 'sessionStorage.key(0)' is not a function.
I am able to get a single items using the key name from session storage without issue like in the following example.
public async Task<string> GetStringAsync(string key)
{
return await JsRuntime.InvokeAsync<string>("sessionStorage.getItem", key);
}
When I use the .length or .key(0) in the Chrome console they work as expected, but not when using the JsRuntime.
I was able to get this to work without using the sessionStorage.length property. I am not 100% happy with the solution, but it does work as needed.
Please see below code. The main thing on the .key was to use the count as a separate variable in the InvokeAsync method.
I think the reason for this is the JsRuntime.InvokeAsync method adds the () automatically to the end of the request, so sessionStorage.length is becoming sessionStorage.length() thus will not work. sessionStorage.key(0) was becoming sessionStorage.key(0)(). etc. Just that is just a guess.
public async Task<List<string>> GetKeysAsync()
{
var dataToReturn = new List<string>();
var dataPoint = "1";
while (!string.IsNullOrEmpty(dataPoint) )
{
dataPoint = await JsRuntime.InvokeAsync<string>($"sessionStorage.key", $"{dataToReturn.Count}");
if (!string.IsNullOrEmpty(dataPoint))
dataToReturn.Add(dataPoint);
}
return dataToReturn;
}
I'm using Atom with my init.js below, the objective are :
select all
Prettify json
Change grammar to json
I'm having difficulties with step #3, below is my script :
atom.commands.add("atom-workspace", {
"custom:prettify-json": function() {
var view;
view = atom.views.getView(atom.workspace.getActiveTextEditor());
atom.commands.dispatch(view, "core:select-all");
atom.commands.dispatch(view, "pretty-json:prettify");
atom.commands.dispatch(view, "grammar-selector:show");
return true;
}
});
So far I only found that grammar-sellector only has show function, is there any way to choose "source.json" ?
There's the private method setGrammar() that has been around since forever. It should serve the task, unless the developers decide to remove/replace it in future versions.
atom.commands.add("atom-workspace", {
"custom:prettify-json": function() {
const editor = atom.workspace.getActiveTextEditor();
const view = atom.views.getView(editor);
atom.commands.dispatch(view, "core:select-all");
atom.commands.dispatch(view, "pretty-json:prettify");
editor.setGrammar(atom.grammars.grammarForScopeName('source.json'));
return true;
}
});
I am using Tessaract's Xamarin Forms Nuget(https://github.com/halkar/Tesseract.Xamarin), and am trying to scan a picture taken by the Android Device. This is the code that I am using:
private async System.Threading.Tasks.Task<string> OCRAsync(byte[] bytes)
{
TesseractApi api;
api = new TesseractApi(this, AssetsDeployment.OncePerInitialization);
await api.Init("bul");
await api.SetImage(bytes);
var detectedText = api.Results(PageIteratorLevel.Block);
result = string.Empty;
if (detectedText != null)
{
foreach (var annotation in detectedText)
{
result = FindWordInDictionary(annotation.Text);
}
}
return result;
}
The method is called from a synchronized method like this:
var task = OCRAsync(data);
result = task.Result;
Whenever the compiler gets to "await api.Init("bul");" the app freezes indefinitely. Do you know what may cause this problem? Thank you.
The problem was that I needed to give a file location in the .init function:
await api.Init(pathToDataFile, "bul");
I need a function that emits individual lines from a file with newlines. Nothing hard.
But with node, it is hard, and with Meteor, there's an additional complication: you must use Meteor.wrapAsync. Surprisingly, there isn't an example of how to use wrapAsync in the docs, and I could only find a couple of examples online, none of which helped.
I have something like:
var readFileAsync = function (file, cb) {
// From here to below comment works synchronously
var instream = fs.createReadStream(file, function () {
var outstream = new stream;
outstream.readable = true;
outstream.writable = true;
var rl = readline.createInterface({
input: instream,
output: outstream,
terminal: false
});
rl.on('line', function(line) {
console.log(line);
return line;
});
});
// Reference to aforementioned comment
};
var readWatFile = Meteor.wrapAsync(readFileAsync);
var line = readWatFile('/path/to/my/file');
console.log(line);
I know this is wrong because it doesn't work, so how do I write this?
There are two ways to go around it.
Load the whole file into memory and do whatever you want. To do that you can use the Private Assets API
Use node.js streams and stream the file line by line. You would have something like this.
Example code that you would need to tweak to your favorite streaming methods:
var Future = Npm.require('fibers/future');
var byline = Npm.require('byline');
var f = new Future;
// create stream in whatever way you like
var instream = fs.createReadStream(...);
var stream = byline.createStream(instream);
// run stream handling line-by-line events asynchronously
stream.on('data', Meteor.bindEnvironment(function (line) {
if (line) console.log(line)
else future.return();
}));
// await on the future yielding to the other fibers and the line-by-line handling
future.wait();
I would like to descend a directory, and examine the name of every file I see there against a regular expression. Basically, a version of the common unix find command, only written in Node.js. I don't care about the order of the files, but I do want to make sure I get all of them.
I have the following code, which is close (I think) to what I want. It takes a startdir, a regexp, and a callback; for each file it analyzes it increments the value of sentinel by one, and when it is done with the analysis it decrements the sentinel. My concern is that if there's one file, and a deeply nested collection of directories, it will analyze that file and trigger the callback long before it finds a second file, and possible the callback will be called twice.
Obviously, I could prevent the callback from being called twice by having a fired variable to restrain it from firing a second time. But that still would give me erroneous data. What am I doing wrong here, and is there a more node-appropriate way to do it?
fs = require('fs')
path = require('path')
function get_all_files(startdir, regexp, callback) {
var sentinel = 0;
var results = [];
function check_sentinel() {
sentinel--;
if (sentinel === 0) {
callback(results);
}
}
function check_file(dir, filename) {
var fname;
sentinel++;
if (regexp.test(filename)) {
results.push(path.join(dir, filename));
}
check_sentinel();
}
function check_directory(dir) {
fs.readdir(path.join(this.rootpath, dirpath), function(err, files) {
var fname, i, len, npath;
if (err) {
throw err
}
for (i = 0, len = files.length; i < len; i++) {
fname = files[i];
npath = path.join(dir, fname);
fs.stat(npath, function(err, stats) {
if (stats.isFile()) {
check_file(dir, fname);
} else {
if (stats.isDirectory()) {
check_directory(npath);
}
}
});
}
});
}
check_directory(startdir);
}
A couple of thoughts...
I have never used it, but the simplest way to do what you are asking might be to use the async.js walkfiles function. See the tests for an example here.
Otherwise, I would consider building an array of function calls and returning the array from your recursive directory walking function (rather than using a sentinel, etc). In other words, check_directory returns an array of function calls matching the files you are looking for. If there is no file, the array is empty.
Finally, combine the array at the top of the recursion and use the async library (not the same as async.js) to execute the array of functions all at once using the parallel function (see this thread for an example using "series").