My app requires the Y-axis to have strings like 'Charging', 'Discharging' and 'Charging Failed'. Is it possible to plot a graph with this and have the parameter in question depicted in accordance with these strings on Android Plot?
I'm still not 100% sure I'm understanding the desired visualization but here are the basic steps I would suggest:
To start, you're going to need to convert your CSV data in to XYSeries data. To accomplish this, you'll need to map your current X/Y string values to numbers. I'd suggest creating a method that looks something like this:
// parses a CSV string into an XYSeries
// for example, DISCHARGE = 1, MPPT = 2
public XYSeries convertCSVToXYSeries(String csvContent) {...}
Next, setup your Plot etc. pretty much the same way you would for any other XYPlot as shown in the Androidplot Quickstart Tutorial.
When you add the XYSeries you get back from convertCSVToXYSeries to your plot, use an XYStepFormatter:
StepFormatter stepFormatter = new StepFormatter(Color.BLUE, Color.BLUE);
stepFormatter.setVertexPaint(null); // don't draw individual points
plot.addSeries(series, stepFormatter);
Finally, add a custom range value formatter to print your status strings instead of the int values they've been mapped to:
// create a custom getFormatter to draw our state names as range tick labels:
plot.setRangeValueFormat(new Format() {
#Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
Number num = (Number) obj;
switch(num.intValue()) {
case 1:
toAppendTo.append("DISCHARGE");
break;
case 2:
toAppendTo.append("MPPT");
break;
default:
toAppendTo.append("Unknown");
break;
}
return toAppendTo;
}
#Override
public Object parseObject(String source, ParsePosition pos) {
return null;
}
});
Related
I have a map1 which holds the information as
[40256942,6] [60246792,5]
Now that I want to prepare a map2 that holds information such as
itemNo, 40256942
qty, 6
itemNo, 60246792
qty, 5
to prepare final information as json
“partialArticlesInfo”: [{itemNo:”40256942”, availQty:”6”}, {itemNo:”60246792”, availQty:”5”}]
I am trying to iterate map1 to retrieve values and set that against the key. But I am getting only one entry which is last one. Is there any way , I get the new map with entries such as mentioned above
Map<String, String> partialArticlesInfo = new HashMap<String,String>();
Map<String, String> partialArticlesTempMap = null;
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet())
{
partialArticlesTempMap = new HashMap<String,String>();
partialArticlesTempMap.put("itemNo",entry.getKey());
partialArticlesTempMap.put("availQty",entry.getValue());
partialArticlesInfo.putAll(partialArticlesTempMap);
}
In Java (I'm assuming you're using Java, in the future it would be helpful to specify that) and every other language I know of, a map holds mappings between keys and values. Only one mapping is allowed per key. In your "map2", the keys are "itemNo" and "availQty". So what is happening is that your for loop sets the values for the first entry, and then is overwriting them with the data from the second entry, which is why that is the only one you see. Look at Java - Map and Map - Java 8 for more info.
I don't understand why you are trying to put the data into a map, you could just put it straight into JSON with something like this:
JSONArray partialArticlesInfo = new JSONArray();
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet()) {
JSONObject stockEntry = new JSONObject();
stockEntry.put("itemNo", entry.getKey());
stockEntry.put("availQty", entry.getValue());
partialArticlesInfo.put(stockEntry);
}
JSONObject root = new JSONObject();
root.put("partialArticlesInfo",partialArticlesInfo);
This will take "map1" (partialStockArticlesQtyMap in your code) and create a JSON object exactly like your example - no need to have map2 as an intermediate step. It loops over each entry in map1, creates a JSON object representing it and adds it to a JSON array, which is finally added to a root JSON object as "partialArticlesInfo".
The exact code may be slightly different depending on which JSON library you are using - check the docs for the specifics.
I agree with Brendan. Another solution would be otherwise to store in the Set or List objects like the following.
class Item {
Long itemNo;
int quantity;
public int hashCode() {
Long.hashCode(itemNo) + Integer.hashCode(quantity);
}
public int equals(Object other) {
other instanceOf Item && other.itemNo == this.itemNo && other.quantity = this.quantity;
}
}
}
then you can use the JsonArray method described by him to get the Json string in output
This means that adding new variables to the object won't require any more effort to generate the Json
.NET 4.5, C#, Npgsql 3.1.0
I have a query which retrieves a Postgis geometry field - the only way I could see of doing this was:
public class pgRasterChart
{
...
public NpgsqlTypes.PostgisGeometry GEOMETRY;
...
}
...
NpgsqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
pgRasterChart chart = new pgRasterChart();
chart.GEOMETRY = (PostgisGeometry) reader.GetValue(21);
...
This functions but I need to get at the coordinates of the GEOMETRY field and I can't find a way of doing that? I want to use the coordinates to display the results on an OpenLayers map.
Any answers most gratefully received. This is my first post so my apologies if the etiquette is clumsy or question unclear.
Providing another answer because the the link above to the documentation for PostGisTypes is now broken.
PostGisGeometry is an abstract base class that does not contain anything more exiting than the SRID. Instead, you want to cast the object obtained by your datareader to the appropriate type (any of the following):
PostGisLineString
PostGisMultiLineString
PostGisMultiPoint
PostGisMultiPolygon
PostGisPoint
PostGisPolygon
These classes have ways of getting to the coordinates.
eg:
...
NpgsqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
var geom = (PostgisLineString) reader.GetValue(0);
var firstCoordinate = geom[0]; // Coordinate in linestring at index 0
var X = firstCoordinate.X;
var Y = firstCoordinate.Y;
...
As you can see here
https://github.com/npgsql/npgsql/blob/dev/src/Npgsql.LegacyPostgis/PostgisTypes.cs
PostgisGeometry types are a set of xy pairs.
For example, a linestring is an array of points, a polygon is an array of rings and so on..
You could traverse those structures and get the coordinates.
However, if you just want to display geometries using openlayers, I suggest you to use the wkt format.
You should change your query, selecting st_astext(geometry) instead of geometry, than treat the result as a string and give it back to OpenLayers.
Then use OpenLayers.Geometry.fromWKT to parse the WKT into an OpenLayers.Geometry
Using iTextSharp, I create a pdf writing some text into it.
What I need is to draw a line to delimiter the text every 25 words, like the following image:
Basically, I need to do that: draw a line every 25 words, just like the image.
I'm aware there's a way of finding the position of a word on a page, but considering I'm writing the text to the pdf file, I guess there could be a way of calculating this without really having to find the text position, right?
Please take a look at the Every25Words examples. In that example, I read a text file into a String with the readFile() method. I then split the text into words based on the occurrence of spaces, and I add each word one by one:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
writer.setPageEvent(new WordCounter());
writer.setInitialLeading(16);
document.open();
String[] words = readFile().split("\\s+");
Chunk chunk = null;
for (String word : words) {
if (chunk != null) {
document.add(new Chunk(" "));
}
chunk = new Chunk(word);
chunk.setGenericTag("");
document.add(chunk);
}
document.close();
}
The magic happens in this line:
writer.setPageEvent(new WordCounter());
chunk.setGenericTag("");
First we declare an instance of the WordCounter event. You may choose a better name for that class, as not only does it count words, it also draws a dashed line:
public class WordCounter extends PdfPageEventHelper {
public int count = 0;
#Override
public void onGenericTag(PdfWriter writer, Document document, Rectangle rect, String text) {
count++;
if (count % 25 == 0) {
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineDash(5, 5);
canvas.moveTo(document.left(), rect.getBottom());
canvas.lineTo(rect.getRight(), rect.getBottom());
canvas.lineTo(rect.getRight(), rect.getTop());
canvas.lineTo(document.right(), rect.getTop());
canvas.stroke();
canvas.restoreState();
}
}
}
Do you see what we do between the saveState() and restoreState() method? We define a dash pattern, we move to the left of the page, we construct a path to the right of the word, then we draw a short upwards line, to finish the path with a line to the right. Once the path is constructed, we stroke the line.
This onGenericTag() method will be triggered every time a Chunk is added on which we used the setGenericTag method.
This is what the result looks like every25words.pdf:
I want to program some kind of game where the player has to name loacations shown on a map. I am using the slick library.
My problem is that I need some way to get the keyboard input from the player. I tried it with InputDialog from JOptionPane but I do not really like it. I would rather have the string appear on some part of the screen. But I do not have any idea how I can read from the keyboard directly into a variable that should be drawn on the screen. I thought that it would be possible to use streams but if I try to get some examples, they are always about reading from files and I do not know how to use that for reading from keyboard.
String answer;
public void render(GameContainer gameContainer, StateBasedGame sbGame, Graphics g){
g.drawString(answer, 50, 50);
}
public void update(GameContainer gameContainer, StateBasedGame sbGame, int delta){
//user types something which I now call "inputFromUser"
//it does not appear anywhere before the string is drawn on the screen.
answer = inputFromUser;
}
Something like a Scanner does not work for me because the user has to type that into the console, and I want him to type it "directly into the game" like it works with a textfield. (But I do not want to use a textfield.)
I have one way to accomplish that but it's fairly resource intensive. First create a global variable to keep track of the current letters. now create a new method that runs through all of the keys to check if they are down
private String totalString;
private void handelUserInput(Input input){
if(input.isKeyDown(Input.KEY_BACK)){
totalString = totalString.substring(0, totalString.length() - 1);
}
if(input.isKeyDown(Input.KEY_A)){
totalString += "a";
}
if(input.isKeyDown(Input.KEY_B)){
totalString += "b";
}
...etc
}
next create an input handler in the update loop to pass into the handle input method.
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
Input input = gc.getInput();
handelUserInput(input);
}
and then print the string somewhere on your window in the render loop. by the way the Input class is built into slick.
I'm an Android newbie.
I'm trying to set custom colors inside an ExpandableListView adapter. I have defined my colors in colors.xml, but I'm unable to use them in my adapter. I get an error "The method getResources() is undefined for the type ExpandableListAdapter"
The function expects an int. I've tried to pass my result from getResources in, but, it does'nt work. I've also tried to pass in a hex value, but it does'nt change anything.
How can I use my custom colors in my code?
public View getGroupView(int groupPosition, boolean arg1, View convertView,
ViewGroup arg3) {
int n = 0;
String laptopName = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.group_item, null);
}
TextView item = (TextView) convertView.findViewById(R.id.demo);
item.setTypeface(null, Typeface.BOLD);
item.setText(laptopName);
convertView.setBackgroundColor(getResources().getColor(R.color.purple));
return convertView;
}
Thanks guys, the following snippet works
this.context = (Activity) context;
convertView.setBackgroundColor(this.context.getResources().getColor(R.color.purple));
Assuming you have a context instance somewhere in the adapter instead of this
convertView.setBackgroundColor(getResources().getColor(R.color.purple));
it should be this
convertView.setBackgroundColor((your context).getResources().getColor(R.color.purple));
and if you don't have a reference to the context just pass it in to the adapter constructor
As loulou8284 mentioned you can put it in your XML, or if it is fixed, define it with Color.rgb(), but to make your code running you need to get the reference to your Context as your class is not declared inside a context-class:
convertView.setBackgroundColor(getContext().getResources().getColor(R.color.purple));
You can declare the color in you .xml file ( in your item xml file )
Use setBackgroundResource() rather than setBackgroundColor()
setBackgroundResource() takes an integer resource index as parameter, and load whatever resource that index points to (for example; a drawable, a string or in your case a color).
setBackgroundColor(), however takes an integer representing a color. That is, not a color-resource, but a direct, hexadecimal, rgba value (0xAARRGGBB).