text stringlengths 14 410k | label int32 0 9 |
|---|---|
public boolean equals(Object object) {
if (! (object instanceof CycConstant))
return false;
Guid thisGuid = getGuid();
Guid thatGuid = ((CycConstant) object).getGuid();
return thisGuid.equals(thatGuid);
} | 1 |
@Override
public void execute() {
MahTreez.status = "Chopping";
SceneObject tree = SceneEntities.getNearest(MahTreez.activeTree.getIds());
if (tree == null) {
System.out.println("Chop: cannot find the tree! Camera rotation (for next tree).");
if (Random.nextInt(1, 3) == 1) {
Camera.setAngle(Camera.getYaw()+Random.nextInt(-90, -70));
// Set pitch angle?
} else {
Camera.setAngle(Camera.getYaw()+Random.nextInt(70, 90));
// Set pitch angle?
}
return;
}
if (!tree.isOnScreen()) {
System.out.println("Chop: tree is not on screen. Camera rotation and walk towards tree.");
// switch (Random.nextInt(1, 5)) {
// case 1:
// Camera.setAngle(Camera.getYaw()+Random.nextInt(-90, -70));
// Camera.setPitch(Random.nextInt(1, 20));
// break;
// case 2:
// Camera.setAngle(Camera.getYaw()+Random.nextInt(70, 90));
// Camera.setPitch(Random.nextInt(1, 20));
// break;
// case 3:
// Camera.setAngle(Camera.getYaw()+Random.nextInt(-90, -70));
// Camera.setPitch(Random.nextInt(67, 87));
// break;
// case 4:
// Camera.setAngle(Camera.getYaw()+Random.nextInt(70, 90));
// Camera.setPitch(Random.nextInt(67, 87));
// break;
// }
Camera.turnTo(tree);
// Walking.walk(tree.getLocation());
Task.sleep(200, 300);
return;
}
if (Players.getLocal().isIdle()) {
System.out.println("Chop: 1-player is idle.");
tree.interact("Chop");
System.out.println("Chop: 2-interaction with tree.");
Task.sleep(200, 300);
if (Random.nextInt(1, 3) == 1) {
Camera.setAngle(Camera.getYaw()+Random.nextInt(-90, -70));
} else {
Camera.setAngle(Camera.getYaw()+Random.nextInt(70, 90));
}
}
return;
} | 5 |
protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException {
out.writeStartElement(getXMLElementTagName());
out.writeAttribute(ID_ATTRIBUTE, getId());
if (destination != null) {
out.writeAttribute("destination", destination.getId());
}
out.writeAttribute("transportPriority",
Integer.toString(transportPriority));
if (transport != null) {
if (getAIMain().getAIObject(transport.getId()) == null) {
logger.warning("broken reference to transport");
} else if (transport.getMission() != null
&& transport.getMission() instanceof TransportMission
&& !((TransportMission) transport.getMission()).isOnTransportList(this)) {
logger.warning("We should not be on the transport list.");
} else {
out.writeAttribute("transport", transport.getId());
}
}
goods.toXML(out);
out.writeEndElement();
} | 6 |
public static boolean phone(String phone){
if(phone.matches("(\\d){10}"))
return true;
return false;
} | 1 |
private final void method3914(byte i) {
anInt7922++;
anInterface5_Impl1_8201 = method3889(false, 16711680);
if (i <= -97) {
anInterface5_Impl1_8201.method20(3096, (byte) 126, 12);
for (int i_225_ = 0; i_225_ < 4; i_225_++) {
Buffer buffer = anInterface5_Impl1_8201.method19(true, 26775);
if (buffer != null) {
Stream stream = method3893(buffer, 9179);
stream.a(0.0F);
stream.a(0.0F);
stream.a(0.0F);
for (int i_226_ = 0; i_226_ <= 256; i_226_++) {
double d = (3.141592653589793 * (double) (i_226_ * 2)
/ 256.0);
float f = (float) Math.cos(d);
float f_227_ = (float) Math.sin(d);
if (!Stream.c()) {
stream.b(f_227_);
stream.b(f);
stream.b(0.0F);
} else {
stream.a(f_227_);
stream.a(f);
stream.a(0.0F);
}
}
stream.a();
if (anInterface5_Impl1_8201.method18(6331))
break;
}
}
aClass130_8190
= method3812(0, (new Class58[]
{ new Class58(Class325.aClass325_4073) }));
}
} | 6 |
public ControllerCrlv(ViewCrlv tela, ModelCRLV c, ViewGerenciarCrlvs g) {
jifCrlv = tela;
daoCrlv = new DAOCrlv();
gcrlv = g;
if(c == null)
crlv = new ModelCRLV();
else{
crlv = c;
jifCrlv.setModelCrlv(crlv);
}
jifCrlv.getBtSalvar().addActionListener(this);
} | 1 |
public void updateCellData(String key, String value) {
if (jt_language.getSelectedRow() != -1) {
row = jt_language.getSelectedRow();
}
// System.out.println(row);
cellData[row][0] = key;
cellData[row][1] = value;
prop.put(key, value);
} | 1 |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Edge-control", "no-store");
if ("clear".equalsIgnoreCase(request.getParameter("clear"))) {
tistat.clear();
}
ServletOutputStream out = response.getOutputStream();
String datestr = getHostName() + " - " + (new SimpleDateFormat("yyyyMMdd - HHmmss")).format(new Date());
//
// xml
if (request.getParameter("memxml") != null) {
memoryXml(out, tistat.getMemoryInfo().getValues(), 1, "JVM Memory - " + datestr);
out.flush();
return;
} else if (request.getParameter("histxml") != null) {
memoryXml(out, tistat.getResponseTimes(), 1, "Response Histogram - " + datestr);
out.flush();
return;
}
//
// html
if (request.getParameter("qon") != null) {
tistat.setAddQueryToKey(true);
} else if (request.getParameter("qoff") != null) {
tistat.setAddQueryToKey(false);
}
String sort = request.getParameter("sort");
String baseurl = request.getRequestURI();
if (request.getParameter("freq") != null) {
NumberFormat nf0 = NumberFormat.getInstance();
nf0.setMaximumFractionDigits(0);
nf0.setMinimumFractionDigits(0);
header(NAME + " - Frequency - " + datestr, false, out);
baseurl += "?freq=Frequency";
frequencyTable(out, tistat, sort, baseurl);
String title1 = " Response " + nf0.format(tistat.getAverage()) + " [ms]";
pixelPlot(out, tistat.getResponseTimes(), 0, "red", 55, title1);
String title2 = "Bitrate " + nf0.format(tistat.getBitrateAverage() / 1024D) + " [KB/s]";
pixelPlot(out, tistat.getRatesSizes(), 1, "blue", 270, title2);
footer(out);
} else if (request.getParameter("mem") != null) {
header(NAME + " - JVM Memory - " + datestr, true, out);
String title = "JVM Memory";
pixelPlot(out, tistat.getMemoryInfo().getValues(), 1, "navy", 60, title);
footer(out);
} else if (request.getParameter("payload") != null) {
header(NAME + " - Payload Histogram - " + datestr, false, out);
String title = "Payload";
pixelPlot(out, tistat.getChunkSizes(), 0, "green", 60, title);
footer(out);
} else {
boolean reload = false;
if (request.getParameter("reload") != null) {
reload = true;
}
NumberFormat nf0 = NumberFormat.getInstance();
nf0.setMaximumFractionDigits(0);
nf0.setMinimumFractionDigits(0);
header(NAME + " - Performance - " + datestr, reload, out);
baseurl += "?stat=Performance";
statisticsTable(out, tistat, "X", null, sort, baseurl);
String title1 = " Response " + nf0.format(tistat.getAverage()) + " [ms]";
pixelPlot(out, tistat.getResponseTimes(), 0, "red", 55, title1);
String title2 = "Bitrate " + nf0.format(tistat.getBitrateAverage() / 1024D) + " [KB/s]";
pixelPlot(out, tistat.getRatesSizes(), 1, "blue", 270, title2);
footer(out);
}
out.flush();
} | 9 |
public int inserir (Usuario us){
Connection conn = null;
PreparedStatement pstm = null;
int retorno = -1;
try{
conn = ConnectionFactory.getConnection();
pstm = conn.prepareStatement(INSERT, Statement.RETURN_GENERATED_KEYS);
pstm.setString(1, us.getNome_us());
pstm.setString(2, us.getUsuario_us());
pstm.setString(3, us.getSenha_us());
pstm.setString(4, us.getNivelAcesso_us());
pstm.execute();
try(ResultSet rs = pstm.getGeneratedKeys()){
if(rs.next()){
retorno = rs.getInt(1);
}
}
}catch (Exception e){
JOptionPane.showMessageDialog(null,"Erro ao cadastrar um usuário "+ e);
}finally{
try{
ConnectionFactory.closeConnection(conn, pstm);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao desconectar com o banco " + e );
}
}
return -1;
} | 3 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = "";
StringBuilder out = new StringBuilder();
int t = 1;
while ((line = in.readLine()) != null && line.length() != 0) {
int times = Integer.parseInt(line);
for (int i = 0; i < times; i++) {
double[] v = readDoubles(in.readLine());
double la0, lo0, la1, lo1;
la0 = toR(v[0]);
lo0 = toR(v[1]);
la1 = toR(v[2]);
lo1 = toR(v[3]);
double disEspheric = disEspherical(la0, lo0, la1, lo1);
double disTunnel = disTunnel(la0, lo0, la1, lo1);
long ans = Math.round(Math.abs(disEspheric - disTunnel));
out.append(ans + "\n");
}
}
System.out.print(out);
} | 3 |
public static String valorMonetario(String valor) {
int pontos = -1;
valor = valor.replaceAll(",", ".");
valor = valor.replace("..", ".");
for (int i = 0; i < valor.length(); i++) {
if (valor.charAt(i) == '.') {
pontos++;
}
}
if (!IsNumero.isDinheiro(valor) || valor.equals("") || pontos > 0) {
return "";
} else {
if (pontos == -1) {
valor += ".00";
} else if (valor.indexOf(".") > 0) {
if (valor.indexOf(".") == valor.length() - 1) {
valor += "00";
} else if (valor.indexOf(".") == valor.length() - 2) {
valor += "0";
}
valor = valor.substring(0, valor.indexOf(".") + 3);
}
}
return valor;
} | 9 |
public void start() {
if (!this.socket.isBound()) {
throw new IllegalStateException("Can't start ConnectionHandler " +
"without a bound socket!");
}
this.stop = false;
if (this.thread == null || !this.thread.isAlive()) {
this.thread = new Thread(this);
this.thread.setName("bt-serve");
this.thread.start();
}
} | 3 |
private void trimTexts(Field field, Object prop) {
if(prop instanceof JTextComponent) {
JTextComponent txtComp=(JTextComponent)prop;
Trim trim=field.getAnnotation(Trim.class);
if(trim!=null) {
if(trim.value()==YesNo.YES) {
txtComp.setText(txtComp.getText()==null?null:txtComp.getText().trim());
}
}else if("true".equals(SwingObjProps.getSwingObjProperty("guielements.texttrim"))){
txtComp.setText(txtComp.getText()==null?null:txtComp.getText().trim());
}
}
} | 6 |
public void loadCardConfigFile(String file) throws FileNotFoundException, BadConfigFormatException {
FileReader cardReader = new FileReader(file);
Scanner cardScanner = new Scanner(cardReader);
Card toAdd;
final int numColumns = 2;
String name;
Card.cardType type = null;
while(cardScanner.hasNextLine()) {
String line = cardScanner.nextLine();
String[] parts = line.split(",");
if(parts.length != numColumns) {
throw new BadConfigFormatException("Error in card file");
}
else {
name = parts[0];
if(parts[1].equals("WEAPON"))
type = Card.cardType.WEAPON;
else if (parts[1].equals("PERSON"))
type = Card.cardType.PERSON;
else if (parts[1].equals("ROOM"))
type = Card.cardType.ROOM;
else
throw new BadConfigFormatException("invalid card type");
toAdd = new Card(name, type);
this.cards.add(toAdd);
this.fullDeck.add(toAdd);
}
}
} | 5 |
public void returnOperation(
final AbstractInsnNode insn,
final Value value,
final Value expected) throws AnalyzerException
{
if (!isSubTypeOf(value, expected)) {
throw new AnalyzerException(insn,
"Incompatible return type",
expected,
value);
}
} | 1 |
public String toString(){
StringBuffer map = new StringBuffer( );
//goes through all the rooms and appends -[ ]-
//if there are any people in the room, it cuts out a space and adds the first letter of their names.
for(int y=0; y<worldHeight; y++){
for(int x=0; x<worldWidth; x++){
if (this.getRoom(x,y) != null){
map.append(this.getRoom(x,y));
if (this.getRoom(x,y).getMoversNum()>0){
map.delete(map.length()-3, map.length()-3+this.getRoom(x,y).getMoversNum());
for(int z=0; z<this.getRoom(x,y).getMoversNum(); z++){
map.insert(map.length()-1, this.getRoom(x,y).getMovers().get(z).getName().substring(0,1));
}
}
}
else{
map.append(" ");
}
map.append("-");
}
//this just cuts off the extra dash at the end of a line.
map.delete(map.length()-1, map.length());
map.append("\n");
map.append("\n");
}
System.out.println(people.size());
return map.toString();
} | 5 |
@Override
public void setPystyNopeus(double pystyNopeus){
for (KentallaOlija osa : osat){
osa.setPystyNopeus(pystyNopeus);
}
} | 1 |
@Test
public void testBothWays() throws IOException, InterruptedException {
for(File org : testdataDirectory.listFiles()) {
if(org.isFile()) {
System.out.println("checking " + org.getName());
byte[] originalData = TestUtil.readFully(org);
ByteArrayOutputStream compressedData = new ByteArrayOutputStream();
SnzOutputStream sos = new SnzOutputStream(compressedData);
sos.write(originalData);
sos.close();
ByteArrayOutputStream decompressedData = new ByteArrayOutputStream();
SnzInputStream sis = new SnzInputStream(new ByteArrayInputStream(compressedData.toByteArray()));
TestUtil.pipe(sis, decompressedData);
Assert.assertArrayEquals(originalData, decompressedData.toByteArray());
}
}
} | 2 |
private void eol() throws XMLStreamException {
mWriter.writeCharacters("\n"); //$NON-NLS-1$
for (int i = 0; i < mDepth; i++) {
mWriter.writeCharacters(mIndent);
}
} | 1 |
@Override
public void createPossibleMoves() {
possibleMoves = new ArrayList<Square>();
//direction boolean is set to false if a piece is blocking the direction
boolean nw = true, ne = true, sw = true, se = true;
for(int i = 1; i < ChessEngine.SQUARE_HEIGHT; i++) {
//if no more squares can be valid, break.
if(!nw && !ne && !sw &&!se) break;
/* Check north west direction */
if(nw) {
int dx = x, dy = y;
//new coordinates for North-West direction.
dx += i * -1;
dy += i * -1;
nw = checkMovableSquare(dx, dy);
}
/* Check North-East direction */
if(ne) {
int dx = x, dy = y;
//new coordinates for North-East direction
dx += i * 1;
dy += i * -1;
ne = checkMovableSquare(dx, dy);
}
/* Check South-West direction */
if(sw) {
int dx = x, dy = y;
//new coordinates for North-West direction.
dx -= i;
dy += i;
sw = checkMovableSquare(dx, dy);
}
/* Check South-East direction */
if(se) {
int dx = x, dy = y;
//new coordinates for North-West direction.
dx += i;
dy += i;
se = checkMovableSquare(dx, dy);
}
}
} | 9 |
protected void scanDirectory(File dir)
{
boolean ok = true;
File[] files = ( fileFilter != null ? dir.listFiles(fileFilter) :
dir.listFiles() );
// Process all the FILES first
for (int i = 0; i < files.length && ok; i++)
{
if (files[i].isFile())
ok = processFile(files[i]);
}
// Process all the SUB-DIRECTORIES
for (int i = 0; i < files.length && ok; i++)
{
if (files[i].isDirectory())
{
ok = processDirectory(files[i]);
if (ok && subDirs) // recurse downward
scanDirectory(files[i]);
}
}
} | 9 |
public List<String> listIpAddress(String id) throws Exception
{
String response = getServer(id);
if (containsErrorMessage(response))
{
throw new Exception("Error retrieving ip address for instance id:" + id);
}
Document doc = stringToXmlDocument(response);
NodeList list = doc.getElementsByTagName("ipaddress");
List<String> ips = new ArrayList<String>();
for (int i = 0; i < list.getLength(); i++)
{
ips.add(list.item(i).getTextContent().trim());
}
return ips;
} | 2 |
void updateTable() {
table.getItems().setAll(select());
} | 0 |
public String toLowerThis(String input){
MethodReferenceSAM methodReferenceSAM = this::toLowerCase;
return methodReferenceSAM.process(input);
} | 0 |
@Override
public void executeMsg(Environmental affecting, CMMsg msg)
{
super.executeMsg(affecting,msg);
final MOB source=msg.source();
if(!canFreelyBehaveNormal(affecting))
return;
final MOB observer=(MOB)affecting;
if((source!=observer)
&&(msg.amITarget(observer))
&&(msg.targetMinor()==CMMsg.TYP_GIVE)
&&(!CMSecurity.isAllowed(source,source.location(),CMSecurity.SecFlag.CMDROOMS))
&&(!(msg.tool() instanceof Coins))
&&(msg.tool() instanceof Item))
{
final double cost=cost((Item)msg.tool());
CMLib.beanCounter().subtractMoney(source,CMLib.beanCounter().getCurrency(observer),cost);
final String costStr=CMLib.beanCounter().nameCurrencyLong(observer,cost);
source.recoverPhyStats();
((Item)msg.tool()).setUsesRemaining(100);
CMMsg newMsg=CMClass.getMsg(observer,source,msg.tool(),CMMsg.MSG_GIVE,L("<S-NAME> give(s) <O-NAME> to <T-NAMESELF> and charges <T-NAMESELF> @x1.",costStr));
msg.addTrailerMsg(newMsg);
newMsg=CMClass.getMsg(observer,source,null,CMMsg.MSG_SPEAK,L("^T<S-NAME> say(s) 'There she is, good as new! Thanks for your business' to <T-NAMESELF>.^?"));
msg.addTrailerMsg(newMsg);
newMsg=CMClass.getMsg(observer,msg.tool(),null,CMMsg.MSG_DROP,null);
msg.addTrailerMsg(newMsg);
}
} | 7 |
public void execute() {
Process pro;
try {
pro = Runtime.getRuntime().exec("javac " + mapperClass + ".java"); // compile
pro.waitFor();
Class<?> myClass = Class.forName(mapperClass);
Class<?>[] paramsClass = new Class<?>[2];
paramsClass[0] = String.class;
paramsClass[1] = Output.class;
Constructor<?> myCons = myClass.getConstructor();
Object object = myCons.newInstance();
Method method = null;
Output output = new Output(numReducer, jobID + "_mapper");
method = object.getClass().getMethod(mapperFunction, paramsClass);
BufferedReader br = new BufferedReader(new FileReader(localFnName));
String str = "";
while ((str = br.readLine()) != null) {
method.invoke(object, str, output);
}
br.close();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
} | 6 |
public Node<T> getNode(T value) {
if (value == null) {
return null;
}
Node<T> node = root;
while (node != null) {
int delta = compare(node.getValue(), value);
if (delta < 0) {
node = node.getRight();
} else if (delta > 0) {
node = node.getLeft();
} else {
break;
}
}
return node;
} | 4 |
public GenKTR(Simulation simulation){
//Récupération de variables nécessaires à l'élaboration du fichier de sortie
int hyperperiode = simulation.getHyperperiode();
//Ouverture d'un flux d'écriture String
StringBuilder result = new StringBuilder();
//Définition de la précision
result.append(KIWI_INSTRUCTIONS.PRECISION.getMeaning() + SPACE + "0" + END_LINE);
result.append(KIWI_INSTRUCTIONS.DURATION.getMeaning() + SPACE + hyperperiode + END_LINE);
List<Tache> taches = simulation.getTaches();
for (Tache tache : taches) {
result.append(KIWI_INSTRUCTIONS.LINE_NAME + SPACE + tache.getId() + SPACE + "\"" + tache.getKtrName() + "\"" + END_LINE);
}
result.append(KIWI_INSTRUCTIONS.PALETTE.getMeaning() + SPACE + "Rainbow" + END_LINE);
result.append(KIWI_INSTRUCTIONS.ZOOM_X.getMeaning() + TAB + "4"+ END_LINE);
result.append(KIWI_INSTRUCTIONS.ZOOM_Y.getMeaning() + TAB + "16" + END_LINE);
result.append(END_LINE);
//On affiche le contenu du collecteur de log :
List<Event> events = simulation.getEvents();
Collections.sort(events);
for(Event event : events) {
result.append(event.toString());
}
//On réserve le pire pour la fin : écriture dans le fichier
Date date = new Date();
try{
PrintWriter fichier = new PrintWriter (
new FileWriter(simulation.getOutputDir() + SEPARATOR + "RepresentationGraphique"+ simulation.getTypeSimulation() + "-" + date.toString().replace(" ", "").replace(":", "") +".ktr")
);
fichier.println(result.toString());
fichier.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public void ReadFile() {
JSONParser jsonParser = new JSONParser();
try {
FileReader json = new FileReader("src/config.json");
Object obj = jsonParser.parse(json);
JSONObject jsonObject = (JSONObject) obj;
setHost((String) jsonObject.get("host"));
setPort((String) jsonObject.get("port"));
setUsername((String) jsonObject.get("username"));
setDbname((String) jsonObject.get("dbname"));
setPassword((String) jsonObject.get("password"));
setServerport((String) jsonObject.get("serverport"));
setWeather_expiration_time((String) jsonObject.get("weather_expiration_time"));
setWeather_lat((String) jsonObject.get("weather_lat"));
setWeather_lon((String) jsonObject.get("weather_lon"));
setWeather_future_in_days((String) jsonObject.get("weather_future_in_days"));
setQOTD_expiration_time((String) jsonObject.get("qotd_expiration_time"));
setEncryptionkey ((String) jsonObject.get("encryptionkey"));
} catch (ParseException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 4 |
public static void main(String[] args) throws IOException, ParseException {
// 0. Specify the analyzer for tokenizing text.
// The same analyzer should be used for indexing and searching
StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
// 1. create the index
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);
IndexWriter w = new IndexWriter(index, config);
addDoc(w, "Lucene in Action", "193398817");
addDoc(w, "Lucene for Dummies", "55320055Z");
addDoc(w, "Managing Gigabytes", "55063554A");
addDoc(w, "The Art of Computer Science", "9900333X");
w.close();
// 2. query
String querystr = args.length > 0 ? args[0] : "lucene";
// the "title" arg specifies the default field to use
// when no field is explicitly specified in the query.
Query q = new QueryParser(Version.LUCENE_40, "title", analyzer).parse(querystr);
// 3. search
int hitsPerPage = 10;
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
searcher.search(q, collector);
ScoreDoc[] hits = collector.topDocs().scoreDocs;
// 4. display results
System.out.println("Found " + hits.length + " hits.");
for(int i=0;i<hits.length;++i) {
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println((i + 1) + ". " + d.get("isbn") + "\t" + d.get("title"));
}
// reader can only be closed when there
// is no need to access the documents any more.
reader.close();
} | 2 |
private String getTextAsEps(String text) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
final char c = text.charAt(i);
if (c == '\\') {
sb.append("\\\\");
} else if (c == '(') {
sb.append("\\(");
} else if (c == ')') {
sb.append("\\)");
} else if (c < ' ') {
sb.append("?");
} else if (c >= ' ' && c <= 127) {
sb.append(c);
} else {
final String s = "" + c;
try {
final byte b[] = s.getBytes("ISO-8859-1");
if (b.length == 1) {
final int code = (b[0] & 0xFF);
sb.append("\\" + Integer.toOctalString(code));
} else {
sb.append('?');
}
} catch (UnsupportedEncodingException e) {
sb.append('?');
}
}
}
return sb.toString();
} | 9 |
public static SpriteStore get() {
if (instance == null) {
instance = new SpriteStore();
}
return instance;
} | 1 |
@Override
public byte[] runBinaryMacro(HTTPRequest httpReq, String parm, HTTPResponse httpResp) throws HTTPServerException
{
final MIMEType mimeType = MIMEType.All.getMIMEType(getFilename(httpReq,""));
if(mimeType != null)
httpResp.setHeader("Content-Type", mimeType.getType());
final String last=httpReq.getUrlParameter("PLAYER");
if(last==null) return null; // for binary macros, null is BREAK
byte[] img=null;
if(last.length()>0)
{
img=(byte[])Resources.getResource("CMPORTRAIT-"+last);
if(img==null)
{
final List<PlayerData> data=CMLib.database().DBReadPlayerData(last,"CMPORTRAIT");
if((data!=null)&&(data.size()>0))
{
final String encoded=data.get(0).xml();
img=B64Encoder.B64decode(encoded);
if(img!=null)
Resources.submitResource("CMPORTRAIT-"+last,img);
}
}
}
return img;
} | 7 |
@Override
public void onEnable() {
getServer().getScheduler().scheduleSyncDelayedTask(this,
new Runnable() {
public void run() {
{
// CraftBukkit-specific
Configuration bukkitYML = new Configuration(
new File("bukkit.yml"));
bukkitYML.load();
List<String> worlds = bukkitYML.getKeys("worlds");
if (worlds != null) {
for (String world : worlds) {
if (bukkitYML.getString(
"worlds." + world + ".generator",
".").split(":")[0]
.equals(getDescription().getName())
&& getServer().getWorld(world) == null) {
getServer().createWorld(world,
Environment.NORMAL, dg);
inBukkitYML = true;
}
}
}
}
if (!inBukkitYML) {
getServer().createWorld("dungeon",
Environment.NORMAL, dg);
}
}
});
} | 5 |
Tree makeList()
{
Tree myleft, myright;
Tree tleft,tright;
Tree retval = this;
// head of left list
if (left != null)
myleft = left.makeList();
else
myleft = null;
// head of right list
if (right != null)
myright = right.makeList();
else
myright = null;
if (myright != null) {
retval = myright;
right.next = this;
}
if (myleft != null) {
retval = myleft;
if (myright != null)
left.next = myright;
else
left.next = this;
}
next = null;
return retval;
} | 5 |
private ArrayList buildPredicates() throws Exception {
ArrayList predicates = new ArrayList(); /* The result. */
Predicate predicate;
Attribute attr;
Enumeration attributes = m_instances.enumerateAttributes();
boolean individual = (m_parts != null); /* Individual-based learning ? */
/* Attributes. */
while (attributes.hasMoreElements()) {
attr = (Attribute) attributes.nextElement();
/* Identifiers do not appear in rules in individual-based learning. */
if (!(individual && attr.name().equals("id"))) {
predicate = buildPredicate(m_instances, attr, false);
predicates.add(predicate);
}
}
/* Class attribute. */
attr = m_instances.classAttribute();
/* Identifiers do not appear in rules. */
if (!(individual && attr.name().equals("id"))) {
predicate = buildPredicate(m_instances, attr, true);
predicates.add(predicate);
}
/* Attributes of the parts in individual-based learning. */
if (individual) {
attributes = m_parts.enumerateAttributes();
while (attributes.hasMoreElements()) {
attr = (Attribute) attributes.nextElement();
/* Identifiers do not appear in rules. */
if (!attr.name().equals("id")) {
predicate = buildPredicate(m_parts, attr, false);
predicates.add(predicate);
}
}
}
return predicates;
} | 8 |
@Override
public void notifyObservers() {
for (Observer observer : observers) {
observer.update(temperature, humidity, pressure);
}
} | 1 |
private void updateLinks(){
Link l = null;
for(Node source:nodes){
for(Node dest:nodes){
if(source.getName().equals(dest.getName())){
continue; // same node
}
l = getLink(source,dest);
if(l==null){
continue; //nodes arent neighbours
}
//if link has been taken down. (do I need to see if its up?)
//do source and dest, so can set the flag back
//should really check to see if this link is the one being used
if(l.isActivityChange()){
System.out.println("link has been changed");
if(!l.isActive()){
source.getRoutingTable().put(dest, Node.infinity);
source.getVectorTable().remove(dest);
dest.getRoutingTable().put(source, Node.infinity);
dest.getVectorTable().remove(source);
}
}
//and adjust vector info
if(l.isCostChange()){
source.getRoutingTable().put(dest,l.getCost());
source.getVectorTable().remove(dest);
dest.getRoutingTable().put(source, l.getCost());
dest.getVectorTable().remove(source);
}
}
}
l.setActivityChange(false);
l.setCostChange(false);
} | 7 |
private static boolean isEmpty(int r, int t) {
if (r < 15 && t < 15 && r >= 0 && t >= 0){
String täht = Mang.MangulaudMassiiv[r][t];
return täht.equalsIgnoreCase(" ") ||
täht.equalsIgnoreCase("") ||
täht.equalsIgnoreCase("3xs") ||
täht.equalsIgnoreCase("2xs") ||
täht.equalsIgnoreCase("3xt") ||
täht.equalsIgnoreCase("2xt");
} else return false;
} | 9 |
public ITable getTable() {
return _table;
} | 0 |
@Override
public boolean insertAlbum(Album album) {
AlbumXML albumXML = new AlbumXML();
int lastAlbumID = 0;
try {
CDOrganizer cdOrganizer = XmlDAOFactory.unmarschallFile();
for (ArtistXML a : cdOrganizer.getArtistList()) {
if (a.getID() == album.getArtist().getId()) {
if ( a.getAlbumList() != null) {
for (AlbumXML b : a.getAlbumList()) {
lastAlbumID = b.getID();
if (b.getTitle().equals(album.getTitle())) {
System.out.println("Albumname existiert bereits bei dem Artist!");
return false;
}
}
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
albumXML.setID(lastAlbumID +1);
albumXML.setReleaseDate(formatter.format(album.getReleaseDate()));
albumXML.setTitle(album.getTitle());
//albumXML.setArtist(a);
a.addAlbum(albumXML);
XmlDAOFactory.marshallFile(cdOrganizer);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
} | 6 |
@Override
protected void setup()
{
if (createdByJADE)
{
Object[] args = getArguments();
if (args != null && args.length > 0)
{
String first = args[0].toString();
if (first.equals("full"))
{
int numberOfRequests = args.length/3;
if (args.length%3 == 1)
{
for (int i = 0; i < numberOfRequests; i++)
{
AID origin = new AID(args[i*3+1].toString(),false);
AID destination = new AID(args[i*3+2].toString(),false);
long waketime = Integer.parseInt(args[i*3+3].toString());
addBehaviour(new PassengerGroupAgent.RequestTransportBehaviour(this,waketime,origin,destination));
}
}
else
{
System.err.println("ERROR :: PassengerGroupAgent JADE GUI bad arguments");
this.doDelete();
}
}
else
{
for (int i = 0; i < args.length; i++)
{
String requestData = args[i].toString();
String []components = requestData.split(" ");
if (components.length == 3)
{
int o = Integer.parseInt(components[0]);
int d = Integer.parseInt(components[1]);
long t = Integer.parseInt(components[2]);
AID origin = new AID("Postaja"+o,false);
AID destination = new AID("Postaja"+d,false);
addBehaviour(new PassengerGroupAgent.RequestTransportBehaviour(this,t,origin,destination));
}
else
{
System.err.println("ERROR :: PassengerGroupAgent JADE GUI bad arguments");
}
}
}
}
else
{
System.err.println("ERROR :: PassengerGroupAgent JADE GUI bad arguments");
this.doDelete();
}
}
else
{
addBehaviour(new PassengerGroupAgent.RequestTransportBehaviour(this,timeout,originAID,destinationAID));
}
} | 8 |
private void showHelp(CommandSender sender) {
StringBuilder user = new StringBuilder();
StringBuilder admin = new StringBuilder();
for (Command cmd : commands.values()) {
CommandInfo info = cmd.getClass().getAnnotation(CommandInfo.class);
if(!PermHandler.hasPerm(sender, info.permission())) continue;
StringBuilder buffy;
if (info.permission().startsWith("adrundaalgods.admin"))
buffy = admin;
else
buffy = user;
buffy.append("\n")
.append(ChatColor.RESET).append(info.usage()).append(" ")
.append(ChatColor.YELLOW).append(info.desc());
}
if (admin.length() == 0) {
Messenger.sendMessage(sender, "Available Commands: "+user.toString());
} else {
Messenger.sendMessage(sender, "User Commands: "+user.toString());
Messenger.sendMessage(sender, "Admin Commands: "+admin.toString());
}
} | 4 |
static void createFiles() {
try {
boolean success = new File("data" + File.separator + "logins-db").mkdirs(); // make directory
if (success) {
Server.display("Created directory: data" + File.separator + "logins-db");
} else {
// File already exists
}
File file0 = new File("data" + File.separator + "logins-db" + File.separator + "console.dat");
// Create file if it does not exist
success = file0.createNewFile();
if (success) {
Server.display("Created file: " + file0);
} else {
// File already exists
}
File file1 = new File("data" + File.separator + "users-ops.txt");
// Create file if it does not exist
success = file1.createNewFile();
if (success) {
Server.display("Created file: " + file1);
} else {
// File already exists
}
File file2 = new File("data" + File.separator + "users-voiced.txt");
// Create file if it does not exist
success = file2.createNewFile();
if (success) {
Server.display("Created file: " + file2);
} else {
// File already exists
}
File file3 = new File("data" + File.separator + "users-banned.txt");
// Create file if it does not exist
success = file3.createNewFile();
if (success) {
Server.display("Created file: " + file3);
} else {
// File already exists
}
File file4 = new File("data" + File.separator + "users-admins.txt");
// Create file if it does not exist
success = file4.createNewFile();
if (success) {
Server.display("Created file: " + file4);
} else {
// File already exists
}
File file5 = new File("data" + File.separator + "motd.txt");
// Create file if it does not exist
success = file5.createNewFile();
if (success) {
BufferedWriter motdFile = new BufferedWriter(new FileWriter(file5));
motdFile.write("This is the default Message of the Day.");
motdFile.newLine();
motdFile.write("It can be changed by editing data" + File.separator + "motd.txt.");
motdFile.close();
Server.display("Created file: " + file5);
} else {
// File already exists
}
} catch (IOException e) {
Server.display("Could not create file: " + e);
}
} | 8 |
public String decodeText(String _text) {
// Obfuscated code will return by using StringBuilder;
StringBuilder sb = new StringBuilder();
// Change text to Char array.
char ch[] = _text.toCharArray();
// Make String array per 1 character from ch[].
// This String array uses to check key character and etc.
String choppedText[] = new String[_text.length()];
for (int i = 0; i < _text.length(); i++) {
choppedText[i] = String.valueOf(ch[i]);
}
// Decode text with binary transportation.
// Use while because it needs variable count up i.
int i = 0;
while (i < _text.length()) {
// Deprecated cause of hard coding.
// Checking tab and line separator characters.
// First step : Reach key character, check next character.
if (choppedText[i].matches(_keyChar)) {
// Case next character is "9", this might means it's tab code.
if (choppedText[i + 1].matches("9")) {
sb.append(new String(DatatypeConverter.parseHexBinary(TAB)));
i = i + 2;
} else if (choppedText[i + 1].matches("a")) {
// Case next character is "a", this might means line
// separator character.
sb.append(new String(DatatypeConverter.parseHexBinary(LINE_SEPARATOR)));
i = i + 2;
} else if (choppedText[i + 1].matches("/")) {
// Case next character is ".", this might means likes
// "/@'/'g"
// So no needs more decoding.
break;
} else {
// Case next character is "0~F", this might correctly binary
// code.
sb.append(new String(DatatypeConverter.parseHexBinary(choppedText[i + 1] + choppedText[i + 2])));
i = i + 3;
}
} else {
// If it's note key character, no needs to decoding.
i++;
}
}
return new String(sb);
} | 6 |
void add(String value, DefaultListModel valuesLM, JList jList)
{
if ((value == null) || (value.length() == 0))
{
return;
}
int i = 0;
for (Enumeration<?> e = valuesLM.elements(); e.hasMoreElements(); i++)
{
String s = (String)e.nextElement();
int compare = s.compareTo(value);
if (compare == 0)
{
return;
}
else if (compare > 0)
{
valuesLM.add(i, value);
if (jList.isSelectedIndex(i))
{
jList.removeSelectionInterval(i, i);
}
return;
}
}
valuesLM.addElement(value);
} | 7 |
public RuleDefinitionInterface getRuleDefinition(URL defnFile) throws Exception {
RuleDefinitionInterface ruleDefi=(RuleDefinitionInterface)Factory.getFactory().getDataObject(Factory.ObjectTypes.RuleDefinition);
Document doc=getDocument(defnFile.openStream());
NodeList ruleSets=doc.getElementsByTagName("rulesets");
if(ruleSets!=null && ruleSets.getLength()==1){
Element ruleSetsElem=(Element)ruleSets.item(0);
ruleSets=ruleSetsElem.getElementsByTagName("ruleset");
if(ruleSets!=null){
for(int i=0;i<ruleSets.getLength();i++){
RuleSet rules=processRuleSet((Element)ruleSets.item(i));
ruleDefi.addRuleSet(rules);
}
}
}
NodeList ruless=doc.getElementsByTagName("rules");
if(ruless!=null){
for(int i=0;i<ruless.getLength();i++){
Rules rules=processRules((Element)ruless.item(i),ruleDefi);
ruleDefi.addRules(rules);
}
}
return ruleDefi;
} | 6 |
public void setNext(Items next) {
this.next = next;
} | 0 |
public void updateEntity() {
this.lastProgress = this.progress;
if(this.lastProgress >= 1.0F) {
this.func_31010_a(1.0F, 0.25F);
this.worldObj.removeBlockTileEntity(this.xCoord, this.yCoord, this.zCoord);
this.invalidate();
if(this.worldObj.getBlockId(this.xCoord, this.yCoord, this.zCoord) == Block.pistonMoving.blockID) {
this.worldObj.setBlockAndMetadataWithNotify(this.xCoord, this.yCoord, this.zCoord, this.storedBlockID, this.storedMetadata);
}
} else {
this.progress += 0.5F;
if(this.progress >= 1.0F) {
this.progress = 1.0F;
}
if(this.extending) {
this.func_31010_a(this.progress, this.progress - this.lastProgress + 0.0625F);
}
}
} | 4 |
@Override
public void endDocument () {} | 0 |
public static boolean intersects(Polygon obj, Polygon gridBoundary)
{
Line2D[] objLines = new Line2D[obj.npoints];
Line2D[] gridLines = new Line2D[gridBoundary.npoints];
objLines[0] = new Line2D.Double(obj.xpoints[0], obj.ypoints[0] + 1,
obj.xpoints[1] + 1, obj.ypoints[1]);
objLines[1] = new Line2D.Double(obj.xpoints[1] + 1, obj.ypoints[1],
obj.xpoints[2], obj.ypoints[2] - 1);
objLines[2] = new Line2D.Double(obj.xpoints[2], obj.ypoints[2] - 1,
obj.xpoints[3] - 1, obj.ypoints[3]);
objLines[3] = new Line2D.Double(obj.xpoints[3] - 1, obj.ypoints[3],
obj.xpoints[0], obj.ypoints[0] + 1);
for (int i = 0; i < gridLines.length; i++)
{
gridLines[i] = new Line2D.Double(gridBoundary.xpoints[i],
gridBoundary.ypoints[i], gridBoundary.xpoints[(i + 1)
% gridBoundary.npoints],
gridBoundary.ypoints[(i + 1) % gridBoundary.npoints]);
}
for (int i = 0; i < objLines.length; i++)
{
for (int j = 0; j < gridLines.length; j++)
{
if (objLines[i].intersectsLine(gridLines[j]))
{
return true;
}
}
}
return false;
} | 4 |
public static void main(String[] args) {
double d = 3.5;
int i = (int)d;
System.out.println(i);
} | 0 |
public void dispose() {
if (this.soundtrack != null) {
soundtrack.dispose();
}
for (Sound sound : sounds) {
sound.dispose();
}
// this.manager.unload("music/soundtrack.ogg");
} | 2 |
@Override
public void improveSolution(Board board) {
// handle black cells
outer: while (board.getCount(CellColor.BLACK) < board.getSolutionBlackCount()) {
for (final Set<Cell> group : board.getGroups(CellColor.BLACK)) {
if (tryExpand(board, group, CellColor.BLACK)) {
// we need to start from the beginning because the black groups could have changed
continue outer;
}
}
break;
}
// handle white cells
outer: while (true) {
board.connectWhiteCells();
for (final Set<Cell> group : board.getGroups(CellColor.WHITE)) {
final FixedCell fixedCell = group.iterator().next().getFixedCell();
if (fixedCell == null || fixedCell.getNumber() > group.size()) {
if (tryExpand(board, group, CellColor.WHITE)) {
// we need to start from the beginning because the white groups could have changed
continue outer;
}
}
}
break;
}
} | 8 |
@Override
public void deserialize(Buffer buf) {
firstNameId = buf.readShort();
if (firstNameId < 0)
throw new RuntimeException("Forbidden value on firstNameId = " + firstNameId + ", it doesn't respect the following condition : firstNameId < 0");
lastNameId = buf.readShort();
if (lastNameId < 0)
throw new RuntimeException("Forbidden value on lastNameId = " + lastNameId + ", it doesn't respect the following condition : lastNameId < 0");
worldX = buf.readShort();
if (worldX < -255 || worldX > 255)
throw new RuntimeException("Forbidden value on worldX = " + worldX + ", it doesn't respect the following condition : worldX < -255 || worldX > 255");
worldY = buf.readShort();
if (worldY < -255 || worldY > 255)
throw new RuntimeException("Forbidden value on worldY = " + worldY + ", it doesn't respect the following condition : worldY < -255 || worldY > 255");
mapId = buf.readInt();
subAreaId = buf.readShort();
if (subAreaId < 0)
throw new RuntimeException("Forbidden value on subAreaId = " + subAreaId + ", it doesn't respect the following condition : subAreaId < 0");
} | 7 |
public void open() {
// Create the dialog window
Shell shell = new Shell(getParent(), getStyle()); //Creates a shell object
shell.setText(getText()); //Sets the shell text to the return of getText
shell.setSize(WIDTH, HEIGHT); //Sets the size
createContents(shell); //Calls create contents
shell.open(); //Opens the shell
Display display = getParent().getDisplay(); //Sets the display to the display object of the parent
while (!shell.isDisposed()) { //While the shell isn't disposed
if (!display.readAndDispatch()) { //If there are no events on the stack
display.sleep(); //Put the display to sleep
}
}
} | 2 |
public Enter(String title) {
super(title);
this.setLayout(new BorderLayout());
buttonList = new ButtonList();
tabs = new TabPane();
Container contentPane = getContentPane();
contentPane.add(buttonList,BorderLayout.NORTH);
contentPane.add(tabs,BorderLayout.CENTER);
setSize(700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
} | 0 |
public boolean predictFromKBestList(GuideDecision decision) throws MaltChainedException {
if (decision instanceof SingleDecision) {
throw new GuideException("A sequantial decision model expect a sequence of decisions, not a single decision. ");
}
boolean success = false;
final SingleDecision singleDecision = ((MultipleDecision)decision).getSingleDecision(decisionIndex);
// TODO develop different strategies for resolving which kBestlist that should be used
if (nextDecisionModel != null && singleDecision.continueWithNextDecision()) {
success = nextDecisionModel.predictFromKBestList(decision);
}
if (!success) {
success = singleDecision.updateFromKBestList();
if (success && singleDecision.continueWithNextDecision() && decisionIndex+1 < decision.numberOfDecisions()) {
if (nextDecisionModel == null) {
initNextDecisionModel(((MultipleDecision)decision).getSingleDecision(decisionIndex+1), branchedDecisionSymbols);
}
nextDecisionModel.predict(decision);
}
}
return success;
} | 8 |
public Detalle(int idDetalle, Encargo encargo, Producto producto, String otro, double precio, int cantidad, String color) {
this.idDetalle = idDetalle;
this.encargo = encargo;
this.producto = producto;
this.otro = otro;
this.precio = precio;
this.cantidad = cantidad;
this.color = color;
} | 0 |
public static void main(String[] args) {
Random rand = new Random();
Integer[] states;
double[] distributionTheorique;
AlgorithmMCMC<Integer> algo;
MarkovChain mc;
double[] distributionExperimentale;
final int ITERATION = 100;
double pourcentages = 0;
int i = 0;
while (i < ITERATION) {
try {
int N = rand.nextInt(10) + 1;
states = new Integer[N];
for (int j = 0; j < N; j++) {
states[j] = j;
}
// distributionTheorique = Alea.createRandomDistribution(N, N*100);
distributionTheorique = Alea.createRandomDistributionProbabilistWithNoZero(N, N * 100);
// Myst.afficherTableau(distributionTheorique);
// System.out.println("ok");
algo = AlgorithmFactory.getInstance().getAlgorithm(AlgorithmFactory.METROPOLIS_HASTING, states, distributionTheorique);
mc = algo.constructChain();
mc.computeStationaryDistributionUntilStabilityFitness(0.000001, 0.001);
distributionExperimentale = mc.getStationary_distribution();
double difference_ditrib = 0.0;
for (int j = 0; j < N; j++) {
//assertEquals(distributionExperimentale[j],distributionTheorique[j],0.05);
difference_ditrib += Math.abs(distributionExperimentale[j] - distributionTheorique[j]);
}
difference_ditrib /= N;
pourcentages += difference_ditrib;
i++;
} catch (Exception ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
}
pourcentages /= ITERATION;
System.out.println("taux d'erreur : " + pourcentages * 100 + "%");
} | 4 |
@Override
public void mouseReleased(MouseEvent e) {
for (Button b : buttons) {
if (e.getPoint().x > b.p.x && e.getPoint().x < b.p.x + b.d.width && e.getPoint().y > b.p.y && e.getPoint().y < b.p.y + b.d.height) {
if(e.getButton() == 1){
b.left.run();
} else if(e.getButton() == 3){
b.right.run();
}
}
}
} | 7 |
public static String computeXpath (Node node) {
String Xpath = localXpath(node);
if ("" == Xpath) {
return Xpath;
}
else {
Node parent = node.getParentNode();
String moreXpath;
while (null != parent.getLocalName()) {
moreXpath = localXpath(parent);
Xpath = moreXpath + "/" + Xpath;
parent = parent.getParentNode();
}
return "/" + Xpath;
}
} | 2 |
public boolean equals(Phasor a){
boolean test = false;
if(this.isNaN() && a.isNaN()){
test=true;
}
else{
if(this.magnitude == a.magnitude && this.phaseInDeg == a.phaseInDeg)test = true;
}
return test;
} | 4 |
private void set(String d, String in) {
if (d.equals(MovieColumn.LANGUAGE)) {
language = in;
}
else if (d.equals(MovieColumn.MOVIE_ID)) {
movie_id = in;
}
else if (d.equals(MovieColumn.MOVIE_NAME)) {
movie_name = in;
}
else if (d.equals(MovieColumn.MOVIE_AUTHOR)) {
movie_author = in;
}
else if (d.equals(MovieColumn.MOVIE_DESCRIPTION)) {
movie_description = in;
}
else if (d.equals(MovieColumn.MOVIE_DURATION)) {
movie_duration = in;
}
else if (d.equals(MovieColumn.MOVIE_STARTDATE)) {
movie_startDate = in;
}
else if (d.equals(MovieColumn.MOVIE_ENDDATE)) {
movie_endDate = in;
}
this.setChangedTrue();
} | 8 |
public void printList(){
System.out.println("Name: " + this.name + ", Age: " + this.age + ", Illness: " + this.illness);
if (nextPatient != null){
nextPatient.printList();
}
} | 1 |
static private int jjMoveStringLiteralDfa8_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(6, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(7, active0);
return 8;
}
switch(curChar)
{
case 65:
return jjMoveStringLiteralDfa9_0(active0, 0x3c0L);
case 69:
return jjMoveStringLiteralDfa9_0(active0, 0x30L);
case 76:
return jjMoveStringLiteralDfa9_0(active0, 0xf000L);
default :
break;
}
return jjStartNfa_0(7, active0);
} | 5 |
protected String format(ProtectionDomain pd, Permission... perms) {
final CodeSource cs = pd.getCodeSource();
if (null == cs) {
return null;
}
final URL url = cs.getLocation();
if (null == url) {
return null;
}
final StringBuilder sb = new StringBuilder();
sb.append("grant codeBase \"");
sb.append(url.toString());
sb.append("\" {");
sb.append("\n");
for (Permission p : perms) {
sb.append("\tpermission ");
sb.append(" ");
sb.append(p.getClass().getName());
sb.append(" ");
sb.append("\"");
/* Some complex permissions have quoted strings embedded or
literal carriage returns that must be escaped. */
final String permissionName = p.getName();
final String escapedPermissionName = permissionName.replace("\"", "\\\"").replace("\r", "\\\r");
sb.append(escapedPermissionName);
sb.append("\", ");
sb.append("\"");
sb.append(p.getActions());
sb.append("\";");
sb.append("\n");
}
sb.append("};");
return sb.toString();
} | 3 |
public static int findClosingParenIteratively(String s, int startingParenLoc) {
// check for valid parens location
int openParenCounter = 1;
int returnVal = -1;
if (errorCheck(s, startingParenLoc))
return -1;
for (int i = startingParenLoc + 1; i < s.length(); i++) {
if (s.charAt(i) == '(') {
openParenCounter++;
} else if (s.charAt(i) == ')') {
openParenCounter--;
}
if (openParenCounter == 0) {
returnVal = i;
break;
}
}
return returnVal;
} | 5 |
public int firstIndexOf(int datum) {
for (int i = 0; i < size; i++) {
if (data[i] == datum) {
return i;
}
}
return -1;
} | 2 |
public static SqlMod updateSql(Model model) {
List<Object> params = new ArrayList<Object>();
String tableName = tableName(model);
List<Field> fields = fields(model);
List<String> _fields = new ArrayList<String>();
Serializable idVal = 0;
String idName = null;
for (Field f : fields) {
Id id = f.getAnnotation(Id.class);
if (id != null) {
f.setAccessible(true);
try {
idVal = (Serializable) f.get(model);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
Column column = f.getAnnotation(Column.class);
if (column != null) {
idName = column.name();
} else {
idName = defaultName(f.getName());
}
continue;
}
Column column = f.getAnnotation(Column.class);
if (column != null) {
_fields.add(column.name());
} else {
_fields.add(defaultName(f.getName()));
}
f.setAccessible(true);
Object val = null;
try {
val = f.get(model);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
params.add(val);
}
StringBuilder values = new StringBuilder();
for (int i = 0; i < _fields.size(); i++) {
if (i != _fields.size() - 1) {
values.append(_fields.get(i) + "= ?, ");
} else {
values.append(_fields.get(i) + "= ?");
}
}
SqlMod mod = new SqlMod();
mod.setSql(String.format("UPDATE %s SET %s WHERE %s = %s", tableName,
values.toString(), idName, idVal.toString()));
mod.setParams(params);
return mod;
} | 8 |
public int solution(final int[] sizes, final int[] directions) {
final Deque<Fish> stack = new LinkedList<Fish>();
final int N = sizes.length;
for (int i = 0; i < N; i++) {
final Fish downstreamFish = new Fish(sizes[i], directions[i]);
while (!stack.isEmpty()) {
final Fish upstreamFish = stack.peek();
if (upstreamFish.direction == DOWNSTREAM && downstreamFish.direction == UPSTREAM) {
if (upstreamFish.size < downstreamFish.size) {
stack.pop(); // Upstream fish eaten.
} else if (upstreamFish.size == downstreamFish.size) {
stack.push(downstreamFish);
break;
}
else {
break; // Downstream fish eaten.
}
}
else { // Fish can never meet.
stack.push(downstreamFish);
break;
}
}
if (stack.isEmpty()) {
stack.push(downstreamFish);
}
}
return stack.size();
} | 7 |
@Override
public boolean equals(Object other)
{
boolean result = false;
if (other instanceof RouteLeg)
{
RouteLeg that = (RouteLeg) other;
result = this.startNode == that.startNode && this.endNode == that.endNode;
}
return result;
} | 2 |
@Override
public void execute(MapleClient c, MessageCallback mc, String[] splitted) throws Exception {
String cmd = splitted[0];
MapleCharacter pl = c.getPlayer();
if (cmd.equalsIgnoreCase("donated")) {
if (splitted.length != 4) {
pl.dropMessage("syntax : !donated <ign> <amount> <paypal e-mail>");
}
short damount = 0;
try {
damount = Short.parseShort(splitted[2]);
} catch (NumberFormatException nfe) {
pl.dropMessage(nfe.toString());
return;
}
DonationProcessor.doDonation(c, cmd, damount, cmd);
} else if (cmd.equalsIgnoreCase("setdamount")) {
if (splitted.length != 3) {
mc.dropMessage("[Anbu]Drunk?? read the commands. Syntax : !setdamount ign amount");
return;
}
String name = splitted[1];
short amt = 0;
try {
amt = Short.parseShort(splitted[2]);
} catch (NumberFormatException nfe) {
pl.dropMessage(nfe.toString());
return;
}
DonationProcessor.setDAmount(c, name, amt);
} else if (cmd.equalsIgnoreCase("setdpoint")) {
if (splitted.length != 3) {
mc.dropMessage("[Anbu]Drunk?? read the commands. Syntax : !setdpoint ign amount");
return;
}
String name = splitted[1];
short amt = 0;
try {
amt = Short.parseShort(splitted[2]);
} catch (NumberFormatException nfe) {
pl.dropMessage(nfe.toString());
return;
}
DonationProcessor.setDPoints(c, name, amt);
}
} | 9 |
@Override
public void evaluate(final Population a_chromosomes) {
double curFitness;
final Iterator itChromosomes = a_chromosomes.iterator();
IChromosome chromosome;
while (itChromosomes.hasNext()) {
chromosome = (IChromosome) itChromosomes.next();
curFitness = chromosome.getFitnessValueDirectly();
if (curFitness < 0) {
// fitness was not evaluated for this chromosome yet.
curFitness = fitnessFunction.getFitnessValue(chromosome);
// And store it to avoid evaluation of the same Chromosome again:
chromosome.setFitnessValue(curFitness);
} else {
chromosome.setFitnessValue(curFitness);
}
}
} | 2 |
public static void play(Resource res, boolean loop) {
synchronized(Music.class) {
if(player != null)
player.interrupt();
if(res != null) {
player = new Player(res, player);
player.loop = loop;
player.start();
}
}
} | 2 |
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
config = plugin.getConfig();
if (args.length == 0){
if (sender instanceof Player) {
if (commandLabel.equalsIgnoreCase("winner")) {
Player player = Bukkit.getServer().getPlayer(args[0]);
Bukkit.getServer().broadcastMessage(ChatColor.GOLD + player.getName() + " has won the event! Server will stop in" + config.get("Time before shutdown after /winner [name]. (In seconds)") + " seconds!");
}
}
}
return true;
} | 3 |
public void removeListener (Listener listener) {
if (listener == null) throw new IllegalArgumentException("listener cannot be null.");
synchronized (listenerLock) {
Listener[] listeners = this.listeners;
int n = listeners.length;
if (n == 0) return;
Listener[] newListeners = new Listener[n - 1];
for (int i = 0, ii = 0; i < n; i++) {
Listener copyListener = listeners[i];
if (listener == copyListener) continue;
if (ii == n - 1) return;
newListeners[ii++] = copyListener;
}
this.listeners = newListeners;
}
if (TRACE) trace("kryonet", "Connection listener removed: " + listener.getClass().getName());
} | 6 |
public void saveCape(SpoutPlayer player) {
File saveFile = new File(getDataFolder(), "saved.yml");
if (!saveFile.exists()) {
try {
saveFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(PlayerPlus.class.getName()).log(Level.SEVERE, null, ex);
}
}
YamlConfiguration yFile = YamlConfiguration.loadConfiguration(saveFile);
yFile.set(player.getName()+"."+"CAPES", player.getCape());
try {
yFile.save(saveFile);
} catch (IOException ex) {
Logger.getLogger(PlayerPlus.class.getName()).log(Level.SEVERE, null, ex);
}
} | 3 |
@Override
public boolean confirmOrder(ArrayList<Product> order) {
//Verify
for (Product p : order) {
if (!dbHandler.verifyInventory(p.getId(), -p.getInCurrentCart())) {
return false;
}
}
//Change inventory
for (Product p : order) {
dbHandler.addInventory(p.getId(), -p.getInCurrentCart());
}
return true;
} | 3 |
public void visit_invokeinterface(final Instruction inst) {
final MemberRef method = (MemberRef) inst.operand();
final Type type = method.nameAndType().type();
stackHeight -= type.stackHeight() + 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += type.returnType().stackHeight();
} | 1 |
public static World createWorld(int width, int height) {
stoneBoundary = height - 2*(height/3);
dirtBoundary = height - 2*(height/3) - height/12;
blockSheet = new int[width][height];
createStone(width, height);
createDirt(width, height);
createTrees(width, height);
FacilityGenerator.createFacility(blockSheet);
return new World(width, height, blockSheet);
} | 0 |
public int MovePacket(int inputBufferNumber, int outputBufferNumber, int TIME)
{
//ONLY ONE BUS PRESENT IN THIS FABRIC
//if Active status was successful and the flag is true for having
//control of the bus
//set packet moved default
packetMoved = false;
//get the RouterPacket in the InputBuffer selected
RouterPacket peekPacket = (RouterPacket)inputBuffers[inputBufferNumber].peek();
//esure there is a packet to move, packet activate bus successfully,bus becomes active
if((peekPacket != null) && (sequence[0] == peekPacket.GetSequenceNumber()) &&
(GetBusActiveStatus(0)== true))
{
//ensure there is packet in the buffer
if(inputBuffers[inputBufferNumber].size() > 0)
{
//System.out.println("MOVEPACKET FROM: "+inputBufferNumber+" TO: "+outputBufferNumber);
//get RouterPacket from input buffer
RouterPacket rPacket = (RouterPacket)inputBuffers[inputBufferNumber].remove();
//update the time delivered
rPacket.SetTimeDelivered(TIME);
//set the recent packet moved
recentPacket = rPacket;
//set the recent bus used
recentBus = 0;
//move the data to the output buffer
this.outputBuffers[outputBufferNumber].add(rPacket);
//set packet successfully moved
packetMoved = true;
}
}
//tell the bus used to send the packet, has only 1 bus
return recentBus;
} | 4 |
@Override
public void generateChunk(InitialBlocks chunk, int chunkX, int chunkZ) {
//EC: use the one passed in instead
//int chunkX = chunk.getX();
//int chunkZ = chunk.getZ();
for(int x=0; x<16; x++) {
for(int z=0; z<16; z++) {
int trueX = chunkX*16+x;
int trueZ = chunkZ*16+z;
chunk.setBlocks(x, 1, surfaceAt, z, materialLiquid);
// chunk.setBlocks(x, 1, surfaceAt, z, 64);
// for(int y=0; y<64; y++)
// result[xyzToByte(x,y,z)] = (byte) Material.STATIONARY_WATER.getId();
double h = BananaTrigFunction.get(trueX, trueZ)*50+surfaceAt;
// double h = BananaTrigFunction.get(trueX, trueZ)*77+50;
boolean river = false;
if(BananaTrigFunction.holes(trueX, trueZ)) {
river = true;
h = h-6;
chunk.setBlocks(x, (int)h, (int)h+4, z, materialLiquid);
// for(int y=(int) h; y<h+4; y++)
// result[xyzToByte(x,y,z)] = (byte) Material.STATIONARY_WATER.getId();
}
if (!river) {
chunk.setBlocks(x, (int)h-1, (int)h, z, materialGrass);
chunk.setBlocks(x, (int)h-5, (int)h-1, z, materialDirt);
} else
chunk.setBlocks(x, (int)h-5, (int)h, z, materialDirt);
chunk.setBlocks(x, 1, (int)h-5, z, materialStone);
// for(int y=0; y<h; y++) {
// byte mat = byteAir;
// if(y>h-2 && !river)
// mat = byteGrass;
// else if(y>h-5)
// mat = byteDirt;
// else
// mat = byteStone;
// result[xyzToByte(x,y,z)] = mat;
// }
// CAVES
int highest = -1;
for(int i=125; i>0; i--) {
if(highest == -1)
if(chunk.getBlockType(x, i, z) != Material.AIR)
// if(result[xyzToByte(x,i,z)] > 0)
highest=i;
}
if(highest>40) {
double height = (Math.sin(BananaTrigFunction.normalise(trueX+trueZ))+Math.sin(BananaTrigFunction.normalise(trueX))+Math.sin(BananaTrigFunction.normalise(trueZ)))*5+5;
if(height>5) {
chunk.setBlocks(x, (int)(highest/2.0), (int)(highest/2.0+height), z, Material.AIR);
// for(int y=highest/2; y<highest/2+height; y++) {
// result[xyzToByte(x,y,z)] = 0;
// }
}
}
//This will set the floor of each chunk at bedrock level to bedrock
//result[xyzToByte(x,0,z)] = (byte) Material.BEDROCK.getId();
}
}
} | 9 |
private static CtClass findCommonSuperClass(CtClass one, CtClass two) throws NotFoundException {
CtClass deep = one;
CtClass shallow = two;
CtClass backupShallow = shallow;
CtClass backupDeep = deep;
// Phase 1 - Find the deepest hierarchy, set deep and shallow correctly
for (;;) {
// In case we get lucky, and find a match early
if (eq(deep, shallow) && deep.getSuperclass() != null)
return deep;
CtClass deepSuper = deep.getSuperclass();
CtClass shallowSuper = shallow.getSuperclass();
if (shallowSuper == null) {
// right, now reset shallow
shallow = backupShallow;
break;
}
if (deepSuper == null) {
// wrong, swap them, since deep is now useless, its our tmp before we swap it
deep = backupDeep;
backupDeep = backupShallow;
backupShallow = deep;
deep = shallow;
shallow = backupShallow;
break;
}
deep = deepSuper;
shallow = shallowSuper;
}
// Phase 2 - Move deepBackup up by (deep end - deep)
for (;;) {
deep = deep.getSuperclass();
if (deep == null)
break;
backupDeep = backupDeep.getSuperclass();
}
deep = backupDeep;
// Phase 3 - The hierarchy positions are now aligned
// The common super class is easy to find now
while (!eq(deep, shallow)) {
deep = deep.getSuperclass();
shallow = shallow.getSuperclass();
}
return deep;
} | 8 |
public boolean hasLocationpath(String xpathExpression){
if (xpathExpression.contains("/")){
return true;
}else{
return false;
}
} | 1 |
public void open(Player player) {
Inventory inventory = Bukkit.createInventory(player, size, name);
for (int i = 0; i < optionIcons.length; i++) {
if (optionIcons[i] != null) {
inventory.setItem(i, optionIcons[i]);
}
}
player.openInventory(inventory);
} | 2 |
public boolean canScroll(Direction scrollDirection) {
Point robot = model.getRobotLocation();
int topBorder = Math.abs(panel.getScroll());
int bottomBorder = Math.abs(panel.getScroll()) + panel.getHeight();
switch(scrollDirection) {
case DOWN:
return robot.y <= (topBorder + 50);
case UP:
return robot.y >= (bottomBorder - 50);
default:
// It's only ever supposed to be scrolling up or down
break;
}
return false;
} | 2 |
public Coordinate setAIMove() throws IndexOutOfBoundsException,
InterruptedException {
boolean test = false;
if (test || m_test) {
System.out.println("OthelloAI :: setAIMove() BEGIN");
}
ArrayList<Coordinate> listTwo = new ArrayList<Coordinate>();
listTwo = getAvailableMoves();
int maximum = 0;
if(!listTwo.isEmpty()){
Coordinate takeCoord = listTwo.get(0);
for (Coordinate coord : listTwo) {
int move = getGame().moveScore(coord);
System.out.println("Max: " + maximum + "move: " + move);
if (move >= maximum) {
takeCoord = coord;
maximum = move;
}
}
maximum = 0;
if (test || m_test) {
System.out.println("ConnectFourAI :: setAIMove() END");
}
return takeCoord;
} else {
if (test || m_test) {
System.out.println("ConnectFourAI :: setAIMove() END");
}
return null;
}
} | 9 |
public void deleteFile() {
String dirPath = "resources/files/RecipeData/" + recipeID + ".json";
File currFile = new File(dirPath + recipeID + ".json");
if (!currFile.exists()) {
return; //there is nothing to delete
}
String jsonString = ""; //the json String representation of the last File
RecipeData lastRecipeData;
File f = new File(dirPath);
int lastID = f.listFiles().length - 1; //with 2 files, last ID 1 -> -1
File lastFile = new File("resources/files/RecipeData/" + lastID + ".json");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(lastFile));
String lastReadLine = reader.readLine();
while (lastReadLine != null) {
jsonString += lastReadLine;
lastReadLine = reader.readLine();
} //Get the json String representation of the last File
lastRecipeData = new RecipeData(jsonString); //load the last recipe
lastRecipeData.setRecipeID(recipeID); //set the last recipe's ID to the curr one
lastRecipeData.writeFile(); //overwrite the file to be deleted with the last one
reader.close(); //close reader in order to delete the last file
lastFile.delete(); //deletes the last file as it is already written at the currFile's id
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
finally {
if(reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} | 6 |
public double rawStandardDeviationCorrelationCoefficients(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.covariancesCalculated)this.covariancesAndCorrelationCoefficients();
return this.rawStandardDeviationRhoWithoutTotals;
} | 2 |
public ArrayList<Geometry> calculate(ArrayList<Residue> residueList) {
ArrayList<Geometry> geoArray = new ArrayList<Geometry>();
for (int i = 0; i < residueList.size() - 5; i += 2) {
if (!residueList.get(i).getSS().equals("T") && !residueList.get(i+4).getSS().equals("T")
&& !residueList.get(i+1).getSS().equals("T") && !residueList.get(i+5).getSS().equals("T")) {
/**
* I know this looks insane but it's seriously the only way to
* get this to work. Don't judge, alright?
*
* Also if you waste more time on it I ask that you increment
* the following counter:
*
* time_wasted_here = 20 hrs ;-;
*/
double magnitudeOfX = 0;
double distance;
double delta;
double theta;
double rho = 0;
CartesianCoord p0, p1, p2, p3, e1, l, e2;
p0 = (residueList.get(i).getPMOI());
p1 = (residueList.get(i + 1).getPMOI());
p2 = (residueList.get(i + 4).getPMOI());
p3 = (residueList.get(i + 5).getPMOI());
// calculate e1, vector
e1 = calcE1LE2(p0, p1);
// calculate l, vector
l = calcE1LE2(p2, p1);
// calculate e2, vector
e2 = calcE1LE2(p3, p2);
// calculate distance, d, scalar
distance = calcDistance(p2, p1);
// calc delta angle
delta = calcAngles(e1, l);
// calc theta angle
theta = calcAngles(e1, e2);
// calc n, this is a vector
CartesianCoord crossProd = calcCrossProd(l, e1);
double lengthOfCrossProd = calcMagnitude(l) * calcMagnitude(e1)
* Math.sin(theta);
CartesianCoord n = new CartesianCoord(crossProd.getX()
/ lengthOfCrossProd, crossProd.getY()
/ lengthOfCrossProd, crossProd.getZ()
/ lengthOfCrossProd);
// calc x, this is a vector
double e1e2DotProd = calcDotProd(e1, e2);
CartesianCoord secondTermOfX = new CartesianCoord(e1.getX()
* e1e2DotProd, e1.getY() * e1e2DotProd, e1.getZ()
* e1e2DotProd);
CartesianCoord x = new CartesianCoord(e2.getX() - e1.getX(),
e2.getY() - e1.getY(), e2.getZ() - e1.getZ());
// calc rho angle
double xOfX = x.getX();
double yOfX = x.getY();
double zOfX = x.getZ();
magnitudeOfX = calcMagnitude(x);
CartesianCoord vectorXDividedByLength = new CartesianCoord(xOfX
/ magnitudeOfX, yOfX / magnitudeOfX, zOfX
/ magnitudeOfX);
//check if rho exists as a real number
double doesRhoExist = Math.abs(calcDotProd(vectorXDividedByLength, n));
boolean isRhoReal = false;
//if rho does exist, check which case rho should be calculated
double whichCaseOfRho = calcDotProd(x, calcCrossProd(e1, n));
if (doesRhoExist > 1.0) {
System.out.println("Error: Rho does not exist--Not a number");
} else if (whichCaseOfRho >= 0) {
rho = Math.acos(calcDotProd(vectorXDividedByLength, n));
isRhoReal = true;
} else if (whichCaseOfRho <= 0) {
rho = (2 * Math.PI)
- Math.acos(calcDotProd(vectorXDividedByLength, n));
isRhoReal = true;
}
String stRes = residueList.get(i).getResNum();
String endRes = residueList.get(i + 5).getResNum();
// Constructor takes info:
// (String stRes, String endRes,
// String distance, String delta, String theta, String rho
delta = delta * (180/Math.PI);
theta = theta * (180/Math.PI);
rho = rho * (180/Math.PI);
//don't create a residue if rho does not exist
if (isRhoReal) {
geoArray.add(new Geometry(stRes, endRes,
"" + distance + "", "" + delta + "", "" + theta
+ "", "" + rho + ""));
}
}
}
return geoArray;
} | 9 |
public static void createOpponentCardInfo(ItemStack item, Card c) {
if(MonsterCard.class.isInstance(c)) {
MonsterCard mc = MonsterCard.class.cast(c);
if(mc.faceup)
Duelist.createCardInfo(item, c);
else {
Main.setItemName(item, "?");
Main.giveLore(item, 4);
Main.setItemData(item, 0, "[Monster] ?/?");
Main.setItemData(item, 1, "?/?");
Main.setItemData(item, 2, "Face-down " + mc.position.toString());
Main.setItemData(item, 3, mc.star.toString());
}
} else if(SpellCard.class.isInstance(c)) {
SpellCard sc = SpellCard.class.cast(c);
if(sc.faceup)
Duelist.createCardInfo(item, c);
else {
Main.setItemName(item, "?");
Main.giveLore(item, 2);
Main.setItemData(item, 0, "[Spell/Trap]");
Main.setItemData(item, 1, "Face-down");
}
} else if(EquipCard.class.isInstance(c)) {
EquipCard ec = EquipCard.class.cast(c);
if(ec.faceup)
Duelist.createCardInfo(item, c);
else {
Main.setItemName(item, "?");
Main.giveLore(item, 2);
Main.setItemData(item, 0, "[Spell/Trap]");
Main.setItemData(item, 1, "Face-down");
}
}
} | 6 |
void setObjectAlreadyInDB(boolean objectAlreadyInDB) {
this.objectAlreadyInDB = objectAlreadyInDB;
}//setObjectAlreadyInDB | 0 |
public void testBinaryCycAccess10() {
System.out.println("\n**** testBinaryCycAccess 10 ****");
CycAccess cycAccess = null;
try {
try {
if (connectionMode == LOCAL_CYC_CONNECTION) {
cycAccess = new CycAccess(testHostName, testBasePort);
} else if (connectionMode == SOAP_CYC_CONNECTION) {
cycAccess = new CycAccess(endpointURL, testHostName, testBasePort);
} else {
fail("Invalid connection mode " + connectionMode);
}
} catch (Throwable e) {
fail(e.toString());
}
System.out.println(cycAccess.getCycConnection().connectionInfo());
//cycAccess.traceOn();
doTestCycAccess10(cycAccess);
} finally {
if (cycAccess != null) {
cycAccess.close();
cycAccess = null;
}
}
System.out.println("**** testBinaryCycAccess 10 OK ****");
} | 4 |
@Test
public void selectLocationTest() {
System.out.println(board.getPlayers().size());
ComputerPlayer player = (ComputerPlayer)board.getPlayers().get(0);
// Pick a location with no rooms in target, just three targets
board.calcTargets(board.calcIndex(3, 3),2);
int loc1 = 0;
int loc2 = 0;
int loc3 = 0;
// Run the test 100 times
for (int i=0; i<100; i++) {
BoardCell selected = player.pickLocation(board.getTargets());
if (selected == board.getCellAt(board.calcIndex(3, 5)))
loc1++;
else if (selected == board.getCellAt(board.calcIndex(5,3)))
loc2++;
else if (selected == board.getCellAt(board.calcIndex(4,4)))
loc3++;
else
Assert.fail("Invalid target selected");
}
// Ensure we have 100 total selections (fail should also ensure)
Assert.assertEquals(100, loc1 + loc2 + loc3);
// Ensure each target was selected more than once
Assert.assertTrue(loc1 > 10);
Assert.assertTrue(loc2 > 10);
Assert.assertTrue(loc3 > 10);
board.calcTargets(board.calcIndex(5, 1), 1);
for(int i = 0; i < 100; i++){
player.lastVisitedName = 'z';
BoardCell selected = player.pickLocation(board.getTargets());
Assert.assertEquals(selected, board.getCellAt(board.calcIndex(4, 1)));
}
player.lastVisitedName = 'E';
loc1 = 0;
loc2 = 0;
loc3 = 0;
// Run the test 100 times
for (int i=0; i<100; i++) {
BoardCell selected = player.pickLocation(board.getTargets());
if (selected.equals(board.getCellAt(board.calcIndex(5, 0))))
loc1++;
else if (selected.equals(board.getCellAt(board.calcIndex(5, 2))))
loc2++;
else if (selected.equals(board.getCellAt(board.calcIndex(4, 1))))
loc3++;
}
// Ensure we have 100 total selections (fail should also ensure)
Assert.assertEquals(100, loc1 + loc2 + loc3);
// Ensure each target was selected more than once
Assert.assertTrue(loc1 > 10);
Assert.assertTrue(loc2 > 10);
Assert.assertTrue(loc3>10);
} | 9 |
public static GoHomeAndSleepTillRested getSingleton(){
// needed because once there is singleton available no need to acquire
// monitor again & again as it is costly
if(singleton==null) {
synchronized(GoHomeAndSleepTillRested.class){
// this is needed if two threads are waiting at the monitor at the
// time when singleton was getting instantiated
if(singleton==null)
singleton = new GoHomeAndSleepTillRested();
}
}
return singleton;
} | 2 |
**/
private void exciteVerticalSameShapeRecognizers(int shape) {
int shapeOffset = 2500 * shape;
double weight = 0.3;
for (int neuron = 0; neuron < 2500; neuron++) {
if (neuron % 5 != 0) {// not the inhibitory ones
int toNeuron;
int fromNeuron = neuron + shapeOffset;
int fromCol = neuron % 50;
int fromRow = neuron / 50;
if ((fromRow % 10) >= 5) {// only for bottom half.
int fromBigRow = neuron / 500;
int fromBigCol = fromCol / 10;
int toBigCol = fromBigCol; // going up column "n"
for (int toBigRow = 0; toBigRow < 5; toBigRow++) { // through all the
// other rows
if (toBigRow != fromBigRow) { // not self
for (int toRow = 5; toRow < 10; toRow++) {// ignoring the top half
// of the big rows
for (int i = 0; i < 10; i++) {
toNeuron = shapeOffset + toBigRow * 500 + toRow * 50
+ toBigCol * 10 + i;
addConnection(fromNeuron, toNeuron + 4, weight);
}
}
}
}
}
}
}
} | 7 |
public DisplayMode[] getCompatibleDisplayModes() {
return device.getDisplayModes();
} | 0 |
public void renderElementalCircle(int xp, int yp, Element e, int phase) {
int col = 0;
Sprite sprite = Sprite.elementalCircle[phase];
switch (e) {
case FIRE: { col = 0xffE5554C; break; }
case WATER: { col = 0xff4C70E5; break; }
case EARTH: { col = 0xff82E54C; break; }
case WIND: { col = 0xffE5E5E5; break; }
}
for (int y = 0; y < sprite.height; y++){
int ya = y + yp;
for (int x = 0; x < sprite.width; x++) {
int xa = x + xp;
int c = 0xffff00ff, c2 = 0xffffff55;
if (sprite.pixels[x + y * sprite.width] != c
&& sprite.pixels[x + y * sprite.width] != c2) pixels[xa + ya * width] = sprite.pixels[x + y * sprite.width];
if (sprite.pixels[x + y * sprite.width] == 0xffff55ff) pixels[xa + ya * width] = col;
}
}
} | 9 |
private void checkForRotation(){
double tangent = (this.highYaxisXpixel - this.lowYaxisXpixel)/(this.highYaxisYpixel - this.lowYaxisYpixel);
this.angleYaxis = Math.toDegrees(Math.atan(tangent));
tangent = (this.lowXaxisYpixel - this.highXaxisYpixel)/(this.highXaxisXpixel - this.lowXaxisXpixel);
this.angleXaxis = Math.toDegrees(Math.atan(tangent));
this.angleMean = (this.angleXaxis + this.angleYaxis)/2.0;
double absMean = Math.abs(this.angleMean);
if(absMean!=0.0 && absMean>this.angleTolerance)performRotation();
} | 2 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.