I haven't used java since version 4 and casting seams to have changed to the point where it's almost annoying. I don't understand how to approach the following compile error.
HelloWorld.java:70: error: no suitable method found for
add(Series)
lineChart.getData().add(series);
^
method List.add(int,Series) is not applicable
(actual and formal argument lists differ in length)
method List.add(Series) is not applicable
(actual argument Series cannot be converted to Series by method invocation conversion)
Here is my code:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.*;
import javafx.stage.Stage;
import javafx.geometry.Side;
import java.lang.*;
import java.net.*;
import java.io.*;
import java.util.*;
public class HelloWorld extends Application {
#Override public void start(Stage stage) {
Vector <String[]> v = new Vector<String[]>();
try{
File f = new File("audjpy.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
String[] data;
int count = 0;
while ((line = br.readLine()) != null) {
data = line.split(",");
if(count>0)v.add(data);
if(count == 400)break;
count++;
}
br.close();
}catch(IOException e){System.out.println(e);}
stage.setTitle("Line Chart Sample");
//defining the axes
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
yAxis.setSide(Side.RIGHT);
xAxis.setLabel("Number of Month");
//creating the chart
final LineChart<Number,Number> lineChart =
new LineChart<Number,Number>(xAxis,yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
//defining a series
XYChart.Series<Double, Double> series = new XYChart.Series<Double, Double>();
series.setName("My portfolio");
//populating the series with data
//<TICKER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>
Enumeration<String[]> e = v.elements();
while(e.hasMoreElements()){
String[] data = e.nextElement();
double x = Double.parseDouble(data[4]);
double y = Double.parseDouble(data[5]);
series.getData().add(new XYChart.Data<Double, Double>(x,y));
}
Scene scene = new Scene(lineChart,800,600);
lineChart.getData().add(1, series);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The reasons seems like it is because you are using Double and Number interchangeable, change every generic to Number and your problem should be solved.
#Override
public void start(Stage stage) {
Vector<String[]> v = new Vector<String[]>();
try {
File f = new File("audjpy.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
String[] data;
int count = 0;
while ((line = br.readLine()) != null) {
data = line.split(",");
if (count > 0) {
v.add(data);
}
if (count == 400) {
break;
}
count++;
}
br.close();
} catch (IOException e) {
System.out.println(e);
}
stage.setTitle("Line Chart Sample");
//defining the axes
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
yAxis.setSide(Side.RIGHT);
xAxis.setLabel("Number of Month");
//creating the chart
final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
lineChart.setTitle("Stock Monitoring, 2010");
//defining a series
XYChart.Series<Number, Number> series = new XYChart.Series<Number, Number>();
series.setName("My portfolio");
//populating the series with data
//<TICKER>,<DTYYYYMMDD>,<TIME>,<OPEN>,<HIGH>,<LOW>,<CLOSE>,<VOL>
Enumeration<String[]> e = v.elements();
while (e.hasMoreElements()) {
String[] data = e.nextElement();
double x = Double.parseDouble(data[4]);
double y = Double.parseDouble(data[5]);
series.getData().add(new XYChart.Data<Number, Number>(x,y));
}
Scene scene = new Scene(lineChart, 800, 600);
lineChart.getData().add(1, series);
stage.setScene(scene);
stage.show();
}
Related
I im currently having an issue with when performing an operation with my structure.
On form load, I am loading a comma delimited file with 6 indexes then using a 2d array i display the structured list's field to a grid view cell.
In the last for loop, perform the operation using my total field?
{
public partial class Form1 : Form
{
public struct Costomers
{
public string firstN;
public string lastN;
public string address;
public string item;
public double price;
public int quantity;
public double total;
}
public Form1()
{
InitializeComponent();
}
List<Costomers> consumers = new List<Costomers>();
private void Form1_Load(object sender, EventArgs e)
{
var inputfile = File.ReadAllLines("customers.txt");
for (int i = 0; i < inputfile.Length; i++)
{
var SplitArr = inputfile[i].Split(',');
// next declare a new instace of costomers
Costomers ConsumerInfo = new Costomers();
// the ConsumerInfo object now contains all of the fields i declared in the structer.
// next i want to access the Objects fields and assign them
ConsumerInfo.firstN = SplitArr[0];
ConsumerInfo.lastN = SplitArr[1];
ConsumerInfo.address = SplitArr[2];
ConsumerInfo.item = SplitArr[3];
ConsumerInfo.price = Convert.ToDouble(SplitArr[4]);
ConsumerInfo.quantity = Convert.ToInt32(SplitArr[5]);
//ConsumerInfo.total = consumers[i].price * consumers[i].quantity;
consumers.Add(ConsumerInfo);
}
// Next i need to disply each field in the grid view
// i will resue my code from section F to do this.
for (int i = 0; i < consumers.Count; i++)
{
dgInfo.Rows.Add();
dgInfo[0, i].Value = consumers[i].firstN;
dgInfo[1, i].Value = consumers[i].lastN;
dgInfo[2, i].Value = consumers[i].address;
dgInfo[3, i].Value = consumers[i].item;
dgInfo[4, i].Value = consumers[i].price;
dgInfo[5, i].Value = consumers[i].quantity;
}
// next in a seperat for loop i need too mutiply the price by the quantity
for (int i = 0; i < consumers.Count; i++)
{
Costomers totalPrice = new Costomers();
totalPrice.total = consumers[i].price * consumers[i].quantity;
dgInfo[6,i].Value = totalPrice.total;
}
}
}
}```
Second, because the file i load does not contain a index for total; how to i display the total in its own column?
Text file as shown below:
The, Batman, 123 Gotham Drive, bat belt, 193.82,17
The, Joker, 12432 Joker Way, Bat Spray, 19.99, 1022
Cat, Women, 8787 Meow St., Kibbles, 9.99, 4700
The, Penguin, 17 Waddel Ave., pointy cigarettes, 24.99, 51700
sidekick, Robin, 123 Gotham Drive, junior bat belt, 67.80, 10000
Adam, West, 1782 Hollywood Dr., hasbeen kit, 10305018.18, 1
I am learning hadoop mapreduce framework ,i am trying to join 2 data sets have first record(Text) in the line as the Key , i tried to search in stackoverflow previous posts but nothing worked out.Here i am trying to customize the InputFormat and trying to join with the ID which is first record in the each line of data set.
My input file1:
cdd8dde3-0349-4f0d-b97a-7ae84b687f9c,Esther,Garner,4071 Haven Lane,Okemos,MI
81a43486-07e1-4b92-b92b-03d0caa87b5f,Timothy,Duncan,753 Stadium Drive,Taunton,MA
File2 :
cdd8dde3-0349-4f0d-b97a-7ae84b687f9c,517-706-9565,EstherJGarner#teleworm.us,Waskepter38,noL2ieghie,MasterCard,5305687295670850
81a43486-07e1-4b92-b92b-03d0caa87b5f,508-307-3433,TimothyDDuncan#einrot.com,Conerse,Gif4Edeiba,MasterCard,5265896533330445
**Driver class:**
conf.setInputFormat(CompositeInputFormat.class);
String strJoinStmt = CompositeInputFormat.compose("inner",
KeyValueLongInputFormat.class, dirEmployeesData, dirSalaryData);
conf.set("mapred.join.expr", strJoinStmt);
conf.setNumReduceTasks(0);
dirOutput.getFileSystem(conf).delete(dirOutput);
TextOutputFormat.setOutputPath(conf, dirOutput);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setOutputFormat(TextOutputFormat.class);
**Custom RecordReader class:**
public class KeyValueLongLineRecordReader implements
RecordReader<Text, Text> {
private final LineRecordReader lineRecordReader;
private byte separator = (byte) ',';
private LongWritable dummyKey;
private Text innerValue;
public Class getKeyClass() {
return Text.class;
}
public Text createKey() {
return new Text("");
}
public Text createValue() {
return new Text();
}
public KeyValueLongLineRecordReader(Configuration job, FileSplit split)
throws IOException {
lineRecordReader = new LineRecordReader(job, split);
dummyKey = lineRecordReader.createKey();
innerValue = lineRecordReader.createValue();
String sepStr = job.get("key.value.separator.in.input.line", ",");
this.separator = (byte) sepStr.charAt(0);
}
public static int findSeparator(byte[] utf, int start, int length, byte sep) {
for (int i = start; i < (start + length); i++) {
if (utf[i] == sep) {
return i;
}
}
return -1;
}
/** Read key/value pair in a line. */
public synchronized boolean next(Text key, Text value)
throws IOException {
Text tKey = key;
Text tValue = value;
byte[] line = null;
int lineLen = -1;
if (!lineRecordReader.next(dummyKey, innerValue)) {
return false;
}
else
line = innerValue.getBytes();
lineLen = innerValue.getLength();
if (line == null)
return false;
int pos = findSeparator(line, 0, lineLen, this.separator);
if (pos == -1) {
tKey.set(new String(line, 0, lineLen));
tValue.set("");
} else {
int keyLen = pos;
byte[] keyBytes = new byte[keyLen];
System.arraycopy(line, 0, keyBytes, 0, keyLen);
int valLen = lineLen - keyLen - 1;
byte[] valBytes = new byte[valLen];
System.arraycopy(line, pos + 1, valBytes, 0, valLen);
tKey.set(new String(keyBytes));
tValue.set(valBytes);
}
return true;
}
}
**InputFormat class:**
public class KeyValueLongInputFormat extends
FileInputFormat<Text, Text> implements JobConfigurable {
private CompressionCodecFactory compressionCodecs = null;
#Override
public void configure(JobConf conf) {
compressionCodecs = new CompressionCodecFactory(conf);
}
protected boolean isSplitable(FileSystem fs, Path file) {
return compressionCodecs.getCodec(file) == null;
}
#Override
public RecordReader<Text, Text> getRecordReader(
InputSplit genericSplit, JobConf job, Reporter reporter)
throws IOException {
reporter.setStatus(genericSplit.toString());
return new KeyValueLongLineRecordReader(job, (FileSplit) genericSplit);
}
}
**Finally Mapper class:**
enter code here
public class MapperMapSideJoinLargeDatasets extends MapReduceBase implements
Mapper<Text, TupleWritable, Text, Text> {
Text txtKey = new Text("");
Text txtValue = new Text("");
#Override
public void map(Text key, TupleWritable value,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException {
if (value.toString().length() > 0) {
txtKey.set(key.toString());
String arrEmpAttributes[] = value.get(0).toString().split(",");
String arrDeptAttributes[] = value.get(1).toString().split(",");
txtValue.set(arrEmpAttributes[1].toString() + "\t"
+ arrEmpAttributes[2].toString() + "\t"
+ arrDeptAttributes[0].toString());
output.collect(txtKey, txtValue);
}
}
In the logs Map input records is 0.No output can be seen on hdfs .Someone please help me to understand this issue. Thanks
The problem lies in the Driver class where in InputFormat mentioned as KeyValueLongInputFormat.class in the strJoinStmt property which actually works for LongWritable key and Text value. Instead KeyValueTextInputFormat.class can be used when both the key and value are of Text type.As the input is comma separated file, also specify a custom delimiter as comma by setting a property in the job's configuration object as follows in the Driver class.conf.set("key.value.separator.in.input.line",",");
For Complete details please check the below example:
https://github.com/sudha-pn/CompositeInputFormat
////OSMdroid centered on the markers////
I add markers, I need to map the maximum increases or decreases in such a way that all markers were visible
my code:
public class mapcode extends Activity {
globalvar appState;
int stats=0;
private MapView mapView;
private IMapController mapController;
private SimpleLocationOverlay mMyLocationOverlay;
private ScaleBarOverlay mScaleBarOverlay;
ItemizedIconOverlay<OverlayItem> currentLocationOverlay;
DefaultResourceProxyImpl resourceProxy;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.map);
appState = ((globalvar) getApplicationContext());
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setTileSource(TileSourceFactory.MAPNIK);
// mapView.setBuiltInZoomControls(true); //кнопка ZOOM +-
mapView.setMultiTouchControls(true);
mapController = this.mapView.getController();
mapController.setZoom(2);
this.mMyLocationOverlay = new SimpleLocationOverlay(this);
this.mapView.getOverlays().add(mMyLocationOverlay);
this.mScaleBarOverlay = new ScaleBarOverlay(this);
this.mapView.getOverlays().add(mScaleBarOverlay);
// this.mapView
/////////////////
resourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
GeoPoint currentLocation = new GeoPoint(55.860863,37.115046);
GeoPoint currentLocation2 = new GeoPoint(63.557413,-156.102119);
OverlayItem myLocationOverlayItem = new OverlayItem("Here", "Current Position", currentLocation);
Drawable myCurrentLocationMarker = this.getResources().getDrawable(R.drawable.a);
myLocationOverlayItem.setMarker(myCurrentLocationMarker);
// myLocationOverlayItem.setMarkerHotspot(HotspotPlace.CENTER); //no working/
final ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
items.add(myLocationOverlayItem);
myLocationOverlayItem = new OverlayItem("Here", "Current Position", currentLocation2);
myCurrentLocationMarker = this.getResources().getDrawable(R.drawable.a);
myLocationOverlayItem.setMarker(myCurrentLocationMarker);
// myLocationOverlayItem.setMarkerHotspot(HotspotPlace.CENTER); // no working
items.add(myLocationOverlayItem);
currentLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
return true;
}
public boolean onItemLongPress(final int index, final OverlayItem item) {
return true;
}
}, resourceProxy);
this.mapView.getOverlays().add(this.currentLocationOverlay);
}
I added two markers, but only one is visible:
and I need to osmdroid is centered and immediately showed both marker
I think you want something like this:
int minLat = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLong = Integer.MIN_VALUE;
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
for (OverlayItem item : items) {
GeoPoint point = item.getPoint();
if (point.getLatitudeE6() < minLat)
minLat = point.getLatitudeE6();
if (point.getLatitudeE6() > maxLat)
maxLat = point.getLatitudeE6();
if (point.getLongitudeE6() < minLong)
minLong = point.getLongitudeE6();
if (point.getLongitudeE6() > maxLong)
maxLong = point.getLongitudeE6();
}
BoundingBoxE6 boundingBox = new BoundingBoxE6(maxLat, maxLong, minLat, minLong);
mMapView.zoomToBoundingBox(boundingBox);
You can calculate boundingBox by BoundingBox.fromGeoPoints(geoPoints)
fun zoomToBounds(points: List<LatLng>) {
val geoPoints = points.map { GeoPoint(it.latitude, it.longitude) }
val boundingBox = BoundingBox.fromGeoPoints(geoPoints)
mapView.zoomToBoundingBox(boundingBox, true)
}
It is also possible to have some paddings by using zoomtoBoundingBox overloaded method and setting the pBorderSizeInPixels parameter
public double zoomToBoundingBox(
final BoundingBox pBoundingBox,
final boolean pAnimated,
final int pBorderSizeInPixels,
final double pMaximumZoom,
final Long pAnimationSpeed
)
I need to convert:
List<Map>([{1,2},{2,3}])
To:
List<List>([[1,2],[2,3]])
Can anyone help me with example for this ...
Thanks
I would suggest making a list of specific objects instead of a raw list that the get(0) returns the key and get(1) the value as follows:
List<List<Pair>> convert(List<Map<Integer,Integer> mapList){
List<List<Pair>> listOfList = new ArrayList<List<Pair>>();
for(Map<Integer,Integer> map:mapList){
List<Pair> list = new ArrayList<Pair>();
for(Entry<Integer,Integer> e:map.entrySet()){
list.add(Pair(e.getKey(),e.getValue());
}
listOfList.add(list);
}
return listOfList;
}
class Pair{
Integer first;
Integer second;
//constructor
}
You can try the following Code:
import java.util.*;
class ListOfMapToListOfList
{
public static List<List> toList(List<Map<Integer,Integer>> lList)//method to convert List<Map> to List<List>
{
List<List> list = new ArrayList<List>();
for (int i = 0 ; i < lList.size() ; i++)
{
Map<Integer,Integer> map = lList.get(i);
List<Integer> aList = new ArrayList<Integer>();
Set<Integer> keySet = map.keySet();
for (Integer key : keySet)
{
aList.add(key);
aList.add(map.get(key));
}
list.add(aList);
}
return list;
}
public static void main(String[] args) //main body
{
List<Map<Integer,Integer>> list1 = new ArrayList<Map<Integer,Integer>>();
Map<Integer,Integer> map1 = new HashMap<Integer,Integer>();
map1.put(1,2);
Map<Integer,Integer> map2 = new HashMap<Integer,Integer>();
map2.put(1,2);
list1.add(map1);list1.add(map2);
System.out.println(list1);
System.out.println(toList(list1));//Conversion is done here..and out put is shown.
}
}
Does exist any method which bind BooleanProperty to conjunction of every element in ObservableList?
ObservableList<BooleanProperty> list;
list = FXCollections.observableList(new ArrayList<BooleanProperty>));
BooleanProperty emptyProperty = new SimpleBooleanProperty();
emptyProperty.bind(Bindings.conunction(list));`
Is there such a method as:
static BooleanBinding conjunction(ObservableList<BooleanProperty> op)
There is no conjunction api defined in the JavaFX 2.2 platform.
You could create a ConjunctionBooleanBinding (aka AllTrueBinding) by subclassing BooleanBinding.
Accept the ObservableList in the constructor of your new class, and use the low level binding api in an overridden computeValue method to set the binding value based upon logically anding together all of the boolean values in the list.
Here is a sample implementation. The sample could be further performance optimized and make use of WeakReferences, so it does not require manual disposition.
import javafx.beans.binding.BooleanBinding;
import javafx.beans.property.BooleanProperty;
import javafx.collections.*;
public class AllTrueBinding extends BooleanBinding {
private final ObservableList<BooleanProperty> boundList;
private final ListChangeListener<BooleanProperty> BOUND_LIST_CHANGE_LISTENER =
new ListChangeListener<BooleanProperty>() {
#Override public void onChanged(
ListChangeListener.Change<? extends BooleanProperty> change
) {
refreshBinding();
}
};
private BooleanProperty[] observedProperties = {};
AllTrueBinding(ObservableList<BooleanProperty> booleanList) {
booleanList.addListener(BOUND_LIST_CHANGE_LISTENER);
boundList = booleanList;
refreshBinding();
}
#Override protected boolean computeValue() {
for (BooleanProperty bp: observedProperties) {
if (!bp.get()) {
return false;
}
}
return true;
}
#Override public void dispose() {
boundList.removeListener(BOUND_LIST_CHANGE_LISTENER);
super.dispose();
}
private void refreshBinding() {
super.unbind(observedProperties);
observedProperties = boundList.toArray(new BooleanProperty[0]);
super.bind(observedProperties);
this.invalidate();
}
}
And here is a test harness to demonstrate how it works:
import java.util.*;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
public class ListBindingTest {
final BooleanProperty a = new SimpleBooleanProperty(true);
final BooleanProperty b = new SimpleBooleanProperty(true);
final BooleanProperty c = new SimpleBooleanProperty(true);
final BooleanProperty d = new SimpleBooleanProperty(true);
final ObservableList<BooleanProperty> booleanList =
FXCollections.observableArrayList(a, b, c, d);
public static void main(String[] args) {
new ListBindingTest().test();
}
private void test() {
AllTrueBinding at = new AllTrueBinding(booleanList);
System.out.println(at.get() + forArrayString(booleanList));
b.set(false);
System.out.println(at.get() + forArrayString(booleanList));
b.set(true);
System.out.println(at.get() + forArrayString(booleanList));
booleanList.add(new SimpleBooleanProperty(false));
System.out.println(at.get() + forArrayString(booleanList));
booleanList.remove(3, 5);
System.out.println(at.get() + forArrayString(booleanList));
at.dispose();
}
private String forArrayString(List list) {
return " for " + Arrays.toString(list.toArray());
}
}
You can easily implement the method as follows:
public static BooleanBinding conjunction(ObservableList<BooleanProperty> list){
BooleanBinding and = new SimpleBooleanProperty(true).and(list.get(0));
for(int i = 1; i < list.size(); i++){
and = and.and(list.get(i));
}
return and;
}