How to enter a multi-line command in the Scala REPL? - scala

I would like to enter something like the following match instruction, but formatted across multiple lines. Is that possible in the Scala REPL?
myString match { case patt(a) => true case _ => false }

If you're just typing it in as-is, the REPL should detect the opening brace when you return, so that it won't try to parse and execute the code until it finds the closing brace.
You could also use paste mode by typing :pa or :paste. This will allow you to enter as much as you want in any format (two blank lines will automatically quit from it). Then when finished entering in code, you can press Ctrl + D to evaluate.

One way to enter into multi-line mode in the Scala REPL is to hit enter right after the opening curly brace "{", then hit enter after each line until the last closing curly brace has been entered "}". Hitting enter after it will exit the multi-line mode
myScript match { <enter> //enter multi-line mode
| case scriptStart(a) => true <enter>
| case _ => false <enter>
|} <enter> //exit multi-line mode

When cascading transformations, it is as simple as ending each line with a dot. For example:
val wordcount = sc.
textFile("MYFILE.txt").
flatMap( x => x.split(" ") ).
map( w => (w,1) ).
reduceByKey( (a,b) => a+b )

Related

Vs code select text between quotes

I have a vast array list like below
$data= [
'user_name' => 's',
'user_place' => 'a',
'address_list_code' => 's',
'block_number' => 3,
];
so I want to replace the key string with all uppercase.I know to convert selected text to uppercase using vs code shortcut Ctl+Alt+u and it works.
But I want to select only all keys in between a single quote and make it uppercase so the expected output is
[
'USER_NAME' => 's',
'USER_PLACE' => 'a',
'ADDRESS_LIST_CODE' => 's',
'BLOCK_NUMBER' => 3,
];
Even I tried this extension but not suceded to select all text in between single quotes
https://marketplace.visualstudio.com/items?itemName=dbankier.vscode-quick-select&ssr=false#version-history
Check out this fiddle : https://jsfiddle.net/m82ycfxw/
I made a normal JS code to convert the desired text to upper case.
This might be a temporary thing but I hope this will work for you.
let str = `
$data= [
'user_name' => 's',
'user_place' => 'a',
'address_list_code' => 's',
'block_number' => 3,
]
`;
var regex = /'[a-z_]+' =>/g;
str = str.replace(regex, foundText => {
return foundText.toUpperCase();
});
console.log(str);
Just change the str variable. Put all your complete data object inside backticks (` `)and run the code.
The extension Select By could help.
Place cursors at the start of the lines where you want to Uppercase text
with MoveBy: Move cursors based on regex move to the next '
with SelectBy: Mark positions of cursors
with MoveBy: Move cursors based on regex move to the next '
with SelectBy: Mark positions of cursors (create selections)
execute: Transform to Uppercase
Esc to exit multi Cursor
Sure, you can do this natively:
In settings.json, temporarily remove _ as a word separators (e.g. "editor.wordSeparators": "!##$%^&*()-=+[{]}\\|;:'\",.<>/?,) (Notice no _)
.
Place cursors at beginnings of all desired lines.
Right arrow to move all cursors within the quotes.
Execute command expand selection. Since you turned off _ as a word delimiter, this will expand to fill the quotes; otherwise, all the keys would need to have the same number of words for this to work.
Execute upper case.
In settings.json re-add _ to word separators.
Easy with Find and Replace. See regex101 demo
Find: (^\s+')([^']*)'
Replace: $1\U$2'
The \U will uppercase the following capture group $2.
Starting the find at the beginning of the line with ^ makes it easy to target just the "keys" (the first '-delimmited strings) and not the other following strings.

Getting the cursor context in Dragon NaturallySpeaking's advanced scripting

I wonder whether it is possible to get the cursor context in Dragon NaturallySpeaking's advanced scripting.
By cursor context, I mean the surrounding characters. For example, I sometimes want to condition some steps of a voice command on whether the character preceding the cursor is a space.
Best I could come up with is my CheckNewPara function shown here: http://knowbrainer.com/forums/forum/messageview.cfm?catid=4&threadid=2739&discTab=true&messid=11427&parentid=11409&FTVAR_FORUMVIEWTMP=Single
Function CheckNewPara()
Clipboard$()
SendKeys "+{Left}^c", True ' copy previous character
Select Case Clipboard$()
Case "" ' if the prior character is nothing
CheckNewPara = "" ' add no space
Case Chr(13)&Chr(10), Chr(9), ")" ' if the prior character is a Lf-CR, tab or )
SendKeys "{Right}", True
CheckNewPara = "" ' add no space
Case "." ' if the prior character is a period
SendKeys "{Right}", True
Clipboard$() ' check for No.
SendKeys "+{Left 3}^c", True ' copy prior three characters
SendKeys "{Right}", True
If Clipboard$() = "No." Then
CheckNewPara = " " ' add one space after No.
Else
CheckNewPara = " " ' add two spaces after period
End If
Case "?", "!"
SendKeys "{Right}", True
CheckNewPara = " " ' add two spaces after other ends of sentence
Case Else
SendKeys "{Right}", True
CheckNewPara = " " ' add one space in the usual case
End Select
Clipboard$()
End Function
You should look at the complete topic at http://knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=4&threadid=2739&discTab=true to get all the context, but the code in the post I pointed to should get you started.
My newest version of the function actually calls an AutoHotKey script which looks at both the prior three characters (or as many as there are, if there are any) and the next two characters (or how ever many there are, if there are any) and returns either a space, two spaces, or nothing depending on the context. The context could be a terminal punctuation (requiring two spaces) or a pound/hash # symbol or close paren bracket or brace ) ] } all requiring no spaces, or else by default one space. I also have it so I can call it before and/or after typing in the results of a Dragon command.
HTH, YMMV,

How to catch empty lines in user input for Scala?

Consider the following code
val sc = new java.util.Scanner (System.in)
while (sc.hasNext()) {
var temp = sc.nextLine()
println(temp.nonEmpty)
println (temp)
}
whenever I press enter with empty line the program simply waits for next input to happen and does not execute the statement inside
For example
input:
<enter>
<enter>
1
cause
output:
<space>
false
<space>
false
1
true
I am trying to make user enter a list of lines, and exit on empty lines
eg.
1 2 3 4
5 6 7 8
<enter> // -> will exit
How would I achieve that?
I think this is a bit more idiomatic:
Iterator.continually(scala.io.StdIn.readLine).takeWhile(_.nonEmpty).foreach(line =>
println(s"read $line")
)
Add if (temp.isEmpty) sys.exit(1)

Passing delimiter as command line argument in scala and use it to split a string

I have a scala program where I take "\t" as a command line input.
Inside the program I want to split a string on the basis of the delimiter passed from command line.
val splitter = args(0).charAt(0)
if(splitter == '\t')
println("true")
else
println("false")
This prints "false" and splitter "\".
The above method works for "," comma delimiter.
Please suggest how can I pass a tab or any other delimiter as command line parameter and use it for the splitting purpose.
It's because if you're passing "\t" in on the command line, then it's coming in as a two-character string \t, not a single-character tab. To do what you want, you can't just take the first character (charAt(0)) since you'll miss the t. Instead you'll have to unescape it by converting from the string \t to the tab character.
An easy way:
val splitter = args(0) match {
case "\\t" => '\t'
case x => x.head // same as x.charAt(0)
}

Scala string pattern matching for mathematical symbols

I have the following code:
val z: String = tree.symbol.toString
z match {
case "method +" | "method -" | "method *" | "method ==" =>
println("no special op")
false
case "method /" | "method %" =>
println("we have the special div operation")
true
case _ =>
false
}
Is it possible to create a match for the primitive operations in Scala:
"method *".matches("(method) (+-*==)")
I know that the (+-*) signs are used as quantifiers. Is there a way to match them anyway?
Thanks from a avidly Scala scholar!
Sure.
val z: String = tree.symbol.toString
val noSpecialOp = "method (?:[-+*]|==)".r
val divOp = "method [/%]".r
z match {
case noSpecialOp() =>
println("no special op")
false
case divOp() =>
println("we have the special div operation")
true
case _ =>
false
}
Things to consider:
I choose to match against single characters using [abc] instead of (?:a|b|c).
Note that - has to be the first character when using [], or it will be interpreted as a range. Likewise, ^ cannot be the first character inside [], or it will be interpreted as negation.
I'm using (?:...) instead of (...) because I don't want to extract the contents. If I did want to extract the contents -- so I'd know what was the operator, for instance, then I'd use (...). However, I'd also have to change the matching to receive the extracted content, or it would fail the match.
It is important not to forget () on the matches -- like divOp(). If you forget them, a simple assignment is made (and Scala will complain about unreachable code).
And, as I said, if you are extracting something, then you need something inside those parenthesis. For instance, "method ([%/])".r would match divOp(op), but not divOp().
Much the same as in Java. To escape a character in a regular expression, you prefix the character with \. However, backslash is also the escape character in standard Java/Scala strings, so to pass it through to the regular expression processing you must again prefix it with a backslash. You end up with something like:
scala> "+".matches("\\+")
res1 : Boolean = true
As James Iry points out in the comment below, Scala also has support for 'raw strings', enclosed in three quotation marks: """Raw string in which I don't need to escape things like \!""" This allows you to avoid the second level of escaping, that imposed by Java/Scala strings. Note that you still need to escape any characters that are treated as special by the regular expression parser:
scala> "+".matches("""\+""")
res1 : Boolean = true
Escaping characters in Strings works like in Java.
If you have larger Strings which need a lot of escaping, consider Scala's """.
E. g. """String without needing to escape anything \n \d"""
If you put three """ around your regular expression you don't need to escape anything anymore.