The method clone() from the type Object is not visible - clone

for the life of me I can't figure out what is wrong with this code, please help. I have three classes, GeometricObject, Octagon which extends GeometricObject and TestOctagon which is being used to test the Octagon class. When I run the TestOctagon class I get this error:
The method clone() from the type Object is not visible
Here is my code:
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
protected GeometricObject() {
}
protected GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
import java.lang.Comparable;
import java.lang.Cloneable;
public class Octagon extends GeometricObject implements Comparable<Octagon>, Cloneable{
double side;
public Octagon() {
}
public Octagon(double side) {
this.side = side;
}
public Octagon(double side, String color, boolean filled) {
this.side = side;
setColor(color);
setFilled(filled);
}
public double getSide() {
return side;
}
public void setSide(double side) {
this.side = side;
}
public double getArea() {
return (2+4/Math.sqrt(2))*side*side;
}
public double getPerimeter() {
return 8*side;
}
#Override
public int compareTo(Octagon o) {
if (getArea() > o.getArea())
return 1;
else if (getArea() < o.getArea())
return -1;
else
return 0;
}
#Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class TestOctagon {
public static void main(String[] args) {
// TODO Auto-generated method stub
GeometricObject oc1 = new Octagon(5);
System.out.println(oc1.getArea());
System.out.println(oc1.getPerimeter());
GeometricObject oc2 = (GeometricObject)oc1.clone();
}
}

Don,
Please note that the access specifier for method Object::clone() is protected. It is not accessible from your TestOctagon class as you are invoking this method on object of type GeometriObject (oc1) where the clone method is still protected as neither it or its super classes have overridden it. Try moving the clone method from Octagon class to GeometriObject class. Please retain the public access specifier. Refer this sample on how to do it http://www.javatpoint.com/object-cloning

Related

trino udf how to create a aggregate function for the window function

I tried to write a udf function to calculate my data. In the trino's docs, I knew I should to write a function plugin and I succeed to execute my udf aggregate function sql.
But when I write sql with aggregate function and window function, the sql executed failed.
The error log is com.google.common.util.concurrent.ExecutionError: java.lang.NoClassDefFoundError: com/example/ListState.
I think I may implement the interface about the window function.
The ListState.java file code
#AccumulatorStateMetadata(stateSerializerClass = ListStateSerializer.class, stateFactoryClass = ListStateFactory.class)
public interface ListState extends AccumulatorState {
List<String> getList();
void setList(List<String> value);
}
The ListStateSerializer file code
public class ListStateSerializer implements AccumulatorStateSerializer<ListState>
{
#Override
public Type getSerializedType() {
return VARCHAR;
}
#Override
public void serialize(ListState state, BlockBuilder out) {
if (state.getList() == null) {
out.appendNull();
return;
}
String value = String.join(",", state.getList());
VARCHAR.writeSlice(out, Slices.utf8Slice(value));
}
#Override
public void deserialize(Block block, int index, ListState state) {
String value = VARCHAR.getSlice(block, index).toStringUtf8();
List<String> list = Arrays.asList(value.split(","));
state.setList(list);
}
}
The ListStateFactory file code
public class ListStateFactory implements AccumulatorStateFactory<ListState> {
public static final class SingleListState implements ListState {
private List<String> list = new ArrayList<>();
#Override
public List<String> getList() {
return list;
}
#Override
public void setList(List<String> value) {
list = value;
}
#Override
public long getEstimatedSize() {
if (list == null) {
return 0;
}
return list.size();
}
}
public static class GroupedListState implements GroupedAccumulatorState, ListState {
private final ObjectBigArray<List<String>> container = new ObjectBigArray<>();
private long groupId;
#Override
public List<String> getList() {
return container.get(groupId);
}
#Override
public void setList(List<String> value) {
container.set(groupId, value);
}
#Override
public void setGroupId(long groupId) {
this.groupId = groupId;
if (this.getList() == null) {
this.setList(new ArrayList<String>());
}
}
#Override
public void ensureCapacity(long size) {
container.ensureCapacity(size);
}
#Override
public long getEstimatedSize() {
return container.sizeOf();
}
}
#Override
public ListState createSingleState() {
return new SingleListState();
}
#Override
public ListState createGroupedState() {
return new GroupedListState();
}
}
Thanks for help!!!!
And I found the WindowAccumulator class in the trino source code. But I don't know how to use it.
How to create a aggregate function for window function?

Grid SelectionMode.MULTI is missing the header checkbox to select all for BackEndDataProvider

I am working with a new application written to version 8 (currently testing with 8.1.0.rc2).
The issue surrounds the "select all" checkbox that appears in the header of a Grid when using SelectionMode.MULTI. In particular, the problem is that the checkbox appears and operates as expected when the DataProvider implements InMemoryDataProvider, but the checkbox does not appear when the DataProvider implements BackEndDataProvider.
The following code creates two grids that differ only in whether they use InMemory or BackEnd:
public class Test {
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
private String name;
}
public class TestView extends BaseView {
public TestView() {
super("Test");
addComponent(new TestGrid(new TestDataProvider0()));
addComponent(new TestGrid(new TestDataProvider1()));
}
}
public class TestGrid extends Grid<Test> {
public TestGrid(DataProvider<Test, ?> dataProvider) {
setHeightByRows(4);
setSelectionMode(SelectionMode.MULTI);
setDataProvider(dataProvider);
addColumn(Test::getName).setCaption("Name");
}
}
public class TestDataProvider0 extends AbstractDataProvider<Test, SerializablePredicate<Test>> implements
BackEndDataProvider<Test, SerializablePredicate<Test>> {
public Stream<Test> fetch(Query<Test, SerializablePredicate<Test>> query) {
List<Test> tests = new ArrayList<>(query.getLimit());
for (int i = 0; i < query.getLimit(); i++) {
Test test = new Test();
test.setName(String.valueOf(query.getOffset() + i));
tests.add(test);
}
return tests.stream();
}
public int size(Query<Test, SerializablePredicate<Test>> query) {
return 100;
}
public void setSortOrders(List<QuerySortOrder> sortOrders) {
}
}
public class TestDataProvider1 extends AbstractDataProvider<Test, SerializablePredicate<Test>> implements
InMemoryDataProvider<Test> {
public Stream<Test> fetch(Query<Test, SerializablePredicate<Test>> query) {
List<Test> tests = new ArrayList<>(query.getLimit());
for (int i = 0; i < query.getLimit(); i++) {
Test test = new Test();
test.setName(String.valueOf(query.getOffset() + i));
tests.add(test);
}
return tests.stream();
}
public int size(Query<Test, SerializablePredicate<Test>> query) {
return 100;
}
public SerializablePredicate<Test> getFilter() {
return null;
}
public void setFilter(SerializablePredicate<Test> filter) {
}
public SerializableComparator<Test> getSortComparator() {
return null;
}
public void setSortComparator(SerializableComparator<Test> comparator) {
}
}
Here is how the grids are rendered:
Have I missed a critical step in setting up my BackEnd-based data provider/grid? The related documentation does not seem to address this issue.
Is there a known issue related to this?
Is select-all not available by design? Obviously, this could interact really badly with the concept of lazy-loading on a large data set...
MultiSelectionModelImpl has this method:
protected void updateCanSelectAll() {
switch (selectAllCheckBoxVisibility) {
case VISIBLE:
getState(false).selectAllCheckBoxVisible = true;
break;
case HIDDEN:
getState(false).selectAllCheckBoxVisible = false;
break;
case DEFAULT:
getState(false).selectAllCheckBoxVisible = getGrid()
.getDataProvider().isInMemory();
break;
default:
break;
}
}
This indicates that the default behavior for non-in-memory providers is to not show the select-all checkbox, but that this behavior can be overridden by setting the visibility to VISIBLE.
Tweaking the original code here:
public class TestGrid extends Grid<Test> {
public TestGrid(DataProvider<Test, ?> dataProvider) {
setHeightByRows(4);
MultiSelectionModel<Test> selectionModel = (MultiSelectionModel<Test>) setSelectionMode(SelectionMode.MULTI);
selectionModel.setSelectAllCheckBoxVisibility(SelectAllCheckBoxVisibility.VISIBLE);
setDataProvider(dataProvider);
addColumn(Test::getName).setCaption("Name");
}
}
Specifically, this call is required for the checkbox to appear for data providers that implement BackEndDataProvider:
MultiSelectionModel<Test> selectionModel = (MultiSelectionModel<Test>) setSelectionMode(SelectionMode.MULTI);
selectionModel.setSelectAllCheckBoxVisibility(SelectAllCheckBoxVisibility.VISIBLE);
With this change, the select-all checkbox now appears:

nativescript: cannot convert object to Landroid/view/textureview/surfacetexturelistener

I am trying to implement java interface in nativescript plugin (typescript)
but when i call view it gives me this error. cannot convert object to Landroid/view/textureview/surfacetexturelistener
I assume my typescript class is not implementing interface SurfaceTextureListener. But I added all 4 method needed.
here is working java code
public class FFmpegRecordActivity extends AppCompatActivity implements
TextureView.SurfaceTextureListener, View.OnClickListener {
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPreview = (FixedRatioCroppedTextureView) findViewById(R.id.camera_preview);
mCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
// Switch width and height
mPreview.setPreviewSize(previewHeight, previewWidth);
mPreview.setCroppedSizeWeight(videoWidth, videoHeight);
mPreview.setSurfaceTextureListener(this);
}
#Override
public void onSurfaceTextureAvailable(final SurfaceTexture surface, int width, int height) {
startPreview(surface);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
}
...
}
Typescript code I am trying
export class NumberPicker extends view.View {
public _createUI() {
// this._android = new android.widget.NumberPicker(this._context);
this.mCameraId = android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT;
this._android = new com.github.crazyorr.ffmpegrecorder.FixedRatioCroppedTextureView(this._context);
this._android.setPreviewSize(100, 100);
this._android.setCroppedSizeWeight(100, 100);
this._android.setSurfaceTextureListener(this);
console.log("my-plugin - Android : _createUI")
};
public onSurfaceTextureAvailable(surface, width, height) {
this.startPreview(surface);
}
public onSurfaceTextureSizeChanged(surface, width, height) {
}
public onSurfaceTextureDestroyed(surface): Boolean {
return true;
}
public onSurfaceTextureUpdated(surface) {
}
}
I tried adding
declare var android:any;
// #Interfaces([android.view.TextureView.SurfaceTextureListener]) /* the interfaces that will be inherited by the resulting MyVersatileCopyWriter class */
export class NumberPicker extends view.View implements {
// interfaces:[android.view.TextureView.SurfaceTextureListener]
But all got error of cant find android in ts compiler
I believe you need to add implements android.view.TextureView.SurfaceTextureListener to your component

Factory Pattern: Enum Parameter vs Explicit Method Name?

Say you have a factory that returns instances of ILightBulb. Two ways (there may be more) of implementing the factory are as follows:
Option 1 - Passing in an enum type
enum LightBulbType
{
Incandescent,
Halogen,
Led,
}
class ILightBulbFactory
{
public ILightBulb Create(LightBulbType type)
{
switch (type)
{
case LightBulbType.Incandescent:
return new IncandescentBulb();
case LightBulbType.Halogen:
return new HalogenBulb();
case LightBulbType.Led:
return new LedBulb();
}
}
}
Option 2 - Explicit method names
class ILightBulbFactory
{
public ILightBulb CreateIncandescent()
{
return new IncandescentBulb();
}
public ILightBulb CreateHalogen()
{
return new HalogenBulb();
}
public ILightBulb CreateLed()
{
return new LedBulb();
}
}
Which method is most preferable, and why?
Thanks.
In java, you can solve it in the enum, thus making sure that if you add new enums, all your code will remain working, instead of forgetting to add statements to your case.
enum LightBulbType
{
Incandescent{
#Override
public ILightBulb getInstance() {
return new IncandescentBulb();
}
},
Halogen{
#Override
public ILightBulb getInstance() {
return new HalogenBulb();
}
},
Led{
#Override
public ILightBulb getInstance() {
return new LedBulb();
}
};
public abstract ILightBulb getInstance();
}
class ILightBulbFactory
{
public ILightBulb Create(LightBulbType type)
{
return type.getInstance();
}
}
The equivalent for c# would be
public sealed class LightBulbType
{
public static readonly LightBulbType Incandescent = new
LightBulbType("Incandescent", new IncandescentBulb());
public static readonly LightBulbType Halogen = new
LightBulbType("Halogen", new HalogenBulb());
public static readonly LightBulbType LedBulb = new LightBulbType("Led",
new LedBulb());
public static IEnumerable<LightBulbType> Values
{
get
{
yield return Incandescent;
yield return Halogen;
yield return LedBulb;
}
}
private string Name { get; set; }
private ILightBulb Instance { get;}
private LightBulbType(string name, ILightBulb instance)
{
this.Name = name;
this.Instance = instance;
}
public override string ToString() => Name;
public ILightBulb GetInstance()
{
return Instance;
}
}
public interface ILightBulb
{
}
public class IncandescentBulb : ILightBulb
{
}
public class HalogenBulb : ILightBulb
{
}
public class LedBulb : ILightBulb
{
}
public static class LightBulbFactory
{
public static ILightBulb Create(LightBulbType type)
{
return type.GetInstance();
}
}
For call
ILightBulb halogenBulb = new HalogenBulb();
ILightBulb incandescentBulb = new IncandescentBulb();
ILightBulb ledBulb = new LedBulb();
or
ILightBulb halo = LightBulbFactory.Create(LightBulbType.Halogen);
ILightBulb inca = LightBulbFactory.Create(LightBulbType.Incandescent);
ILightBulb led = LightBulbFactory.Create(LightBulbType.LedBulb);

GWT retrieve list from datastore via serviceimpl

Hi I'm trying to retrieve a linkedhashset from the Google datastore but nothing seems to happen. I want to display the results in a Grid using GWT on a page. I have put system.out.println() in all the classes to see where I go wrong but it only shows one and I don't recieve any errors. I use 6 classes 2 in the server package(ContactDAOJdo/ContactServiceImpl) and 4 in the client package(ContactService/ContactServiceAsync/ContactListDelegate/ContactListGui). I hope someone can explain why this isn't worken and point me in the right direction.
public class ContactDAOJdo implements ContactDAO {
#SuppressWarnings("unchecked")
#Override
public LinkedHashSet<Contact> listContacts() {
PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
String query = "select from " + Contact.class.getName();
System.out.print("ContactDAOJdo: ");
return (LinkedHashSet<Contact>) pm.newQuery(query).execute();
}
}
public class ContactServiceImpl extends RemoteServiceServlet implements ContactService{
private static final long serialVersionUID = 1L;
private ContactDAO contactDAO = new ContactDAOJdo() {
#Override
public LinkedHashSet<Contact> listContacts() {
LinkedHashSet<Contact> contacts = contactDAO.listContacts();
System.out.println("service imp "+contacts);
return contacts;
}
}
#RemoteServiceRelativePath("contact")
public interface ContactService extends RemoteService {
LinkedHashSet<Contact> listContacts();
}
public interface ContactServiceAsync {
void listContacts(AsyncCallback<LinkedHashSet <Contact>> callback);
}
public class ListContactDelegate {
private ContactServiceAsync contactService = GWT.create(ContactService.class);
ListContactGUI gui;
void listContacts(){
contactService.listContacts(new AsyncCallback<LinkedHashSet<Contact>> () {
public void onFailure(Throwable caught) {
gui.service_eventListContactenFailed(caught);
System.out.println("delegate "+caught);
}
public void onSuccess(LinkedHashSet<Contact> result) {
gui.service_eventListRetrievedFromService(result);
System.out.println("delegate "+result);
}
});
}
}
public class ListContactGUI {
protected Grid contactlijst;
protected ListContactDelegate listContactService;
private Label status;
public void init() {
status = new Label();
contactlijst = new Grid();
contactlijst.setVisible(false);
status.setText("Contact list is being retrieved");
placeWidgets();
}
public void service_eventListRetrievedFromService(LinkedHashSet<Contact> result){
System.out.println("1 service eventListRetreivedFromService "+result);
status.setText("Retrieved contactlist list");
contactlijst.setVisible(true);
this.contactlijst.clear();
this.contactlijst.resizeRows(1 + result.size());
int row = 1;
this.contactlijst.setWidget(0, 0, new Label ("Voornaam"));
this.contactlijst.setWidget(0, 1, new Label ("Achternaam"));
for(Contact contact: result) {
this.contactlijst.setWidget(row, 0, new Label (contact.getVoornaam()));
this.contactlijst.setWidget(row, 1, new Label (contact.getVoornaam()));
row++;
System.out.println("voornaam: "+contact.getVoornaam());
}
System.out.println("2 service eventListRetreivedFromService "+result);
}
public void placeWidgets() {
System.out.println("placewidget inside listcontactgui" + contactlijst);
RootPanel.get("status").add(status);
RootPanel.get("contactlijst").add(contactlijst);
}
public void service_eventListContactenFailed(Throwable caught) {
status.setText("Unable to retrieve contact list from database.");
}
}
It could be the query returns a lazy list. Which means not all values are in the list at the moment the list is send to the client. I used a trick to just call size() on the list (not sure how I got to that solution, but seems to work):
public LinkedHashSet<Contact> listContacts() {
final PersistenceManager pm = PmfSingleton.get().getPersistenceManager();
try {
final LinkedHashSet<Contact> contacts =
(LinkedHashSet<Contact>) pm.newQuery(Contact.class).execute();
contacts.size(); // this triggers to get all values.
return contacts;
} finally {
pm.close();
}
}
But I'm not sure if this is the best practice...

Resources