The console does not respond to this code. Here I tried to use stdout.write(), instead of print().
'For your convenience, I use Microsoft VS code.'
import 'dart:io';
void main() {
stdout.write('Enter your name:');
String name = stdin.readLineSync(); //Read name
stdout.write('Enter your age:');
int age = int.parse(stdin.readLineSync()); //Read age as int
stdout.write('You are $age and your name is $name');
}
The problem is that the vs code console doesn't allow input.
You need to create a launch config and set console to terminal.
Related
I'm trying to get list of top level class declarations with Dart's analysis server. So, I'm sending search.findTopLevelDeclarations request, but search results are always empty.
It seems to me that analysis server don't know where to search. I've tried to set my project's root as execution context (execution.createContext) root and/or analysis root (analysis.setAnalysisRoots), but search results are still empty.
What should I do to make server understand where to search declarations?
Never played with this before so I got into quite a journey...
I don't know how you are interacting with the analysis server but I have made a working example using the analysis_server_client package. One problem doing that is that the version on pub.dev is quite old so I ended up fetching the version from the stable branch of Dart SDK:
https://github.com/dart-lang/sdk/tree/stable/pkg/analysis_server_client
You can then import the package in your pubspec.yaml by doing:
dependencies:
analysis_server_client:
path: /path/to/analysis_server_client
I then made a simplified version of the example code from:
https://github.com/dart-lang/sdk/blob/stable/pkg/analysis_server_client/example/example.dart
import 'dart:io' show exit;
import 'package:analysis_server_client/handler/connection_handler.dart';
import 'package:analysis_server_client/handler/notification_handler.dart';
import 'package:analysis_server_client/protocol.dart';
import 'package:analysis_server_client/server.dart';
final server = Server();
Future<void> main(List<String> args) async {
const targetDirPath = r'C:\tmp\simple_project';
const searchPattern = 'main';
// Launch the server
await server.start();
// Connect to the server
final handler = _Handler(server);
server.listenToOutput(notificationProcessor: handler.handleEvent);
if (!await handler.serverConnected(timeLimit: const Duration(seconds: 15))) {
exit(1);
}
await server.send(ANALYSIS_REQUEST_SET_ANALYSIS_ROOTS,
AnalysisSetAnalysisRootsParams([targetDirPath], const []).toJson());
await server.send(SEARCH_REQUEST_FIND_TOP_LEVEL_DECLARATIONS,
SearchFindTopLevelDeclarationsParams(searchPattern).toJson());
}
class _Handler with NotificationHandler, ConnectionHandler {
#override
final Server server;
_Handler(this.server);
#override
void onSearchResults(SearchResultsParams params) {
print('-- Start of result --');
params.results.forEach(print);
print('-- End of result --');
server.stop();
}
}
The project at C:\tmp\simple_project is a simple project created with the following which means it just contains a single main method:
dart create -t console-simple simple_project
When I run my analyzer program I get the following output:
-- Start of result --
{"location":{"file":"C:\\tmp\\simple_project\\bin\\simple_project.dart","offset":5,"length":4,"startLine":1,"startColumn":6,"endLine":1,"endColumn":10},"kind":"DECLARATION","isPotential":false,"path":[{"kind":"FUNCTION","name":"main","location":{"file":"C:\\tmp\\simple_project\\bin\\simple_project.dart","offset":5,"length":4,"startLine":1,"startColumn":6,"endLine":1,"endColumn":10},"flags":8,"parameters":"(List<String> arguments)","returnType":"void"},{"kind":"COMPILATION_UNIT","name":"simple_project.dart","location":{"file":"C:\\tmp\\simple_project\\bin\\simple_project.dart","offset":0,"length":0,"startLine":1,"startColumn":1,"endLine":1,"endColumn":1},"flags":16},{"kind":"LIBRARY","name":"","location":{"file":"C:\\tmp\\simple_project\\bin\\simple_project.dart","offset":0,"length":0,"startLine":1,"startColumn":1,"endLine":1,"endColumn":1},"flags":0}]}
-- End of result --
If I change searchPattern to an empty String, I gets a long list of top level declarations around the default included Dart SDK libraries. I am sure there are a way to exclude those.
But as far as I can see, the searchPattern is a regular expression tested against the name of each top level declaration and includes the declaration if its name contain any part of the regular expression.
I found the code responsible for the search here:
#override
Future<List<SearchMatch>> searchTopLevelDeclarations(String pattern) async {
var allElements = <Element>{};
var regExp = RegExp(pattern);
var drivers = _drivers.toList();
for (var driver in drivers) {
var elements = await driver.search.topLevelElements(regExp);
allElements.addAll(elements);
}
return allElements.map(SearchMatchImpl.forElement).toList();
}
https://github.com/dart-lang/sdk/blob/1278bd5adb6a857580f137e47bc521976222f7b9/pkg/analysis_server/lib/src/services/search/search_engine_internal.dart#L113-L123
Which calls into:
/// Returns top-level elements with names matching the given [regExp].
Future<List<Element>> topLevelElements(RegExp regExp) async {
List<Element> elements = <Element>[];
void addElement(Element element) {
if (!element.isSynthetic && regExp.hasMatch(element.displayName)) {
elements.add(element);
}
}
List<FileState> knownFiles = _driver.fsState.knownFiles.toList();
for (FileState file in knownFiles) {
var unitResult = await _driver.getUnitElement(file.path);
if (unitResult is UnitElementResult) {
CompilationUnitElement unitElement = unitResult.element;
unitElement.accessors.forEach(addElement);
unitElement.classes.forEach(addElement);
unitElement.enums.forEach(addElement);
unitElement.extensions.forEach(addElement);
unitElement.functions.forEach(addElement);
unitElement.mixins.forEach(addElement);
unitElement.topLevelVariables.forEach(addElement);
unitElement.typeAliases.forEach(addElement);
}
}
return elements;
}
https://github.com/dart-lang/sdk/blob/1278bd5adb6a857580f137e47bc521976222f7b9/pkg/analyzer/lib/src/dart/analysis/search.dart#L166-L192
I've executed my code in selenium-java and i need a value of Identifiers(2nd line, not the 4th one) from .XML which is opened in MS edge browser.
My XML:
<Application Type="ABCD">
<Identifier>18753</Identifier>
<SalesChannel SalesChannelType="PQRS" SalesChannelSegment="XYZ">
<Identifier>AB1234</Identifier>
Can anyone help me with the code to get a values(18753) which is between Identifier 2nd line.
Note: I've a code which is working fine for chrome & FF, but bot able to work for MSedge:
Assert.assertTrue(driver.getPageSource().contains("Identifier"));
String xml = driver.getPageSource();
String appID = xml.split("<Identifier>")[0].split("</Identifier>")[1];
I think there's a mistake in your split function. The right code should be like this:
String appID = xml.split("</Identifier>")[0].split("<Identifier>")[1];
Sample code:
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
public class Edgeauto {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "your_path_of_webdriver\\msedgedriver.exe");
EdgeOptions edgeOptions = new EdgeOptions();
WebDriver driver = new EdgeDriver(edgeOptions);
driver.get("http://xxx.xml");
Assert.assertTrue(driver.getPageSource().contains("Identifier"));
String xml = driver.getPageSource();
String appID = xml.split("</Identifier>")[0].split("<Identifier>")[1];
System.out.println(appID);
}
}
Result:
According to the readme for the Dart-Yaml pub package, I should be able to do the following:
var db = loadYamlDocument("db.yaml");
with print(db['hostname']); giving me the value I have specified for port in that yaml, however I'm told that YamlDocument has no instance method []. Okay, I guess that object doesn't have map behaviors, which is something I would have expected it to have. Looking through the docs, there's mention of a YamlMap, but I don't see how to implement that at all.
If I simply try print(db); I actually get the string: 'db.yaml'.
So I tried using new File('db.yaml'); and then sending that variable into the loadYamlDocument method, but that doesn't work either.
Does anyone have any luck reading a yaml document and getting a map out of it in Dart?
import "dart:io";
import "package:yaml/yaml.dart";
main() {
File file = new File('pubspec.yaml');
String yamlString = file.readAsStringSync();
Map yaml = loadYaml(yamlString);
}
EDIT:
Map loadYamlFileSync(String path) {
File file = new File(path);
if (file?.existsSync() == true) {
return loadYaml(file.readAsStringSync());
}
return null;
}
Future<Map> loadYamlFile(String path) async{
File file = new File(path);
if ((await file?.exists()) == true) {
String content = await file.readAsString();
return loadYaml(content);
}
return null;
}
main(List<String> args){
print(loadYamlFileSync("pubspec.yaml"));
}
Check the documentation pages for the Yaml package.
loadYamlDocument() returns a YamlDocument which is a 'heavyweight' class that gives you access to all the features of a Yaml document.
You probably want to use loadYaml, which in most cases is going to return a Map. The description says that the actual implementation of the map is a YamlMap (the Yaml package's implementation of a Map, that they presumably need to use instead of a HashMap for some technical reason).
I have noticed that sometimes Logback/Slf4j logs wrong file and line numbers in Groovy.
I have a lot of bad file/line number logs in my Grails application (more than 50% of all logs)
Is there any workaround?
Simplest example:
logback.groovy
appender("STDOUT", ConsoleAppender) {
encoder(PatternLayoutEncoder) {
pattern = '%d{HH:mm:ss.SSS} [%-5level] %msg \\(%file:%line\\)%n'
}
}
root(DEBUG, ["STDOUT"])
Test.groovy
#Slf4j
class Test {
static void main(String[] args) {
log.info("${'Wrong file and line number!'}")
}
}
Output
23:24:23.894 [INFO ] 0 Wrong file and line number! (NativeMethodAccessorImpl.java:-2)
Example of my grails log output with problem
10:16:44.881 [DEBUG] [org.grails.plugin.resource.ResourceProcessor] -------------------------------------------------- (null:-1)
The problem occurs when a GString is logged (any normal String logs the correct line number). I have no clue why it works like this but I have found two workarounds: Either convert GString to String by calling the toString() method (ugly) or use template format with parameters
import groovy.util.logging.Slf4j;
#Slf4j
class Test {
static void main(String[] args) {
def x = 1
log.info("Does not work: ${x}")
log.info("Works ${x}".toString())
log.info("Works {}", x)
}
}
I am trying to save some settings but the tutorial I am following(android tutorial) is not helping as I am stuck on the first line of code since it seems monodroid does it differently?
select your mode to be either private or public.
int mode= Activity.MODE.PRIVATE;
// get the sharedPreference of your context.
SharedPreference s mySharedPreferences ; mySharedPreferences=getSharedPreferences(“Name_of_your_preference”,mode);
// retrieve an editor to modify the shared preferences
SharedPreferences.Editor editor= mySharedPreferences.edit();
/* now store your primitive type values. In this case it is true, 1f and Hello! World */
editor.putBolean(“myBoolean”,true);
editor.putFloat(“myFloat”,1f);
editor.putString(“myString”,” Hello! World”);
//save the changes that you made
editor.commit();
I don't see Activity.MODE.PRIVATE; in monodroid.
Here is my func to do this:
protected void SaveSetting(string name, string value)
{
var prefences = GetSharedPreferences(Consts.Application.SETTINGS_FILE, FileCreationMode.Private);
var editor = prefences.Edit();
editor.Remove(name);
editor.PutString(name, value);
editor.Commit();
}
Assuming you mean MODE_PRIVATE, it should be Android.Content.FileCreationMode.Private.
Fortunately you don't really have to know that, as we mapped the int in GetSharedPreferences to take the Android.Content.FileCreationMode enum, so intellisense should help you out.