Cocos2d Assert failed: reference count should be greater than 0 - cocos2d-x

Im trying to add a public node in another with touchBegan but i get this error by console
Assert failed: reference count should be greater than 0
Assertion failed: (_referenceCount > 0), function retain, file /Users/user/Desktop/App/cocos2d/cocos/base/CCRef.cpp, line 93.
This is my code:
.h
cocos2d::Node* node1 = cocos2d::Node::create();
cocos2d::Node* node2 = cocos2d::Node::create();
.ccp
bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
node1->removeAllChildren();
node1->addChild(node2);
return true
}

You're createing node in .h file? That's not gonna work. Do it in init fuction:
bool HelloWorld::init()
{
if (!Layer::init())
{
return false;
}
auto node1 = Node::create();
auto node2 = Node::create();
}

.h
class HelloWorld
{
...
Node *node1;
Node *node2;
}
.cpp
bool HelloWorld::init()
{
if (!Layer::init())
{
return false;
}
node1 = Node::create();
addChild(node1);
}
bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
node1->removeAllChildren();
node2 = Node::create();
node1->addChild(node2);
return true
}

Related

How to access StackTrace property form my Custom Exceptions in dot net core

I'm trying to implement my own custom exceptions in dot net core.
This is what I have so far:
public class WSException: Exception
{
// some custom stuff...
private readonly string _developerMessage = "";
public string DeveloperMessage { get { return _developerMessage; } }
public WSException() {}
public WSException(string message) : base(message) {
this._developerMessage = message;
}
public WSException(string message, Exception inner) : base(message, inner) {
this._developerMessage = message;
}
public WSException(Exception ex) : base(ex.Message, ex.InnerException) {
_developerMessage = ex.Message;
Source = ex.Source;
//StackTrace = ex.StackTrace; // cannot be assigned to, it's read only
}
public WSException(string message) : base(message) {
this._developerMessage = (String.IsNullOrWhiteSpace(developerMessage) ? message : developerMessage);
}
}
When I catch a general exception, I try to create one of my own (a WSException) to handle it in a common way, like this:
try {
// whatever
}
catch (WSException e) {
HandleException(e);
}
catch (Exception e) {
HandleException(new WSException(e));
}
When I do it like that, e.Source and e.StackTrace are null, and when I try to assign StackTrace I get a Propery or indexer 'Exception.StackTrace' cannot be assigned to --it is read only.
How should such I implement this constructor?
public WSException(Exception ex) : base(ex.Message, ex.InnerException) {
_developerMessage = ex.Message;
Source = ex.Source;
//StackTrace = ex.StackTrace; // cannot be assigned to, it's read only
}
The workaround I found so far is to handle it when I'm serializing the error to json, something like this:
public class WSExceptionJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var ex = value as WSException;
writer.WriteStartObject();
// buch of properties[...]
string stackTrace = null;
if (ex.StackTrace != null) {
stackTrace = ex.StackTrace;
} else if (ex.InnerException != null && ex.InnerException.StackTrace != null) {
stackTrace = ex.InnerException.StackTrace;
} else {
stackTrace = null;
}
writer.WritePropertyName("stacktrace");
serializer.Serialize(writer, stackTrace.Split('\n'));
writer.WriteEndObject();
}
But it feels too hacky

Does anybody knows if API openshift-restclient-java can restart a POD

I am trying programmatically to restart a POD in openshift? I can connect and query using this client API openshift-restclient-java
If so is there any sample code or link to one that can be provided?
I am currently playing around the first time with opensfhit-restclient-java and have achieved your task by doing as the following snippet illustrates.
What does the code do:
Scale the service instance to 0
Wait until the pod is really gone
Scale the service instance back to 1
Wait until the service instance is really up
Whatever needs to be done, when the service instance is up
Implementation:
private static boolean scaleDeployment(final IClient client,
final String dcName,
final String namespace,
final int scale) {
DeploymentConfig dc = client.get(ResourceKind.DEPLOYMENT_CONFIG, dcName, namespace);
boolean result = false;
if (dc != null) {
dc.setDesiredReplicaCount(scale);
client.update(dc);
result = true;
}
return result;
}
private static boolean waitForPodToDisappear(final IClient client,
final String namespace,
final Map<String, String> labels,
final int maxTries,
final int waitInMillis) {
int tries = 0;
List<Pod> pods = client.list(ResourceKind.POD, namespace, labels);
while (!pods.isEmpty() && tries < maxTries) {
pods = client.list(ResourceKind.POD, namespace, labels);
if (!pods.isEmpty()) {
tries += 1;
try {
Thread.sleep(waitInMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return pods.isEmpty();
}
private static boolean isPodReady(final Pod pod) {
final List<ModelNode> conditions = pod.getNode()
.get("status")
.get("conditions")
.asList();
return conditions.stream()
.filter(node -> (node.get("type").asString().contains("Ready")))
.filter(node -> node.get("status").asString().contains("True"))
.count() == 1;
}
private static boolean waitForPodToBecomeReady(final IClient client,
final String namespace,
final Map<String, String> labels,
final int maxTries,
final int waitInMillis) {
int tries = 0;
boolean result = false;
while (!result && tries < maxTries) {
final List<Pod> pods = client.list(ResourceKind.POD, namespace, labels);
if (pods.size() == 1) {
result = isPodReady(pods.get(0));
}
if (!result) {
tries += 1;
try {
Thread.sleep(waitInMillis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return result;
}
private static void main(String args[]) {
IClient client = new ClientBuilder().toCluster("https://127.0.0.1:8443")
.withConnectTimeout(2, TimeUnit.SECONDS)
.withUserName("developer")
.withPassword("developer")
.build();
boolean result = false;
// Stop service instance
scaleDeployment(client, "myservice-dc", "namespace", 0);
// Wait until service Pod is gone
result = waitForPodToDisappear(client, "namespace", new HashMap<String, String>() {{
put("name", "myservice-dc-label");
}}, 100, 1000);
if(result) {
// Start backup service instance
scaleDeployment(client, "myservice-dc", "namespace", 1);
result = waitForPodToBecomeReady(client, "namespace", new HashMap<String, String>() {{
put("name", "myservice-dc-label");
}}, 100, 1000);
if(result) {
// Do stuff, which requires the pod to be ready
}
}
}
As I already wrote, theses are my fist steps with the openshift-restclient-java.
You need the following dependency for oc 3.6+
<dependency>
<groupId>com.openshift</groupId>
<artifactId>openshift-restclient-java</artifactId>
<version>6.1.2.Final</version>
</dependency>
I used this method to restart the pod. I am posting this answer in case somebody have the same task.
def restartPod(podName: String, nameSpace: String): Boolean = {
val serviceList: Seq[IResource] = openshiftClient.list[IResource](ResourceKind.DEPLOYMENT_CONFIG, nameSpace).filter(service => service.getName.startsWith(podName)).toList
serviceList match {
case service :: _ => {
scaleTo(service, 0) match {
case None => println(s"Pod ${podName} successfully stopped.")
case Some(ex) => {
println(s"Error stopping pod ${podName} reason: ${ex.getMessage}")
}
}
scaleTo(service, 1) match {
case None => {
val message = s"Pod ${podName} successfully started."
println(message)
(true)
}
case Some(ex) => {
val message = s"Error starting pod ${podName} reason: ${ex.getMessage}"
logger.error(message)
(false)
}
}
}
case _ => {
val message = s"Pod ${podName} could not be restarted because it was not found with that name."
logger.error(message)
(false)
}
}
}
You would need the following library:
<dependency>
<groupId>com.openshift</groupId>
<artifactId>openshift-restclient-java</artifactId>
<version>1.0.1.6</version>
</dependency>

JavaFX: Getting the Exception from another Class and setting it to a label

I have a controller that has a button to start a copy and a Label (lblError) to print error messages. To copy files, I call my CopyTask class. In case the file is existing, I'd like to set the lblError's text with an error message (from my CopyTask).
Here's my CopyTask class
public class CopyTask {
String error;
protected List<File> call() throws Exception {
File dir = new File("/Users/Ellen/EllenA/Tennis Videos");
File[] files = dir.listFiles();
int count = files.length;
List<File> copied = new ArrayList<File>();
int i = 0;
for (File file : files) {
if (file.isFile()) {
this.copy(file);
copied.add(file);
}
i++;
}
return copied;
}
private void copy(File file) throws Exception {
try{
Path from = Paths.get(file.toString());
System.out.println(file.toString());
Path to = Paths.get("/Users/Ellen/EllenA/TEMP COPY",file.getName());
CopyOption[] options = new CopyOption[]{
//StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
Files.copy(from, to, options);
} catch (FileAlreadyExistsException e){
System.err.println("FILE EXISTING");
this.error = "FILE EXISTING";
} catch (IOException e){
System.err.println(e);
this.error = e.toString();
}
}
public String getError(){
return error;
}
}
Extend Task<List<File>>. This class contains a message property you could bind to the label text.
public class CopyTask extends Task<List<File>> {
...
#Override
protected List<File> call() throws Exception {
...
}
private void copy(File file) throws Exception {
try {
...
} catch (FileAlreadyExistsException e){
System.err.println("FILE EXISTING");
// update message property from application thread
updateMessage("FILE EXISTING");
}
...
}
}
Calling code
Task<File> task = new CopyTask();
lblError.textProperty().bind(task);
new Thread(task).start();

how to execute statements only after junit reports are generated by TESTNG?

I'm converting junit reports generated by testng to some other format.
I've written this code to do so:
#AfterTest
public void execute()
{
String junitReport = "TEST-"+this.getClass().getCanonicalName()+".xml";
TestManagerLogger obj = new TestManagerLogger();
obj.convertLog(junitReport);
}
But this doesn't work as reports are not generated before the execution of this method.
Is there any way by which this method can be called only after report generation?
My test Case :
#Test(dataProvider = "jobCount")
public void testJobCount(String Scenario, String URL,String methodType, String status) {
URL = URL.replaceFirst("ip", ip);
String logonToken=LogonUtility.logon();
String result= ResponseGenerator.response(URL, logonToken, methodType);
List<HashMap> valuesFromExcel = StringSplitter.getKeyValuePairs(status);// Returns hashmap containing key values ex: failed =0 , total =3
List<HashMap> valuesFromRest = new ArrayList<HashMap>();
Document doc = StringSplitter.convertStringToDocument(result);
javax.xml.xpath.XPath xPath = XPathFactory.newInstance().newXPath();
NodeList node,node1;
try{
node =(NodeList)xPath.evaluate("/feed/entry/content/attrs/attr[#name='status_type']", doc, XPathConstants.NODESET);
node1 = (NodeList) xPath.evaluate("/feed/entry/content/attrs/attr[#name='count']", doc, XPathConstants.NODESET);
HashMap<String,String> hm = new HashMap<String,String>();
for(int i=0;i<node.getLength();i++)
{
hm.put(node.item(i).getTextContent(),node1.item(i).getTextContent() );
}
valuesFromRest.add(hm);
if(valuesFromRest.equals(valuesFromExcel))
{
AssertJUnit.assertTrue(true);
}
else
{
AssertJUnit.assertTrue(false);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Expected XML Report
<logfile>
<logrecord>
<case>scenario</case>
<etime>Execution time</etime>
</logrecord>
</logfile>
Scenario is passed as a parameter in testcase
What you should instead do is to implement your own reporter: http://testng.org/doc/documentation-main.html#logging-reporters
public class TestManagerReporter implements IReporter {
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
// print <logfile>
for (ISuite suite : suites) {
for (IInvokedMethod method : suite.getAllInvokedMethods()) {
if (method.isTestMethod()) {
ITestResult result = method.getTestResult();
if (result.getStatus() == SUCCESS) {
// print <logrecord>
// print <case>
// print result.getName()
// print </case>
// print <etime>
// print result.getEndMillis() - result.getStartMillis()
// print </etime>
// print </logrecord>
}
}
}
}
// print </logfile>
}
}

null pointer exception at run time

This is my first post here. I am trying to create a singly link list. I am using AtEnd and AtStart methods to insert values at the end or in the beginning of the list and using display method to print all the values. The insertion methods seems to be working fine (at least I think so) but whenever I call display method it shows only the first value and then there is a null pointer exception. For example when I run this code I see only 9 and then there is the NPE despite the fact that I have put a check on the display method for "not null".
class node {
private int data;
private node next;
node() {
}
node(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data=data;
}
public node getNext() {
return next;
}
public void setNext(node next) {
this.next = next;
}
}
public class list extends node {
node head;
list() {
}
public void AtStart(int val) {
node n = new node(val);
if (head == null) {
head=n;
} else {
n.setNext(head);
int temp = head.getData();
head.setData(val);
n.setData(temp);
//n = head;
}
}
public void AtEnd(int val) {
if (head == null) {
node n = new node(val);
head = n;
} else {
node t = head;
for(; t.getNext() != null; ) {
if(t.getNext() == null) {
t.setNext(new node (val));
}
t = t.getNext();
}
}
}
public void display() {
node t = head;
for(; t.getNext() == null;) {
if (t !=null) {
System.out.println(t.getData());
t = t.getNext();
}
}
}
}
public static void main(String args[]) {
list l = new list();
l.AtStart(16);
l.AtEnd(6);
l.AtEnd(36);
l.AtStart(9);
l.AtEnd(22);
l.display();
}
i dont get what your AtStart function does, it should be much simpler:
public void AtStart(int val){
if(head==null){
head=n;
}
else{
head.setnext(head);
head.setData(val);
}
}