IntelliJ IDEs - Wrap line different depending on finalising comma existence - intellij-idea

Hey I want different styles how my objects or arrays are formatted. The difference should only make the syntax and the code formatter from IntelliJ. I wonder if there is any setting in the IDE for that or if its possible with a linter.
I think my question becomes more clear with an example.
NO finalising comma
cons arr = [1,2,3]
cons obj = {street: 'Mainstreet', number: 30}
should stay the same after formatting
cons arr = [1,2,3]
cons obj = {street: 'Mainstreet', number: 30}
Finalising comma
cons arr = [1,2,3,]
cons obj = {street: 'Mainstreet', number: 30,}
should change after formatting
cons arr = [
1,
2,
3,
]
cons obj = {
street: 'Mainstreet',
number: 30,
}
My IDE
I use PhpStorm 2022.3.1 (JavaScript, TypeScript) & IDEA 2022.2.3 (Kotlin).
Thanks for any help or suggestions!

Related

How can I reformat a list of items from lua to kotlin?

I am working on a project that originally started in Lua and I want to update it to Kotlin.
I have about 5000 questions/answers that look like:
['Question'][1] = "'7x' was used to refer to the secret ingredient of what drink";
['Answers'][1] = {"coca cola"};
['Question'][2] = "'And the big wheel keep on turning neon burning up above and I'm just high on the world come on and take the low ride with me girl on the.....' What's the Dire Straits song title?";
['Answers'][2] = {"tunnel of love"};
I want to change the format of these without manually going through all 5000, so that they look like:
val que1 = Question(
1, "'7x' was used to refer to the secret ingredient of what drink",
"coca cola"
)
val que2 = Question(
2, "'And the big wheel keep on turning neon burning up above and I'm just high on the world come on and take the low ride with me girl on the.....' What's the Dire Straits song title?",
"tunnel of love"
)
Please help me figure out how to reformat these questions/answers. Thanks.
You can write a script like this to get the desired output.
Step 1: Create input.txt and paste your lua code here which you want to translate
['Question'][1] = "'7x' was used to refer to the secret ingredient of what drink";
['Answers'][1] = {"coca cola"};
['Question'][2] = "'And the big wheel keep on turning neon burning up above and I'm just high on the world come on and take the low ride with me girl on the.....' What's the Dire Straits song title?";
['Answers'][2] = {"tunnel of love"};
Step 2: Create an empty file named output.txt. This file will consist of converted code.
Step 3: Run this main function. You might need to modify file path base on your directory structure. Note: This code is written in Kotlin.
fun main() {
val input = File("src/main/kotlin", "input.txt").readLines()
val outputWriter = File("src/main/kotlin", "output.txt").printWriter()
val lines = input.windowed(2, 2)
val questions = mutableListOf<String>()
lines.forEachIndexed { index, str ->
val que = str[0].split("\"")[1]
val ans = str[1].split("\"")[1]
val question = "val que${index + 1} = Question(${index + 1}, \"$que\", \"$ans\")"
println(question)
questions.add(question)
}
outputWriter.use { out->
questions.forEach {
out.println(it)
}
}
}
After running the script you will get the desired output in output.txt. Alternatively, you can also get this from the console.

Convert CONLL file to a list of Doc objects

Is there a way to convert CONLL file into list of Doc objects without having to parse the sentence using the nlp object. I have a list of annotations that I have to pass to the automatic component that uses Doc objects as input. I have found a way to create the doc:
doc = Doc(nlp.vocab, words=[...])
And that I can use the from_array function to recreate the other linguistic features. This array can be recreated by using index value from StringStore object, I have successfully created Doc object with LEMMA and TAG information but cannot recreate HEAD data. My question is how to pass HEAD data to Doc object using from_array method.
The confusing thing about the HEAD is that for sentence that has this structure:
Ona 2
je 2
otišla 2
u 4
školu 2
. 2
The output of this code snippet:
from spacy.attrs import TAG, HEAD, DEP
doc.to_array([TAG, HEAD, DEP])
is:
array([[10468770234730083819, 2, 429],
[ 5333907774816518795, 1, 405],
[11670076340363994323, 0, 8206900633647566924],
[ 6471273018469892813, 1, 8110129090154140942],
[ 7055653905424136462, 18446744073709551614, 435],
[ 7173976090571422945, 18446744073709551613, 445]],
dtype=uint64)
I cannot correlate the center column of the from_array output to dependency tree structure given above.
Thanks in advance for the help,
Daniel
Ok, so I finally cracked it it appears that head - index if the index is lower than head and 18446744073709551616 - index otherwise. This is the function that I used if anyone else needed it:
import numpy as np
from spacy.tokens import Doc
docs = []
for sent in sents:
generated_doc = Doc(doc.vocab, words=[word["word"] for word in sent])
heads = []
for idx, word in enumerate(sent):
if word["pos"] not in doc.vocab.strings:
doc.vocab.strings.add(word["pos"])
if word["dep"] not in doc.vocab.strings:
doc.vocab.strings.add(word["dep"])
if word["head"] >= idx:
heads.append(word["head"] - idx)
else:
heads.append(18446744073709551616-idx)
np_array = np.array([np.array([doc.vocab.strings[word["pos"]], heads[idx], doc.vocab.strings[word["dep"]]], dtype=np.uint64) for idx, word in enumerate(sent)], dtype=np.uint64)
generated_doc.from_array([TAG, HEAD, DEP], np_array)
docs.append(generated_doc)

Schema validation of empty array for nested structure verification

I am working on a POC with Karate framework (latest version 0.9.6) and I came across with the following:
* match each response.bar contains { id:"#uuid ? _ != ''", name: "#notnull", foo: "#[] #object"}
I noticed that, when foo is an empty array, it does not fail the step.
Is it possible to add a length verification on the above step to fail if the array is empty?
Thanks in advance.
Yes, read the docs: https://github.com/intuit/karate#schema-validation
* match each response.bar contains { id:"#uuid ? _ != ''", name: "#notnull", foo: "#[_ > 0] #object"}

How do I make an edit_traits() GUI item responsive to changes in its dependencies?

I'm designing a HasTraits subclass with dependent properties:
#!/usr/bin/env python
# Example for SO question on dynamically changing Dict contents.
from traits.api import HasTraits, Dict, Property, Trait, Int, cached_property
from traitsui.api import View, Item
class Foo(HasTraits):
"Has dependent properties, which I'd like to remain up-to-date in the GUI."
_dicts = [
{"zero": 0, "one": 1},
{"zero": 1, "one": 2},
{"zero": 2, "one": 3},
]
zap = Int(0)
bar = Property(Trait, depends_on=["zap"])
baz = Trait(list(_dicts[0])[0], _dicts[0])
#cached_property
def _get_bar(self):
return Trait(list(self._dicts)[self.zap], self._dicts)
traits_view = View(
Item("zap"),
Item("bar"),
Item("baz"),
width=500,
)
if __name__ == '__main__':
Foo().configure_traits()
When I run this code I see:
And if I change the value of Zap:
Note the following:
After changing Zap, the address of Bar has changed.
This means that changes to Bar are being dynamically updated in the GUI, while it's still opened; that's great! However...
The way Bar is displayed in the GUI is not very useful.
I'd love to have Bar displayed as Baz is displayed: selectable by the user.
What I'd like is to have the best of both worlds:
the dynamic GUI updating I see with Bar, and
the display format of Baz.
Does anyone know how I can get this?
I've tried several ways of updating a Baz-like item dynamically, to no avail.
(See this previous SO question.)
I assume you wish both bar and baz to be dict type (in traits Dict). Actually, there are default display widgets for pre-defined trait types, which are more useful than showing address. I believe traitsui doesn't know how to properly display your custom Trait object unless you explicitly assign an editor for it. Note that for baz, although a dropdown menu is generated, it is only displaying the keys, which is not very useful either.
With that said, the following codes might meet your expectations.
class Foo(HasTraits):
"Has dependent properties, which I'd like to remain up-to-date in the GUI."
_dicts = [
{"zero": 0, "one": 1},
{"zero": 1, "one": 2},
{"zero": 2, "one": 3},
]
zap = Int(0)
bar = Property(Dict, depends_on=["zap"])
baz = Trait(list(_dicts[0])[0], _dicts[0])
#cached_property
def _get_bar(self):
return self._dicts[self.zap]
traits_view = View(
Item("zap"),
Item("bar", style="custom"),
Item("baz"),
width=500,
)
The following code gets me the behavior I want:
#!/usr/bin/env python
# Example for SO question on dynamically changing Dict contents.
from traits.api import HasTraits, Dict, Property, Trait, Int, cached_property, Enum, List
from traitsui.api import View, Item
class Foo(HasTraits):
"Has dependent properties, which I'd like to remain up-to-date in the GUI."
_dict = {
"zero": 0,
"one": 1,
"two": 2,
}
_zaps = [
["zero", "one"],
["one", "two"],
["zero", "two"],
]
zaps = List(_zaps[0])
zap = Enum([0,1,2]) # Selection of `zap` should limit the items of `_dict` available for selection.
bar = Enum(_zaps[0][0], values="zaps")
bar_ = Int(_dict[_zaps[0][0]])
def _zap_changed(self, new_value):
self.zaps = self._zaps[new_value]
self.bar_ = self._dict[self.bar]
def _bar_changed(self, new_value):
self.bar_ = self._dict[self.bar]
traits_view = View(
Item("zap"),
Item("bar"),
Item("bar_", style="readonly"),
width=500,
)
if __name__ == '__main__':
Foo().configure_traits()
Immediately after program start-up:
And after changing to Zap to '1':

Lingo Code "[cc]" is coming up as a fault

The game is a word search game in an advanced lingo book and the lingo code is using [cc] which is coming up as a code fault. What is wrong or is this use of [cc] obsolete? And if so, how can it be corrected?
on getPropertyDescriptionList me
list = [:]
-- the text member with the words in it
addProp list, #pWordSource,[cc]
[#comment: "Word Source",[cc]
#format: #text,[cc]
#default: VOID]
addProp list, #pEndGameFrame,[cc]
[#comment: "End Game Frame",[cc]
#format: #marker,[cc]
#default: #next]
return list
end
I guess this is code from here, right?
That seems like an older version of Lingo syntax. [cc], apparently, stands for "continuation character". It basically makes the compiler ignore the linebreak right after it, so that it sees everything from [#comment: to #default: VOID] as one long line, which is the syntactically correct way to write it.
If I remember correctly, once upon a time, the guys who made Lingo made one more crazy decision and made the continuation character look like this: ¬ Of course, this didn't print in lots of places, so some texts like your book used things like [cc] in its place.
In modern versions of Lingo, the continuation character is \, just like in C.
I programmed in early director but have gone on to other languages in the many years since. I understand this code. The function attempts to generate a dictionary of dictionaries. in quasi-JSON:
{
'pWordSource': { ... } ,
'pEndGameFrame': { ... }
}
It is creating a string hash, then storing a "pWordSource" as a new key pointing to a 3 item hash of it's own. The system then repeats the process with a new key "pEndGameFrame", providing yet another 3 item hash. So just to expand the ellipses ... from the above code example:
{
'pWordSource': { 'comment': 'Word Source', 'format': 'text', 'default': null } ,
'pEndGameFrame': { 'End Game Frame': 'Word Source', 'format': 'marker', 'default': 'next' }
}
So I hope that explains the hash characters. It's lingo's way of saying "this is not just a string, it's a special director-specific system we're calling a symbol. It can be described in more conventional programming terms as a constant. The lingo compiler will replace your #string1 with an integer, and it's always going to be the same integer associated with #string1. Because the hash keys are actually integers rather than strings, we can change the json model to look something more like this:
{
0: { 2: 'Word Source', 3: 'text', 4: null } ,
1: { 2:'End Game Frame', 3: 'marker', 4: 'next' }
}
where:
0 -> pWordSource
1 -> pEndGameFrame
2 -> comment
3 -> format
4 -> default
So to mimic the same construction behavior in 2016 lingo, we use the newer object oriented dot syntax for calling addProp on property lists.
on getPropertyDescriptionList me
list = [:]
-- the text member with the words in it
list.addProp(#pWordSource,[ \
#comment: "Word Source", \
#format: #text, \
#default: void \
])
list.addProp(#pEndGameFrame,[ \
#comment: "End Game Frame", \
#format: #marker, \
#default: #next \
])
return list
end
Likewise, the same reference shows examples of how to use square brackets to "access" properties, then initialize them by setting their first value.
on getPropertyDescriptionList me
list = [:]
-- the text member with the words in it
list[#pWordSource] = [ \
#comment: "Word Source", \
#format: #text, \
#default: void \
]
list[#pEndGameFrame] = [ \
#comment: "End Game Frame", \
#format: #marker, \
#default: #next \
]
return list
end
And if you are still confused about what the backslashes are doing, there are other ways to make the code more vertical.
on getPropertyDescriptionList me
list = [:]
-- the text member with the words in it
p = [:]
p[#comment] = "Word Source"
p[#format] = #text
p[#default] = void
list[#pWordSource] = p
p = [:] -- allocate new dict to avoid pointer bug
p[#comment] = "End Game Frame"
p[#format] = #marker
p[#default] = #next
list[#pEndGameFrame] = p
return list
end
The above screenshot shows it working in Director 12.0 on OS X Yosemite.