TextIO.outputSubstr() does not write anything - io

I have a really annoying problem.
This function:
fun writeAFile() =
let
val outstream = TextIO.openOut "look_at_me_im_a_file.txt"
in
TextIO.outputSubstr(outstream,Substring.full("I'm so sad right now :("))
end;
Just creates the file look_at_me_im_a_file.txt but it's empty.
I get no errors and it does not work with either SML/NJ or PolyML.
I have no problems reading from files.

First of all, Substring.full isn't needed - it doesn't really do anything other than give you something of the substring type. Instead, you can do:
TextIO.output (outstream, "I'm so sad right now :(");
Now, the reason it doesn't work:
When you tell sml to write something to a file (using TextIO.output or TextIO.outputSubstr) it doesn't actually write it in the file right away. It writes to a buffer. Well, sometimes it writes to the file right away, but not often enough that you can depend on it.
Now, this seems terribly impractical, but it's more efficient - if you tell it to write several small pieces of data after each other, it can just lump it all together in one write operation.
The way to get around it is to tell sml "Hey, I really want that write to happen right now." There's a function just for that, which is called TextIO.flushOut. Alternatively, closing the stream will also cause everything to be written.
Actually, you should always remember to close your streams. Leaving open file handles lying around is messy - how will the filesystem know that you're done with it, and that it can let other programs write to the file?

Being an rookie i didn't check our lecture notes :/
a functioning version of the code is
fun writeAFile() =
let
val outstream = TextIO.openOut "look_at_me_im_a_file.txt"
in
(
TextIO.output(outstream,"I'm so glad right now :)");
TextIO.closeOut(outstream)
)
end;
Although its noteworthy that the online documentation at http://www.standardml.org/Basis/text-io.html only gives a vague reference to the output function.
And looking at the documentation for the IMPERATIVE_IO says val output : outstream * vector -> unit which is confusing since it is non apparent that string is actually of type CharVector.vector and is thus a valid argument for the output function.
I hope this will be of help to some other rookie out there.

Related

Instrumenting VHDL code

My simulator (which shall remain nameless) is crashing. I can't find out where. (It just crashes when I single step over a wait statement, so I guess it's jumping somewhere else, but who knows where.)
I have been trying to instrument my code to try to find out where. Ideally, I'd line to report filename and line number. This is easy in System-Verilog:
$display(`__FILE__,, `__LINE__);
or something like that. I had the idea of doing something similar by replacing the 486 occurrences of begin in my code with
constant CCCCCC : boolean := true; begin report CCCCCC'instance_name;
which broke the four architectures, but that was easily fixed. (Most of the stuff is in functions and procedures.) Unfortunately, using the
`instance_name
and
`path_name
attributes inside a subprogram also crashes my simulator. Doh! And
`simple_name
doesn't provide enough information.
I guess I could write a script to do this, but can anyone think of a smart way to do it in pure VHDL?

Write text to file function python

so I would like to ask you for help.
I was scooping and sweeping the internet so long for that and I did not find how to do it. What I just produced is totally wrong and my professor did bad time with formulating the task. it is entry level task on university I have already finished the hardest ones, but this one I just dont get what he wants
Translation is made by me so it might be little bit off, but bear with me, please.
"Create file "linewriter.py". This file will have function writeTextToFile, that will accept one parameter and on end is also one parameter. Function will take the parameter on input and chain it with variable STATIC_TEXT (stated bellow). Queue of chaining will be as follows: 1st static text and then argument of function. This way chained input will write to file of any given name and a the name of this file will be returned as input parameter of function.
STATIC_TEXT: “This is my static text which must be added to file. It is very long text and I do not know what they want to do with this terrible text. ”
...
What? I really don't get what he want's from me. Can you help? Thank you all :)
STATICKY_TEXT = "This is my static text which must be added to file. It is very long text and I do not know what they want to do with this terrible text.\nNew Line! "
saveFile = open ("exampleFile.txt","w")
saveFile.write(STATICKY_TEXT)
saveFile.close()
solved it :) but I COULD not figure it out for days haha ... silly me

Ternary operator should not be used on a single line in Node.js. Why?

Consider the following sample codes:
1.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)
? 'yes'
: 'no';
console.log(IsAdminUser);
2.Sample
var IsAdminUser = (User.Privileges == AdminPrivileges)?'yes': 'no';
console.log(IsAdminUser);
The 2nd sample I am very comfortable with & I code in that style, but it was told that its wrong way of doing without any supportive reasons.
Why is it recommended not to use a single line ternary operator in Node.js?
Can anyone put some light on the reason why it is so?
Advance Thanks for great help.
With all coding standards, they are generally for readability and maintainability. My guess is the author finds it more readable on separate lines. The compiler / interpreter for your language will handle it all the same. As long as you / your project have a set standard and stick to it, you'll be fine. I recommend that the standards be worked on or at least reviewed by everyone on the project before casting them in stone. I think that if you're breaking it up on separate lines like that, you may as well define an if/else conditional block and use that.
Be wary of coding standards rules that do not have a justification.
Personally, I do not like the ternary operator as it feels unnatural to me and I always have to read the line a few times to understand what it's doing. I find separate if/else blocks easier for me to read. Personal preference of course.
It is in fact wrong to put the ? on a new line; even though it doesn’t hurt in practice.
The reason is a JS feature called “Automatic Semicolon Insertion”. When a var statement ends with a newline (without a trailing comma, which would indicate that more declarations are to follow), your JS interpreter should automatically insert a semicolon.
This semicolon would have the effect that IsAdminUser is assigned a boolean value (namely the result of User.Privileges == AdminPrivileges). After that, a new (invalid) expression would start with the question mark of what you think is a ternary operator.
As mentioned, most JS interpreters are smart enough to recognize that you have a newline where you shouldn’t have one, and implicitely fix your ternary operator. And, when minifying your script, the newline is removed anyway.
So, no problem in practice, but you’re relying on an implicit fix of common JS engines. It’s better to write the ternary operator like this:
var foo = bar ? "yes" : "no";
Or, for larger expressions:
var foo = bar ?
"The operation was successful" : "The operation has failed.";
Or even:
var foo = bar ?
"Congratulations, the operation was a total success!" :
"Oh, no! The operation has horribly failed!";
I completely disagree with the person who made this recommendation. The ternary operator is a standard feature of all 'C' style languages (C,C++,Java,C#,Javascript etc.), and most developers who code in these languages are completely comfortable with the single line version.
The first version just looks weird to me. If I was maintaining code and saw this, I would correct it back to a single line.
If you want verbose, use if-else. If you want neat and compact use a ternary.
My guess is the person who made this recommendation simply wasn't very familiar with the operator, so found it confusing.
Because it's easier on the eye and easier to read. It's much easier to see what your first snippet is doing at a glance - I don't even have to read to the end of a line. I can simply look at one spot and immediately know what values IsAdminUser will have for what conditions. Much the same reason as why you wouldn't write an entire if/else block on one line.
Remember that these are style conventions and are not necessarily backed up by objective (or technical) reasoning.
The reason for having ? and : on separate lines is so that it's easier to figure out what changed if your source control has a line-by-line comparison.
If you've just changed the stuff between the ? and : and everything is on a single line, the entire line can be marked as changed (based on your comparison tool).

How to write a self reproducing code (prints the source on exec)?

I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source.
some solutions --
http://www.cprogramming.com/challenges/solutions/self_print.html
Quine Page solution in many languages
There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...
Aside from cheating¹ there is no difference between compiled and interpreted languages.
The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something:
print ...
However, what should it print? Itself. So it needs to print the "print" command:
print "print ..."
What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too:
print "print \"print ...\""
Now the program grew again, so there's again more to print:
print "print \"print \\\"...\\\"\""
And so on.
With every added code there's more code to print.
This approach is getting nowhere,
but it reveals an interesting pattern:
The string "print \"" is repeated over and over again.
It would be nice to put the repeating part
into a variable:
a = "print \""
print a
However, the program just changed,
so we need to adjust a:
a = "a = ...\nprint a"
print a
When we now try to fill in the "...",
we run into the same problems as before.
Ultimately, we want to write something like this:
a = "a = " + (quoted contents of a) + "\nprint a"
print a
But that is not possible,
because even if we had such a function quoted() for quoting,
there's still the problem that we define a in terms of itself:
a = "a = " + quoted(a) + "\nprint a"
print a
So the only thing we can do is putting a place holder into a:
a = "a = #\nprint a"
print a
And that's the whole trick!
Anything else is now clear.
Simply replace the place holder
with the quoted contents of a:
a = "a = #\nprint a"
print a.replace("#", quoted(a))
Since we have changed the code,
we need to adjust the string:
a = "a = #\nprint a.replace(\"#\", quoted(a))"
print a.replace("#", quoted(a))
And that's it!
All quines in all languages work that way
(except the cheating ones).
Well, you should ensure that you replace only
the first occurence of the place holder.
And if you use a second place holder,
you can avoid needing to quote the string.
But those are minor issues
and easy to solve.
If fact, the realization of quoted() and replace()
are the only details in which the various quines really differ.
¹ by making the program read its source file
There are a couple of different strategies to writing quines. The obvious one is to just write code that opens the code and prints it out. But the more interesting ones involve language features that allow for self-embedding, like the %s-style printf feature in many languages. You have to figure out how to embed something so that it ends up resolving to the request to be embedded. I suspect, like palindromes, a lot of trial and error is involved.
The usual approach (when you can't cheat*) is to write something that encodes its source in a string constant, then prints out that constant twice: Once as a string literal, and once as code. That gets around the "every time I write a line of code, I have to write another to print it out!" problem.
'Cheating' includes:
- Using an interpreted language and simply loading the source and printing it
- 0-byte long files, which are valid in some languages, such as C.
For fun, I came up with one in Scheme, which I was pretty proud of for about 5 minutes until I discovered has been discovered before. Anyways, there's a slight modification to the "rules" of the game to better count for the duality of data and code in Lisp: instead of printing out the source of the program, it's an S-expression that returns itself:
((lambda (x) (list x `',x)) '(lambda (x) (list x `',x)))
The one on Wikipedia has the same concept, but with a slightly different (more verbose) mechanism for quoting. I like mine better though.
One idea to think about encoding and how to give something a double meaning so that it can be used to output something in a couple of forms. There is also the cavaet that this type of problem comes with restrictions to make it harder as without any rules other than the program output itself, the empty program is a solution.
How about actually reading and printing your source code? Its not difficult at all!! Heres one in php:
<?php
{
header("Content-Type: text/plain");
$f=fopen("5.php","r");
while(!feof($f))
{
echo fgetc($f);
}
fclose($f);
}
?>
In python, you can write:
s='c=chr(39);print"s="+c+s+c+";"+s';c=chr(39);print"s="+c+s+c+";"+s
inspired from this self printing pseudo-code:
Print the following line twice, the second time with quotes.
"Print the following line twice, the second time with quotes."
I've done a AS3 example for those interested in this
var program = "var program = #; function main(){trace(program.replace('#',
String.fromCharCode(34) + program + String.fromCharCode(34)))} main()";
function main(){
trace(program.replace('#', String.fromCharCode(34) + program + String.fromCharCode(34)))
}
main()
In bash it is really easy
touch test; chmod oug+x test; ./test
Empty file, Empty output
In ruby:
puts File.read(_ _ FILE _ _)

How to make this Groovy string search code more efficient?

I'm using the following groovy code to search a file for a string, an account number. The file I'm reading is about 30MB and contains 80,000-120,000 lines. Is there a more efficient way to find a record in a file that contains the given AcctNum? I'm a novice, so I don't know which area to investigate, the toList() or the for-loop. Thanks!
AcctNum = 1234567890
if (testfile.exists())
{
lines = testfile.readLines()
words = lines.toList()
for (word in words)
{
if (word.contains(AcctNum)) { done = true; match = 'YES' ; break }
chunks += 1
if (done) { break }
}
}
Sad to say, I don't even have Groovy installed on my current laptop - but I wouldn't expect you to have to call toList() at all. I'd also hope you could express the condition in a closure, but I'll have to refer to Groovy in Action to check...
Having said that, do you really need it split into lines? Could you just read the whole thing using getText() and then just use a single call to contains()?
EDIT: Okay, if you need to find the actual line containing the record, you do need to call readLines() but I don't think you need to call toList() afterwards. You should be able to just use:
for (line in lines)
{
if (line.contains(AcctNum))
{
// Grab the results you need here
break;
}
}
When you say efficient you usually have to decide which direction you mean: whether it should run quickly, or use as few resources (memory, ...) as possible. Often both lie on opposite sites and you have to pick a trade-off.
If you want to search memory-friendly I'd suggest reading the file line-by-line instead of reading it at once which I suspect it does (I would be wrong there, but in other languages something like readLines reads the whole file into an array of strings).
If you want it to run quickly I'd suggest, as already mentioned, reading in the whole file at once and looking for the given pattern. Instead of just checking with contains you could use indexOf to get the position and then read the record as needed from that position.
I should have explained it better, if I find a record with the AcctNum, I extract out other information on the record...so I thought I needed to split the file into multiple lines.
if you control the format of the file you are reading, the solution is to add in an index.
In fact, this is how databases are able to locate records so quickly.
But for 30MB of data, i think a modern computer with a decent harddrive should do the trick, instead of over complicating the program.

Resources