Jython no module named random - java

I'm working on a server that is made off of Java. At certain points of time (ie someone clicks on a object in the game for example), the server will load a script made using Jython. I'm having trouble getting the script to work, mainly because one imports the module random. Here is the script:
from resources.common import RadialOptions
import sys
import random
def createRadial(core, owner, target, radials):
radials.add(RadialOptions(0, 21, 1, '')) #Use
radials.add(RadialOptions(0, RadialOptions.diceRoll, 3, '#dice/dice:dice_roll_single'))
return
def handleSelection(core, owner, target, option):
if option == RadialOptions.diceRoll or 21:
stringOptions = ['red', 'blue']
owner.sendSystemMessage('Your chance cube rolled the color ' + random.choice(stringOptions) , 0)
return
When the server is loaded up and the script is called, I receive an import error saying there is no module named "random". It doesn't matter what module I call that exists within Jython/Python, it won't except anything but sys and java classes.
I then went ahead and opened up a PyDev console and tried to see if I was able to import random. It was successful.
How come the PyDev console will let me import random or any other module, but not the server when it calls the script?

Try in PyDev entering:
import sys
print sys.path
then add the same to your script - before the problem and compare the two, if they are the same in both cases search the elements of both for random on your local machine and the one your server runs on.

Related

Working on a legacy java program using NetBeans, I am unable to import the junit.framework.TestCase the original author used in Test.java files

To start things off, I am entirely new to Java. I'm a C#/Powershell guy. A client at my IT Firm had an issue with a java program that they were executing on a daily basis that was having issues. According to Windows, the original program was written in April of 2011. I was able to unzip the file and pulled out all of the java files. I then rebuilt the program's structure in NetBeans and am getting ready to start editing. However, each *Test.java file is unable to import junit.framework.TestCase. In the original program file, each of these files were in the same folders as their associated files. From what I can tell, that is not best practices but it was the folder structure I found in the *.jar file I pulled them from. i.e.:
+ Source Packages
|
+--+ Folder
|
+--Example.java
|
+--ExampleTest.java
This leads me to 2 potential issues:
Reading similar threads regarding junit.framework "does not exist", there is mention of adding the junit.jar to the POM or adding the dependency to maven. For NetBeans, how do I do this? Using the "Add Dependency" menu, I am unable to find a "junit.framework" and there is 125,000 results for junit that I am unsure which one I need. Any insights? At the time of the original program's writing, v3 and v4 were both released, although v3.8.1 remained in use for some time beyond the adoption of v4.
For its use-case, see below. I assume all the errors are related to the junit import, so I included them as comments.
package com.example.program;
import java.util.Properties;
import junit.framework.TestCase;
/* Import files specific to program */
public class ExampleTest extends TestCase { //Cannot find symbol (class) "TestCase"
private Properties config = null;
#Override //Error: method does not override or implement a method from a supertype
/* SetUp function/method w/out any issues, creates config Properties object */
public void testExample(){
String line = "*"; // some csv line being parsed
CSVLine csvLine = new CSVLine(line, config);
assertEquals(/* does stuff */); // Error: cannot find "symbol" (method) "assertEquals"
assertTrue(/* does stuff */); // Error: cannot find "symbol" (method) "assertTrue"
assertTrue(/* does stuff*/); // Error: cannot find "symbol" (method) "assertTrue"
}
}
Do I need to move these Test.java files into a folder under the Test Packages section of the POM? Why would the original program have them in the same directory as their counterparts? Does some aspect of compiling/building move them to the same location?

Issue while compilng java code from django

I am new to django web development currently i am trying to create online java compiler using django which consists of two fields i.e code(we can write our own logic) and inputfield(we can provide our own input field) in this process i am facing issue while executing java program
with below code
here is my code
and i am using python 2.7 and django 1.8
import re
import os
from django.shortcuts import render
from django.http import HttpResponse
from .forms import GetForm
import subprocess
def index(request):
if request.method=="GET":
form=GetForm()
return render(request,'compile.html',{'form':form})
else:
form =GetForm(request.POST)
if form.is_valid():
main_class_name=""
text=form.cleaned_data["code"]
// here main_class_name holds main class java name
for i in re.split('class ',text)[1:]:
if re.search('public static void main',i):
main_class_name=re.search('(\w*)',i).group(1)
os.chdir('/home/username/Desktop/onlineproject/projectCompiler/javacompile/')
sd=open(main_class_name+".java","a")
sd.write(text)
proc =
subprocess.Popen(['javac',main_class_name+'.java'],stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
cmd=['java', main_class_name]
output =subprocess.check_output(cmd,shell=True,
stdin=subprocess.PIPE,stderr=subprocess.PIPE)
form.save()
return render(request,'compile.html',{'form1':text})
#My issue
My issue is i am able to compile and generate the .class file using above python script but i am unable to run the java code using "java classname" using above python script
and also i am not getting any error while executing the above code
please help me

OpenCV for Eclipse

Installation instructions: http://docs.opencv.org/doc/tutorials/introduction/desktop_java/java_dev_intro.html
I have downloaded everything. Everything seems to be working except when I run this sample program:
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to OpenCV " + Core.VERSION);
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat m = Mat.eye(3, 3, CvType.CV_8UC1);
System.out.println("m = " + m.dump());
}
}
I get the output:
m = [1, 0, 0;
0, 1, 0;
0, 0, 1]
(which I hope is right).
But I also get these error messages:
objc[63784]: Class CVWindow is implemented in both /Users/.../cv2.so and /Users/... /libopencv_java246.dylib. One of the two will be used. Which one is undefined.
objc[63784]: Class CVView is implemented in both /Users/.../cv2.so and /Users/.../libopencv_java246.dylib. One of the two will be used. Which one is undefined.
objc[63784]: Class CVSlider is implemented in both /Users/.../cv2.so and /Users/.../libopencv_java246.dylib. One of the two will be used. Which one is undefined.
objc[63784]: Class CaptureDelegate is implemented in both /Users/... /cv2.so and /Users/jsuit/opencv/lib/libopencv_java246.dylib. One of the two will be used. Which one is undefined.
I have tried moving the cv2.so file to another folder, but then the program won't compile.
The problem has to do, as far as I can make out, with a reference to the Python libraries (the .so version) that ends up included within the Java libraries themselves. This would seem to be a build configuration error (following the instructions does produce it).
I was able to eliminate the double-definition error by re-building the Java version without support for the Python libraries in it, using the following in the cmake step (all else the same):
cmake -D BUILD_SHARED_LIBS=OFF -D BUILD_NEW_PYTHON_SUPPORT=NO ..
The newly produced Java libraries and .jar work just as before, but without the error message.
(Note that I can't guarantee this won't cause other problems, especially if you want to do some sort of mixed-language programming, but it does produce libraries useful for Java and Eclipse. You can always build multiple versions of OpenCV, too, some with support for Python, some without, and use whichever one you like if you switch languages at some point.)
Hat tip: http://answers.opencv.org/question/16015/mac-opencv-246-java-exception/

Java and R integration

I am trying to build a java project which contains R codes. Main logic behind that is I want to automate the data structuring and data analysis with in a same project. Partially I am being able to do that. I connected R to Java and my R codes are running well. I did all my set up in the local machine and its giving me all output as I need. As data set is big I am trying to run this on amazon server. But when I am shifting it to server, my project is not working properly. Its not being able to execute library(XLConnect), library(rJava). When ever I am calling this two libraries in my java project it's crashing. Independently in R codes are running and giving me output. What I can I for that, and how to fix thus error. Please help me out from this.
My java codes is
import java.io.InputStreamReader;
import java.io.Reader;
public class TestRMain {
public static void main(String[] arg)throws Exception{
ProcessBuilder broker = new ProcessBuilder("R.exe","--file=E:\\New\\Modified_Best_Config.R");
Process runBroker = broker.start();
Reader reader = new InputStreamReader(runBroker.getInputStream());
int ch;
while((ch = reader.read())!= -1)
System.out.print((char)ch);
reader.close();
runBroker.waitFor();
System.out.println("Execution complete");
}
}
And in the Modified_Best_Config.R I have written these codes
library('ClustOfVar');
library("doBy");
library(XLConnect)
#library(rJava)
#library(xlsx)
path="E:/New/";
############Importing and reading the excel files into R##############
Automated_R <- loadWorkbook("E:/New/Option_Mix_Calculation1.xlsx")
sheet1 <- readWorksheet(Automated_R, sheet = "Current Output")
sheet2 <- readWorksheet(Automated_R, sheet = "Actual Sales monthly")
sheet3 <- readWorksheet(Automated_R, sheet = "Differences")
#####################Importing raw Data###############################
optionData<- read.csv(paste(path,"ModifiedStructureNewBestConfig1.csv",sep=""),head=TRUE,sep=",");
nrow(optionData)
optionDemand=sapply(split(optionData,optionData$Trim),trimSplit);
optionDemand1=t(optionDemand[c(-1,-2),]);
optionDemand1
################Calculating the equipment Demand####################
optionDemand2<-t(optionDemand2[c(-1,0)]);
Rownames <- as.data.frame(row.names(optionDemand2))
writeWorksheet(Automated_R,Rownames, sheet = "Current Output", startRow = 21, startCol = 1)
writeWorksheet(Automated_R,optionDemand2, sheet = "Current Output", startRow = 21, startCol = 2)
saveWorkbook(Automated_R)
But java is stopping its operation after these line.
library("doBy");
Whole set of codes are running on nicely on my local machine. But whenever I am trying to run this on amazon server it's not running. Individually in R this code is running on server. I have couple of more R codes which are running with out any error. What can I do for that, please help me out.
Thanks for updating your question with some example code. I cannot completely replicate your circumstances because I presently don't have immediate access to Amazon EC2, and I don't know the specific type of instance you are using. But here a couple of suggestions for de-bugging your issue, which I have a hunch is being caused by a missing package.
1. Try to install the offending packages via your R script
At the very beginning of your R script, before you try to load any packages, insert the following:
install.packages(c("XLConnect", "rJava"))
If your instance includes a specified CRAN mirror (essentially, the online repository where R will first look to download the package source code from), this should install the packages in the same repo where your other packages are kept on your server. Then, either library or require should load your packages.
(sidenote: rJava is actually a dependency of XLConnect, so it will automatically load anyway if you only specify library(XLConnect))
2. If the above does not work, try installing the packages via the command line
This is essentially what #Ben was suggesting with his comment. Alternatively, see perhaps this link, which deals with a similar problem with a different package. If you can, in terminal on the server, I would try entering the following three commands:
sudo add-apt-repository ppa:marutter/rrutter
sudo apt-get update
sudo apt-get install r-cran-XLConnect
In my experience this has been a good go-to repo when I can't seem to find a package I need to install. But you may or may not have permission to install packages on your server instance.

PyDev Jython module_not_found_in_the_pythonpath, autocomplete not working

I've been searching for two days now trying to get PyDev to recognize my external .JAR (It's obfuscated for protection), however no matter what I do it doesn't want to work. I've read over the documentation for nearly a hour straight trying to get it to work.
I'm helping to work on an emulation server which uses Jython for scripting. I can compile and run the emulation server with the scripts working just fine however, without using autocompletion for the methods inside the engine part of the server which is obfuscated in a external .jar.
Here is an example code of a script which uses methods from the obfuscated .JAR (which isn't working with autocomplete, so I have to navigate through the package explorer to find the method I want to use):
import sys
def CreateStartingCharacter(core, object):
testObject = core.objectService.createObject('object/weapon/ranged/rifle/shared_rifle_t21.iff', object.getPlanet())
testObject.setCustomName('This is a Jython Rifle')
testObject.setStringAttribute('crafter', 'Light')
inventory = object.getSlottedObject('inventory')
inventory.add(testObject)
testClothing = core.objectService.createObject('object/tangible/wearables/cape/shared_cape_rebel_01.iff', object.getPlanet())
testClothing.setCustomName('Test Cape')
testCloak = core.objectService.createObject('object/tangible/wearables/robe/shared_robe_jedi_dark_s05.iff', object.getPlanet())
testCloak.setCustomName('Test Cloak')
inventory.add(testClothing)
inventory.add(testCloak)
return
This script is executed by the following command in Java (core is the class inside the external JAR, obfuscated)
core.scriptService.callScript("scripts/", "demo", "CreateStartingCharacter", object);
object is...
CreatureObject object = (CreatureObject)core.objectService.createObject(sharedRaceTemplate, core.terrainService.getPlanetList().get(0));
Like I said above, all of those methods that I used in the script were from the obfuscated JAR which isn't working with autocomplete. However, I can use a method that isn't in that JAR just fine such as:
from resources.common import RadialOptions
from services.sui import SUIWindow
from services.sui.SUIWindow import Trigger
from java.util import Vector
import sys
def createRadial(core, owner, target, radials):
radials.clear()
bank = owner.getSlottedObject('bank')
if bank:
radials.add(RadialOptions(0, 21, 1, ''))
radials.add(RadialOptions(0, 7, 1, ''))
radials.add(RadialOptions(1, RadialOptions.bankTransfer, 3, '#sui:bank_credits'))
radials.add(RadialOptions(1, RadialOptions.bankitems, 3, '#sui:bank_items'))
if owner.getBankCredits() > 0:
radials.add(RadialOptions(1, RadialOptions.bankWithdrawAll, 3, '#sui:bank_withdrawall'))
if owner.getCashCredits() > 0:
radials.add(RadialOptions(1, RadialOptions.bankDepositAll, 3, '#sui:bank_depositall'))
return
... and using RadialOptions. control+space will show me all the methods.
Help would be much appreciated. At this point I feel that it's not working because the JAR file is obfuscated or something like that. And yes, I've already added it to my PYTHONPATH and updated the interpreter, just like with the bin folder for my project.

Categories

Resources