print() without a newline in Dart? - dart

In Dart, I am using print() to write content to the console.
Is it possible to use print() without it automatically adding a newline to the output?

You can use stdout:
import "dart:io";
stdout.write("foo");
will print foo to the console but not place a \n after it.
You can also use stderr. See:
How can I print to stderr in Dart in a synchronous way?

You cannot customize the print() to prevent printing a newline in Dart (as in Python by using 'end' argument).
To achieve this in Dart, use stdout.write() function, like
stdout.write("<your_message>");

Have a look are the dcli package you can use the echo function.

1. By using the dart io package
import 'dart:io';
void main() {
for(int r = 0; r < 5; r++){
for(int c = 0; c < r; c++){
stdout.write('Text ');
}
print('');
}
}
Output:
Text
Text Text
Text Text Text
Text Text Text Text
2. By using the direct print() method (Support to Dartpad)
void main() {
for(int r = 0; r < 5; r++){
print('Text ' * r);
}
}
Output:
Text
Text Text
Text Text Text
Text Text Text Text
Example for when multiplying by 0, 1, 2
void main() {
print('String' * 1);
print('String' * 0);
print('String' * 2);
}
Output:
String
StringString

Related

How to remove previous printed line from Console in Dart

How I can remove previously printed line in console with print() in Dart?
I am willing to display a progress indicator such as:
int n = 0;
for (var item in list) {
n++;
print('${(n / list.length * 100).toStringAsFixed(0)}%');
// do something
}
Currently it prints:
1%
2%
3%
...
But I would like to delete the previous line and replace it with the newly calculated percent.
print always adds a newline, but you can write directly to stdout to avoid that.
To overwrite the previous line, you can place a carriage return ('\r') character at the start of your string, which tells the cursor to return to the beginning of the line. You may also want to pad the end of your string with some spaces to overwrite any text which might still be remaining from the previous write, although that's not necessary in this case.
It may look something like this in the end:
// At top of file
import 'dart:io';
int n = 0;
for (var item in list) {
n++;
stdout.write('\r${(n / list.length * 100).toStringAsFixed(0)}%');
// do something
}
You can use dart:io and a carriage return (\r):
import "dart:io";
void main() {
for (int i = 0; i < 5; i++) {
stdout.write("\r $i");
}
}

DXL script producing syntax error with char c = str[i]

I'm currently trying to run Export to PDF script, however when I try running it in DOORS ver 9.6.1, I get a couple of errors.
Line 8: char c = str[i]; contains a syntax error
Any thoughts on how I can resolve this issue?
string makeCaption(Buffer& str)
{
setempty(tempBuf);
int i = 0;
{
for(i = 0; i < length(str); ++i)
char c = str[i];
if('\n' != c) && '\\' != c)
{
tempBuf += c;
}
}
escapeSpecialLaTeXCharacters(tempBuf);
return stringOf(tempBuf);
}
Seems to me like copy/paste problems. When you compare your code with the original you might notice that you moved line 6 with the sole { one line up. If you put it back where it belongs i.e. after the line "for(...)", the code works

what does Caret sign do in Dart

I am looking at some Flutter projects and I notice this codes:
#override
int get hashCode => todos.hashCode ^ isLoading.hashCode;
What is this ^ sign doing here? This line of code is found in the AppState of Flutter projects. Is this used to compare the before and after State?
It is the bitwise XOR operator
https://www.dartlang.org/guides/language/language-tour#operators
Below is the way to use XOR operator. I think this is not useful to you but it is helpful to some one who searching for XOR operation
Call below method encryptDecrypt("123456") . you will get output as abcdef
String encryptDecrypt(String input) {
int xorKey = "P".codeUnitAt(0);
String output = "";
int length = input.length;
for (int i = 0; i < length; i++) {
output = (output + String.fromCharCode((input[i].codeUnitAt(0) ^ xorKey)));
}
return output;
}

How to work with char types in Dart? (Print alphabet)

I am trying to learn the Dart language, by transposing the exercices given by my school for C programming.
The very first exercice in our C pool is to write a function print_alphabet() that prints the alphabet in lowercase; it is forbidden to print the alphabet directly.
In POSIX C, the straightforward solution would be:
#include <unistd.h>
void print_alphabet(void)
{
char c;
c = 'a';
while (c <= 'z')
{
write(STDOUT_FILENO, &c, 1);
c++;
}
}
int main(void)
{
print_alphabet();
return (0);
}
However, as far as I know, the current version of Dart (1.1.1) does not have an easy way of dealing with characters. The farthest I came up with (for my very first version) is this:
void print_alphabet()
{
var c = "a".codeUnits.first;
var i = 0;
while (++i <= 26)
{
print(c.toString());
c++;
}
}
void main() {
print_alphabet();
}
Which prints the ASCII value of each character, one per line, as a string ("97" ... "122"). Not really what I intended…
I am trying to search for a proper way of doing this. But the lack of a char type like the one in C is giving me a bit of a hard time, as a beginner!
Dart does not have character types.
To convert a code point to a string, you use the String constructor String.fromCharCode:
int c = "a".codeUnitAt(0);
int end = "z".codeUnitAt(0);
while (c <= end) {
print(String.fromCharCode(c));
c++;
}
For simple stuff like this, I'd use "print" instead of "stdout", if you don't mind the newlines.
There is also:
int char_a = 'a'.codeUnitAt(0);
print(String.fromCharCodes(new Iterable.generate(26, (x) => char_a + x)));
or, using newer list literal syntax:
int char_a = 'a'.codeUnitAt(0);
int char_z = 'z'.codeUnitAt(0);
print(String.fromCharCodes([for (var i = char_a; i <= char_z; i++) i]));
As I was finalizing my post and rephrasing my question’s title, I am no longer barking up the wrong tree thanks to this question about stdout.
It seems that one proper way of writing characters is to use stdout.writeCharCode from the dart:io library.
import 'dart:io';
void ft_print_alphabet()
{
var c = "a".codeUnits.first;
while (c <= "z".codeUnits.first)
stdout.writeCharCode(c++);
}
void main() {
ft_print_alphabet();
}
I still have no clue about how to manipulate character types, but at least I can print them.

Why does Pygment.rb not highlight <code> tags within <pre class="lang"> properly -i.e. Google Prettify friendly tags?

I am calling it in my view like this:
<%= markdown question.body %>
This is what my ApplicationHelper looks like:
module ApplicationHelper
class HTMLwithPygments < Redcarpet::Render::HTML
def block_code(code, language)
Pygments.highlight(code, lexer:language)
end
end
def markdown(text)
renderer = HTMLwithPygments.new(hard_wrap: true)
options = {
autolink: true,
no_intra_emphasis: true,
fenced_code_blocks: true,
lax_html_blocks: true,
strikethrough: true,
superscript: true
}
Redcarpet::Markdown.new(renderer, options).render(text).html_safe
end
end
But, when it encounters tags like this:
<pre class="lang-cpp prettyprint-override">
It doesn't apply the color highlights to that code. Why is that?
P.S. This is generated, for instance, by Stack Overflow by doing this: <!-- language: lang-cpp -->
Edit 1
Or more specifically, it seems that it won't format the <code> tags that are within <pre> tags. Once <code> is not within <pre> it seems to format it fine. How do I remedy that?
Edit 2
The problem seems to be the data that Pygment.rb is acting on. It is HTML, as can be seen in this gist - https://gist.github.com/marcamillion/14fa121cf3557d38c1a8. So what I want to be able to do is to have Pygment properly format the code returned in the body attribute of that object in my gist.
How do I do that?
Edit 3
This is the HTML code that I would like Pygment.rb and Redcarpet to perform syntax highlighting on:
<p>Here is a piece of C++ code that shows some very peculiar performance. For some strange reason, sorting the data miraculously speeds up the code by almost 6x:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}
</code></pre>
<ul>
<li>Without <code>std::sort(data, data + arraySize);</code>, the code runs in <strong>11.54</strong> seconds.</li>
<li>With the sorted data, the code runs in <strong>1.93</strong> seconds.</li>
</ul>
<hr>
<p>Initially I thought this might be just a language or compiler anomaly. So I tried it in Java:</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// !!! With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 100000; ++i)
{
// Primary loop
for (int c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}
}
</code></pre>
<p>with a similar but less extreme result.</p>
<hr>
<p>My first thought was that sorting brings the data into cache, but my next thought was how silly that is because the array was just generated.</p>
<p>What is going on? Why is a sorted array faster than an unsorted array? The code is summing up some independent terms, the order should not matter.</p>
You can see the current way that this particular question is being rendered at: http://boso.herokuapp.com
It is the most popular question on that site, the first one that you see. You will notice that the code simply has a grey background and is indented. There is no pretty highlighting like Pygment.rb promises and does on other code snippets (similarly to how #rorra has illustrated in other examples in his answer).
I can't strip out the HTML - because I want to parse it properly (i.e. make sure the spacing, etc. is included properly). The only difference that I want, is to get syntax highlighting on the code represented in the body of the question.
Is there something else you can add in order to reproduce the issue? Like the content of question.body?
If I do something like this on the controller:
class HomeController < ApplicationController
def index
#data = <<EOF
~~~ cpp
#include <fstream.h>
int main (int argc, char *argv[]) {
return(0);
}
~~~
EOF
end
end
and the on the view:
<pre class="lang-cpp prettyprint-override">
<%= markdown #data %>
</pre>
it works totally fine, I can see the parsed code without any problem. What's the content of question.body? And can you save the content of the web page (from your browser) and save it on a gist so we can debug?
Thx
Regarding your last comment, its a simple css issue, on your stylesheet, you can add:
.code {
color: #DD1144 !important;
}
and it will work, the problem is that you have a css rule written like:
pre .code {
color: inherited;
}
and that's using the color #333333 inherited from the body class
Here's a screen on how it looks like with the css updated:
The sample app with your code runs totally fine, I would need a sample app code app, or a sample code where we can reproduce the issue you are having (not having the right css/stylesheets for the formatted code).
This is an example of how the sample app looks like:
Final edit, the problem is not the library, and its not the way you are rendering the question, its the content you are rendering, check the body of your questions, this is one of the questions I got with the body that actually is rendered as the library should render, but its not rendering as you are expecting :)
#data = <<EOF
<p>I've been messing around with JSON for some time, just pushing it out as text and it hasn't hurt anybody (that I know of), but I'd like to start doing things properly.</p>
<p>I have seen <em>so</em> many purported "standards" for the JSON content type:</p>
<pre><code>application/json
application/x-javascript
text/javascript
text/x-javascript
text/x-json
</code></pre>
<p>But which is correct, or best? I gather that there are security and browser support issues varying between them.</p>
<p>I know there's a similar question, <em>What MIME type if JSON is being returned by a REST API?</em>, but I'd like a slightly more targeted answer.</p>
EOF
And this is another one I just copied/pastle from stackoverflow, that renders with all the syntax highlighted, do you notice the difference? So update your crawler to get the questions in the right format and it will work
#data = <<EOF
Here is a piece of C++ code that shows some very peculiar performance. For some strange reason, sorting the data miraculously speeds up the code by almost 6x:
<!-- language: lang-cpp -->
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}
- Without `std::sort(data, data + arraySize);`, the code runs in **11.54** seconds.
- With the sorted data, the code runs in **1.93** seconds.
----------
Initially I thought this might be just a language or compiler anomaly. So I tried it in Java:
<!-- language: lang-java -->
import java.util.Arrays;
import java.util.Random;
public class Main
{
public static void main(String[] args)
{
// Generate data
int arraySize = 32768;
int data[] = new int[arraySize];
Random rnd = new Random(0);
for (int c = 0; c < arraySize; ++c)
data[c] = rnd.nextInt() % 256;
// !!! With this, the next loop runs faster
Arrays.sort(data);
// Test
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < 100000; ++i)
{
// Primary loop
for (int c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
}
}
System.out.println((System.nanoTime() - start) / 1000000000.0);
System.out.println("sum = " + sum);
}
}
with a similar but less extreme result.
----------
My first thought was that sorting brings the data into cache, but my next thought was how silly that is because the array was just generated.
What is going on? Why is a sorted array faster than an unsorted array? The code is summing up some independent terms, the order should not matter.
EOF

Resources