I want to print a varValue of an object with it's related review objects.
This is really frustrating. I would like to print out the name of the game object alongside the comment objects related to them. The reviews/replies are called by reference of the the object. I can tell the compiler knows the reference because it groups reviews and replies by game.
I want it like this:
Reviews for The Witcher 3 --- the part I want, the rest is easy.
Rev1/ User ID: u1; Name: JD; "This game is timeless!"
Rep1/ User ID: u2; Name: Boss; "Really? You run around in imaginary fields hunting for imaginary creatures...lame."
Rep2/ User ID: u1; Name: JD; "Blah, blah, something."
Other games ect...
Reviews group perfect for game type and replies group perfectly under the review. But I can't find a way to show the game the reviews are for. Is there a way?
Any help would be great.
review and reply methods are called like this:
game1.addReviews(review1);
review1.addReply(reply1);
reply1.addReply(reply2);
....
public class Comment {
protected List<Comment> reply = new ArrayList<Comment>();
private User user;
private String usrComment;
public Comment() {
}
public void addReply(Comment r) {
this.reply.add(r);
}
@Override
public String toString() {
return this.user.getUsr() + '"' + this.usrComment + '"';
}
...
public abstract class Content {
protected List<Comment> Review = new ArrayList<Comment>();
private String ID;
private String Application_Name;
// constructor to take ID, name and price of app
public Content(String iD, String application_Name, double price) {
super();
ID = iD;
Application_Name = application_Name;
Price = price;
}
public void addReviews(Comment a) {
this.Review.add(a);
}
}
...
public class Game extends Content {
private boolean isMultiPlayer;
private OS o;
private double Price = 0;
public Game(String iD, String application_Name, double price, boolean isMultiPlayer, OS o) {
super(iD, application_Name, price);
this.isMultiPlayer = isMultiPlayer;
this.o = o;
}
}
1 answer
-
answered 2018-05-16 10:35
N Woods
This was silly. The object (game) is the object calling the method and passing another object as an argument. So any method or value related to the calling game object can be accessed within the method called. I was using two advanced loops and recursion, so I may have confused myself a little.
See also questions close to this topic
-
Can searchResponse.getHits().getHits(); throw nullpointer exception
We are getting a nullpointerexception at searchResponse.getHits().getHits(); I'm totally new to elastic search and don't know how it works but need to analyse this issue.
Let me know if it throws nullpointerexception in any case ? If it throws how to handle this ?
-
Is it possible to disable SSL certificate checking in the amazon kinesis consumer library v2?
When developing a Kinesis Consumer using Version 2 of the Kinesis Consumer Library and overriding the Dynamo DB endpoint to a localstack endpoint the library fails to create the leasing table due to SSL handshake errors.
I can confirm that creating the table succeeds when using AWS' Dynamo DB, but as soon as I override the endpoint url to a localstack url the Dynamo DB client fails to create the lease table after multiple retries. The stack trace isn't that useful but Wireshark shows all of the SSL handshake errors so I can only assume the Amazon SDK is not accepting the localstack certificate. I cannot find any mention of how to disable certificate verification using the
software.amazon.awssdk
package.Region region = Region.of("us-east-1"); DefaultCredentialsProvider credentialsProvider = DefaultCredentialsProvider.create(); DynamoDbAsyncClient dynamoClient = DynamoDbAsyncClient.builder() .region(region) .endpointOverride(URI.create("https://localhost:4569")) .credentialsProvider(credentialsProvider) .build();
/edit This is based off the example from Amazon found here: https://docs.aws.amazon.com/streams/latest/dev/kcl2-standard-consumer-java-example.html
-
Problem creating an OracleDataSource correctly from tomcat context.xml
In the project im working at the following problem occurs:
We use Database connections defined in our tomcat context.xml. For now this has worked without problems.
Example:
<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" logAbandoned="true" maxIdle="10" maxTotal="100" maxWaitMillis="5000" name="NAME" password="PASSWORD" removeAbandonedOnMaintenance="true" removeAbandonedTimeout="60" type="javax.sql.DataSource" url="URL" username="USERNAME" />
This type of resource definition is used in the webapp for every database connection, retreiving the datasource like this:
InitialContext ctx = new InitialContext(); DataSource dsAux = (DataSource) ctx.lookup(dbCon);
The problem begins here. Oracle queues are being used with jms (Java Message System) for a lot of processes. For this, as it is coded right now, we need an OracleDataSource that can be created having only the db url, password and username.
My question is, is it possible in any way or form to get all the data needed from the context for this type of datasource correctly? I have tried changing the datasource type without any luck, unwrapping the already created datasource to try and create an OracleDataSource, in the end, the only possible solution I have come up with is to change how database connections are saved.
-
How can I wrap my input field with a <div> tag when using with Symfony formbuilder?
I am creating an input field with Symfony:
$formBuilder->add($field['fieldName'], TextType::class, array('attr' => array('class' => 'form-control')));
The output is:
<input type="text" id="form_color" name="form[color]" class="form-control">
The output I would need is:
<div class="cp input-group colorpicker-component"> <input type="text" id="form_color" name="form[color]" class="form-control" /> <span class="input-group-addon"><i></i></span> </div>
This means I somehow have to add a parent to the specific form field. I cannot add it to the actual form, because this parent div is only added to the field in specific cases. Is there a way to do it in the formbuilder?
-
JavaFX: where is the best place to declare nodes of controller
I created a LoginFieldsController custom controller that inherits from the VBox class. Later in the programs I use this controller as an ordinary node like Button, TextFiled, etc. Please note that I only write pure Java code, I do not use FXML.
Question: is it better to declare LoginFieldsController nodes as the fields of the LoginFieldsController class, or inside the LoginFieldsController constructor? Outside the constructor I was doing nothing.
In other words, it would be better like this:
public class LoginFieldsController extends VBox { private TextField loginField; private TextField passwordField; public LoginFieldsController( ... ) { loginField = new TextFeild("Login"); passwordField = new TextFeild("Password"); this.addAll(loginField, passwordField); ... }
Or that:
public class LoginFieldsController extends VBox { //no fields in that class public LoginFieldsController( ... ) { TextField loginField = new TextFeild("Login"); TextField passwordField = new TextFeild("Password"); this.addAll(loginField, passwordField); ... }
-
Bundle specific exception listener
Lets say I have 3 different bundles.
I am adding to event listeners to each bundle. When there is any exception in Bundle1, then Bundle2 and Bundle3 should not listen it.
I have tested it adding to each bundle eventlistener but when there is any error in Bundle2 then Bundle1 will listen try to handle it as well.
How to handle this situation?
if needed any code then here is my service.yaml in bundle:
kernel.listener.test1bundle.exceptionlistener: class: App\test1bundle\EventListener\ExceptionListener tags: - { name: kernel.event_listener, event: kernel.exception}
and here is my exception listener:
public function onKernelException(GetResponseForExceptionEvent $event) { // You get the exception object from the received event $exception = $event->getException(); $message = [ "errors" => [ [ "title" => "Internal error in test1 bundle", "detail" => $exception->getMessage() ] ] ]; $response = new JsonResponse(); $response->setData($message); $response->headers->set('Content-Type', 'application/problem+json'); $event->setResponse($response); }
i read that it is possible just listen controller. But in that case will controller listener listen exceptions as well?
-
Avoid rerender in React caused by objects literal : how to do with variables in the object?
I read in this article React is Slow, React is Fast: Optimizing React Apps in Practice that :
In fact, each time you pass an object literal as prop to a child component, you break purity.
Alright, I got it. So the best to avoid that is to create a variable with the object, and insert this variable in the prop, like that :
import React from 'react'; const style = { marginTop: 10 }; const AnyComponent = (props) => ( <div style={style}> ... </div> )
But what if the style prop depend on a received prop ? Where should be the object ? So for instance, I have this component:
import React from 'react'; const AnyComponent = (props) => ( <div style={{ marginTop: props.marginTop }}> ... </div> )
Is it a good practice to do:
import React from 'react'; const style = (marginTop) => ({ marginTop }) const AnyComponent = (props) => ( <div style={style(props.marginTop)}> ... </div> )
[EDIT] I forgot to say that most of my components have state, so in that case, is it a good idea to do :
import React from 'react'; class App extends React.Component { style = () => ({ marginTop: this.props.marginTop }) render() { return( <div style={this.style()}> </div> ) } }
-
Appending to attribute of a specific object, where objects are stored in a dict
I am having trouble appending an element to a list, where the list is an attribute of a custom class I have created. The object containing the list should be accessible through a dict.
For context, I am creating a game which can have multiple players, each player has a 'Player' object associated with them that tracks their socket, name, character a list of their previous moves and kill status:
class Player(): def __init__(self, sock, name, char, moves, kill_status): self.sock = sock self.name = name self.char = char self.moves = moves self.kill_status = kill_status
These Player objects are stored in the PLAYER dict, which resembles the following:
PLAYER = { 1: Player(sock, name, char, moves, kill_status) 2: Player(sock, name, char, moves, kill_status) }
So that if I want to access the name for player1 for example, I simply use:
player1_name = PLAYER[1].name
the moves attribute is initially passed in as an empty list, so that I can append an individual player's moves as they make them.
The issue is that when i use
PLAYER[1].moves.append(move)
The move is added to the list of every player in the dict, so that even
PLAYER[2].moves
would return a list including the move I was trying to add to player 1
How can I add the move specifically to the list of Player it was made by?
EDIT:
This is how a create the dict initially:
moves = [] for i in range(1, LOBBY_SIZE + 1): PLAYER[i] = pi.Player(None, name, None, moves, kill_status)
-
Is there a pythonic way to trigger an instance method when calling an attribute
I have an object some methods of which require an attribute
b
. This attribute is pretty expensive to get so I'd rather not defining it in the__init__
but calling the relevant method (method_A
) IIF the method require it. Here is how I fixed my problem with an ugly ifclass MyClass: def __init__(self, something): self.attr_a = something def method_A(self): self.attr_b = SomeExpensiveFunction() def method_B(self): if hasattr(self, attr_b) == False: # quick and dirty fix self.method_A() do_somehing_with(self.attr_b)
I wondered if there were a more elegant way to do it, as I need to add this clause at the beginning of every method requiring
attr_b
. It would be nice if, every time I calledself.attr_b
, Python would check whether or not the attribute is already defined and calculate it if needed. Basically, I am looking for a "unicorn decorator":class MyClass: def __init__(self, something): self.attr_a = something @unicorn_decorator def method_A(self): self.attr_b = SomeExpensiveFunction(arg) def method_B(self): self.method_A() do_somehing_with(self.attr_b) # method_A triggered if required
Is there such a thing? I tried to work my way with getters and setters but I am not even sure that they are relevant for the current context (still miss some part of the logic). How would you do this?
-
Why sometimes 2 objects reference the same but not always
Following the last answer : Recursive method to convert flat collection to hierarchal collection?
I want to use the same method CreateTree but with another object than Hierarchy: ItemNode:
public class ItemNode { public string Id { get; set; } public Item Item { get; set; } public ICollection<ItemNode> Children { get; set; } }
and the definition of Item:
public class Item { public string ID { get; set; } public string Name { get; set; } public int Level { get; set; } public string ParentId { get; set; } }
And here the CreateTree methods with the ItemNode:
static List<ItemNode> CreateTreeItems(IEnumerable<ItemNode> nodes) { Dictionary<string,ItemNode> idToNode = nodes.ToDictionary(n => n.Id, n => n); List<ItemNode> roots = new List<ItemNode>(); ItemNode root = null; foreach (var n in nodes) { if (n.Item.ParentId == null) { if (root != null) { roots.Add(root); } root = n; continue; } ItemNode parent = idToNode[n.Item.ParentId]; //if (!idToNode.TryGetValue(n.Item.ParentId, out parent)) //{ // //Parent doesn't exist, orphaned entry //} parent?.Children.Add(n); // RETURNS FALSE WHEREAS IN THE ORIGINAL METHOD IT RETURNS TRUE var test = Object.ReferenceEquals(parent, root); Debug.WriteLine(test); } if (root == null) { //There was no root element } roots.Add(root); return roots; }
It does not work because parent and root does not reference the same object (whereas in the original method, it does). I guess it was linked to the fact that I have added an Item property to the ItemNode class. But I don't know how to fix it.
Thank you !
-
How to work with "++" in the context of references and parameters
int f1(int i,int j) {j=++i; return i++;} int main() { int i, j, k; i=2, j=4, k=f1(i,j); cout << "i: " << i <<" j: " << j << " k: " << k << endl; return 0; }
In this case
i=2
,j=4
,k=3
int f1(int& i,int& j) {j=++i; return i++;} int main() { int i, j, k; i=2, j=4, k=f1(i,j); cout << "i: " << i <<" j: " << j << " k: " << k << endl; return 0; }
In this case
i=4
,j=3
,k=3
.Are there any good references, with respect to the rules of "++" regarding the differences between parameters and references?
Any help is greatly appreciated.
-
Python3.x self as parameter in a method call to an other class
I am trying to call a method on an other class and give the called class a reference of the current class along with some other parameters. But somehow it takes the self given as a parameter as the self of the called class.
Let me show you:
import os, sys from wsPart import wsPart class thermo(wsPart): functional = False ## see line 8 file = '/sys/bus/w1/devices/28-00000833e8ff/w1_slave' def __init__(self, name, logger): super().__init__(name, logger) functional = True def read(self): fileobject = open(self.file) filecontent = fileobject.read() fileobject.close() self.logger.writeLog(self,"Completed Meassurement") ##Problem on this line return filecontent
So I call the class
logger
and the methodwriteLog
on it. Giving the Parameters message and a reference of the class thermo (self).import datetime from wsPart import wsPart class logger(): logfile = "/var/log/wheaterstation.log" name = "Logger" def writeLog(self, sender, message): conn = open(self.logfile, "w") now = str(datetime.datetime.now().isoformat()) conn.write("[" + now + "]" + " (" + sender.getName() + "): " + message + "\n") ##Problem on this line conn.close()
As you can see I put the parameters
self
because its a method that belongs to a class, thesender
should be the reference to the class thermo that was passed as self in the thermo class. Lastly there is themessage
wich was passed in the thermo class aswell. But this just gives me the error:Traceback (most recent call last): File "scrLib/wsControl.py", line 61, in <module> controller = controller() File "scrLib/wsControl.py", line 22, in __init__ self.thermo = thermo("Thermometer", logger) File "/home/joco/git/wheaterstation/scrLib/thermo.py", line 10, in __init__ super().__init__(name, logger) File "/home/joco/git/wheaterstation/scrLib/wsPart.py", line 8, in __init__ self.logger.writeLog(self, "created") TypeError: writeLog() missing 1 required positional argument: 'message'
So it seems that the
self
parameter wich was passed in the thermo class is interpetet as theself
of the classlogger
wich gets it all mixed up.Can you guys help me here?
Thank you all in advance
The full code + additonal comments can be viewed Here
Edit: Both the logger and the thermo class get initilized in the file
wsPart.py
:class controller(): name = "" logger = None thermo = None dbConnector = None def __init__(self): ##THis created the controller and all the other objects self.name = "Controller" ##Create Objects self.logger = logger() self.logger.writeLog(self,"logger created") ##This line Works self.thermo = thermo("Thermometer", logger) self.dbConnector = dbConnector("DBConnector",logger)