jFreechart CategoryDataset sort columns - jfreechart

I create a multi series linechart and fill its dataset dinamically:
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (Map.Entry<Long, TreeMap<Integer, Integer>> entrya : mtypes.entrySet()) {
TreeMap<Integer, Integer> atypes = entrya.getValue();
if (atypes.isEmpty())
continue;
Long aid = entrya.getKey();
String name = (aid < 2 ? "Важное" : (aid < 3 ? "Негатив" : "Позитив"));
for (Map.Entry<Integer, Integer> entrym : atypes.entrySet()) {
int m = entrym.getKey();
dataset.addValue(entrym.getValue(), name, Integer.valueOf(m + 1));
}
image = PDFUtil.printLineChart(writer, "", "", "Баллы", dataset , 500, 0, true);
Source array atypes for one series has the form:
{
1={2=4, 3=1},
2={0=1, 3=1, 4=1},
3={0=3, 1=16, 2=31, 3=2, 4=12}
}
All numerical keys in the map sorted Ascending, but on the chart the columns values are unsorted (horizontal axis):
How can I sort it Ascending? This code didn't help:
chart.getCategoryPlot().getDomainAxis().setColumnRenderingOrder(SortOrder.ASCENDING)

Related

Select random number 1-30, remove that index from a list and continue until all 30 numbers have been selected

Javascript
Using a data table of NBA teams. I am using two columns which are the team "id" and the team "logo" columns. They both range from 1-30(user clicks a button that runs a function to select a random number). I would like to choose a random number and display a random team's logo correlating to the number chosen, then splice the array(in this case my lists are teamIDList = "id" and teamLogosList = "logo", "id" and "logo" are both columns for a dataset). I want to do this so all 30 teams have been displayed once without repeats.
MY CURRENT CODE(Issue: random number chosen is sometimes 30 which is above the list length somehow):
var teamLogosList = getColumn("NBA Teams", "Image");
var teamIDList = getColumn("NBA Teams", "id");
updateScreen();
onEvent("answerButton", "click", function( ) {
updateScreen();
});
function updateScreen() {
var temp = teamIDList[(randomNumber(0, teamIDList.length-1))];
if (temp < teamIDList.length-1) {
var logo = teamLogosList[temp];
setImageURL("teamLogo", logo);
teamIDList.splice(temp,1);
teamLogosList.splice(temp,1);
} else {
updateScreen();
}
}

Swift: Index Out of Range Error when Populating Two-Dimensional Array

I just started to learn Swift and I would like to code the game BubbleBreaker which I have already created in both Java and C# some years ago.
For this, I wanted to create a two-dimensional array of Bubble (which is derived from SKSpriteNode), however, when I am trying to populate the array, I always get an "index out of range error" at index [0][0]. Can somebody please help me?
class GameScene: SKScene {
//game settings
private var columns = 10
private var rows = 16
private var bubbleWidth = 0
private var bubbleHeight = 0
//bubble array
private var bubbles = [[Bubble]]()
override func didMove(to view: SKView) {
initializeGame()
}
private func initializeGame() {
self.anchorPoint = CGPoint(x: 0, y: 0)
//Optimize bubble size
bubbleWidth = Int(self.frame.width) / columns
bubbleHeight = Int(self.frame.height) / rows
if bubbleWidth < bubbleHeight {
bubbleHeight = bubbleWidth
}
else {
bubbleWidth = bubbleHeight
}
//Initialize bubble array
for i in 0 ... columns-1 {
for j in 0 ... rows-1 {
let size = CGSize(width: bubbleWidth, height: bubbleHeight)
let newBubble = Bubble(size: size)
newBubble.position = CGPoint(x: i*bubbleWidth, y: j*bubbleHeight)
bubbles[i][j] = newBubble // THIS IS WERE THE CODE BREAKS AT INDEX [0][0]
self.addChild(newBubble)
}
}
}
}
bubbles starts off empty. There's nothing at any index.
Update your loop to something like this:
//Initialize bubble array
for i in 0 ..< columns {
var innerArray = [Bubble]()
for j in 0 ..< rows {
let size = CGSize(width: bubbleWidth, height: bubbleHeight)
let newBubble = Bubble(size: size)
newBubble.position = CGPoint(x: i*bubbleWidth, y: j*bubbleHeight)
innertArray.append(newBubble)
self.addChild(newBubble)
}
bubbles.append(innerArray)
}
This builds up an array of arrays.
Instead of assigning new value as unexisting value, append new empty array of Bubble for every column and then append to this array newBubble for every row
for i in 0 ... columns-1 {
bubbles.append([Bubble]())
for j in 0 ... rows-1 {
let size = CGSize(width: bubbleWidth, height: bubbleHeight)
let newBubble = Bubble(size: size)
newBubble.position = CGPoint(x: i*bubbleWidth, y: j*bubbleHeight)
bubbles[i].append(newBubble)
self.addChild(newBubble)
}
}

LINQ : filter multiple string values - partial match - not full match as in multiple online examples

There are many good examples of searching multiple string values in LINQ e.g.
public static Product[] GetProducts(Guid[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Contains(p.ProductID)
select p).ToArray<Product>();
}
I have a list of Products that I need to match from a customer,
but I dont have an exact match - the Customers List Of Products contains my ProductID - but it is not exact - e.g.
Customer MyCompany
Description Description
Prod1XY Prod1
AProd2B Prod2
XXXProd3 Prod3
I thus cannot filter from the prodIDs [string array] because Prod1 does not contain Prod1XY
and thus cannot use the examples that are available.
How can I effectively change (reverse) the working examples
as to search CustomerProducts where it contains my Product Description please?
So to confirm : this is not a duplicate. The examples use the string[] x
input parameter and then searches:
where x.contains
I need help to get it : myProducts.Contains(x)
another online example modified to show the situation:
static void Main(string[] args) {
var table = new[] {
new { uid = 1 },
new { uid = 2 },
new { uid = 3 },
new { uid = 4 },
new { uid = 5 }
};
var stringarray = new[] { "1", "5", "10" };
var results = from xx in table
where table.Contains(stringarray)
select xx;
foreach (var result in results) {
Console.WriteLine("Result: " + result.uid.ToString());
}
}
It is not clear enough what you are trying to accomplish, but under assumption that you want to select all products where ProductID contains any value from specified list, it looks like that it:
public static Product[] GetProducts(string[] prodIDs)
{
return (from p in GetProducts()
where prodIDs.Any(id=>p.ProductID.Contains(id))
select p).ToArray<Product>();
}
Try this
public static Product[] GetProducts(string[] prodIDs)
{
return (
from p in GetProducts()
from q in prodIDs
where p.ProductID.IndexOf(q) > -1
select p)
.ToArray<Product>();
}

extracting csv data and plotting 2D array using scala and processing

I was wondering if anybody might be able to shed some light on this problem, I'm quite new to scala and generally non R programming, so i'm still learning some of the ropes so to speak.
What i'm trying to do is plot a 2D array, so a grid of squares on a gray scale with a darker colour representing a higher value. I have a csv file of x and y locations on the grid and a third value z which will be represented by the colour.
I've written two pieces of code which do what I want, one extracts data from a csv file, the other plots the type of data that is extracted. The problem I have is getting them to work together.
So piece of code 1 extracts data which is as follows:
x, y, z
50, 16, 52
21, 25, 29
13, 12, 445
etc...
code:
import scala.io.Source
import java.io._
///////extract the data
object DataExtractor extends App {
def using[T <: Closeable, R](resource: T)(block: T => R): R = {
try { block(resource) }
finally { resource.close() }
}
for (line <- io.Source.fromFile("C://~//TestData.csv").getLines.drop(1)) {
val array = line.split(",")
try {
val xloc = array(0)
val yloc = array(1)
val intense = array (2)
}catch { case ex: Exception => }
}
}
This gives me a value from each line of the csv the x axis location (xloc), y axis (yloc) and what will be the intensity value (intense) in order to plot how darkly shaded the grid square is.
The second piece of code plots a 2D array using "processing"
/////////plotting data
import processing.core._
class FT extends processing.core.PApplet {
val xloc = 9 //define locations
val yloc = 1
val intense = 4 //define intensity of colour
var grid: Array[Array[Cell]] = _
var cols: Int = 100 // grid size
var rows: Int = 100
override def setup() {
size(200, 200) //window size
grid = Array.ofDim[Cell](cols, rows)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j) = new Cell(i * 10, j * 10, 10, 10, i + j) //cell size
}
}
override def draw() {
background(0)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j).display()
grid(i)(j).height()
grid(i)(j).xl()
grid(i)(j).yl()
}
}
class Cell(var x: Float,
var y: Float,
var w: Float,
var h: Float,
var strength: Float) {
def display() {
stroke(255)
fill(strength)
rect(x, y, w, h)
}
def height() {
strength = intense
}
def xl() {
x = xloc
}
def yl() {
y = yloc
}
}
}
As you can see, in my second piece of code i've given xloc, yloc and intense arbitrary values. What i'm trying to do is to loop through a csv file and for each line plug in the data to the plotting code so the final result is a grid with differing colour intensities based on the x, y and z values in the csv file.
Any help will be much appreciated as i'm still trying to figure out how one links chunks of code together in scala.
Edit:
So what i've tried is to integrate the two pieces of code, however I'm running into a new problem which is that scala will not initialize a local varaible within a method (var grid). But by moving grid outside of the loop it can no longer access the Cell class...any pointers or ideas would be much appreciated
import processing.core._
import scala.io.Source
import java.io._
class FT extends processing.core.PApplet {
for (line <- io.Source.fromFile("C:~TestData.csv").getLines.drop(1)) {
try {
val array = line.split(",")
var xloct = array(0)
var yloct = array(1)
var intenset = array (2)
val xloc = xloct.toFloat
val yloc = yloct.toFloat
val intense = intenset.toFloat
var grid: Array[Array[Cell]] =_ // error "local variables must be initialized"
var cols: Int = 100 // grid size
var rows: Int = 100
def setup() {
size(200, 200) //window size
grid = Array.ofDim[Cell](cols, rows)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j) = new Cell(i * 10, j * 10, 10, 10, i + j) //cell size
}
}
def draw() {
background(0)
for (i <- 0 until cols; j <- 0 until rows) {
grid(i)(j).display()
grid(i)(j).height()
grid(i)(j).xl()
grid(i)(j).yl()
}
}
class Cell(var x: Float,
var y: Float,
var w: Float,
var h: Float,
var strength: Float) {
def display() {
stroke(255)
fill(strength)
rect(x, y, w, h)
}
def height() {
strength = intense
}
def xl() {
x = xloc
}
def yl() {
y = yloc
}
}
} catch { case ex: Exception => }
}
}

Loop design for first/last items and item groups?

I'm often confronted with the following situation: I have some data in a table (nested arrays) and need to loop over all items in it.
Requirements:
The first item should be identified and handled separately.
The last item should be identified and handled separately.
If similiar items are sorted they should be identified in groups with the first and last group item identified. (in this case sort/group by gender)
Subtotals of group items and total of all items should be given.
DATA:
Comic characters with firstname, lastname, tvshow, gender
assuming to be ordered by gender, lastname.
Turanga|Leela|Futurama|Female
Marge|Simpson|The Simpsons|Female
Eric|Cartman|South Park|Male
Peter|Griffin|Family Guy|Male
Homer|Simpson|The Simpsons|Male
QUESTION:
How would you code a loop (any language welcome!) that produces the following output?
Indention is not important.
OUTPUT:
First Entry: Turanga Leele (Futurama)
--
First Female: Turanga Leela (Futurama)
Last Female : Marge Simpson (The Simpsons)
--
Total Females: 2
--
First Male: Eric Cartman (South Park)
Peter Griffin (Family Guy)
Last Male : Homer Simpson (The Simpsons)
--
Total Males: 3
--
Last Entry: Homer Simpson (The Simpsons)
--
Total Entries: 5
I picked the world's most verbose language to do this in (Java), but this should do what you want. It requires only a single pass, but needs one row of look ahead. It also requires at least two lines of input although it would be relatively easy to adapt to any number of lines:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import static java.lang.System.out;
public class Loop {
static enum Col { FIRST_NAME, LAST_NAME, TV_SHOW, GENDER }
private static final List<String[]> characters = Arrays.asList(
new String[] {"Turanga", "Leela", "Futurama", "Female"},
new String[] {"Marge", "Simpson", "The Simpsons", "Female"},
new String[] {"Eric", "Cartman", "South Park", "Male"},
new String[] {"Peter", "Griffin", "Family Guy", "Male"},
new String[] {"Homer", "Simpson", "The Simpsons", "Male"});
public static void summarize(List<String[]> character, Col groupBy) {
assert character.size() > 1;
int total = 0;
Iterator<String[]> i = characters.iterator();
String[] row = next(i);
String[] peek = next(i);
String group;
out.print("First Entry:" + format(row));
Map<String, Integer> subTotals = new HashMap<String, Integer>();
do {
group = col(row, groupBy);
out.print("First " + group + ":");
subTotals.put(group, 0);
do {
out.print(format(row));
total = incrementTotals(total, group, subTotals);
row = peek;
peek = next(i);
} while (peek != null && col(peek, groupBy).equals(group));
total = incrementTotals(total, group, subTotals);
out.print("Last " + group + ":" + format(row));
out.println("--");
out.println("Total " + group + "s:" + subTotals.get(group));
out.println("--");
if (peek == null) break;
row = peek;
peek = next(i);
} while(true);
out.print("Last Entry:" + format(row));
out.println("--");
out.println("Total Entries:" + total);
}
private static String[] next(Iterator<String[]> i) {
if (i.hasNext())
return i.next();
return null;
}
private static int incrementTotals(int total, String group,
Map<String, Integer> subTotals) {
total++;
subTotals.put(group, subTotals.get(group) + 1);
return total;
}
private static String format(String[] row) {
return col(row, Col.FIRST_NAME) + " " + col(row, Col.LAST_NAME)
+ "(" + col(row, Col.TV_SHOW) + ")\n";
}
private static String col(String[] row, Col col) {
return row[col.ordinal()];
}
public static void main(String args[]) {
summarize(characters, Col.GENDER);
}
}
Output is:
First Entry:Turanga Leela(Futurama)
First Female:Turanga Leela(Futurama)
Last Female:Marge Simpson(The Simpsons)
--
Total Females:2
--
First Male:Eric Cartman(South Park)
Peter Griffin(Family Guy)
Last Male:Homer Simpson(The Simpsons)
--
Total Males:3
--
Last Entry:Homer Simpson(The Simpsons)
--
Total Entries:5
For interest sake, I decided to see what this would look like in Groovy which is a real language with closures, metaprogramming and some cool list operators. The following code gives more or less the same results, although it requires the list to be in memory and is not particularly efficient. It is however far more readable, and well.. groovier.
enum Col { FIRST_NAME, LAST_NAME, TV_SHOW, GENDER }
def characters = [
[ "Turanga", "Leela", "Futurama", "Female" ],
[ "Marge", "Simpson", "The Simpsons", "Female" ],
[ "Eric", "Cartman", "South Park", "Male" ],
[ "Peter", "Griffin", "Family Guy", "Male" ],
[ "Homer", "Simpson", "The Simpsons", "Male" ]
]
// Use Groovy Metaprogramming to add some methods to the List class
List.metaClass.first = { cl -> if (delegate.size > 0) cl(delegate[0]) }
List.metaClass.middle = { cl ->
if (delegate.size > 2) 1..delegate.size-2.each { i -> cl(delegate[i]) }
}
List.metaClass.last = { cl -> if (delegate.size > 1) return cl(delegate[delegate.size-1]) }
def format(row) {
return row[Col.FIRST_NAME.ordinal()] + " " +
row[Col.LAST_NAME.ordinal()] + " (" +
row[Col.TV_SHOW.ordinal()] + ")"
}
// Loop through and summarize the Characters
characters.first { row ->
println("First Entry: ${format(row)}")
}
def groups = characters.groupBy { row -> row[Col.GENDER.ordinal()] }
groups.each { groupType, group ->
group.first { row -> println("First ${groupType}: ${format(row)}") }
group.middle { row -> println(format(row)) }
group.last { row -> println("Last ${groupType}: ${format(row)}") }
println("--")
println("Total ${groupType}s: ${group.size}")
println("--")
}
characters.last { row ->
println("Last Entry : ${format(row)}")
println("--")
println("Total Items: " + characters.size())
}

Resources