String category names with Wisp scala plotting library - scala

I am trying to plot bars for String categories with Wisp. In other words, I have a string (key) and a count (value) in my repl and I want to have a bar chart of the count versus the key.
I don't know if something easy exists. I went as far as the following hack:
val plot = bar(topWords.map(_._2).toList)
val axisType: com.quantifind.charts.highcharts.AxisType.Type = "category"
val newPlot = plot.copy(xAxis = plot.xAxis.map {
axisArray => axisArray.map { _.copy(axisType = Option(axisType),
categories = Option(topWords.map(_._1))) }
})
but I don't know if it works because I don't find a way to visualize newPlot. Or maybe adding a method to the Wisp source implementing the above is the way to go?
Thanks for any help.
PS : I don't have the reputation to create the wisp tag, but I would have...

Update: in wisp 0.0.5 or later this will be supported directly:
column(List(("alpha", 1), ("omega", 5), ("zeta", 8)))
====
Thanks for trying out wisp (I am the author). I think a problem that you may have encountered is by naming your variable plot, you overrode access to the plot method defined by Highcharts, which allows you to plot any Highchart object. (now that I see it, naming your plot "plot" is an unfortunately natural thing to do!)
I'm filing this as a github issue, as category names are very common.
This works for me. I used column for vertical bars:
import com.quantifind.charts.Highcharts._
val topWords = Array(("alpha", 14), ("beta", 23), ("omega", 18))
val numberedColumns = column(topWords.map(_._2).toList)
val axisType: com.quantifind.charts.highcharts.AxisType.Type = "category"
val namedColumns = numberedColumns.copy(xAxis = numberedColumns.xAxis.map {
axisArray => axisArray.map { _.copy(axisType = Option(axisType),
categories = Option(topWords.map(_._1))) }
})
plot(namedColumns)
producing this visualization:
(You could also consider creating one bar at a time, and use the legend to name them)

Related

Write scale/nested conversion with ASAMMDF

I am using this snippet in order to create a mf4 file with a value to text table, found in the examples from asammdf's github.
vals = 5
conversion = {
'val_{}'.format(i): i
for i in range(vals)
}
conversion.update(
{
'text_{}'.format(i): 'key_{}'.format(i).encode('ascii')
for i in range(vals)
}
)
sig = Signal(
np.arange(cycles, dtype=np.uint32) % 30,
t,
name='Channel_value_to_text',
conversion=conversion,
comment='Value to text channel',
)
sigs.append(sig)
mdf.append(sigs, comment='arrays', common_timebase=True)
Is there a way to create a table with ##TX blocks and also ##CC blocks?(in order to simulate a scale conversion)
Thank you!
If anyone needs it, I found the answer and it was simpler than expected.
Create another conversion (i.e conversion2) in the same manner as the first one, then reassign the value of one of the references to it.
conversionBlock = from_dict(conversion)
conversionBlock.referenced_blocks["text_4"] = from_dict(conversion2)

Making text into an array - Swift

For fun I'm helping my school out by creating an app which has all class cancellations for student use. From my IT technician I got a quite complex structure containing class name, teacher, and other information looking like this:
3818,"20170217",5,752,64,"Rh",,"fr_2",,,,"iV5",,,"IS10a~IS10b~IS10c~IS10d","Z",,1,"IS10a~IS10b~IS10c~IS10d",C,201702161517,"-"
3819,"20170217",6,752,102,"Rh",,"fr",,,,"iB3","iB3",,"IT10a","Z",,0,"IT10a",,201702161517,"-"
3820,"20170217",8,752,119,"Rh",,"fr",,,,"iC1.2","iC1.2",,"IS6a","Z",,0,"IS6a",,201702161517,"-"
3821,"20170227",2,753,207,"Dd","Kru","sc",,,,"iB8","iB8",,"IS9b","Z",,2097152,"IS9b",,201702270804,"+~-"
3822,"20170227",3,753,8,"Dd",,"phH_1",,,,"iB8",,,"IS12~IT12","Z",,2097153,"IS12~IT12",C,201702270804,"-"
3823,"20170227",4,753,29,"Dd",,"phH_1",,,,"iB8",,,"IS11~IT11","Z",,2097153,"IS11~IT11",C,201702270804,"-"
3824,"20170227",5,753,30,"Dd",,"phH_1",,,,"iB8",,,"IS11~IT11","Z",,2097153,"IS11~IT11",C,201702270804,"-"
3825,"20170227",6,753,7,"Dd",,"phH_1",,,,"iB8",,,"IS12~IT12","Z",,2097153,"IS12~IT12",C,201702270804,"-"
3826,"20170227",7,753,327,"Dd",,"COV",,,,"AC1",,,,"Z",,2097153,,,201702270803,
3827,"20170227",8,753,46,"Dd",,"ph_1",,,,"iB8",,,"IS10a~IS10b~IS10c~IS10d~IT10a~IT10b","Z",,2097153,"IS10a~IS10b~IS10c~IS10d~IT10a~IT10b",C,201702270804,"-"
From this data I need to get various pieces, such as "20170217" and put them into an array for later use. How would I best do this? For anyone who cares, I added the full snippet below!
https://jsfiddle.net/pztwfsq1/
Since there is one dataset per line you can iterate through all lines. Split each line at , and you'll have an array of the information.
Similar to this (to give you an idea):
let row = "1,Peter,5,92,,Brooklyn"
let data = row.components(separatedBy: ",")
let name = data[1] // Peter
let location = data[5] // Brooklyn

TabularAdapter customization/notifications?

Thanks to another user here on SO (Warren Weckesser), I found a nice way to format my TabularAdapter columns. There are some other customizations I'd like to accomplish, so I thought I'd put this out to SO to see if I can get more help.
The following code puts up a couple of TabularAdapter tables in the format that I want to use. What I'd like to be able to do are 2 things:
I'd like to set the first column as non-editable. I've found how to set a row to non-editable, but not a column -- is this possible?
What I'd really like (even more than #1 above) it to get a notification if one of the values in any of my columns changes! I've heard that there are some 'tweaks' that can be done with numpy arrays to accomplish this, but I'm way too inexperienced yet to pull this off. Is there any TraitsAdapter mentods that might be used to accomplish this feat?
Here's my code so far (thanks to Warren's modifications):
from traits.api import HasTraits, Array, Str
from traitsui.api import View, Item, TabularEditor
from traitsui.tabular_adapter import TabularAdapter
from numpy import dtype
test_dtype = dtype([('Integer#1', 'int'),
('Integer#2', 'int'),
('Float', 'float')])
class TestArrayAdapter1(TabularAdapter):
columns = [('Col1 #', 0), ('Col2', 1), ('Col3', 2)]
even_bg_color = 0xf4f4f4 # very light gray
width = 125
def get_format(self, object, name, row, column):
formats = ['%d', '%d', '%.4f']
return formats[column]
class TestArrayAdapter2(TabularAdapter):
columns = [('Col1 #', 0), ('Col2', 1), ('Col3', 2)]
even_bg_color = 0xf4f4f4 # very light gray
width = 125
object_0_format = Str("%d")
object_1_format = Str("%d")
object_2_format = Str("%.4f")
class Test(HasTraits):
test_array = Array(dtype=test_dtype)
view = \
View(
Item(name='test_array', show_label=False,
editor=TabularEditor(adapter=TestArrayAdapter1())),
Item(name='test_array', show_label=False,
editor=TabularEditor(adapter=TestArrayAdapter2())),
)
test = Test()
test.test_array.resize(5, refcheck=False)
test.configure_traits()
For your item #2, after talking to Enthought folks, I confirmed there isn't an official way to do this yet but:
I created a ticket for it: https://github.com/enthought/traitsui/issues/387
I worked around the issue, by keeping a handle on the ArrayAdapter, subclass it, and override the set_text method like so:
.
class NotifyingArrayAdapter(ArrayAdapter):
value_changed = Event
def set_text(self, object, trait, row, column, text):
super(NotifyingArrayAdapter, self).set_text(object, trait, row,
column, text)
self.value_changed = True
That way, I can just listen to the value_changed event, and do what I need with it.
You can get fancier, and make the event be a more complex object, for example storing information about the old/new values, and the row and column changed:
class ArrayAdapterEvent(HasStrictTraits):
row = Int
column = Int
old = Str
new = Str
class NotifyingArrayAdapter(ArrayAdapter):
value_changed = Event(Instance(ArrayAdapterEvent))
def set_text(self, object, trait, row, column, text):
old = self.get_text(object, trait, row, column)
super(NotifyingArrayAdapter, self).set_text(object, trait, row,
column, text)
event = ArrayAdapterEvent(old=old, new=text, row=row, column=column)
self.value_changed = event

Passing arguments between Gatling scenarios and simulation

I'm current creating some Gatling simulation to test a REST API. I don't really understand Scala.
I've created a scenario with several exec and pause;
object MyScenario {
val ccData = ssv("cardcode_fr.csv").random
val nameData = ssv("name.csv").random
val mobileData = ssv("mobile.csv").random
val emailData = ssv("email.csv").random
val itemData = ssv("item_fr.csv").random
val scn = scenario("My use case")
.feed(ccData)
.feed(nameData)
.feed(mobileData)
.feed(emailData)
.feed(itemData)
.exec(
http("GetCustomer")
.get("/rest/customers/${CardCode}")
.headers(Headers.headers)
.check(
status.is(200)
)
)
.pause(3, 5)
.exec(
http("GetOffers")
.get("/rest/offers")
.queryParam("customercode", "${CardCode}")
.headers(Headers.headers)
.check(
status.is(200)
)
)
}
And I've a simple Simulation :
class MySimulation extends Simulation {
setUp(MyScenario.scn
.inject(
constantUsersPerSec (1 ) during (1)))
.protocols(EsbHttpProtocol.httpProtocol)
.assertions(
global.successfulRequests.percent.is(100))
}
The application I'm trying to simulate is a multilocation mobile App, so I've prepared a set of samples data for each Locale (US, FR, IT...)
My REST API handles all the locales, therefore I want to make the simulation concurrently execute several instances of MyScenario, each with a different locale sample, to simulate the global load.
Is it possible to execute my simulation without having to create/duplicate the scenario and change the val ccData = ssv("cardcode_fr.csv").random for each one?
Also, each locale has its own load, how can I create a simulation that takes a single scenario and executes it several times concurrently with a different load and feeders?
Thanks in advance.
From what you've said, I think this may be a good approach:
Start by grouping your data in such a way that you can look up each item you want to send based on the current locale. For this, I would recommend using a Map that matches a locale string (such as "FR") to the item that matches that locale for the field you're looking to fill in. Then, at the start of each iteration of the scenario, you just pick which locale you want to use for the current iteration from a list. It would look something like this:
val locales = List("US", "FR", "IT")
val names = Map( "US" -> "John", "FR" -> "Pierre", "IT" -> "Guillame")
object MyScenario {
//These two lines pick a random locale from your list
val random_index = rand.nextInt(locales.length);
val currentLocale = locales(random_index);
//This line gets the name
val name = names(currentLocale)
//Do the rest of your logic here
}
This is a very simplified example - you'll have to figure out how you actually want to retrieve the data from files and put it into a Map structure, as I assume you don't want to hard code every item for every field into your code.

Way to Extract list of elements from Scala list

I have standard list of objects which is used for the some analysis. The analysis generates a list of Strings and i need to look through the standard list of objects and retrieve objects with same name.
case class TestObj(name:String,positions:List[Int],present:Boolean)
val stdLis:List[TestObj]
//analysis generates a list of strings
var generatedLis:List[String]
//list to save objects found in standard list
val lisBuf = new ListBuffer[TestObj]()
//my current way
generatedLis.foreach{i=>
val temp = stdLis.filter(p=>p.name.equalsIgnoreCase(i))
if(temp.size==1){
lisBuf.append(temp(0))
}
}
Is there any other way to achieve this. Like having an custom indexof method that over rides and looks for the name instead of the whole object or something. I have not tried that approach as i am not sure about it.
stdLis.filter(testObj => generatedLis.exists(_.equalsIgnoreCase(testObj.name)))
use filter to filter elements from 'stdLis' per predicate
use exists to check if 'generatedLis' has a value of ....
Don't use mutable containers to filter sequences.
Naive solution:
val lisBuf =
for {
str <- generatedLis
temp = stdLis.filter(_.name.equalsIgnoreCase(str))
if temp.size == 1
} yield temp(0)
if we discard condition temp.size == 1 (i'm not sure it is legal or not):
val lisBuf = stdLis.filter(s => generatedLis.exists(_.equalsIgnoreCase(s.name)))