text
stringlengths 30
1.67M
|
|---|
<s> package arch ; import static jason . asSyntax . ASSyntax . createAtom ; import static jason . asSyntax . ASSyntax . createLiteral ; import static jason . asSyntax . ASSyntax . createNumber ; import jason . JasonException ; import jason . ReceiverNotFoundException ; import jason . RevisionFailedException ; import jason . asSemantics . Intention ; import jason . asSemantics . Message ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . Atom ; import jason . asSyntax . Literal ; import jason . asSyntax . LiteralImpl ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Structure ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import jason . mas2j . ClassParameters ; import jason . runtime . Settings ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . Map ; import java . util . Queue ; import java . util . Set ; import java . util . concurrent . LinkedBlockingQueue ; import java . util . concurrent . ScheduledExecutorService ; import java . util . concurrent . ScheduledThreadPoolExecutor ; import java . util . concurrent . TimeUnit ; import java . util . logging . Level ; import java . util . logging . Logger ; import jia . cluster ; import jmoise . OrgAgent ; import agent . SelectEvent ; import env . WorldModel ; import env . WorldView ; import env . WorldModel . Move ; import env . ClusterModelFactory ; import env . CowModelFactory ; import env . IClusterModel ; import env . ICowModel ; import env . Cow ; import env . ClusterModel ; public class CowboyArch extends OrgAgent { LocalWorldModel model = null ; WorldView view = null ; ICowModel cModel = null ; IClusterModel clModel = null ; String simId = null ; int myId = - <NUM_LIT:1> ; boolean gui = false ; boolean playing = false ; String massimBackDir = null ; String teamId = null ; Map < Integer , Integer > lastSeen = new HashMap < Integer , Integer > ( ) ; int simStep = <NUM_LIT:0> ; WriteStatusThread writeStatusThread = null ; protected Logger logger = Logger . getLogger ( CowboyArch . class . getName ( ) ) ; public static Atom aOBSTACLE = new Atom ( "<STR_LIT>" ) ; public static Atom aENEMY = new Atom ( "<STR_LIT>" ) ; public static Atom aENEMYCORRAL = new Atom ( "<STR_LIT>" ) ; public static Atom aALLY = new Atom ( "<STR_LIT>" ) ; public static Atom aEMPTY = new Atom ( "<STR_LIT>" ) ; public static Atom aSWITCH = new Atom ( "<STR_LIT>" ) ; public static Atom aFENCE = new Atom ( "<STR_LIT>" ) ; public static Atom aOPEN = new Atom ( "<STR_LIT>" ) ; public static Atom aCLOSED = new Atom ( "<STR_LIT>" ) ; @ Override public void initAg ( String agClass , ClassParameters bbPars , String asSrc , Settings stts ) throws JasonException { super . initAg ( agClass , bbPars , asSrc , stts ) ; gui = "<STR_LIT:yes>" . equals ( stts . getUserParameter ( "<STR_LIT>" ) ) ; if ( getMyId ( ) == <NUM_LIT:0> ) gui = true ; boolean writeStatus = "<STR_LIT:yes>" . equals ( stts . getUserParameter ( "<STR_LIT>" ) ) ; boolean dumpAgsMind = "<STR_LIT:yes>" . equals ( stts . getUserParameter ( "<STR_LIT>" ) ) ; if ( writeStatus || dumpAgsMind ) writeStatusThread = WriteStatusThread . create ( this , writeStatus , dumpAgsMind ) ; teamId = stts . getUserParameter ( "<STR_LIT>" ) ; if ( teamId == null ) logger . info ( "<STR_LIT>" ) ; else if ( teamId . startsWith ( "<STR_LIT>" ) ) teamId = teamId . substring ( <NUM_LIT:1> , teamId . length ( ) - <NUM_LIT:1> ) ; WriteStatusThread . registerAgent ( getAgName ( ) , this ) ; massimBackDir = stts . getUserParameter ( "<STR_LIT>" ) ; if ( massimBackDir != null && massimBackDir . startsWith ( "<STR_LIT:\">" ) ) massimBackDir = massimBackDir . substring ( <NUM_LIT:1> , massimBackDir . length ( ) - <NUM_LIT:1> ) ; logger = Logger . getLogger ( CowboyArch . class . getName ( ) + "<STR_LIT>" + getAgName ( ) ) ; setCheckCommunicationLink ( false ) ; initialBeliefs ( ) ; } void initialBeliefs ( ) throws RevisionFailedException { getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( WorldModel . agsByTeam ) ) ) ; for ( int i = <NUM_LIT:1> ; i <= WorldModel . agsByTeam ; i ++ ) getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createAtom ( teamId + i ) , createNumber ( i ) ) ) ; getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( cluster . COWS_BY_BOY ) ) ) ; } @ Override public void stopAg ( ) { if ( view != null ) view . dispose ( ) ; if ( writeStatusThread != null ) writeStatusThread . interrupt ( ) ; super . stopAg ( ) ; } void setSimId ( String id ) { simId = id ; } public String getSimId ( ) { return simId ; } public boolean hasGUI ( ) { return gui ; } public int getMyId ( ) { if ( myId < <NUM_LIT:0> ) myId = getAgId ( getAgName ( ) ) ; return myId ; } public LocalWorldModel getModel ( ) { return model ; } void gsizePerceived ( int w , int h , String opponent ) throws RevisionFailedException { model = new LocalWorldModel ( w , h , WorldModel . agsByTeam , getTS ( ) . getAg ( ) . getBB ( ) ) ; model . setOpponent ( opponent ) ; getTS ( ) . getAg ( ) . addBel ( Literal . parseLiteral ( "<STR_LIT>" + w + "<STR_LIT:U+002C>" + h + "<STR_LIT:)>" ) ) ; playing = true ; cModel = CowModelFactory . getModel ( teamId + myId ) ; cModel . setSize ( w , h ) ; clModel = ClusterModelFactory . getModel ( teamId + myId ) ; clModel . setStepcl ( - <NUM_LIT:1> ) ; if ( view != null ) view . dispose ( ) ; if ( gui ) { try { view = new WorldView ( "<STR_LIT>" + ( getMyId ( ) + <NUM_LIT:1> ) + "<STR_LIT>" + opponent , model ) ; } catch ( Exception e ) { logger . info ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } } if ( writeStatusThread != null ) writeStatusThread . reset ( ) ; } void corralPerceived ( Location upperLeft , Location downRight ) throws RevisionFailedException { model . setCorral ( upperLeft , downRight ) ; getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( upperLeft . x ) , createNumber ( upperLeft . y ) , createNumber ( downRight . x ) , createNumber ( downRight . y ) ) ) ; } void stepsPerceived ( int s ) throws RevisionFailedException { getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( s ) ) ) ; model . setMaxSteps ( s ) ; model . restoreObstaclesFromFile ( this ) ; model . createStoreObsThread ( this ) ; } public void cowPerceived ( int cowId , int x , int y ) { Location c = new Location ( x , y ) ; if ( model . getCorral ( ) . contains ( c ) ) { } else { lastSeen . put ( cowId , getSimStep ( ) ) ; cModel . insertCow ( cowId , x , y , getSimStep ( ) ) ; } } public Cow [ ] getPerceivedCows ( ) { return cModel . getCows ( ) ; } public int getLastSeenCow ( int cow ) { return lastSeen . get ( cow ) ; } public void obstaclePerceived ( int x , int y ) { if ( ! model . hasObject ( WorldModel . OBSTACLE , x , y ) ) { model . add ( WorldModel . OBSTACLE , x , y ) ; Message m = new Message ( "<STR_LIT>" , null , null , createCellPerception ( x , y , aOBSTACLE ) ) ; try { broadcast ( m ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { Location l = new Location ( x , y ) ; if ( ephemeralObstacle . remove ( l ) ) logger . info ( "<STR_LIT>" + l + "<STR_LIT>" ) ; } if ( clModel == null ) clModel = ClusterModelFactory . getModel ( teamId + myId ) ; clModel . insertTree ( x , y ) ; } public void enemyCorralPerceived ( int x , int y ) { if ( ! model . hasObject ( WorldModel . ENEMYCORRAL , x , y ) ) { model . add ( WorldModel . ENEMYCORRAL , x , y ) ; Message m = new Message ( "<STR_LIT>" , null , null , createCellPerception ( x , y , aENEMYCORRAL ) ) ; try { broadcast ( m ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public void fencePerceived ( int x , int y , boolean open ) { int obj ; Atom s ; if ( open ) { obj = WorldModel . OPEN_FENCE ; s = aOPEN ; } else { obj = WorldModel . CLOSED_FENCE ; s = aCLOSED ; } if ( ! model . hasObject ( obj , x , y ) ) { model . add ( obj , x , y ) ; Message m = new Message ( "<STR_LIT>" , null , null , createCellPerception ( x , y , ASSyntax . createStructure ( aFENCE . toString ( ) , s ) ) ) ; try { broadcast ( m ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public void switchPerceived ( int x , int y ) throws RevisionFailedException { if ( ! model . hasObject ( WorldModel . SWITCH , x , y ) ) { getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( x ) , createNumber ( y ) ) ) ; Message m = new Message ( "<STR_LIT>" , null , null , createCellPerception ( x , y , aSWITCH ) ) ; try { broadcast ( m ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } model . add ( WorldModel . SWITCH , x , y ) ; } public void lineOfSightPerceived ( int line ) throws RevisionFailedException { model . setAgPerceptionRatio ( line ) ; getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( line ) ) ) ; getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( WorldModel . cowPerceptionRatio ) ) ) ; } private static final int lastRecordCapacity = <NUM_LIT:12> ; Queue < Location > lastLocations = new LinkedBlockingQueue < Location > ( lastRecordCapacity ) ; Queue < Move > lastActions = new LinkedBlockingQueue < Move > ( lastRecordCapacity ) ; Set < Location > ephemeralObstacle = new HashSet < Location > ( ) ; ScheduledExecutorService schedule = new ScheduledThreadPoolExecutor ( <NUM_LIT:30> ) ; private static < T > void myAddQueue ( Queue < T > q , T e ) { if ( ! q . offer ( e ) ) { q . poll ( ) ; q . offer ( e ) ; } } private static < T > boolean allEquals ( Queue < T > q ) { if ( q . size ( ) + <NUM_LIT:1> < lastRecordCapacity ) return false ; Iterator < T > il = q . iterator ( ) ; if ( il . hasNext ( ) ) { T first = il . next ( ) ; while ( il . hasNext ( ) ) { T other = il . next ( ) ; if ( ! first . equals ( other ) ) { return false ; } } } return true ; } public boolean isEphemeralObstacle ( Location l ) { return ephemeralObstacle . contains ( l ) ; } Location oldLoc ; public Location getLastLocation ( ) { return oldLoc ; } public Queue < Location > getLastLocations ( ) { return lastLocations ; } protected String lastAct ; protected void setLastAct ( String act ) { lastAct = act ; if ( act != null ) myAddQueue ( lastActions , Move . valueOf ( act ) ) ; } public String getLastAction ( ) { return lastAct ; } public int getSimStep ( ) { return simStep ; } void locationPerceived ( final int x , final int y ) { if ( model == null ) { logger . info ( "<STR_LIT>" ) ; return ; } oldLoc = model . getAgPos ( getMyId ( ) ) ; if ( oldLoc != null ) { model . clearAgView ( oldLoc ) ; } if ( oldLoc == null || ! oldLoc . equals ( new Location ( x , y ) ) ) { try { model . setAgPos ( getMyId ( ) , x , y ) ; model . incVisited ( x , y ) ; Message m = new Message ( "<STR_LIT>" , null , null , "<STR_LIT>" + x + "<STR_LIT:U+002C>" + y + "<STR_LIT:)>" ) ; broadcast ( m ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } myAddQueue ( lastLocations , new Location ( x , y ) ) ; checkRestart ( ) ; } protected void checkRestart ( ) { if ( allEquals ( lastLocations ) ) { try { logger . info ( "<STR_LIT>" + getAgName ( ) + "<STR_LIT>" + lastLocations ) ; getTS ( ) . getC ( ) . addAchvGoal ( new LiteralImpl ( "<STR_LIT>" ) , Intention . EmptyInt ) ; lastLocations . clear ( ) ; lastSeen . clear ( ) ; } catch ( Exception e ) { logger . info ( "<STR_LIT>" + e ) ; } if ( allEquals ( lastActions ) && lastActions . iterator ( ) . next ( ) != Move . skip ) { final Location newLoc = WorldModel . getNewLocationForAction ( getLastLocation ( ) , lastActions . peek ( ) ) ; if ( newLoc != null && ! model . hasObject ( WorldModel . OBSTACLE , newLoc ) ) { if ( model . hasObject ( WorldModel . FENCE , newLoc ) ) { logger . info ( "<STR_LIT>" + getAgName ( ) + "<STR_LIT>" + lastActions ) ; getTS ( ) . getC ( ) . addAchvGoal ( new LiteralImpl ( "<STR_LIT>" ) , Intention . EmptyInt ) ; } else { logger . info ( "<STR_LIT>" + newLoc + "<STR_LIT>" ) ; model . add ( WorldModel . OBSTACLE , newLoc ) ; ephemeralObstacle . add ( newLoc ) ; schedule . schedule ( new Runnable ( ) { public void run ( ) { if ( ephemeralObstacle . contains ( newLoc ) ) { logger . info ( "<STR_LIT>" + newLoc ) ; model . remove ( WorldModel . OBSTACLE , newLoc ) ; } } } , <NUM_LIT:10> , TimeUnit . SECONDS ) ; } } } } } public static Literal createCellPerception ( int x , int y , Term obj ) { return createLiteral ( "<STR_LIT>" , createNumber ( x ) , createNumber ( y ) , obj ) ; } void initKnownCows ( ) { model . clearKnownCows ( ) ; } void enemyPerceived ( int x , int y ) { model . add ( WorldModel . ENEMY , x , y ) ; } void simulationEndPerceived ( String result ) throws RevisionFailedException { getTS ( ) . getAg ( ) . addBel ( Literal . parseLiteral ( "<STR_LIT>" + result + "<STR_LIT:)>" ) ) ; model = null ; playing = false ; lastSeen . clear ( ) ; if ( view != null ) view . dispose ( ) ; cModel . reset ( ) ; } void setSimStep ( int s ) { ( ( SelectEvent ) getTS ( ) . getAg ( ) ) . cleanCows ( ) ; simStep = s ; super . setCycleNumber ( simStep ) ; if ( view != null ) view . setCycle ( simStep ) ; if ( writeStatusThread != null ) writeStatusThread . go ( ) ; } void setScore ( int s ) { model . setCowsBlue ( s ) ; } @ Override public void broadcast ( Message m ) throws Exception { if ( model == null ) return ; for ( int i = <NUM_LIT:1> ; i <= model . getAgsByTeam ( ) ; i ++ ) { String oname = teamId + i ; if ( ! getAgName ( ) . equals ( oname ) ) { Message msg = new Message ( m ) ; msg . setReceiver ( oname ) ; for ( int t = <NUM_LIT:0> ; t < <NUM_LIT:6> ; t ++ ) { try { sendMsg ( msg ) ; break ; } catch ( ReceiverNotFoundException e ) { logger . info ( "<STR_LIT>" + oname + "<STR_LIT>" + t ) ; Thread . sleep ( <NUM_LIT> ) ; } } } } } @ Override public void checkMail ( ) { super . checkMail ( ) ; Iterator < Message > im = getTS ( ) . getC ( ) . getMailBox ( ) . iterator ( ) ; while ( im . hasNext ( ) ) { Message m = im . next ( ) ; try { if ( m . getIlForce ( ) . equals ( "<STR_LIT>" ) ) { im . remove ( ) ; } else { String ms = m . getPropCont ( ) . toString ( ) ; if ( ms . startsWith ( "<STR_LIT>" ) && model != null ) { im . remove ( ) ; Literal p = ( Literal ) m . getPropCont ( ) ; int x = ( int ) ( ( NumberTerm ) p . getTerm ( <NUM_LIT:0> ) ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) p . getTerm ( <NUM_LIT:1> ) ) . solve ( ) ; if ( model . inGrid ( x , y ) ) { if ( p . getTerm ( <NUM_LIT:2> ) . equals ( aOBSTACLE ) ) { model . add ( WorldModel . OBSTACLE , x , y ) ; } else if ( p . getTerm ( <NUM_LIT:2> ) . equals ( aENEMYCORRAL ) ) { model . add ( WorldModel . ENEMYCORRAL , x , y ) ; } else if ( p . getTerm ( <NUM_LIT:2> ) . equals ( aSWITCH ) ) { model . add ( WorldModel . SWITCH , x , y ) ; Literal l = createLiteral ( "<STR_LIT>" , createNumber ( x ) , createNumber ( y ) ) ; l . addSource ( createAtom ( m . getSender ( ) ) ) ; getTS ( ) . getAg ( ) . addBel ( l ) ; } else if ( p . getTerm ( <NUM_LIT:2> ) . toString ( ) . startsWith ( aFENCE . toString ( ) ) ) { Structure s = ( Structure ) p . getTerm ( <NUM_LIT:2> ) ; if ( s . getTerm ( <NUM_LIT:0> ) . equals ( aOPEN ) ) { model . add ( WorldModel . OPEN_FENCE , x , y ) ; } else if ( s . getTerm ( <NUM_LIT:0> ) . equals ( aCLOSED ) ) { model . add ( WorldModel . CLOSED_FENCE , x , y ) ; } } } } else if ( ms . startsWith ( "<STR_LIT>" ) && model != null ) { im . remove ( ) ; Literal p = Literal . parseLiteral ( m . getPropCont ( ) . toString ( ) ) ; int x = ( int ) ( ( NumberTerm ) p . getTerm ( <NUM_LIT:0> ) ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) p . getTerm ( <NUM_LIT:1> ) ) . solve ( ) ; if ( model . inGrid ( x , y ) ) { try { int agid = getAgId ( m . getSender ( ) ) ; model . setAgPos ( agid , x , y ) ; model . incVisited ( x , y ) ; Literal tAlly = createLiteral ( "<STR_LIT>" , new Atom ( m . getSender ( ) ) , createNumber ( x ) , createNumber ( y ) ) ; getTS ( ) . getAg ( ) . addBel ( tAlly ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } } public static int getAgId ( String agName ) { boolean nbWith2Digits = Character . isDigit ( agName . charAt ( agName . length ( ) - <NUM_LIT:2> ) ) ; if ( nbWith2Digits ) return ( Integer . parseInt ( agName . substring ( agName . length ( ) - <NUM_LIT:2> ) ) ) - <NUM_LIT:1> ; else return ( Integer . parseInt ( agName . substring ( agName . length ( ) - <NUM_LIT:1> ) ) ) - <NUM_LIT:1> ; } public ICowModel getCowModel ( ) { return cModel ; } } </s>
|
<s> package arch ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . Socket ; import java . net . SocketException ; import java . util . logging . Level ; import java . util . logging . Logger ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . TransformerConfigurationException ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; public abstract class ACAgent { private Logger logger = Logger . getLogger ( ACAgent . class . getName ( ) ) ; @ SuppressWarnings ( "<STR_LIT:serial>" ) private class SocketClosedException extends Exception { } private int networkport ; private String networkhost ; private Socket socket ; private InputStream inputstream ; private OutputStream outputstream ; private String username ; private String password ; private DocumentBuilderFactory documentbuilderfactory ; private TransformerFactory transformerfactory ; private boolean connected = false ; public ACAgent ( ) { networkhost = "<STR_LIT:localhost>" ; networkport = <NUM_LIT:0> ; documentbuilderfactory = DocumentBuilderFactory . newInstance ( ) ; transformerfactory = TransformerFactory . newInstance ( ) ; } public String getHost ( ) { return networkhost ; } public void setHost ( String host ) { this . networkhost = host ; } public int getPort ( ) { return networkport ; } public void setPort ( int port ) { this . networkport = port ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } public String getPassword ( ) { return username ; } public void setPassword ( String password ) { this . password = password ; } public void sendAuthentication ( String username , String password ) throws IOException { try { Document doc = documentbuilderfactory . newDocumentBuilder ( ) . newDocument ( ) ; Element root = doc . createElement ( "<STR_LIT:message>" ) ; root . setAttribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ; doc . appendChild ( root ) ; Element auth = doc . createElement ( "<STR_LIT>" ) ; auth . setAttribute ( "<STR_LIT:username>" , username ) ; auth . setAttribute ( "<STR_LIT:password>" , password ) ; root . appendChild ( auth ) ; this . sendDocument ( doc ) ; } catch ( ParserConfigurationException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } public boolean receiveAuthenticationResult ( ) throws IOException { try { Document doc = receiveDocument ( ) ; Element root = doc . getDocumentElement ( ) ; if ( root == null ) return false ; if ( ! root . getAttribute ( "<STR_LIT:type>" ) . equalsIgnoreCase ( "<STR_LIT>" ) ) return false ; NodeList nl = root . getChildNodes ( ) ; Element authresult = null ; for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) == Element . ELEMENT_NODE && n . getNodeName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { authresult = ( Element ) n ; break ; } } return authresult . getAttribute ( "<STR_LIT:result>" ) . equalsIgnoreCase ( "<STR_LIT>" ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return false ; } public boolean doAuthentication ( String username , String password ) throws IOException { sendAuthentication ( username , password ) ; return receiveAuthenticationResult ( ) ; } public byte [ ] receivePacket ( ) throws IOException , SocketClosedException { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int read = inputstream . read ( ) ; while ( read != <NUM_LIT:0> ) { if ( read == - <NUM_LIT:1> ) { throw new SocketClosedException ( ) ; } buffer . write ( read ) ; read = inputstream . read ( ) ; } return buffer . toByteArray ( ) ; } public Document receiveDocument ( ) throws SAXException { try { byte [ ] raw = receivePacket ( ) ; Document doc = documentbuilderfactory . newDocumentBuilder ( ) . parse ( new ByteArrayInputStream ( raw ) ) ; return doc ; } catch ( SocketClosedException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" + e ) ; connected = false ; } catch ( SocketException e ) { connected = false ; logger . log ( Level . SEVERE , "<STR_LIT>" + e ) ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } return null ; } protected boolean connect ( ) { connected = false ; try { socket = new Socket ( networkhost , networkport ) ; inputstream = socket . getInputStream ( ) ; outputstream = socket . getOutputStream ( ) ; if ( doAuthentication ( username , password ) ) { processLogIn ( ) ; connected = true ; } else { logger . log ( Level . SEVERE , "<STR_LIT>" ) ; } } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" + e ) ; } return connected ; } public boolean isConnected ( ) { return connected ; } public boolean processMessage ( Element el_message ) { String type = el_message . getAttribute ( "<STR_LIT:type>" ) ; if ( type . equals ( "<STR_LIT>" ) || type . equals ( "<STR_LIT>" ) || type . equals ( "<STR_LIT>" ) ) { long deadline = <NUM_LIT:0> ; long currenttime = <NUM_LIT:0> ; try { currenttime = Long . parseLong ( el_message . getAttribute ( "<STR_LIT>" ) ) ; } catch ( NumberFormatException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; return true ; } Element el_perception = null ; NodeList nl = el_message . getChildNodes ( ) ; String infoelementname = "<STR_LIT>" ; if ( type . equals ( "<STR_LIT>" ) ) { infoelementname = "<STR_LIT>" ; } else if ( type . equals ( "<STR_LIT>" ) ) { infoelementname = "<STR_LIT>" ; } else if ( type . equals ( "<STR_LIT>" ) ) { infoelementname = "<STR_LIT>" ; } for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) == Element . ELEMENT_NODE && n . getNodeName ( ) . equalsIgnoreCase ( infoelementname ) ) { if ( el_perception == null ) { el_perception = ( Element ) n ; break ; } } } if ( type . equals ( "<STR_LIT>" ) ) { try { deadline = Long . parseLong ( el_perception . getAttribute ( "<STR_LIT>" ) ) ; } catch ( NumberFormatException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; return true ; } processRequestAction ( el_perception , currenttime , deadline ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { processSimulationStart ( el_perception , currenttime ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { processSimulationEnd ( el_perception , currenttime ) ; } } else if ( type . equals ( "<STR_LIT>" ) ) { NodeList nl = el_message . getChildNodes ( ) ; for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) == Element . ELEMENT_NODE && n . getNodeName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { processPong ( ( ( Element ) n ) . getAttribute ( "<STR_LIT:value>" ) ) ; return true ; } } } return true ; } public abstract void processSimulationStart ( Element perception , long currenttime ) ; public abstract void processRequestAction ( Element perception , long currenttime , long deadline ) ; public abstract void processSimulationEnd ( Element result , long currenttime ) ; public void processPong ( String pong ) { logger . info ( "<STR_LIT>" + pong + "<STR_LIT>" ) ; } public void processLogIn ( ) { logger . info ( "<STR_LIT>" ) ; } Object syncSend = new Object ( ) ; public void sendDocument ( Document doc ) { try { if ( logger . isLoggable ( Level . FINE ) ) { ByteArrayOutputStream temp = new ByteArrayOutputStream ( ) ; transformerfactory . newTransformer ( ) . transform ( new DOMSource ( doc ) , new StreamResult ( temp ) ) ; logger . fine ( "<STR_LIT>" + temp . toString ( ) ) ; } synchronized ( syncSend ) { transformerfactory . newTransformer ( ) . transform ( new DOMSource ( doc ) , new StreamResult ( outputstream ) ) ; outputstream . write ( <NUM_LIT:0> ) ; outputstream . flush ( ) ; } } catch ( TransformerConfigurationException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } catch ( TransformerException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } catch ( IOException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; connect ( ) ; } } public void sendPing ( String ping ) throws IOException { Document doc = null ; try { doc = documentbuilderfactory . newDocumentBuilder ( ) . newDocument ( ) ; } catch ( ParserConfigurationException e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; return ; } try { Element root = doc . createElement ( "<STR_LIT:message>" ) ; doc . appendChild ( root ) ; root . setAttribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ; Element payload = doc . createElement ( "<STR_LIT>" ) ; payload . setAttribute ( "<STR_LIT:value>" , ping ) ; root . appendChild ( payload ) ; sendDocument ( doc ) ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" + e ) ; } } } </s>
|
<s> package arch ; import jason . JasonException ; import jason . asSyntax . Literal ; import jason . mas2j . ClassParameters ; import jason . runtime . Settings ; import java . util . List ; import jmoise . OrgAgent ; public class IdentifyCrashed extends OrgAgent { private boolean didPercept = true ; private int maxCycleTime = <NUM_LIT> ; private boolean dead = false ; private Thread agThread = null ; private Thread checkThread = null ; @ Override public void initAg ( String agClass , ClassParameters bbPars , String asSrc , Settings stts ) throws JasonException { super . initAg ( agClass , bbPars , asSrc , stts ) ; processParameters ( ) ; createCheckThread ( ) ; } void processParameters ( ) { String arg = getTS ( ) . getSettings ( ) . getUserParameter ( "<STR_LIT>" ) ; if ( arg != null ) maxCycleTime = Integer . parseInt ( arg ) ; } void createCheckThread ( ) { checkThread = new TestDead ( ) ; checkThread . start ( ) ; } @ Override public List < Literal > perceive ( ) { agThread = Thread . currentThread ( ) ; agDidPerceive ( ) ; return super . perceive ( ) ; } public synchronized void agDidPerceive ( ) { didPercept = true ; notifyAll ( ) ; } private synchronized void waitPerceive ( ) throws InterruptedException { wait ( maxCycleTime ) ; } public boolean isCrashed ( ) { return ! didPercept ; } @ Override public void stopAg ( ) { checkThread . interrupt ( ) ; super . stopAg ( ) ; } protected boolean fix1 ( ) throws Exception { getTS ( ) . getLogger ( ) . warning ( "<STR_LIT>" ) ; dead = true ; waitPerceive ( ) ; try { if ( isCrashed ( ) ) { return fix2 ( ) ; } else { getTS ( ) . getLogger ( ) . warning ( "<STR_LIT>" ) ; return true ; } } finally { dead = false ; } } protected boolean fix2 ( ) throws Exception { if ( agThread != null ) { getTS ( ) . getLogger ( ) . warning ( "<STR_LIT>" ) ; agThread . interrupt ( ) ; waitPerceive ( ) ; if ( isCrashed ( ) ) { getTS ( ) . getLogger ( ) . warning ( "<STR_LIT>" ) ; return fix3 ( ) ; } else { getTS ( ) . getLogger ( ) . warning ( "<STR_LIT>" ) ; return true ; } } else { getTS ( ) . getLogger ( ) . warning ( "<STR_LIT>" ) ; return fix3 ( ) ; } } protected boolean fix3 ( ) throws Exception { return false ; } @ Override public boolean isRunning ( ) { return ! dead && super . isRunning ( ) ; } class TestDead extends Thread { public TestDead ( ) { super ( "<STR_LIT>" + getAgName ( ) ) ; } @ Override public void run ( ) { try { sleep ( maxCycleTime * <NUM_LIT:2> ) ; while ( IdentifyCrashed . super . isRunning ( ) ) { didPercept = false ; sleep ( maxCycleTime ) ; if ( isCrashed ( ) ) { fix1 ( ) ; } } } catch ( Exception e ) { } } } } </s>
|
<s> package arch ; import jason . environment . grid . Location ; import jason . util . asl2xml ; import java . io . File ; import java . io . FileWriter ; import java . io . PrintWriter ; import java . util . HashMap ; import java . util . Iterator ; import java . util . LinkedList ; import java . util . List ; import java . util . Map ; import java . util . logging . Logger ; import env . WorldModel ; public class WriteStatusThread extends Thread { protected Logger logger = Logger . getLogger ( WriteStatusThread . class . getName ( ) ) ; static WriteStatusThread instance = null ; private WriteStatusThread ( ) { } public static WriteStatusThread create ( CowboyArch owner , boolean writeLocations , boolean dumpAgsMind ) { if ( instance == null ) { instance = new WriteStatusThread ( ) ; instance . owner = owner ; instance . writeLocations = writeLocations ; instance . dumpAgsMinds = dumpAgsMind ; instance . start ( ) ; } return instance ; } public static boolean isCreated ( ) { return instance != null ; } private CowboyArch owner = null ; private boolean writeLocations = true ; private boolean dumpAgsMinds = true ; private Map < Integer , List < Location > > locations ; private asl2xml transformer = new asl2xml ( ) ; private static CowboyArch [ ] agents = new CowboyArch [ WorldModel . agsByTeam ] ; public static void registerAgent ( String name , CowboyArch arch ) { agents [ arch . getMyId ( ) ] = arch ; } public void reset ( ) { locations = new HashMap < Integer , List < Location > > ( ) ; for ( int i = <NUM_LIT:0> ; i < WorldModel . agsByTeam ; i ++ ) { locations . put ( i , new LinkedList < Location > ( ) ) ; } } public void run ( ) { String fileName = "<STR_LIT>" ; PrintWriter out = null ; try { out = new PrintWriter ( fileName ) ; while ( true ) { try { if ( writeLocations ) writeLocations ( out ) ; if ( dumpAgsMinds ) writeMind ( ) ; } catch ( InterruptedException e ) { return ; } catch ( Exception e ) { System . out . println ( "<STR_LIT>" + e ) ; e . printStackTrace ( ) ; sleep ( <NUM_LIT:1000> ) ; } } } catch ( Exception e ) { e . printStackTrace ( ) ; } finally { out . close ( ) ; } } private void writeMind ( ) { for ( CowboyArch arch : agents ) { if ( arch == null ) break ; try { File dirmind = new File ( "<STR_LIT>" + arch . getAgName ( ) ) ; if ( ! dirmind . exists ( ) ) dirmind . mkdirs ( ) ; String agmind = transformer . transform ( arch . getTS ( ) . getAg ( ) . getAgState ( ) ) ; String filename = String . format ( "<STR_LIT>" , arch . getSimStep ( ) ) . replaceAll ( "<STR_LIT:U+0020>" , "<STR_LIT:0>" ) ; FileWriter outmind = new FileWriter ( new File ( dirmind + "<STR_LIT:/>" + filename ) ) ; outmind . write ( agmind ) ; outmind . close ( ) ; } catch ( Exception e ) { System . out . println ( "<STR_LIT>" + e ) ; } } } private void writeLocations ( PrintWriter out ) throws InterruptedException { long timebefore = System . currentTimeMillis ( ) ; waitNextCycle ( ) ; long cycletime = System . currentTimeMillis ( ) - timebefore ; StringBuilder s = new StringBuilder ( String . format ( "<STR_LIT>" , owner . getSimStep ( ) - <NUM_LIT:1> ) ) ; for ( int agId = <NUM_LIT:0> ; agId < WorldModel . agsByTeam ; agId ++ ) { if ( agents [ agId ] != null ) { Location agp = agents [ agId ] . getLastLocation ( ) ; if ( agp != null ) { int c = <NUM_LIT:0> ; Iterator < Location > il = locations . get ( agId ) . iterator ( ) ; while ( il . hasNext ( ) && il . next ( ) . equals ( agp ) && c <= <NUM_LIT:11> ) { c ++ ; } String sc = "<STR_LIT:*>" ; if ( c < <NUM_LIT:10> ) sc = "<STR_LIT>" + c ; locations . get ( agId ) . add ( <NUM_LIT:0> , agp ) ; String lastAct = shortActionFormat ( agents [ agId ] . getLastAction ( ) ) ; s . append ( String . format ( "<STR_LIT>" , agp . x , agp . y , sc , lastAct ) ) ; } } } s . append ( String . format ( "<STR_LIT>" , cycletime ) ) ; logger . info ( s . toString ( ) ) ; out . println ( s . toString ( ) ) ; out . flush ( ) ; } public String shortActionFormat ( String act ) { if ( act == null ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . east . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . northeast . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . southeast . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . west . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . northwest . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . southwest . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . north . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . south . toString ( ) ) ) return "<STR_LIT>" ; if ( act . equals ( WorldModel . Move . skip . toString ( ) ) ) return "<STR_LIT>" ; return "<STR_LIT>" ; } synchronized private void waitNextCycle ( ) throws InterruptedException { wait ( <NUM_LIT> ) ; } synchronized void go ( ) { notifyAll ( ) ; } } </s>
|
<s> package arch ; import jason . JasonException ; import jason . RevisionFailedException ; import jason . asSemantics . ActionExec ; import jason . asSyntax . Literal ; import jason . mas2j . ClassParameters ; import jason . runtime . Settings ; import java . util . ArrayList ; import java . util . List ; import java . util . Queue ; import java . util . concurrent . ConcurrentLinkedQueue ; import java . util . concurrent . TimeUnit ; import java . util . concurrent . locks . Condition ; import java . util . concurrent . locks . Lock ; import java . util . concurrent . locks . ReentrantLock ; import java . util . logging . Level ; import java . util . logging . Logger ; public class ACArchitecture extends CowboyArch { public static final int actionTimeout = <NUM_LIT> ; private Logger logger ; private ACProxy proxy ; private List < Literal > percepts = new ArrayList < Literal > ( ) ; private WaitSleep waitSleepThread ; @ Override public void initAg ( String agClass , ClassParameters bbPars , String asSrc , Settings stts ) throws JasonException { super . initAg ( agClass , bbPars , asSrc , stts ) ; logger = Logger . getLogger ( ACArchitecture . class . getName ( ) + "<STR_LIT:.>" + getAgName ( ) ) ; String username = stts . getUserParameter ( "<STR_LIT:username>" ) ; if ( username . startsWith ( "<STR_LIT:\">" ) ) username = username . substring ( <NUM_LIT:1> , username . length ( ) - <NUM_LIT:1> ) ; username = username . replaceAll ( "<STR_LIT>" , "<STR_LIT>" + ( getAgId ( getAgName ( ) ) + <NUM_LIT:1> ) ) ; String password = stts . getUserParameter ( "<STR_LIT:password>" ) ; if ( password . startsWith ( "<STR_LIT:\">" ) ) password = password . substring ( <NUM_LIT:1> , password . length ( ) - <NUM_LIT:1> ) ; waitSleepThread = new WaitSleep ( ) ; waitSleepThread . start ( ) ; proxy = new ACProxy ( this , stts . getUserParameter ( "<STR_LIT>" ) , Integer . parseInt ( stts . getUserParameter ( "<STR_LIT>" ) ) , username , password ) ; new Thread ( proxy , "<STR_LIT>" + username ) . start ( ) ; } @ Override public void stopAg ( ) { super . stopAg ( ) ; proxy . finish ( ) ; waitSleepThread . interrupt ( ) ; } @ Override public List < Literal > perceive ( ) { return new ArrayList < Literal > ( percepts ) ; } @ Override public void sleep ( ) { waitSleepThread . go ( ) ; super . sleep ( ) ; } public void startNextStep ( int step , List < Literal > p ) { percepts = p ; clModel . setStepcl ( step ) ; new Thread ( ( Runnable ) clModel ) . start ( ) ; waitSleepThread . newCycle ( ) ; getTS ( ) . getUserAgArch ( ) . getArchInfraTier ( ) . wake ( ) ; setSimStep ( step ) ; } @ Override public void act ( ActionExec act , List < ActionExec > feedback ) { if ( act . getActionTerm ( ) . getFunctor ( ) . equals ( "<STR_LIT>" ) ) { waitSleepThread . addAction ( act ) ; } else { logger . info ( "<STR_LIT>" + act + "<STR_LIT>" ) ; } } @ Override void simulationEndPerceived ( String result ) throws RevisionFailedException { percepts = new ArrayList < Literal > ( ) ; super . simulationEndPerceived ( result ) ; } class WaitSleep extends Thread { ActionExec lastAction = null ; String lastActionInCurrentCycle ; Queue < ActionExec > toExecute = new ConcurrentLinkedQueue < ActionExec > ( ) ; Lock lock = new ReentrantLock ( ) ; Condition cycle = lock . newCondition ( ) ; long timestartcycle = <NUM_LIT:0> ; long timeLastAction = <NUM_LIT:0> ; int cycleCounter = <NUM_LIT:0> ; StringBuilder notsent ; WaitSleep ( ) { super ( "<STR_LIT>" + getAgName ( ) ) ; } void addAction ( ActionExec action ) { if ( action == null ) return ; logger . info ( "<STR_LIT>" + action . getActionTerm ( ) + "<STR_LIT>" ) ; lock . lock ( ) ; try { if ( lastAction != null ) toExecute . offer ( lastAction ) ; lastAction = action ; } finally { lock . unlock ( ) ; } } void newCycle ( ) { lock . lock ( ) ; try { cycleCounter ++ ; if ( getSimStep ( ) == <NUM_LIT:1> ) cycleCounter = <NUM_LIT:1> ; notsent = new StringBuilder ( ) ; if ( toExecute . size ( ) > <NUM_LIT:1> ) { notsent . append ( "<STR_LIT>" ) ; } List < ActionExec > feedback = getTS ( ) . getC ( ) . getFeedbackActions ( ) ; synchronized ( feedback ) { while ( ! toExecute . isEmpty ( ) ) { ActionExec action = toExecute . poll ( ) ; action . setResult ( true ) ; feedback . add ( action ) ; if ( ! toExecute . isEmpty ( ) ) notsent . append ( action . getActionTerm ( ) + "<STR_LIT:U+0020>" ) ; } } String w = "<STR_LIT>" ; if ( lastActionInCurrentCycle == null && cycleCounter > <NUM_LIT:10> ) { w = "<STR_LIT>" ; } String timetoact = "<STR_LIT>" ; if ( lastActionInCurrentCycle != null && timestartcycle > <NUM_LIT:0> ) { timetoact = "<STR_LIT>" + ( timeLastAction - timestartcycle ) + "<STR_LIT>" ; } timestartcycle = System . currentTimeMillis ( ) ; logger . info ( w + "<STR_LIT>" + lastActionInCurrentCycle + "<STR_LIT>" + getSimStep ( ) + timetoact + notsent ) ; setLastAct ( lastActionInCurrentCycle ) ; lastActionInCurrentCycle = null ; lastAction = null ; go ( ) ; } finally { lock . unlock ( ) ; } } void go ( ) { lock . lock ( ) ; try { cycle . signal ( ) ; } finally { lock . unlock ( ) ; } } boolean waitSleep ( ) throws InterruptedException { lock . lock ( ) ; try { return ! cycle . await ( actionTimeout , TimeUnit . MILLISECONDS ) ; } finally { lock . unlock ( ) ; } } @ Override public void run ( ) { while ( true ) { lock . lock ( ) ; try { waitSleep ( ) ; if ( lastAction != null ) { lastActionInCurrentCycle = lastAction . getActionTerm ( ) . getTerm ( <NUM_LIT:0> ) . toString ( ) ; proxy . sendAction ( lastActionInCurrentCycle ) ; toExecute . offer ( lastAction ) ; timeLastAction = System . currentTimeMillis ( ) ; lastAction = null ; } } catch ( InterruptedException e ) { return ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" + lastAction + "<STR_LIT>" , e ) ; toExecute . clear ( ) ; } finally { lock . unlock ( ) ; } } } } } </s>
|
<s> package arch ; import static jason . asSyntax . ASSyntax . createLiteral ; import static jason . asSyntax . ASSyntax . createNumber ; import static jason . asSyntax . ASSyntax . createStructure ; import jason . asSyntax . Literal ; import jason . environment . grid . Location ; import java . util . ArrayList ; import java . util . List ; import java . util . Random ; import java . util . logging . Level ; import java . util . logging . Logger ; import java . util . concurrent . CyclicBarrier ; import java . util . concurrent . TimeUnit ; import java . io . FileWriter ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import env . WorldModel ; import env . Cow ; public class ACProxy extends ACAgent implements Runnable { String rid ; ACArchitecture arq ; boolean running = true ; private Logger logger = Logger . getLogger ( ACProxy . class . getName ( ) ) ; private DocumentBuilder documentbuilder ; ConnectionMonitor monitor = new ConnectionMonitor ( ) ; private long timeSt , timeEnd ; public ACProxy ( ACArchitecture arq , String host , int port , String username , String password ) { logger = Logger . getLogger ( ACProxy . class . getName ( ) + "<STR_LIT:.>" + arq . getAgName ( ) ) ; if ( host . startsWith ( "<STR_LIT:\">" ) ) { host = host . substring ( <NUM_LIT:1> , host . length ( ) - <NUM_LIT:1> ) ; } setPort ( port ) ; setHost ( host ) ; setUsername ( username ) ; setPassword ( password ) ; this . arq = arq ; try { documentbuilder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } connect ( ) ; monitor . start ( ) ; } public void finish ( ) { running = false ; monitor . interrupt ( ) ; } public void run ( ) { while ( running ) { try { if ( isConnected ( ) ) { Document doc = receiveDocument ( ) ; if ( doc != null ) { Element el_root = doc . getDocumentElement ( ) ; if ( el_root != null ) { if ( el_root . getNodeName ( ) . equals ( "<STR_LIT:message>" ) ) { processMessage ( el_root ) ; } else { logger . log ( Level . SEVERE , "<STR_LIT>" ) ; } } else { logger . log ( Level . SEVERE , "<STR_LIT>" ) ; } } } else { logger . info ( "<STR_LIT>" ) ; try { Thread . sleep ( <NUM_LIT> ) ; } catch ( InterruptedException e1 ) { } } } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } } public void processLogIn ( ) { logger . info ( "<STR_LIT>" ) ; } public void processSimulationStart ( Element simulation , long currenttime ) { try { arq . setSimId ( simulation . getAttribute ( "<STR_LIT:id>" ) ) ; int gsizex = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; int gsizey = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; arq . gsizePerceived ( gsizex , gsizey , simulation . getAttribute ( "<STR_LIT>" ) ) ; int corralx0 = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; int corralx1 = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; int corraly0 = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; int corraly1 = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; arq . corralPerceived ( new Location ( corralx0 , corraly0 ) , new Location ( corralx1 , corraly1 ) ) ; int steps = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; arq . stepsPerceived ( steps ) ; int lineOfSight = Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ; arq . lineOfSightPerceived ( lineOfSight ) ; logger . info ( "<STR_LIT>" ) ; rid = simulation . getAttribute ( "<STR_LIT:id>" ) ; timeSt = currenttime ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } public void processSimulationEnd ( Element result , long currenttime ) { try { timeEnd = currenttime ; String score = result . getAttribute ( "<STR_LIT>" ) + "<STR_LIT:->" + result . getAttribute ( "<STR_LIT:result>" ) ; logger . info ( "<STR_LIT>" + score ) ; if ( arq . myId == <NUM_LIT:1> ) { logger . info ( "<STR_LIT>" + score ) ; logger . info ( "<STR_LIT>" + ( timeEnd - timeSt ) + "<STR_LIT>" ) ; logger . info ( "<STR_LIT>" + ( timeEnd - timeSt ) / <NUM_LIT> + "<STR_LIT>" ) ; String fileName = "<STR_LIT>" ; FileWriter fw = new FileWriter ( fileName , true ) ; fw . write ( "<STR_LIT>" ) ; fw . write ( timeEnd + "<STR_LIT:n>" ) ; fw . write ( ( timeEnd - timeSt ) + "<STR_LIT>" + ( timeEnd - timeSt ) / <NUM_LIT> + "<STR_LIT>" ) ; fw . write ( score + "<STR_LIT:n>" ) ; fw . close ( ) ; } arq . simulationEndPerceived ( result . getAttribute ( "<STR_LIT:result>" ) ) ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } public void processRequestAction ( Element perception , long currenttime , long deadline ) { try { List < Literal > percepts = new ArrayList < Literal > ( ) ; rid = perception . getAttribute ( "<STR_LIT:id>" ) ; int agx = Integer . parseInt ( perception . getAttribute ( "<STR_LIT>" ) ) ; int agy = Integer . parseInt ( perception . getAttribute ( "<STR_LIT>" ) ) ; int step = Integer . parseInt ( perception . getAttribute ( "<STR_LIT>" ) ) ; int score = Integer . parseInt ( perception . getAttribute ( "<STR_LIT>" ) ) ; arq . locationPerceived ( agx , agy ) ; arq . setScore ( score ) ; arq . getCowModel ( ) . freePos ( agx , agy ) ; Literal lpos = createLiteral ( "<STR_LIT>" , createNumber ( agx ) , createNumber ( agy ) , createNumber ( step ) ) ; percepts . add ( lpos ) ; arq . initKnownCows ( ) ; List < Location > switches = new ArrayList < Location > ( ) ; NodeList nl = perception . getElementsByTagName ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Element cell = ( Element ) nl . item ( i ) ; int cellx = Integer . parseInt ( cell . getAttribute ( "<STR_LIT:x>" ) ) ; int celly = Integer . parseInt ( cell . getAttribute ( "<STR_LIT:y>" ) ) ; int absx = agx + cellx ; int absy = agy + celly ; int unk = <NUM_LIT:1> ; NodeList cnl = cell . getChildNodes ( ) ; for ( int j = <NUM_LIT:0> ; j < cnl . getLength ( ) ; j ++ ) { if ( cnl . item ( j ) . getNodeType ( ) == Element . ELEMENT_NODE && cellx != <NUM_LIT:0> && celly != <NUM_LIT:0> ) { Element type = ( Element ) cnl . item ( j ) ; if ( unk == <NUM_LIT:1> && ! type . getNodeName ( ) . equals ( "<STR_LIT:unknown>" ) ) { arq . getCowModel ( ) . freePos ( absx , absy ) ; unk = <NUM_LIT:0> ; } if ( type . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { if ( type . getAttribute ( "<STR_LIT:type>" ) . equals ( "<STR_LIT>" ) ) { } else if ( type . getAttribute ( "<STR_LIT:type>" ) . equals ( "<STR_LIT>" ) ) { arq . enemyPerceived ( absx , absy ) ; } } else if ( type . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { if ( absx < arq . getModel ( ) . getWidth ( ) - <NUM_LIT:1> && absx != <NUM_LIT:0> && absy != <NUM_LIT> && absy < arq . getModel ( ) . getHeight ( ) - <NUM_LIT:1> ) { int cowId = Integer . parseInt ( type . getAttribute ( "<STR_LIT:ID>" ) ) ; arq . cowPerceived ( cowId , absx , absy ) ; } } else if ( type . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { arq . obstaclePerceived ( absx , absy ) ; } else if ( type . getNodeName ( ) . equals ( "<STR_LIT>" ) && type . getAttribute ( "<STR_LIT:type>" ) . equals ( "<STR_LIT>" ) ) { arq . enemyCorralPerceived ( absx , absy ) ; } else if ( type . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { boolean open = type . getAttribute ( "<STR_LIT>" ) . equals ( "<STR_LIT:true>" ) ; arq . fencePerceived ( absx , absy , open ) ; } else if ( type . getNodeName ( ) . equals ( "<STR_LIT>" ) ) { switches . add ( new Location ( absx , absy ) ) ; } } } } arq . getCowModel ( ) . updateCows ( ) ; for ( Location l : switches ) { arq . switchPerceived ( l . x , l . y ) ; } Cow [ ] cows = arq . getCowModel ( ) . getCows ( ) ; for ( Cow cCow : cows ) { Literal lc = createLiteral ( "<STR_LIT>" , createNumber ( cCow . id ) , createNumber ( cCow . x ) , createNumber ( cCow . y ) ) ; lc . addAnnot ( createStructure ( "<STR_LIT>" , createNumber ( cCow . step ) ) ) ; percepts . add ( lc ) ; } arq . startNextStep ( step , percepts ) ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } public void sendAction ( String action ) { try { logger . info ( "<STR_LIT>" + action + "<STR_LIT>" + rid + "<STR_LIT>" + arq . model . getAgPos ( arq . getMyId ( ) ) ) ; Document doc = documentbuilder . newDocument ( ) ; Element el_response = doc . createElement ( "<STR_LIT:message>" ) ; el_response . setAttribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ; doc . appendChild ( el_response ) ; Element el_action = doc . createElement ( "<STR_LIT>" ) ; if ( action != null ) { el_action . setAttribute ( "<STR_LIT:type>" , action ) ; } el_action . setAttribute ( "<STR_LIT:id>" , rid ) ; el_response . appendChild ( el_action ) ; sendDocument ( doc ) ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } } @ Override public void processPong ( String pong ) { monitor . processPong ( pong ) ; } class ConnectionMonitor extends Thread { long sentTime = <NUM_LIT:0> ; int count = <NUM_LIT:0> ; boolean ok = true ; String pingMsg ; synchronized public void run ( ) { int d = new Random ( ) . nextInt ( <NUM_LIT> ) ; try { while ( running ) { if ( isConnected ( ) ) sleep ( <NUM_LIT> + d ) ; else sleep ( <NUM_LIT> ) ; count ++ ; sentTime = System . currentTimeMillis ( ) ; ok = false ; if ( isConnected ( ) ) { pingMsg = "<STR_LIT>" + count ; logger . info ( "<STR_LIT>" + pingMsg ) ; sendPing ( pingMsg ) ; waitPong ( ) ; } else { logger . info ( "<STR_LIT>" ) ; } if ( ! ok ) { logger . info ( "<STR_LIT>" ) ; connect ( ) ; } } } catch ( InterruptedException e ) { } catch ( Exception e ) { logger . log ( Level . WARNING , "<STR_LIT>" , e ) ; } } synchronized void waitPong ( ) throws Exception { wait ( <NUM_LIT> ) ; } synchronized void processPong ( String pong ) { long time = System . currentTimeMillis ( ) - sentTime ; logger . info ( "<STR_LIT>" + pong + "<STR_LIT>" + pingMsg + "<STR_LIT>" + time + "<STR_LIT>" ) ; ok = true ; notify ( ) ; } } } </s>
|
<s> package arch ; import static jason . asSyntax . ASSyntax . createLiteral ; import static jason . asSyntax . ASSyntax . createNumber ; import jason . architecture . AgArch ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . Literal ; import jason . asSyntax . NumberTerm ; import jason . bb . BeliefBase ; import jason . environment . grid . Location ; import java . io . BufferedReader ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileReader ; import java . io . FileWriter ; import java . util . Collections ; import java . util . Date ; import java . util . HashMap ; import java . util . HashSet ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; import java . util . Random ; import java . util . Set ; import jia . Search ; import jia . Vec ; import moise . simple . oe . Pair ; import busca . Nodo ; import env . WorldModel ; public class LocalWorldModel extends WorldModel { int [ ] [ ] visited ; int minVisited = <NUM_LIT:0> ; private Random random = new Random ( ) ; Set < Vec > knownCows = new HashSet < Vec > ( ) ; boolean isKnownCowsUptodate = false ; int [ ] [ ] cowsrep ; int [ ] [ ] obsrep ; int [ ] [ ] enemycorralrep ; Map < Pair < Location , Location > , Integer > dist = new HashMap < Pair < Location , Location > , Integer > ( ) ; boolean distOutdated = true ; BeliefBase bb ; public LocalWorldModel ( int w , int h , int nbAg , BeliefBase bb ) { super ( w , h , nbAg ) ; this . bb = bb ; visited = new int [ getWidth ( ) ] [ getHeight ( ) ] ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) visited [ i ] [ j ] = <NUM_LIT:0> ; cowsrep = new int [ getWidth ( ) ] [ getHeight ( ) ] ; obsrep = new int [ getWidth ( ) ] [ getHeight ( ) ] ; enemycorralrep = new int [ getWidth ( ) ] [ getHeight ( ) ] ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) { obsrep [ i ] [ j ] = <NUM_LIT:0> ; enemycorralrep [ i ] [ j ] = <NUM_LIT:0> ; } } @ Override public void add ( int value , int x , int y ) { switch ( value ) { case OBSTACLE : increp ( obsrep , x , y , <NUM_LIT:1> , <NUM_LIT:1> ) ; distOutdated = true ; break ; case ENEMYCORRAL : increp ( enemycorralrep , x , y , <NUM_LIT:1> , <NUM_LIT:2> ) ; break ; case OPEN_FENCE : if ( hasObject ( CLOSED_FENCE , x , y ) ) remove ( CLOSED_FENCE , x , y ) ; break ; case CLOSED_FENCE : if ( hasObject ( OPEN_FENCE , x , y ) ) remove ( OPEN_FENCE , x , y ) ; break ; case SWITCH : if ( hasObject ( FENCE , x + <NUM_LIT:1> , y ) ) add ( OBSTACLE , x + <NUM_LIT:1> , y ) ; if ( hasObject ( FENCE , x - <NUM_LIT:1> , y ) ) add ( OBSTACLE , x - <NUM_LIT:1> , y ) ; if ( hasObject ( FENCE , x , y + <NUM_LIT:1> ) ) add ( OBSTACLE , x , y + <NUM_LIT:1> ) ; if ( hasObject ( FENCE , x , y - <NUM_LIT:1> ) ) add ( OBSTACLE , x , y - <NUM_LIT:1> ) ; add ( OBSTACLE , x , y ) ; break ; } super . add ( value , x , y ) ; } public boolean isHorizontalFence ( int x , int y ) { return hasObject ( WorldModel . FENCE , x + <NUM_LIT:1> , y ) || hasObject ( WorldModel . FENCE , x - <NUM_LIT:1> , y ) ; } public void clearKnownCows ( ) { isKnownCowsUptodate = false ; } public Set < Vec > getKnownCows ( ) { synchronized ( knownCows ) { if ( ! isKnownCowsUptodate ) updateCowsFromBB ( ) ; return new HashSet < Vec > ( knownCows ) ; } } private static final Literal cowLiteral = Literal . parseLiteral ( "<STR_LIT>" ) ; private void updateCowsFromBB ( ) { if ( bb == null ) return ; synchronized ( knownCows ) { removeAll ( WorldModel . COW ) ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) cowsrep [ i ] [ j ] = <NUM_LIT:0> ; knownCows . clear ( ) ; Iterator < Literal > i = bb . getCandidateBeliefs ( cowLiteral , null ) ; if ( i != null ) { while ( i . hasNext ( ) ) { Literal c = i . next ( ) ; int x = ( int ) ( ( NumberTerm ) c . getTerm ( <NUM_LIT:1> ) ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) c . getTerm ( <NUM_LIT:2> ) ) . solve ( ) ; addKnownCow ( x , y ) ; } } isKnownCowsUptodate = true ; } } public void addKnownCow ( int x , int y ) { add ( WorldModel . COW , x , y ) ; knownCows . add ( new Vec ( this , x , y ) ) ; increp ( cowsrep , x , y , <NUM_LIT:2> , <NUM_LIT:1> ) ; } public int getCowsRep ( int x , int y ) { return cowsrep [ x ] [ y ] ; } public int getObsRep ( int x , int y ) { return obsrep [ x ] [ y ] ; } public int getEnemyCorralRep ( int x , int y ) { return enemycorralrep [ x ] [ y ] ; } private void increp ( int [ ] [ ] m , int x , int y , int ratio , int value ) { for ( int r = <NUM_LIT:1> ; r <= ratio ; r ++ ) for ( int c = x - r ; c <= x + r ; c ++ ) for ( int l = y - r ; l <= y + r ; l ++ ) if ( inGrid ( c , l ) ) { m [ c ] [ l ] += value ; } } public Location nearFree ( Location l , List < Location > occupied ) throws Exception { int w = <NUM_LIT:0> ; Location newl ; if ( occupied == null ) occupied = Collections . emptyList ( ) ; while ( true ) { for ( int y = l . y - w + <NUM_LIT:1> ; y < l . y + w ; y ++ ) { newl = new Location ( l . x - w , y ) ; if ( isFree ( newl ) && ! occupied . contains ( newl ) ) return newl ; newl = new Location ( l . x + w , y ) ; if ( isFree ( newl ) && ! occupied . contains ( newl ) ) return newl ; } for ( int x = l . x - w ; x <= l . x + w ; x ++ ) { newl = new Location ( x , l . y - w ) ; if ( isFree ( newl ) && ! occupied . contains ( newl ) ) return newl ; newl = new Location ( x , l . y + w ) ; if ( isFree ( newl ) && ! occupied . contains ( newl ) ) return newl ; } w ++ ; } } public Set < Location > getAllObj ( int obj ) { Set < Location > all = new HashSet < Location > ( ) ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) if ( hasObject ( obj , i , j ) ) all . add ( new Location ( i , j ) ) ; return all ; } public int countObjInArea ( int obj , Location startPoint , int size ) { int c = <NUM_LIT:0> ; for ( int x = startPoint . x - size ; x <= startPoint . x + size ; x ++ ) { for ( int y = startPoint . y - size ; y <= startPoint . y + size ; y ++ ) { if ( hasObject ( obj , x , y ) ) { c ++ ; } } } return c ; } public int getVisited ( Location l ) { return visited [ l . x ] [ l . y ] ; } public void incVisited ( Location l ) { incVisited ( l . x , l . y ) ; } public void incVisited ( int x , int y ) { visited [ x ] [ y ] += <NUM_LIT:2> ; increp ( visited , x , y , <NUM_LIT:4> , <NUM_LIT:1> ) ; } public int pathLength ( Location start , Location target , boolean fenceAsObstacle , AgArch arch ) throws Exception { if ( distOutdated ) { synchronized ( dist ) { dist . clear ( ) ; distOutdated = false ; } } Pair < Location , Location > pair = new Pair < Location , Location > ( start , target ) ; Integer iDistance = null ; if ( ! fenceAsObstacle ) { iDistance = dist . get ( pair ) ; if ( iDistance == null ) { pair = new Pair < Location , Location > ( target , start ) ; iDistance = dist . get ( pair ) ; } if ( iDistance != null ) { return iDistance ; } } Nodo solution = new Search ( this , start , target , null , false , false , false , false , false , fenceAsObstacle , arch ) . search ( ) ; if ( solution == null ) { return - <NUM_LIT:1> ; } else { int distance = solution . getProfundidade ( ) ; if ( ! fenceAsObstacle ) { synchronized ( dist ) { dist . put ( pair , distance ) ; } } return distance ; } } public Location getNearLeastVisited ( Location agloc , Location tl , Location br ) throws Exception { if ( ! agloc . isInArea ( tl , br ) ) { return nearFree ( new Location ( ( tl . x + br . x ) / <NUM_LIT:2> , ( tl . y + br . y ) / <NUM_LIT:2> ) , null ) ; } Location better = null ; int loopcount = <NUM_LIT:0> ; while ( loopcount < <NUM_LIT:100> ) { loopcount ++ ; int x = agloc . x ; int y = agloc . y ; int w = <NUM_LIT:1> ; int dx = <NUM_LIT:0> ; int dy = <NUM_LIT:0> ; int stage = <NUM_LIT:1> ; better = null ; while ( w < getWidth ( ) ) { switch ( stage ) { case <NUM_LIT:1> : if ( dx < w ) { dx ++ ; break ; } else { stage = <NUM_LIT:2> ; } case <NUM_LIT:2> : if ( dy < w ) { dy ++ ; break ; } else { stage = <NUM_LIT:3> ; } case <NUM_LIT:3> : if ( dx > <NUM_LIT:0> ) { dx -- ; break ; } else { stage = <NUM_LIT:4> ; } case <NUM_LIT:4> : if ( dy > <NUM_LIT:0> ) { dy -- ; break ; } else { stage = <NUM_LIT:1> ; x -- ; y -- ; w += <NUM_LIT:2> ; } } Location l = new Location ( x + dx , y + dy ) ; if ( isFree ( l ) && ! l . equals ( agloc ) && l . isInArea ( tl , br ) && ! hasObject ( WorldModel . FENCE , l . x , l . y ) ) { if ( visited [ l . x ] [ l . y ] < minVisited ) { return l ; } if ( visited [ l . x ] [ l . y ] == minVisited ) { if ( better == null ) { better = l ; } else if ( l . distance ( agloc ) < better . distance ( agloc ) ) { better = l ; } else if ( l . distance ( agloc ) == better . distance ( agloc ) && random . nextBoolean ( ) ) { better = l ; } } } } if ( better != null ) { return better ; } minVisited ++ ; } return better ; } public void clearAgView ( Location l ) { clearAgView ( l . x , l . y ) ; } private static final int cleanPerception = ~ ( ENEMY ) ; public void clearAgView ( int x , int y ) { int r = agPerceptionRatio ; for ( int c = x - r ; c <= x + r ; c ++ ) { for ( int l = y - r ; l <= y + r ; l ++ ) { if ( inGrid ( c , l ) ) { data [ c ] [ l ] &= cleanPerception ; if ( view != null ) view . update ( c , l ) ; } } } } private static final File directory = new File ( "<STR_LIT>" ) ; public void createStoreObsThread ( final CowboyArch arch ) { new Thread ( "<STR_LIT>" ) { @ Override public void run ( ) { directory . mkdirs ( ) ; while ( true ) { try { sleep ( <NUM_LIT> + random . nextInt ( <NUM_LIT> ) ) ; StringBuilder sout = new StringBuilder ( ) ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) { if ( hasObject ( WorldModel . OBSTACLE , i , j ) && ! arch . isEphemeralObstacle ( new Location ( i , j ) ) ) sout . append ( "<STR_LIT>" + i + "<STR_LIT:U+002C>" + j + "<STR_LIT>" ) ; if ( hasObject ( WorldModel . FENCE , i , j ) ) sout . append ( "<STR_LIT>" + i + "<STR_LIT:U+002C>" + j + "<STR_LIT>" ) ; } for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) { if ( hasObject ( WorldModel . SWITCH , i , j ) ) sout . append ( "<STR_LIT>" + i + "<STR_LIT:U+002C>" + j + "<STR_LIT>" ) ; } BufferedWriter out = new BufferedWriter ( new FileWriter ( getObstaclesFileName ( arch ) ) ) ; out . write ( sout . toString ( ) ) ; out . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } } . start ( ) ; } public void restoreObstaclesFromFile ( final CowboyArch arch ) { File f = new File ( getObstaclesFileName ( arch ) ) ; if ( f . exists ( ) ) { Set < Location > included = new HashSet < Location > ( ) ; try { arch . logger . info ( "<STR_LIT>" + f ) ; BufferedReader in = new BufferedReader ( new FileReader ( f ) ) ; String lin = in . readLine ( ) ; while ( lin != null ) { Literal obs = ASSyntax . parseLiteral ( lin ) ; Location l = new Location ( ( int ) ( ( NumberTerm ) obs . getTerm ( <NUM_LIT:0> ) ) . solve ( ) , ( int ) ( ( NumberTerm ) obs . getTerm ( <NUM_LIT:1> ) ) . solve ( ) ) ; if ( obs . getFunctor ( ) . equals ( "<STR_LIT>" ) ) { add ( WorldModel . OBSTACLE , l ) ; included . add ( l ) ; } else if ( obs . getFunctor ( ) . equals ( "<STR_LIT>" ) ) { add ( WorldModel . CLOSED_FENCE , l ) ; included . add ( l ) ; } else if ( obs . getFunctor ( ) . equals ( "<STR_LIT>" ) ) { add ( WorldModel . SWITCH , l ) ; arch . getTS ( ) . getAg ( ) . addBel ( createLiteral ( "<STR_LIT>" , createNumber ( l . x ) , createNumber ( l . y ) ) ) ; included . add ( l ) ; } lin = in . readLine ( ) ; } } catch ( ArrayIndexOutOfBoundsException e ) { for ( Location l : included ) { remove ( WorldModel . OBSTACLE , l ) ; remove ( WorldModel . CLOSED_FENCE , l ) ; remove ( WorldModel . SWITCH , l ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } } } @ SuppressWarnings ( "<STR_LIT:deprecation>" ) private String getObstaclesFileName ( final CowboyArch arch ) { return directory + "<STR_LIT:/>" + arch . getAgName ( ) + "<STR_LIT:->" + getOpponent ( ) + arch . getSimId ( ) + getMaxSteps ( ) + getCorral ( ) + "<STR_LIT:->" + new Date ( ) . getDay ( ) + "<STR_LIT>" ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . Atom ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . Random ; import java . util . logging . Level ; import arch . CowboyArch ; import arch . LocalWorldModel ; import busca . Nodo ; import env . WorldModel ; public class direction extends DefaultInternalAction { WorldModel . Move [ ] actionsOrder = new WorldModel . Move [ WorldModel . nbActions ] ; Random random = new Random ( ) ; public direction ( ) { for ( int i = <NUM_LIT:0> ; i < WorldModel . nbActions ; i ++ ) { actionsOrder [ i ] = Search . defaultActions [ i ] ; } } @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { try { String sAction = "<STR_LIT>" ; Nodo solution = findPath ( ts , terms ) ; if ( solution != null ) { WorldModel . Move m = Search . firstAction ( solution ) ; if ( m != null ) sAction = m . toString ( ) ; } else { ts . getLogger ( ) . info ( "<STR_LIT>" + terms [ <NUM_LIT:0> ] + "<STR_LIT:U+002C>" + terms [ <NUM_LIT:1> ] + "<STR_LIT:U+0020toU+0020>" + terms [ <NUM_LIT:2> ] + "<STR_LIT:U+002C>" + terms [ <NUM_LIT:3> ] + "<STR_LIT:!>" + "<STR_LIT:n>" + ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ) ; } return un . unifies ( terms [ <NUM_LIT:4> ] , new Atom ( sAction ) ) ; } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } protected Nodo findPath ( TransitionSystem ts , Term [ ] terms ) throws Exception { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; Nodo solution = null ; int iagx = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int iagy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; int itox = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:2> ] ) . solve ( ) ; int itoy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:3> ] ) . solve ( ) ; if ( model . inGrid ( itox , itoy ) ) { while ( ! model . isFreeOfObstacle ( itox , itoy ) && itox > <NUM_LIT:0> ) itox -- ; while ( ! model . isFreeOfObstacle ( itox , itoy ) && itox < model . getWidth ( ) ) itox ++ ; Location from = new Location ( iagx , iagy ) ; Location to = new Location ( itox , itoy ) ; int i1 = random . nextInt ( WorldModel . nbActions ) ; int i2 = <NUM_LIT:0> ; WorldModel . Move temp = actionsOrder [ i2 ] ; actionsOrder [ i2 ] = actionsOrder [ i1 ] ; actionsOrder [ i1 ] = temp ; boolean fencesAsObs = terms . length > <NUM_LIT:5> && terms [ <NUM_LIT:5> ] . toString ( ) . equals ( "<STR_LIT>" ) ; Search astar = new Search ( model , from , to , actionsOrder , true , false , true , false , false , fencesAsObs , arch ) ; solution = astar . search ( ) ; if ( solution == null && ! fencesAsObs ) { Search s = new Search ( model , from , to , arch ) ; int fixtimes = <NUM_LIT:0> ; while ( s . search ( ) == null && arch . isRunning ( ) && fixtimes < <NUM_LIT:100> ) { fixtimes ++ ; ts . getLogger ( ) . info ( "<STR_LIT>" + to + "<STR_LIT>" ) ; arch . obstaclePerceived ( to . x , to . y ) ; to = model . nearFree ( to , null ) ; s = new Search ( model , from , to , arch ) ; } astar = new Search ( model , from , to , actionsOrder , true , false , true , false , false , false , arch ) ; solution = astar . search ( ) ; } } return solution ; } } </s>
|
<s> package jia ; import jason . environment . grid . Location ; import java . io . Serializable ; import java . util . ArrayList ; import java . util . Collection ; import java . util . List ; import arch . LocalWorldModel ; public final class Vec implements Serializable , Cloneable , Comparable < Vec > { public final double x , y ; public final double r , t ; public static final double PI2 = <NUM_LIT> * Math . PI ; public Vec ( double x , double y ) { this . x = x ; this . y = y ; this . r = Math . sqrt ( x * x + y * y ) ; this . t = Math . atan2 ( y , x ) ; } public Vec ( LocalWorldModel model , Location l ) { this . x = l . x ; this . y = model . getHeight ( ) - l . y - <NUM_LIT:1> ; this . r = Math . sqrt ( x * x + y * y ) ; this . t = Math . atan2 ( y , x ) ; } public Vec ( LocalWorldModel model , int x , int y ) { this . x = x ; this . y = model . getHeight ( ) - y - <NUM_LIT:1> ; this . r = Math . sqrt ( x * x + this . y * this . y ) ; this . t = Math . atan2 ( this . y , x ) ; } public int getX ( ) { return ( int ) Math . round ( x ) ; } public int getY ( ) { return ( int ) Math . round ( y ) ; } public double magnitude ( ) { return r ; } public double angle ( ) { return t ; } public Location getLocation ( LocalWorldModel model ) { return new Location ( getX ( ) , model . getHeight ( ) - getY ( ) - <NUM_LIT:1> ) ; } public Vec add ( Vec v ) { return new Vec ( x + v . x , y + v . y ) ; } public Vec sub ( Vec v ) { return new Vec ( x - v . x , y - v . y ) ; } public Vec product ( double e ) { return new Vec ( x * e , y * e ) ; } public Vec newAngle ( double t ) { while ( t > PI2 ) t = t - PI2 ; while ( t < <NUM_LIT:0> ) t = t + PI2 ; return new Vec ( r * Math . cos ( t ) , r * Math . sin ( t ) ) ; } public Vec turn90CW ( ) { return new Vec ( y , - x ) ; } public Vec turn90ACW ( ) { return new Vec ( - y , x ) ; } public Vec newMagnitude ( double r ) { return new Vec ( r * Math . cos ( t ) , r * Math . sin ( t ) ) ; } public int octant ( ) { double temp = t + Math . PI / <NUM_LIT:8> ; if ( temp < <NUM_LIT:0> ) temp += Math . PI * <NUM_LIT:2> ; return ( ( int ) ( temp / ( Math . PI / <NUM_LIT:4> ) ) % <NUM_LIT:8> ) ; } public int quadrant ( ) { double temp = t + Math . PI / <NUM_LIT:4> ; if ( temp < <NUM_LIT:0> ) temp += Math . PI * <NUM_LIT:2> ; return ( ( int ) ( temp / ( Math . PI / <NUM_LIT:2> ) ) % <NUM_LIT:4> ) ; } @ Override public int hashCode ( ) { return ( int ) ( ( x + y ) * <NUM_LIT> ) ; } @ Override public boolean equals ( Object o ) { if ( o == null ) return false ; if ( o == this ) return true ; if ( o instanceof Vec ) { Vec v = ( Vec ) o ; return ( getX ( ) == v . getX ( ) ) && ( getY ( ) == v . getY ( ) ) ; } return false ; } public int compareTo ( Vec o ) { if ( r > o . r ) return <NUM_LIT:1> ; if ( r < o . r ) return - <NUM_LIT:1> ; return <NUM_LIT:0> ; } public Object clone ( ) { return this ; } @ Override public String toString ( ) { return getX ( ) + "<STR_LIT:U+002C>" + getY ( ) ; } public static Vec max ( Collection < Vec > vs ) { Vec max = null ; for ( Vec v : vs ) { if ( max == null || max . r < v . r ) max = v ; } return max ; } public static List < Vec > sub ( Collection < Vec > vs , Vec ref ) { List < Vec > r = new ArrayList < Vec > ( vs . size ( ) ) ; for ( Vec v : vs ) { r . add ( v . sub ( ref ) ) ; } return r ; } public static Vec mean ( Collection < Vec > vs ) { if ( vs . isEmpty ( ) ) return new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ; double x = <NUM_LIT:0> , y = <NUM_LIT:0> ; for ( Vec v : vs ) { x += v . x ; y += v . y ; } return new Vec ( x / vs . size ( ) , y / vs . size ( ) ) ; } public static Vec stddev ( Collection < Vec > vs , Vec mean ) { if ( vs . isEmpty ( ) ) return new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ; double x = <NUM_LIT:0> , y = <NUM_LIT:0> ; for ( Vec v : vs ) { x += Math . pow ( v . x - mean . x , <NUM_LIT:2> ) ; y += Math . pow ( v . y - mean . y , <NUM_LIT:2> ) ; } x = x / vs . size ( ) ; y = y / vs . size ( ) ; return new Vec ( Math . sqrt ( x ) , Math . sqrt ( y ) ) ; } public double dot ( Vec a ) { return x * a . y - y * a . x ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class other_side_fence extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; int fx = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int fy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; Vec vtarget = computesOtherSide ( model , new Vec ( model , model . getAgPos ( arch . getMyId ( ) ) ) , new Vec ( model , fx , fy ) ) ; Location ltarget = vtarget . getLocation ( model ) ; ltarget = model . nearFree ( ltarget , null ) ; return un . unifies ( terms [ <NUM_LIT:2> ] , ASSyntax . createNumber ( ltarget . x ) ) && un . unifies ( terms [ <NUM_LIT:3> ] , ASSyntax . createNumber ( ltarget . y ) ) ; } public Vec computesOtherSide ( LocalWorldModel model , Vec start , Vec fence ) { return fence . sub ( start ) . product ( <NUM_LIT:6> ) . add ( start ) ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . NumberTermImpl ; import jason . asSyntax . Structure ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . logging . Level ; import env . WorldModel ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class near_least_visited extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { try { LocalWorldModel model = ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ; if ( model == null ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" ) ; } else { int agx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) ; int agy = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ; Location ag = new Location ( agx , agy ) ; Structure sarea = ( Structure ) args [ <NUM_LIT:2> ] ; int ax1 = ( int ) ( ( NumberTerm ) sarea . getTerm ( <NUM_LIT:0> ) ) . solve ( ) ; int ay1 = ( int ) ( ( NumberTerm ) sarea . getTerm ( <NUM_LIT:1> ) ) . solve ( ) ; int ax2 = ( int ) ( ( NumberTerm ) sarea . getTerm ( <NUM_LIT:2> ) ) . solve ( ) ; int ay2 = ( int ) ( ( NumberTerm ) sarea . getTerm ( <NUM_LIT:3> ) ) . solve ( ) ; Location tl = new Location ( ax1 , ay1 ) ; Location br = new Location ( ax2 , ay2 ) ; Location n = model . getNearLeastVisited ( ag , tl , br ) ; if ( n != null ) { Search s = new Search ( model , ag , n , ts . getUserAgArch ( ) ) ; int loopcount = <NUM_LIT:0> ; while ( s . search ( ) == null && ts . getUserAgArch ( ) . isRunning ( ) && loopcount < <NUM_LIT:5> ) { loopcount ++ ; ts . getLogger ( ) . info ( "<STR_LIT>" + n + "<STR_LIT>" ) ; model . add ( WorldModel . OBSTACLE , n ) ; n = model . getNearLeastVisited ( ag , tl , br ) ; s = new Search ( model , ag , n , ts . getUserAgArch ( ) ) ; } un . unifies ( args [ <NUM_LIT:3> ] , new NumberTermImpl ( n . x ) ) ; un . unifies ( args [ <NUM_LIT:4> ] , new NumberTermImpl ( n . y ) ) ; return true ; } else { ts . getLogger ( ) . info ( "<STR_LIT>" + ag + "<STR_LIT>" + tl + "<STR_LIT>" + br ) ; } } } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . ListTerm ; import jason . asSyntax . ListTermImpl ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . List ; import java . util . logging . Logger ; import arch . CowboyArch ; import arch . LocalWorldModel ; import busca . Nodo ; import env . ClusterModelFactory ; import env . IClusterModel ; import env . WorldModel ; import env . ClusterModel ; public class position_to_cluster extends DefaultInternalAction { private static final long serialVersionUID = <NUM_LIT:1L> ; static Logger logger = null ; private double angular_dis_bet_ag = <NUM_LIT> * Math . PI / <NUM_LIT> ; private double ct = <NUM_LIT:1> ; LocalWorldModel model ; CowboyArch arch ; Search s ; int [ ] radius ; int n ; List < Nodo > path ; IClusterModel cModel ; public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { if ( logger == null ) logger = ts . getLogger ( ) ; if ( cModel == null ) cModel = ClusterModelFactory . getModel ( ts . getUserAgArch ( ) . getAgName ( ) ) ; arch = ( CowboyArch ) ts . getUserAgArch ( ) ; Vec dir = new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ; model = arch . getModel ( ) ; ListTerm pos = new ListTermImpl ( ) ; Vec [ ] centers = cModel . getCenters ( ) ; radius = cModel . getMaxDist ( ) ; if ( args [ <NUM_LIT:0> ] . isNumeric ( ) && args [ <NUM_LIT:1> ] . isNumeric ( ) && args [ <NUM_LIT:2> ] . isNumeric ( ) ) { n = <NUM_LIT:0> ; int x = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ; int dist = centers [ <NUM_LIT:0> ] . getLocation ( model ) . distanceChebyshev ( new Location ( x , y ) ) ; int dist2 ; for ( int i = <NUM_LIT:1> ; i < centers . length ; i ++ ) { dist2 = centers [ i ] . getLocation ( model ) . distanceChebyshev ( new Location ( x , y ) ) ; if ( dist2 < dist ) { dist = dist2 ; n = i ; } } int numAg = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:2> ] ) . solve ( ) ; dir = getDirection ( centers [ n ] ) . newMagnitude ( ( double ) radius [ n ] * cModel . getPrefkPTC ( ) ) ; Location [ ] positions = new Location [ numAg ] ; if ( numAg == <NUM_LIT:1> ) { positions [ <NUM_LIT:0> ] = centers [ n ] . sub ( dir ) . getLocation ( model ) ; } else { double angle = ( ( new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ) . sub ( dir ) ) . t - angular_dis_bet_ag / <NUM_LIT> ; double angle_step = angular_dis_bet_ag / ( ( double ) numAg - <NUM_LIT:1.0> ) ; for ( int i = <NUM_LIT:0> ; i < numAg ; i ++ ) { Vec temp = dir ; temp = dir . newAngle ( angle_step * ( double ) i + angle ) ; positions [ i ] = firstFreeLoc ( temp , centers [ n ] ) ; } } for ( int i = <NUM_LIT:0> ; i < numAg ; i ++ ) { pos . add ( ASSyntax . createStructure ( "<STR_LIT>" , ASSyntax . createNumber ( positions [ i ] . x ) , ASSyntax . createNumber ( positions [ i ] . y ) ) ) ; } } else { ts . getAg ( ) . getLogger ( ) . info ( "<STR_LIT>" ) ; } return un . unifies ( args [ <NUM_LIT:3> ] , pos ) ; } private Vec getDirection ( Vec from ) throws Exception { s = new Search ( model , from . getLocation ( model ) , model . getCorral ( ) . center ( ) , null , false , false , false , false , false , false , arch ) ; path = Search . normalPath ( s . search ( ) ) ; int n = path . size ( ) ; Location temp ; if ( n + <NUM_LIT:1> > model . getCorral ( ) . center ( ) . distanceChebyshev ( from . getLocation ( model ) ) && n > <NUM_LIT:4> ) { temp = Search . getNodeLocation ( path . get ( <NUM_LIT:4> ) ) ; } else { System . out . println ( "<STR_LIT>" ) ; temp = model . getCorral ( ) . center ( ) ; } Vec tempvec = new Vec ( model , temp ) ; return tempvec . sub ( from ) ; } private void printNodes ( List < Nodo > path ) { for ( Nodo no : path ) { System . out . println ( "<STR_LIT>" + Search . getNodeLocation ( no ) ) ; } } private Location firstFreeLoc ( Vec displacement , Vec Origin ) { Location loc = Origin . getLocation ( model ) ; int maxSize = ( int ) displacement . r ; for ( int i = <NUM_LIT:0> ; i <= maxSize ; i ++ ) { Location temp = ( displacement . newMagnitude ( i ) ) . add ( Origin ) . getLocation ( model ) ; if ( ( ! model . inGrid ( temp ) ) || model . hasObject ( WorldModel . OBSTACLE , temp ) || model . hasObject ( WorldModel . FENCE , temp ) || model . hasObject ( WorldModel . SWITCH , temp ) || model . hasObject ( WorldModel . CORRAL , temp ) ) { return loc ; } loc = temp ; } return loc ; } } </s>
|
<s> package jia ; import java . util . logging . Level ; import arch . CowboyArch ; import arch . LocalWorldModel ; import jason . asSemantics . * ; import jason . asSyntax . * ; import env . WorldModel ; public class fence_switch extends DefaultInternalAction { private static final long serialVersionUID = <NUM_LIT:1L> ; @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { try { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; int i , j , posx = <NUM_LIT:0> , posy = <NUM_LIT:0> ; boolean ind = false ; for ( i = - <NUM_LIT:1> ; i <= <NUM_LIT:1> ; i ++ ) { for ( j = - <NUM_LIT:1> ; j <= <NUM_LIT:1> ; j ++ ) { if ( i == <NUM_LIT:0> && j == <NUM_LIT:0> ) continue ; posx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) + i ; posy = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) + j ; while ( model . hasObject ( WorldModel . FENCE , posx , posy ) ) { posx += i ; posy += j ; } if ( model . hasObject ( WorldModel . SWITCH , posx , posy ) ) { ind = true ; break ; } } if ( ind ) break ; } if ( ind ) { ts . getAg ( ) . getLogger ( ) . info ( "<STR_LIT>" + posx + "<STR_LIT:U+002C>" + posy + "<STR_LIT:)>" ) ; return un . unifies ( args [ <NUM_LIT:2> ] , ASSyntax . createNumber ( posx ) ) && un . unifies ( args [ <NUM_LIT:3> ] , ASSyntax . createNumber ( posy ) ) ; } } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } } </s>
|
<s> package jia ; import java . util . List ; import java . util . logging . Logger ; import busca . Nodo ; import arch . CowboyArch ; import arch . LocalWorldModel ; import env . ClusterModel ; import env . ClusterModelFactory ; import env . IClusterModel ; import env . WorldModel ; import jason . * ; import jason . environment . grid . Location ; import jason . asSemantics . * ; import jason . asSyntax . * ; public class weight_of_clusters extends DefaultInternalAction { private static final long serialVersionUID = <NUM_LIT> ; LocalWorldModel model ; static Logger logger ; Search s ; CowboyArch arch ; int size ; IClusterModel ClModel ; @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { if ( ClModel == null ) ClModel = ClusterModelFactory . getModel ( ts . getUserAgArch ( ) . getAgName ( ) ) ; arch = ( CowboyArch ) ts . getUserAgArch ( ) ; model = arch . getModel ( ) ; Location Cl = new Location ( ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) , ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ) ; Location Gr = new Location ( ( int ) ( ( NumberTerm ) args [ <NUM_LIT:2> ] ) . solve ( ) , ( int ) ( ( NumberTerm ) args [ <NUM_LIT:3> ] ) . solve ( ) ) ; int S = getSParameter ( Cl , ts ) ; int L = getDistances ( Cl , Gr ) ; if ( args . length == <NUM_LIT:8> && args [ <NUM_LIT:4> ] . isGround ( ) && args [ <NUM_LIT:5> ] . isGround ( ) ) { Location actCl = new Location ( ( int ) ( ( NumberTerm ) args [ <NUM_LIT:4> ] ) . solve ( ) , ( int ) ( ( NumberTerm ) args [ <NUM_LIT:5> ] ) . solve ( ) ) ; double resp = Math . abs ( ( double ) S * L / <NUM_LIT:100> ) + <NUM_LIT:1.0> / ( <NUM_LIT:1.0> + ( double ) actCl . distanceChebyshev ( Cl ) ) ; return un . unifies ( args [ <NUM_LIT:6> ] , new NumberTermImpl ( resp ) ) & un . unifies ( args [ <NUM_LIT:7> ] , new NumberTermImpl ( size ) ) ; } else if ( args . length == <NUM_LIT:8> ) { double resp = Math . abs ( ( double ) S * L / <NUM_LIT:100> ) ; return un . unifies ( args [ <NUM_LIT:6> ] , new NumberTermImpl ( resp ) ) & un . unifies ( args [ <NUM_LIT:7> ] , new NumberTermImpl ( size ) ) ; } return un . unifies ( args [ <NUM_LIT:4> ] , new NumberTermImpl ( Math . abs ( ( double ) S * L / <NUM_LIT:100> ) ) ) & un . unifies ( args [ <NUM_LIT:5> ] , new NumberTermImpl ( size ) ) ; } private int getDistances ( Location Cl , Location Gr ) throws Exception { s = new Search ( model , Cl , model . getCorral ( ) . center ( ) , null , false , false , false , false , false , false , arch ) ; List < Nodo > path = Search . normalPath ( s . search ( ) ) ; int ClToCo = path . size ( ) ; s = new Search ( model , Gr , model . getCorral ( ) . center ( ) , null , false , false , false , false , false , false , arch ) ; path = Search . normalPath ( s . search ( ) ) ; int GrToCl = path . size ( ) ; return ClToCo + GrToCl ; } private int getSParameter ( Location Cl , TransitionSystem ts ) { Vec [ ] Centers = ClModel . getCenters ( ) ; int [ ] Radius = ClModel . getMaxDist ( ) ; int [ ] NumberOfCows = ClModel . getNumCows ( ) ; int dist = Centers [ <NUM_LIT:0> ] . getLocation ( model ) . distanceChebyshev ( Cl ) ; int k = <NUM_LIT:0> ; for ( int i = <NUM_LIT:1> ; i < Centers . length ; i ++ ) { if ( dist > Centers [ i ] . getLocation ( model ) . distanceChebyshev ( Cl ) ) { dist = Centers [ i ] . getLocation ( model ) . distanceChebyshev ( Cl ) ; k = i ; } } size = Radius [ k ] ; return ( Radius [ k ] - ClModel . getPrefRadius ( ) ) * ( NumberOfCows [ k ] - ClModel . getPrefNCows ( ) ) ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import arch . CowboyArch ; import env . WorldModel ; public class corral extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { WorldModel model = ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ; int x = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; return model . hasObject ( WorldModel . CORRAL , x , y ) ; } } </s>
|
<s> package jia ; import java . util . logging . Logger ; import arch . CowboyArch ; import arch . LocalWorldModel ; import env . ClusterModel ; import env . ClusterModelFactory ; import env . IClusterModel ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . ListTerm ; import jason . asSyntax . ListTermImpl ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; public class getclusters extends DefaultInternalAction { static Logger logger = null ; IClusterModel cM ; public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { if ( logger == null ) logger = ts . getLogger ( ) ; if ( cM == null ) cM = ClusterModelFactory . getModel ( ts . getUserAgArch ( ) . getAgName ( ) ) ; Vec [ ] Center = cM . getCenters ( ) ; int n = cM . getNumberOfCluster ( ) ; int [ ] maxDist = cM . getMaxDist ( ) ; CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; ListTerm Cl = new ListTermImpl ( ) ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { Location l = Center [ i ] . getLocation ( model ) ; logger . info ( "<STR_LIT>" + n + "<STR_LIT>" + i + "<STR_LIT>" + l . x + "<STR_LIT:U+002C>" + l . y + "<STR_LIT:)>" ) ; Cl . add ( ASSyntax . createStructure ( "<STR_LIT>" , ASSyntax . createNumber ( l . x ) , ASSyntax . createNumber ( l . y ) ) ) ; } ListTerm Sizes = new ListTermImpl ( ) ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { Sizes . add ( ASSyntax . createNumber ( maxDist [ i ] ) ) ; } return un . unifies ( args [ <NUM_LIT:0> ] , ASSyntax . createNumber ( n ) ) & un . unifies ( args [ <NUM_LIT:1> ] , Cl != null && ! ( Cl . size ( ) > <NUM_LIT:0> ) ? Cl . get ( <NUM_LIT:0> ) : Cl ) & un . unifies ( args [ <NUM_LIT:2> ] , Sizes ) ; } } </s>
|
<s> package jia ; import static jason . asSyntax . ASSyntax . createNumber ; import static jason . asSyntax . ASSyntax . createStructure ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . ListTerm ; import jason . asSyntax . ListTermImpl ; import jason . asSyntax . ObjectTermImpl ; import jason . asSyntax . Structure ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . ArrayList ; import java . util . Collection ; import java . util . Collections ; import java . util . Iterator ; import java . util . List ; import java . util . logging . Level ; import java . util . logging . Logger ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class cluster extends DefaultInternalAction { public static final int COWS_BY_BOY = <NUM_LIT:6> ; public static final int MAXCLUSTERSIZE = ( <NUM_LIT:7> * COWS_BY_BOY ) - <NUM_LIT:2> ; static Logger logger = null ; @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { if ( logger == null ) logger = ts . getLogger ( ) ; try { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; if ( model == null ) return false ; List < Location > locs = getCluster ( model , <NUM_LIT:3> , arch ) ; if ( args . length == <NUM_LIT:1> ) { return un . unifies ( args [ <NUM_LIT:0> ] , new ObjectTermImpl ( locs ) ) ; } else { Structure nearCow = null ; ListTerm r = new ListTermImpl ( ) ; ListTerm tail = r ; for ( Location l : locs ) { Structure pos = createStructure ( "<STR_LIT>" , createNumber ( l . x ) , createNumber ( l . y ) ) ; tail = tail . append ( pos ) ; if ( nearCow == null ) nearCow = pos ; } if ( args . length > <NUM_LIT:2> && nearCow != null ) un . unifies ( args [ <NUM_LIT:2> ] , nearCow ) ; return un . unifies ( args [ <NUM_LIT:0> ] , new ObjectTermImpl ( locs ) ) && un . unifies ( args [ <NUM_LIT:1> ] , r ) ; } } catch ( Throwable e ) { logger . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } public static List < Location > getCluster ( LocalWorldModel model , int maxDist , CowboyArch arch ) throws Exception { Collection < Vec > cows = model . getKnownCows ( ) ; List < Vec > vs = new ArrayList < Vec > ( ) ; Location center = model . getCorral ( ) . center ( ) ; Vec near = null ; int nearDist = <NUM_LIT:0> ; for ( Vec v : cows ) { Location cl = v . getLocation ( model ) ; if ( ! model . getCorral ( ) . contains ( cl ) ) { vs . add ( v ) ; int dist = model . pathLength ( cl , center , false , arch ) ; if ( dist >= <NUM_LIT:0> ) { if ( near == null || dist < nearDist ) { near = v ; nearDist = dist ; } } } } List < Vec > cs = new ArrayList < Vec > ( ) ; if ( near != null ) { vs . remove ( near ) ; cs . add ( near ) ; } else { logger . info ( "<STR_LIT>" + model . getKnownCows ( ) ) ; } boolean add = true ; while ( add ) { add = false ; Iterator < Vec > i = vs . iterator ( ) ; while ( i . hasNext ( ) ) { Vec v = i . next ( ) ; Iterator < Vec > j = cs . iterator ( ) ; while ( j . hasNext ( ) && cs . size ( ) < MAXCLUSTERSIZE ) { Vec c = j . next ( ) ; if ( c . sub ( v ) . magnitude ( ) < maxDist ) { cs . add ( v ) ; i . remove ( ) ; add = true ; break ; } } } if ( cs . size ( ) > MAXCLUSTERSIZE ) break ; } List < Location > clusterLocs = new ArrayList < Location > ( ) ; for ( Vec v : cs ) { clusterLocs . add ( v . getLocation ( model ) ) ; } return clusterLocs ; } public static List < Location > getCluster2008 ( LocalWorldModel model , int maxDist , CowboyArch arch ) throws Exception { Collection < Vec > cows = model . getKnownCows ( ) ; System . out . println ( cows ) ; List < Vec > cs = new ArrayList < Vec > ( ) ; Vec mean = Vec . mean ( cows ) ; List < Vec > vs = new ArrayList < Vec > ( ) ; for ( Vec v : cows ) { Location cl = v . getLocation ( model ) ; if ( ! model . getCorral ( ) . contains ( cl ) ) { Vec vc = v . sub ( mean ) ; vs . add ( vc ) ; } else { System . out . println ( "<STR_LIT>" + v + "<STR_LIT>" ) ; } } if ( vs . size ( ) > <NUM_LIT:4> ) Collections . sort ( vs ) ; if ( ! vs . isEmpty ( ) ) cs . add ( vs . remove ( <NUM_LIT:0> ) ) ; boolean add = true ; while ( add ) { add = false ; Iterator < Vec > i = vs . iterator ( ) ; while ( i . hasNext ( ) ) { Vec v = i . next ( ) ; Iterator < Vec > j = cs . iterator ( ) ; while ( j . hasNext ( ) && cs . size ( ) < MAXCLUSTERSIZE ) { Vec c = j . next ( ) ; if ( c . sub ( v ) . magnitude ( ) < maxDist ) { cs . add ( v ) ; i . remove ( ) ; add = true ; break ; } } } if ( cs . size ( ) > MAXCLUSTERSIZE ) break ; } List < Location > clusterLocs = new ArrayList < Location > ( ) ; for ( Vec v : cs ) { clusterLocs . add ( v . add ( mean ) . getLocation ( model ) ) ; } return clusterLocs ; } public static List < Vec > location2vec ( LocalWorldModel model , List < Location > clusterLocs ) { List < Vec > cows = new ArrayList < Vec > ( ) ; for ( Location l : clusterLocs ) cows . add ( new Vec ( model , l ) ) ; return cows ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import arch . CowboyArch ; import env . WorldModel ; public class obstacle extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { WorldModel model = ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ; int x = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; return ! model . inGrid ( x , y ) || model . hasObject ( WorldModel . OBSTACLE , x , y ) ; } } </s>
|
<s> package jia ; import env . WorldModel ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class fence extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { LocalWorldModel model = ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ; int x = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int y = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; return model . hasObject ( WorldModel . FENCE , x , y ) ; } } </s>
|
<s> package jia ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . List ; import arch . CowboyArch ; import arch . LocalWorldModel ; import busca . Nodo ; import env . WorldModel ; public class has_object_in_path extends direction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; Nodo solution = findPath ( ts , terms ) ; if ( solution != null ) { int object = WorldModel . stringToObject ( terms [ <NUM_LIT:4> ] . toString ( ) . toUpperCase ( ) ) ; if ( object < <NUM_LIT:0> ) { ts . getLogger ( ) . info ( "<STR_LIT>" + terms [ <NUM_LIT:4> ] + "<STR_LIT>" ) ; return false ; } List < Nodo > path = Search . normalPath ( solution ) ; for ( Nodo n : path ) { Location l = Search . getNodeLocation ( n ) ; if ( model . hasObject ( object , l ) ) { return un . unifies ( terms [ <NUM_LIT:5> ] , ASSyntax . createNumber ( l . x ) ) && un . unifies ( terms [ <NUM_LIT:6> ] , ASSyntax . createNumber ( l . y ) ) && un . unifies ( terms [ <NUM_LIT:7> ] , ASSyntax . createNumber ( n . getProfundidade ( ) ) ) ; } } } else { ts . getLogger ( ) . info ( "<STR_LIT>" + terms [ <NUM_LIT:0> ] + "<STR_LIT:U+002C>" + terms [ <NUM_LIT:1> ] + "<STR_LIT:U+0020toU+0020>" + terms [ <NUM_LIT:2> ] + "<STR_LIT:U+002C>" + terms [ <NUM_LIT:3> ] + "<STR_LIT>" ) ; } return false ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import arch . CowboyArch ; import arch . LocalWorldModel ; import env . WorldModel ; public class is_corral_switch extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) { LocalWorldModel model = ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ; int sx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) ; int sy = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ; if ( model . hasObject ( WorldModel . CORRAL , sx + <NUM_LIT:1> , sy ) ) return true ; if ( model . hasObject ( WorldModel . CORRAL , sx - <NUM_LIT:1> , sy ) ) return true ; if ( model . hasObject ( WorldModel . CORRAL , sx , sy + <NUM_LIT:1> ) ) return true ; if ( model . hasObject ( WorldModel . CORRAL , sx , sy - <NUM_LIT:1> ) ) return true ; return false ; } } </s>
|
<s> package jia ; import jason . JasonException ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTermImpl ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import java . util . Random ; import java . util . Iterator ; public class random extends DefaultInternalAction { private Random random = new Random ( ) ; @ Override public Object execute ( final TransitionSystem ts , final Unifier un , final Term [ ] args ) throws Exception { try { if ( ! args [ <NUM_LIT:0> ] . isVar ( ) ) { throw new JasonException ( "<STR_LIT>" ) ; } if ( ! args [ <NUM_LIT:1> ] . isNumeric ( ) ) { throw new JasonException ( "<STR_LIT>" ) ; } final int max = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ; final int maxIter = args . length < <NUM_LIT:3> ? Integer . MAX_VALUE : ( int ) ( ( NumberTerm ) args [ <NUM_LIT:2> ] ) . solve ( ) ; return new Iterator < Unifier > ( ) { int i = <NUM_LIT:0> ; public boolean hasNext ( ) { return i < maxIter && ts . getUserAgArch ( ) . isRunning ( ) ; } public Unifier next ( ) { i ++ ; Unifier c = un . clone ( ) ; c . unifies ( args [ <NUM_LIT:0> ] , new NumberTermImpl ( random . nextInt ( max ) ) ) ; return c ; } public void remove ( ) { } } ; } catch ( ArrayIndexOutOfBoundsException e ) { throw new JasonException ( "<STR_LIT>" ) ; } catch ( Exception e ) { throw new JasonException ( "<STR_LIT>" + e , e ) ; } } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . NumberTermImpl ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; public class dist extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { int iagx = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int iagy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; int itox = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:2> ] ) . solve ( ) ; int itoy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:3> ] ) . solve ( ) ; int dist = new Location ( iagx , iagy ) . maxBorder ( new Location ( itox , itoy ) ) ; return un . unifies ( terms [ <NUM_LIT:4> ] , new NumberTermImpl ( dist ) ) ; } } </s>
|
<s> package jia ; import static jason . asSyntax . ASSyntax . createNumber ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . logging . Level ; import env . WorldModel ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class switch_places extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { try { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; if ( model == null ) return false ; int lx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) ; int ly = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ; int agx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:2> ] ) . solve ( ) ; int agy = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:3> ] ) . solve ( ) ; Location agPlace = new Location ( agx , agy ) ; Location place1 = null , place2 = null ; if ( model . isHorizontalFence ( lx , ly ) ) { place1 = new Location ( lx , ly + <NUM_LIT:1> ) ; place2 = new Location ( lx , ly - <NUM_LIT:1> ) ; } else { place1 = new Location ( lx + <NUM_LIT:1> , ly ) ; place2 = new Location ( lx - <NUM_LIT:1> , ly ) ; } int distPlace1 = model . pathLength ( agPlace , place1 , false , arch ) ; int distPlace2 = model . pathLength ( agPlace , place2 , false , arch ) ; if ( distPlace1 > distPlace2 | model . hasObject ( WorldModel . CORRAL , place1 ) ) { Location bak = place2 ; place2 = place1 ; place1 = bak ; } return un . unifies ( args [ <NUM_LIT:4> ] , createNumber ( place1 . x ) ) && un . unifies ( args [ <NUM_LIT:5> ] , createNumber ( place1 . y ) ) && un . unifies ( args [ <NUM_LIT:6> ] , createNumber ( place2 . x ) ) && un . unifies ( args [ <NUM_LIT:7> ] , createNumber ( place2 . y ) ) ; } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } } </s>
|
<s> package jia ; import jason . architecture . AgArch ; import jason . environment . grid . Location ; import java . util . ArrayList ; import java . util . Collections ; import java . util . Comparator ; import java . util . LinkedList ; import java . util . List ; import java . util . logging . Logger ; import arch . LocalWorldModel ; import busca . AEstrela ; import busca . Busca ; import busca . Estado ; import busca . Heuristica ; import busca . Nodo ; import env . ClusterModelFactory ; import env . IClusterModel ; import env . WorldModel ; public class Search { public static final int DIST_FOR_AG_OBSTACLE = <NUM_LIT:2> ; private int sizeOfCluster = - <NUM_LIT:1> ; final LocalWorldModel model ; final Location from , to ; final boolean considerAgentsAsObstacles ; final boolean considerCorralAsObstacles ; final boolean considerCowsAsObstacles ; final boolean considerRepulsionForCows ; final boolean considerEnemyCorralRepulsion ; final boolean considerFenceAsObstacle ; int maxDistFromCluster ; WorldModel . Move [ ] actionsOrder ; int nbStates = <NUM_LIT:0> ; AgArch agArch ; public static final WorldModel . Move [ ] defaultActions = { WorldModel . Move . west , WorldModel . Move . east , WorldModel . Move . north , WorldModel . Move . northeast , WorldModel . Move . northwest , WorldModel . Move . south , WorldModel . Move . southeast , WorldModel . Move . southwest } ; Logger logger = Logger . getLogger ( Search . class . getName ( ) ) ; public Search ( LocalWorldModel m , Location from , Location to , WorldModel . Move [ ] actions , boolean considerAgentsAsObstacles , boolean considerCorralAsObstacles , boolean considerCowsAsObstacles , boolean considerRepulsionForCows , boolean considerEnemyCorralRepulsion , boolean considerFenceAsObstacle , AgArch agArch ) { this . model = m ; this . from = from ; this . to = to ; this . considerAgentsAsObstacles = considerAgentsAsObstacles ; this . considerCorralAsObstacles = considerCorralAsObstacles ; this . considerCowsAsObstacles = considerCowsAsObstacles ; this . considerRepulsionForCows = considerRepulsionForCows ; this . considerEnemyCorralRepulsion = considerEnemyCorralRepulsion ; this . considerFenceAsObstacle = considerFenceAsObstacle ; this . agArch = agArch ; if ( actions != null ) this . actionsOrder = actions ; else this . actionsOrder = defaultActions ; this . maxDistFromCluster = <NUM_LIT:4> ; this . nbStates = <NUM_LIT:0> ; model . getKnownCows ( ) ; } public void setMaxDistFromCluster ( int m ) { maxDistFromCluster = m ; } Search ( LocalWorldModel m , Location from , Location to , AgArch agArch ) { this ( m , from , to , null , false , false , false , false , false , false , agArch ) ; } public void setSearchWithCluster ( int a ) { sizeOfCluster = a ; } public Nodo search ( ) throws Exception { Busca searchAlg = new AEstrela ( ) ; GridState root = new GridState ( from , WorldModel . Move . skip , this ) ; root . distFromCluster = sizeOfCluster ; root . setAsRoot ( ) ; return searchAlg . busca ( root ) ; } public static List < Nodo > normalPath ( Nodo n ) { List < Nodo > r = new LinkedList < Nodo > ( ) ; while ( n != null ) { r . add ( <NUM_LIT:0> , n ) ; n = n . getPai ( ) ; } return r ; } public static Location getNodeLocation ( Nodo n ) { return ( ( GridState ) n . getEstado ( ) ) . pos ; } public static WorldModel . Move firstAction ( Nodo solution ) { Nodo root = solution ; Estado prev1 = null ; Estado prev2 = null ; while ( root != null ) { prev2 = prev1 ; prev1 = root . getEstado ( ) ; root = root . getPai ( ) ; } if ( prev2 != null ) { return ( ( GridState ) prev2 ) . op ; } return null ; } } final class GridState implements Estado , Heuristica { int distFromCluster = - <NUM_LIT:1> ; final Location pos ; final WorldModel . Move op ; final Search ia ; final int hashCode ; boolean isRoot = false ; public GridState ( Location l , WorldModel . Move op , Search ia ) { this . pos = l ; this . op = op ; this . ia = ia ; hashCode = pos . hashCode ( ) ; ia . nbStates ++ ; } public void setAsRoot ( ) { isRoot = true ; } public int custo ( ) { if ( isRoot ) return <NUM_LIT:0> ; int c = <NUM_LIT:1> ; if ( ia . considerCowsAsObstacles ) c += ia . model . getCowsRep ( pos . x , pos . y ) ; if ( ia . considerRepulsionForCows ) { c += ia . model . getObsRep ( pos . x , pos . y ) ; } if ( ia . considerEnemyCorralRepulsion ) c += ia . model . getEnemyCorralRep ( pos . x , pos . y ) ; if ( ia . model . hasObject ( WorldModel . FENCE , pos . x , pos . y ) ) c += <NUM_LIT:5> ; return c ; } public boolean ehMeta ( ) { return pos . equals ( ia . to ) ; } public String getDescricao ( ) { return "<STR_LIT>" ; } public int h ( ) { return pos . maxBorder ( ia . to ) ; } public List < Estado > sucessores ( ) { List < Estado > s = new ArrayList < Estado > ( ) ; if ( ia . nbStates > <NUM_LIT> ) { ia . logger . info ( "<STR_LIT>" ) ; return s ; } else if ( ia . agArch != null && ! ia . agArch . isRunning ( ) ) { return s ; } for ( int a = <NUM_LIT:0> ; a < ia . actionsOrder . length ; a ++ ) { suc ( s , WorldModel . getNewLocationForAction ( pos , ia . actionsOrder [ a ] ) , ia . actionsOrder [ a ] ) ; } if ( isRoot ) { Collections . sort ( s , new VisitedComparator ( ia . model ) ) ; } return s ; } private void suc ( List < Estado > s , Location newl , WorldModel . Move op ) { if ( ! ia . model . inGrid ( newl ) ) return ; if ( ia . model . hasObject ( WorldModel . OBSTACLE , newl ) ) return ; if ( ia . considerCorralAsObstacles && ia . model . hasObject ( WorldModel . CORRAL , newl ) ) return ; if ( ia . considerAgentsAsObstacles ) { if ( ia . model . hasObject ( WorldModel . AGENT , newl ) && ia . from . maxBorder ( newl ) <= Search . DIST_FOR_AG_OBSTACLE ) return ; if ( ia . model . hasObject ( WorldModel . ENEMY , newl ) && ia . from . maxBorder ( newl ) <= <NUM_LIT:1> ) return ; } if ( ia . considerCowsAsObstacles && ia . model . hasObject ( WorldModel . COW , newl ) && ia . from . maxBorder ( newl ) <= Search . DIST_FOR_AG_OBSTACLE ) return ; if ( ia . considerFenceAsObstacle && ia . model . hasObject ( WorldModel . FENCE , newl . x , newl . y ) ) return ; if ( distFromCluster != - <NUM_LIT:1> ) { if ( ia . model . hasObject ( WorldModel . OBSTACLE , newl ) && ia . from . maxBorder ( newl ) <= distFromCluster ) { return ; } return ; } s . add ( new GridState ( newl , op , ia ) ) ; } public boolean equals ( Object o ) { if ( o != null && o instanceof GridState ) { GridState m = ( GridState ) o ; return pos . equals ( m . pos ) ; } return false ; } public int hashCode ( ) { return hashCode ; } public String toString ( ) { return "<STR_LIT:(>" + pos + "<STR_LIT:->" + op + "<STR_LIT:)>" ; } } class VisitedComparator implements Comparator < Estado > { LocalWorldModel model ; VisitedComparator ( LocalWorldModel m ) { model = m ; } public int compare ( Estado o1 , Estado o2 ) { int v1 = model . getVisited ( ( ( GridState ) o1 ) . pos ) ; int v2 = model . getVisited ( ( ( GridState ) o2 ) . pos ) ; if ( v1 > v2 ) return <NUM_LIT:1> ; if ( v2 > v1 ) return - <NUM_LIT:1> ; return <NUM_LIT:0> ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . NumberTermImpl ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . logging . Level ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class path_length extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { try { LocalWorldModel model = ( ( CowboyArch ) ts . getUserAgArch ( ) ) . getModel ( ) ; int iagx = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:0> ] ) . solve ( ) ; int iagy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:1> ] ) . solve ( ) ; int itox = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:2> ] ) . solve ( ) ; int itoy = ( int ) ( ( NumberTerm ) terms [ <NUM_LIT:3> ] ) . solve ( ) ; if ( model . inGrid ( itox , itoy ) ) { while ( ! model . isFreeOfObstacle ( itox , itoy ) && itox > <NUM_LIT:0> ) itox -- ; while ( ! model . isFreeOfObstacle ( itox , itoy ) && itox < model . getWidth ( ) ) itox ++ ; Location from = new Location ( iagx , iagy ) ; Location to = new Location ( itox , itoy ) ; boolean fencesAsObs = terms . length > <NUM_LIT:5> && terms [ <NUM_LIT:5> ] . toString ( ) . equals ( "<STR_LIT>" ) ; int dist = model . pathLength ( from , to , fencesAsObs , ts . getUserAgArch ( ) ) ; if ( dist >= <NUM_LIT:0> ) { return un . unifies ( terms [ <NUM_LIT:4> ] , new NumberTermImpl ( dist ) ) ; } else if ( ! fencesAsObs ) { ts . getLogger ( ) . info ( "<STR_LIT>" + from + "<STR_LIT:U+0020toU+0020>" + to + "<STR_LIT:!>" ) ; } } } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } } </s>
|
<s> package jia ; import static jason . asSyntax . ASSyntax . createNumber ; import static jason . asSyntax . ASSyntax . createStructure ; import jason . JasonException ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . ListTerm ; import jason . asSyntax . ListTermImpl ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . NumberTermImpl ; import jason . asSyntax . ObjectTerm ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import jason . stdlib . foreach ; import java . util . ArrayList ; import java . util . List ; import java . util . logging . Level ; import sun . font . EAttribute ; import arch . CowboyArch ; import arch . LocalWorldModel ; import busca . Nodo ; import env . WorldModel ; public class herd_position extends DefaultInternalAction { public static final int agDistanceInFormation = <NUM_LIT:3> ; public enum Formation { one { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) } ; } } , two { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( sd + <NUM_LIT:1> , <NUM_LIT:0> ) , new Vec ( - sd , <NUM_LIT:0> ) } ; } } , three { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) , new Vec ( d , - <NUM_LIT:1> ) , new Vec ( - d , - <NUM_LIT:1> ) } ; } } , four { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( sd + <NUM_LIT:1> , <NUM_LIT:0> ) , new Vec ( - sd , <NUM_LIT:0> ) , new Vec ( d + sd , - <NUM_LIT:3> ) , new Vec ( - ( d + sd ) , - <NUM_LIT:3> ) } ; } } , five { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) , new Vec ( d , - <NUM_LIT:1> ) , new Vec ( - d , - <NUM_LIT:1> ) , new Vec ( d * <NUM_LIT:2> - <NUM_LIT:1> , - <NUM_LIT:4> ) , new Vec ( - d * <NUM_LIT:2> , - <NUM_LIT:4> ) } ; } } , six { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( sd + <NUM_LIT:1> , <NUM_LIT:0> ) , new Vec ( - sd , <NUM_LIT:0> ) , new Vec ( d + sd , - <NUM_LIT:3> ) , new Vec ( - ( d + sd ) , - <NUM_LIT:3> ) , new Vec ( d * <NUM_LIT:2> + sd - <NUM_LIT:2> , - <NUM_LIT:6> ) , new Vec ( - ( d * <NUM_LIT:2> + sd - <NUM_LIT:2> ) , - <NUM_LIT:6> ) } ; } } , seven { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) , new Vec ( d , - <NUM_LIT:1> ) , new Vec ( - d , - <NUM_LIT:1> ) , new Vec ( d * <NUM_LIT:2> - <NUM_LIT:1> , - <NUM_LIT:4> ) , new Vec ( - d * <NUM_LIT:2> , - <NUM_LIT:4> ) , new Vec ( d * <NUM_LIT:3> - <NUM_LIT:1> , - <NUM_LIT:6> ) , new Vec ( - d * <NUM_LIT:3> , - <NUM_LIT:6> ) } ; } } , eight { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( sd + <NUM_LIT:1> , <NUM_LIT:0> ) , new Vec ( - sd , <NUM_LIT:0> ) , new Vec ( d + sd , - <NUM_LIT:3> ) , new Vec ( - ( d + sd ) , - <NUM_LIT:3> ) , new Vec ( d * <NUM_LIT:2> + sd - <NUM_LIT:2> , - <NUM_LIT:6> ) , new Vec ( - ( d * <NUM_LIT:2> + sd - <NUM_LIT:2> ) , - <NUM_LIT:6> ) , new Vec ( d * <NUM_LIT:3> + sd - <NUM_LIT:2> , - <NUM_LIT:8> ) , new Vec ( - ( d * <NUM_LIT:3> + sd - <NUM_LIT:2> ) , - <NUM_LIT:8> ) } ; } } , nine { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) , new Vec ( d , - <NUM_LIT:1> ) , new Vec ( - d , - <NUM_LIT:1> ) , new Vec ( d * <NUM_LIT:2> - <NUM_LIT:1> , - <NUM_LIT:4> ) , new Vec ( - d * <NUM_LIT:2> , - <NUM_LIT:4> ) , new Vec ( d * <NUM_LIT:3> - <NUM_LIT:1> , - <NUM_LIT:6> ) , new Vec ( - d * <NUM_LIT:3> , - <NUM_LIT:6> ) , new Vec ( d * <NUM_LIT:4> - <NUM_LIT:1> , - <NUM_LIT:8> ) , new Vec ( - d * <NUM_LIT:4> , - <NUM_LIT:8> ) } ; } } , ten { Vec [ ] getDistances ( ) { return new Vec [ ] { new Vec ( sd + <NUM_LIT:1> , <NUM_LIT:0> ) , new Vec ( - sd , <NUM_LIT:0> ) , new Vec ( d + sd , - <NUM_LIT:3> ) , new Vec ( - ( d + sd ) , - <NUM_LIT:3> ) , new Vec ( d * <NUM_LIT:2> + sd - <NUM_LIT:2> , - <NUM_LIT:6> ) , new Vec ( - ( d * <NUM_LIT:2> + sd - <NUM_LIT:2> ) , - <NUM_LIT:6> ) , new Vec ( d * <NUM_LIT:3> + sd - <NUM_LIT:2> , - <NUM_LIT:8> ) , new Vec ( - ( d * <NUM_LIT:3> + sd - <NUM_LIT:2> ) , - <NUM_LIT:8> ) , new Vec ( d * <NUM_LIT:4> + sd - <NUM_LIT:2> , - <NUM_LIT:10> ) , new Vec ( - ( d * <NUM_LIT:4> + sd - <NUM_LIT:2> ) , - <NUM_LIT:10> ) } ; } } ; abstract Vec [ ] getDistances ( ) ; private static final int d = agDistanceInFormation ; private static final int sd = agDistanceInFormation / <NUM_LIT:2> ; } ; LocalWorldModel model ; List < Location > lastCluster = null ; public void setModel ( LocalWorldModel model ) { this . model = model ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { try { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; model = arch . getModel ( ) ; if ( model == null ) return false ; Location agLoc = model . getAgPos ( arch . getMyId ( ) ) ; if ( agLoc == null ) { ts . getLogger ( ) . info ( "<STR_LIT>" ) ; return false ; } Formation formation = Formation . six ; if ( args [ <NUM_LIT:0> ] . isNumeric ( ) ) { int index = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) ; formation = Formation . values ( ) [ index - <NUM_LIT:1> ] ; } else { formation = Formation . valueOf ( args [ <NUM_LIT:0> ] . toString ( ) ) ; } List < Location > clusterLocs = ( List < Location > ) ( ( ObjectTerm ) args [ <NUM_LIT:1> ] ) . getObject ( ) ; if ( arch . hasGUI ( ) ) setFormationLoc ( clusterLocs , formation ) ; if ( args . length == <NUM_LIT:4> ) { Location agTarget = getAgTarget ( clusterLocs , formation , agLoc ) ; if ( agTarget != null ) { return un . unifies ( args [ <NUM_LIT:2> ] , new NumberTermImpl ( agTarget . x ) ) && un . unifies ( args [ <NUM_LIT:3> ] , new NumberTermImpl ( agTarget . y ) ) ; } else { ts . getLogger ( ) . info ( "<STR_LIT>" + agLoc + "<STR_LIT>" + formationPlaces ( clusterLocs , formation ) + "<STR_LIT>" + lastCluster ) ; } } else { List < Location > locs = formationPlaces ( clusterLocs , formation ) ; if ( locs != null && locs . size ( ) > <NUM_LIT:0> ) { ListTerm r = new ListTermImpl ( ) ; ListTerm tail = r ; for ( Location l : locs ) { tail = tail . append ( createStructure ( "<STR_LIT>" , createNumber ( l . x ) , createNumber ( l . y ) ) ) ; } return un . unifies ( args [ <NUM_LIT:2> ] , r ) ; } else { ts . getLogger ( ) . info ( "<STR_LIT>" + agLoc + "<STR_LIT>" + formationPlaces ( clusterLocs , formation ) ) ; } } } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } public Location getAgTarget ( List < Location > clusterLocs , Formation formation , Location ag ) throws Exception { Location r = null ; List < Location > locs = formationPlaces ( clusterLocs , formation ) ; if ( locs != null ) { for ( Location l : locs ) { if ( ag . equals ( l ) || ! model . hasObject ( WorldModel . AGENT , l ) ) { r = l ; break ; } } } if ( r != null ) r = model . nearFree ( r , null ) ; return r ; } public void setFormationLoc ( List < Location > clusterLocs , Formation formation ) throws Exception { model . removeAll ( WorldModel . FORPLACE ) ; List < Location > locs = formationPlaces ( clusterLocs , formation ) ; if ( locs != null ) { for ( Location l : locs ) { if ( model . inGrid ( l ) ) { model . add ( WorldModel . FORPLACE , l ) ; } } } } public List < Location > formationPlaces ( List < Location > clusterLocs , Formation formation ) throws Exception { lastCluster = clusterLocs ; List < Vec > cows = cluster . location2vec ( model , clusterLocs ) ; if ( cows . isEmpty ( ) ) return null ; Vec mean = Vec . mean ( cows ) ; int stepsFromCenter = Math . max ( <NUM_LIT:4> , ( int ) Math . round ( Vec . max ( cows ) . sub ( mean ) . magnitude ( ) ) + <NUM_LIT:1> ) ; Search s = new Search ( model , mean . getLocation ( model ) , model . getCorral ( ) . center ( ) , null , false , false , false , false , false , false , null ) ; s . setMaxDistFromCluster ( stepsFromCenter + Search . DIST_FOR_AG_OBSTACLE ) ; List < Nodo > np = Search . normalPath ( s . search ( ) ) ; int n = Math . min ( stepsFromCenter , np . size ( ) ) ; if ( n == <NUM_LIT:0> ) throw new JasonException ( "<STR_LIT>" + clusterLocs + "<STR_LIT>" + cows ) ; Vec cowstarget = new Vec ( model , Search . getNodeLocation ( np . get ( n ) ) ) ; Vec farcow = null ; for ( Vec c : cows ) if ( farcow == null || farcow . getLocation ( model ) . maxBorder ( model . getCorral ( ) . center ( ) ) < c . getLocation ( model ) . maxBorder ( model . getCorral ( ) . center ( ) ) ) farcow = c ; Vec agsTarget = mean . sub ( cowstarget ) . newMagnitude ( farcow . sub ( mean ) . magnitude ( ) + <NUM_LIT:1> ) ; List < Location > r = new ArrayList < Location > ( ) ; for ( Vec position : formation . getDistances ( ) ) { Location l = findFirstFreeLocTowardsTarget ( agsTarget , position , mean , false , model ) ; if ( l == null ) { l = model . nearFree ( agsTarget . add ( mean ) . getLocation ( model ) , r ) ; } else { if ( formation == Formation . one || formation == Formation . two ) l = pathToNearCow ( l , clusterLocs ) ; if ( ! model . inGrid ( l ) || model . hasObject ( WorldModel . OBSTACLE , l ) || r . contains ( l ) ) l = model . nearFree ( l , r ) ; } r . add ( l ) ; } return r ; } public static Location findFirstFreeLocTowardsTarget ( Vec start , Vec direction , Vec ref , boolean fenceAsObs , LocalWorldModel model ) { Vec startandref = start . add ( ref ) ; Vec t = start . turn90CW ( ) ; t = t . newAngle ( t . angle ( ) + direction . angle ( ) ) ; int maxSize = ( int ) direction . magnitude ( ) ; Location l = t . newMagnitude ( maxSize ) . add ( startandref ) . getLocation ( model ) ; Location lastloc = null ; for ( int s = <NUM_LIT:1> ; s <= maxSize ; s ++ ) { l = t . newMagnitude ( s ) . add ( startandref ) . getLocation ( model ) ; if ( ( ! model . inGrid ( l ) || model . hasObject ( WorldModel . OBSTACLE , l ) || model . hasObject ( WorldModel . CORRAL , l ) ) && lastloc != null ) return lastloc ; if ( fenceAsObs && model . hasObject ( WorldModel . FENCE , l ) && lastloc != null ) return lastloc ; lastloc = l ; } return l ; } private Location pathToNearCow ( Location t , List < Location > cows ) { Location near = null ; for ( Location c : cows ) { if ( near == null || t . maxBorder ( c ) < t . maxBorder ( near ) ) near = c ; } if ( near != null && t . maxBorder ( near ) > WorldModel . cowPerceptionRatio ) { Vec nearcv = new Vec ( model , near ) ; Vec dircow = new Vec ( model , t ) . sub ( nearcv ) ; for ( int s = <NUM_LIT:1> ; s <= <NUM_LIT:3> ; s ++ ) { Location l = dircow . newMagnitude ( s ) . add ( nearcv ) . getLocation ( model ) ; if ( ! model . hasObject ( WorldModel . COW , l ) ) return l ; } } return t ; } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . NumberTermImpl ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . logging . Level ; import arch . CowboyArch ; import arch . LocalWorldModel ; public class scouter_pos extends DefaultInternalAction { @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { try { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; LocalWorldModel model = arch . getModel ( ) ; if ( model == null ) return false ; int lx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) ; int ly = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ; int tx = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:2> ] ) . solve ( ) ; int ty = ( int ) ( ( NumberTerm ) args [ <NUM_LIT:3> ] ) . solve ( ) ; Location leaderPos = new Location ( lx , ly ) ; Location leaderTarget = new Location ( tx , ty ) ; Location agTarget = getScouterTarget ( model , leaderPos , leaderTarget ) ; if ( agTarget != null ) { return un . unifies ( args [ <NUM_LIT:4> ] , new NumberTermImpl ( agTarget . x ) ) && un . unifies ( args [ <NUM_LIT:5> ] , new NumberTermImpl ( agTarget . y ) ) ; } else { ts . getLogger ( ) . info ( "<STR_LIT>" ) ; } } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } public Location getScouterTarget ( LocalWorldModel model , Location leaderPos , Location leaderTarget ) throws Exception { Vec leader = new Vec ( model , leaderPos ) ; Vec target = new Vec ( model , leaderTarget ) . sub ( leader ) ; Vec me = new Vec ( model . agPerceptionRatio * <NUM_LIT:2> - <NUM_LIT:3> , <NUM_LIT:0> ) ; return model . nearFree ( herd_position . findFirstFreeLocTowardsTarget ( target , me , leader , true , model ) , null ) ; } } </s>
|
<s> package jia ; import java . util . Arrays ; import java . util . Comparator ; import java . util . List ; import java . util . logging . Logger ; import env . ClusterModelFactory ; import env . IClusterModel ; import busca . Nodo ; import arch . CowboyArch ; import arch . LocalWorldModel ; import jason . environment . grid . Location ; import jason . asSemantics . * ; import jason . asSyntax . * ; public class preferable_cluster extends DefaultInternalAction { private static final long serialVersionUID = - <NUM_LIT> ; LocalWorldModel model ; static Logger logger ; Search s ; CowboyArch arch ; int size ; IClusterModel ClModel ; int n = <NUM_LIT:20> ; @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] args ) throws Exception { arch = ( CowboyArch ) ts . getUserAgArch ( ) ; model = arch . getModel ( ) ; if ( ClModel == null ) ClModel = ClusterModelFactory . getModel ( ts . getUserAgArch ( ) . getAgName ( ) ) ; Location Gr = new Location ( ( int ) ( ( NumberTerm ) args [ <NUM_LIT:0> ] ) . solve ( ) , ( int ) ( ( NumberTerm ) args [ <NUM_LIT:1> ] ) . solve ( ) ) ; ListTerm pos = new ListTermImpl ( ) ; ListTerm sizs = new ListTermImpl ( ) ; if ( args . length == <NUM_LIT:5> ) { contCluster [ ] ClChosed = getClusterWith ( null , Gr ) ; if ( ClChosed . length > <NUM_LIT:0> ) { contCluster cCl = nearCorralCluster ( ClChosed ) ; Location loc = cCl . v . getLocation ( model ) ; pos . add ( ASSyntax . createStructure ( "<STR_LIT>" , ASSyntax . createNumber ( loc . x ) , ASSyntax . createNumber ( loc . y ) ) ) ; sizs . add ( ASSyntax . createNumber ( cCl . d ) ) ; } return un . unifies ( args [ <NUM_LIT:2> ] , pos ) & un . unifies ( args [ <NUM_LIT:3> ] , sizs ) & un . unifies ( args [ <NUM_LIT:4> ] , new NumberTermImpl ( <NUM_LIT:1> ) ) ; } else if ( args . length == <NUM_LIT:7> ) { if ( args [ <NUM_LIT:2> ] . isGround ( ) && args [ <NUM_LIT:3> ] . isGround ( ) ) { Location Cl = new Location ( ( int ) ( ( NumberTerm ) args [ <NUM_LIT:2> ] ) . solve ( ) , ( int ) ( ( NumberTerm ) args [ <NUM_LIT:3> ] ) . solve ( ) ) ; contCluster [ ] ClChosed = getClusterWith ( Cl , Gr ) ; for ( int i = <NUM_LIT:0> ; i < ClChosed . length ; i ++ ) { Location loc = ClChosed [ i ] . v . getLocation ( model ) ; pos . add ( ASSyntax . createStructure ( "<STR_LIT>" , ASSyntax . createNumber ( loc . x ) , ASSyntax . createNumber ( loc . y ) ) ) ; sizs . add ( ASSyntax . createNumber ( ClChosed [ i ] . d ) ) ; } return un . unifies ( args [ <NUM_LIT:4> ] , pos ) & un . unifies ( args [ <NUM_LIT:5> ] , sizs ) & un . unifies ( args [ <NUM_LIT:6> ] , new NumberTermImpl ( ClChosed . length ) ) ; } contCluster [ ] ClChosed = getClusterWith ( null , Gr ) ; for ( int i = <NUM_LIT:0> ; i < ClChosed . length ; i ++ ) { Location loc = ClChosed [ i ] . v . getLocation ( model ) ; pos . add ( ASSyntax . createStructure ( "<STR_LIT>" , ASSyntax . createNumber ( loc . x ) , ASSyntax . createNumber ( loc . y ) ) ) ; sizs . add ( ASSyntax . createNumber ( ClChosed [ i ] . d ) ) ; } return un . unifies ( args [ <NUM_LIT:4> ] , pos ) & un . unifies ( args [ <NUM_LIT:5> ] , sizs ) & un . unifies ( args [ <NUM_LIT:6> ] , new NumberTermImpl ( ClChosed . length ) ) ; } logger . warning ( "<STR_LIT>" ) ; return null ; } private contCluster nearCorralCluster ( contCluster [ ] ClChosed ) { contCluster cCl = ClChosed [ <NUM_LIT:0> ] ; Location loc = cCl . v . getLocation ( model ) ; int dist = loc . distance ( model . getCorral ( ) . center ( ) ) ; for ( int i = <NUM_LIT:1> ; i < ClChosed . length ; i ++ ) { loc = ClChosed [ i ] . v . getLocation ( model ) ; int newDist = loc . distance ( model . getCorral ( ) . center ( ) ) ; if ( newDist < dist ) { cCl = ClChosed [ i ] ; } } return cCl ; } private int getDistances ( Location Cl , Location Gr ) throws Exception { s = new Search ( model , Cl , model . getCorral ( ) . center ( ) , null , false , false , false , false , false , false , arch ) ; List < Nodo > path = Search . normalPath ( s . search ( ) ) ; int ClToCo = path . size ( ) ; s = new Search ( model , Gr , model . getCorral ( ) . center ( ) , null , false , false , false , false , false , false , arch ) ; path = Search . normalPath ( s . search ( ) ) ; int GrToCl = path . size ( ) ; return ClToCo + GrToCl ; } private contCluster [ ] getClusterWith ( Location befCl , Location Gr ) throws Exception { Vec [ ] Centers = ClModel . getCenters ( ) ; int [ ] NumberOfCows = ClModel . getNumCows ( ) ; int [ ] Radius = ClModel . getMaxDist ( ) ; int clo = - <NUM_LIT:1> ; if ( befCl != null ) { int d = <NUM_LIT:9> ; for ( int i = <NUM_LIT:0> ; i < Centers . length ; i ++ ) { if ( befCl . distanceChebyshev ( Centers [ i ] . getLocation ( model ) ) < d ) { d = befCl . distanceChebyshev ( Centers [ i ] . getLocation ( model ) ) ; clo = i ; } } } contCluster [ ] cC = new contCluster [ Centers . length ] ; for ( int i = <NUM_LIT:0> ; i < Centers . length ; i ++ ) { boolean clotemp ; if ( i == clo ) { clotemp = true ; } else { clotemp = false ; } Location Cl = Centers [ i ] . getLocation ( model ) ; int actdist = getDistances ( Cl , Gr ) ; cC [ i ] = new contCluster ( Centers [ i ] , actdist , NumberOfCows [ i ] , Radius [ i ] , clotemp ) ; } Arrays . sort ( cC ) ; return cC ; } private class contCluster implements Comparable < contCluster > { Vec v ; int n ; int r ; int d ; boolean clo ; public contCluster ( Vec v , int n , int r , int d , boolean clo ) { this . v = v ; this . n = n ; this . r = r ; this . d = d ; this . clo = clo ; } public int compareTo ( contCluster arg0 ) { contCluster c = ( contCluster ) arg0 ; if ( this . clo ) return - <NUM_LIT:1> ; if ( c . clo ) return <NUM_LIT:1> ; if ( this . n > n && c . n < n ) return - <NUM_LIT:1> ; if ( c . n > n && this . n < n ) return <NUM_LIT:1> ; if ( this . d < c . d ) return - <NUM_LIT:1> ; if ( this . d > c . d ) return <NUM_LIT:1> ; if ( this . r < c . r ) return - <NUM_LIT:1> ; if ( c . r < this . r ) return <NUM_LIT:1> ; return <NUM_LIT:0> ; } } } </s>
|
<s> package jia ; import jason . asSemantics . DefaultInternalAction ; import jason . asSemantics . TransitionSystem ; import jason . asSemantics . Unifier ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Term ; import jason . environment . grid . Location ; import java . util . logging . Level ; import arch . CowboyArch ; import env . WorldModel ; public class set_target extends DefaultInternalAction { Location oldTarget = null ; @ Override public Object execute ( TransitionSystem ts , Unifier un , Term [ ] terms ) throws Exception { try { CowboyArch arch = ( CowboyArch ) ts . getUserAgArch ( ) ; WorldModel model = arch . getModel ( ) ; if ( model == null ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" ) ; } else { if ( oldTarget != null && model . inGrid ( oldTarget ) ) { model . remove ( WorldModel . TARGET , oldTarget ) ; } NumberTerm x = ( NumberTerm ) terms [ <NUM_LIT:0> ] ; NumberTerm y = ( NumberTerm ) terms [ <NUM_LIT:1> ] ; Location t = new Location ( ( int ) x . solve ( ) , ( int ) y . solve ( ) ) ; if ( model . inGrid ( t ) ) { model . add ( WorldModel . TARGET , t ) ; oldTarget = t ; } } return true ; } catch ( Throwable e ) { ts . getLogger ( ) . log ( Level . SEVERE , "<STR_LIT>" + e , e ) ; } return false ; } } </s>
|
<s> package test ; import java . io . ByteArrayInputStream ; import java . io . ByteArrayOutputStream ; import java . io . IOException ; import java . io . InputStream ; import java . io . OutputStream ; import java . net . InetSocketAddress ; import java . net . Socket ; import java . text . SimpleDateFormat ; import java . util . Date ; import java . util . logging . Level ; import java . util . logging . Logger ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import javax . xml . transform . TransformerConfigurationException ; import javax . xml . transform . TransformerException ; import javax . xml . transform . TransformerFactory ; import javax . xml . transform . dom . DOMSource ; import javax . xml . transform . stream . StreamResult ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . Node ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXException ; public abstract class AbstractAgent { @ SuppressWarnings ( "<STR_LIT:serial>" ) private class SocketClosedException extends Exception { } private int networkport ; private String networkhost ; private InetSocketAddress socketaddress ; private Socket socket ; private InputStream inputstream ; private OutputStream outputstream ; protected String username ; private String password ; protected DocumentBuilderFactory documentbuilderfactory ; private TransformerFactory transformerfactory ; protected static Logger logger = Logger . getLogger ( "<STR_LIT>" ) ; public static String getDate ( ) { Date dt = new Date ( ) ; SimpleDateFormat df = new SimpleDateFormat ( "<STR_LIT>" ) ; return df . format ( dt ) ; } public AbstractAgent ( ) { networkhost = "<STR_LIT:localhost>" ; networkport = <NUM_LIT:0> ; socket = new Socket ( ) ; documentbuilderfactory = DocumentBuilderFactory . newInstance ( ) ; transformerfactory = TransformerFactory . newInstance ( ) ; } public String getHost ( ) { return networkhost ; } public void setHost ( String host ) { this . networkhost = host ; } public int getPort ( ) { return networkport ; } public void setPort ( int port ) { this . networkport = port ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } public String getPassword ( ) { return password ; } public void setPassword ( String password ) { this . password = password ; } public void start ( ) { new Thread ( ) { public void run ( ) { agentThread ( ) ; } } . start ( ) ; } public void sendAuthentication ( String username , String password ) throws IOException { try { Document doc = documentbuilderfactory . newDocumentBuilder ( ) . newDocument ( ) ; Element root = doc . createElement ( "<STR_LIT:message>" ) ; root . setAttribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ; doc . appendChild ( root ) ; Element auth = doc . createElement ( "<STR_LIT>" ) ; auth . setAttribute ( "<STR_LIT:username>" , username ) ; auth . setAttribute ( "<STR_LIT:password>" , password ) ; root . appendChild ( auth ) ; this . sendDocument ( doc ) ; } catch ( ParserConfigurationException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; } } public boolean receiveAuthenticationResult ( ) throws IOException { try { Document doc = receiveDocument ( ) ; Element root = doc . getDocumentElement ( ) ; if ( root == null ) return false ; if ( ! root . getAttribute ( "<STR_LIT:type>" ) . equalsIgnoreCase ( "<STR_LIT>" ) ) return false ; NodeList nl = root . getChildNodes ( ) ; Element authresult = null ; for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) == Element . ELEMENT_NODE && n . getNodeName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { authresult = ( Element ) n ; break ; } } if ( ! authresult . getAttribute ( "<STR_LIT:result>" ) . equalsIgnoreCase ( "<STR_LIT>" ) ) return false ; } catch ( SAXException e ) { e . printStackTrace ( ) ; return false ; } catch ( ParserConfigurationException e ) { e . printStackTrace ( ) ; return false ; } catch ( SocketClosedException e ) { e . printStackTrace ( ) ; return false ; } return true ; } public boolean doAuthentication ( String username , String password ) throws IOException { sendAuthentication ( username , password ) ; return receiveAuthenticationResult ( ) ; } public byte [ ] receivePacket ( ) throws IOException , SocketClosedException { ByteArrayOutputStream buffer = new ByteArrayOutputStream ( ) ; int read = inputstream . read ( ) ; while ( read != <NUM_LIT:0> ) { if ( read == - <NUM_LIT:1> ) { throw new SocketClosedException ( ) ; } buffer . write ( read ) ; read = inputstream . read ( ) ; } String s = "<STR_LIT>" + this . username + "<STR_LIT:n>" + buffer . toString ( ) ; synchronized ( logger ) { logger . log ( Level . ALL , s ) ; } return buffer . toByteArray ( ) ; } public Document receiveDocument ( ) throws SAXException , IOException , ParserConfigurationException , SocketClosedException { byte [ ] raw = receivePacket ( ) ; Document doc = documentbuilderfactory . newDocumentBuilder ( ) . parse ( new ByteArrayInputStream ( raw ) ) ; return doc ; } public void agentThread ( ) { try { socketaddress = new InetSocketAddress ( networkhost , networkport ) ; socket . connect ( socketaddress ) ; inputstream = socket . getInputStream ( ) ; outputstream = socket . getOutputStream ( ) ; boolean auth = doAuthentication ( username , password ) ; if ( ! auth ) { System . err . println ( "<STR_LIT>" ) ; return ; } processLogIn ( ) ; while ( true ) { Document doc = null ; try { doc = receiveDocument ( ) ; } catch ( SAXException e ) { e . printStackTrace ( ) ; } catch ( ParserConfigurationException e ) { e . printStackTrace ( ) ; } Element el_root = doc . getDocumentElement ( ) ; if ( el_root == null ) { System . err . println ( "<STR_LIT>" ) ; continue ; } if ( el_root . getNodeName ( ) . equals ( "<STR_LIT:message>" ) ) { if ( ! processMessage ( el_root ) ) break ; } else { System . err . println ( "<STR_LIT>" ) ; } } } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; return ; } catch ( SocketClosedException e ) { System . err . println ( "<STR_LIT>" ) ; } } @ SuppressWarnings ( "<STR_LIT>" ) public boolean processMessage ( Element el_message ) { String type = el_message . getAttribute ( "<STR_LIT:type>" ) ; if ( type . equals ( "<STR_LIT>" ) || type . equals ( "<STR_LIT>" ) || type . equals ( "<STR_LIT>" ) ) { Element el_perception = null ; NodeList nl = el_message . getChildNodes ( ) ; String infoelementname = "<STR_LIT>" ; if ( type . equals ( "<STR_LIT>" ) ) { infoelementname = "<STR_LIT>" ; } else if ( type . equals ( "<STR_LIT>" ) ) { infoelementname = "<STR_LIT>" ; } else if ( type . equals ( "<STR_LIT>" ) ) { infoelementname = "<STR_LIT>" ; } for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) == Element . ELEMENT_NODE && n . getNodeName ( ) . equalsIgnoreCase ( infoelementname ) ) { if ( el_perception == null ) el_perception = ( Element ) n ; else { System . err . println ( "<STR_LIT>" ) ; return true ; } } } Document doc = null ; try { doc = documentbuilderfactory . newDocumentBuilder ( ) . newDocument ( ) ; } catch ( ParserConfigurationException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; System . exit ( <NUM_LIT:1> ) ; } Element el_response = doc . createElement ( "<STR_LIT:message>" ) ; doc . appendChild ( el_response ) ; Element el_action = doc . createElement ( "<STR_LIT>" ) ; el_response . setAttribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ; el_response . appendChild ( el_action ) ; long currenttime = <NUM_LIT:0> ; try { currenttime = Long . parseLong ( el_message . getAttribute ( "<STR_LIT>" ) ) ; } catch ( NumberFormatException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; return true ; } long deadline = <NUM_LIT:0> ; if ( type . equals ( "<STR_LIT>" ) ) { try { deadline = Long . parseLong ( el_perception . getAttribute ( "<STR_LIT>" ) ) ; } catch ( NumberFormatException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; return true ; } processRequestAction ( el_perception , el_action , currenttime , deadline ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { processSimulationStart ( el_perception , currenttime ) ; } else if ( type . equals ( "<STR_LIT>" ) ) { processSimulationEnd ( el_perception , currenttime ) ; } el_action . setAttribute ( "<STR_LIT:id>" , el_perception . getAttribute ( "<STR_LIT:id>" ) ) ; try { if ( type . equals ( "<STR_LIT>" ) ) sendDocument ( doc ) ; } catch ( IOException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; System . exit ( <NUM_LIT:1> ) ; } } else if ( type . equals ( "<STR_LIT>" ) ) { NodeList nl = el_message . getChildNodes ( ) ; for ( int i = <NUM_LIT:0> ; i < nl . getLength ( ) ; i ++ ) { Node n = nl . item ( i ) ; if ( n . getNodeType ( ) == Element . ELEMENT_NODE && n . getNodeName ( ) . equalsIgnoreCase ( "<STR_LIT>" ) ) { processPong ( ( ( Element ) n ) . getAttribute ( "<STR_LIT:value>" ) ) ; return true ; } } } return true ; } public void processRequestAction ( Element perception , Element target , long currenttime , long deadline ) { System . err . println ( "<STR_LIT>" ) ; } public void processSimulationEnd ( Element perception , long currenttime ) { System . err . println ( "<STR_LIT>" ) ; } public void processSimulationStart ( Element perception , long currenttime ) { System . err . println ( "<STR_LIT>" ) ; } public void processPong ( String pong ) { System . err . println ( "<STR_LIT>" + pong + "<STR_LIT>" ) ; } public void processLogIn ( ) { System . err . println ( "<STR_LIT>" ) ; } public void sendDocument ( Document doc ) throws IOException { try { transformerfactory . newTransformer ( ) . transform ( new DOMSource ( doc ) , new StreamResult ( outputstream ) ) ; ByteArrayOutputStream temp = new ByteArrayOutputStream ( ) ; transformerfactory . newTransformer ( ) . transform ( new DOMSource ( doc ) , new StreamResult ( temp ) ) ; String s = "<STR_LIT>" + temp . toString ( ) ; logger . log ( Level . ALL , s ) ; outputstream . write ( <NUM_LIT:0> ) ; outputstream . flush ( ) ; } catch ( TransformerConfigurationException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; System . exit ( <NUM_LIT:1> ) ; } catch ( TransformerException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; System . exit ( <NUM_LIT:1> ) ; } } public void sendPing ( String ping ) throws IOException { Document doc = null ; try { doc = documentbuilderfactory . newDocumentBuilder ( ) . newDocument ( ) ; } catch ( ParserConfigurationException e ) { System . err . println ( "<STR_LIT>" ) ; e . printStackTrace ( ) ; System . exit ( <NUM_LIT:1> ) ; } Element root = doc . createElement ( "<STR_LIT:message>" ) ; doc . appendChild ( root ) ; root . setAttribute ( "<STR_LIT:type>" , "<STR_LIT>" ) ; Element payload = doc . createElement ( "<STR_LIT>" ) ; payload . setAttribute ( "<STR_LIT:value>" , ping ) ; root . appendChild ( payload ) ; sendDocument ( doc ) ; } } </s>
|
<s> package test ; import org . w3c . dom . Element ; public class DemoAgent extends AbstractAgent { public static void main ( String [ ] args ) { DemoAgent agent = new DemoAgent ( ) ; agent . setPort ( <NUM_LIT> ) ; agent . setHost ( "<STR_LIT:localhost>" ) ; agent . setUsername ( args [ <NUM_LIT:0> ] ) ; agent . setPassword ( args [ <NUM_LIT:1> ] ) ; agent . start ( ) ; } public void processLogIn ( ) { System . out . println ( "<STR_LIT>" ) ; new Thread ( ) { public void run ( ) { int i = <NUM_LIT:0> ; while ( true ) { try { sleep ( <NUM_LIT:1000> ) ; System . out . println ( "<STR_LIT>" + i ) ; sendPing ( "<STR_LIT:test>" + i ) ; i ++ ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } } ; } . start ( ) ; } public void processPong ( String pong ) { System . out . println ( "<STR_LIT>" + pong ) ; } public void processSimulationEnd ( Element perception , long currenttime ) { } public void processSimulationStart ( Element perception , long currenttime ) { System . out . println ( "<STR_LIT>" ) ; } public void processRequestAction ( Element perception , Element target , long currenttime , long deadline ) { System . out . println ( "<STR_LIT>" ) ; } } </s>
|
<s> package test ; import static org . junit . Assert . assertEquals ; import static org . junit . Assert . assertTrue ; import jason . environment . grid . Location ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import jia . Search ; import jia . Vec ; import jia . cluster ; import jia . herd_position ; import jia . other_side_fence ; import jia . scouter_pos ; import jia . herd_position . Formation ; import org . junit . Before ; import org . junit . Ignore ; import org . junit . Test ; import arch . LocalWorldModel ; import busca . Nodo ; import env . WorldModel ; public class TestBasicHerding { Vec cowboy ; LocalWorldModel model ; @ Before public void scenario ( ) { model = new LocalWorldModel ( <NUM_LIT> , <NUM_LIT> , WorldModel . agsByTeam , null ) ; model . setCorral ( new Location ( <NUM_LIT:0> , <NUM_LIT> ) , new Location ( <NUM_LIT:2> , <NUM_LIT> ) ) ; model . wall ( <NUM_LIT:7> , <NUM_LIT> , <NUM_LIT:7> , <NUM_LIT> ) ; } public void scenario1 ( ) { cowboy = new Vec ( <NUM_LIT:3> , <NUM_LIT:5> ) ; model . add ( WorldModel . AGENT , cowboy . getLocation ( model ) ) ; addCowsToModel ( new Vec ( <NUM_LIT:6> , <NUM_LIT:7> ) , new Vec ( <NUM_LIT:5> , <NUM_LIT:30> ) , new Vec ( <NUM_LIT:4> , <NUM_LIT:8> ) , new Vec ( <NUM_LIT:5> , <NUM_LIT:10> ) , new Vec ( <NUM_LIT:2> , <NUM_LIT:0> ) ) ; } public void scenario2 ( ) { cowboy = new Vec ( <NUM_LIT:11> , <NUM_LIT:3> ) ; model . add ( WorldModel . AGENT , cowboy . getLocation ( model ) ) ; addCowsToModel ( new Vec ( <NUM_LIT:8> , <NUM_LIT:0> ) , new Vec ( <NUM_LIT:9> , <NUM_LIT:0> ) , new Vec ( <NUM_LIT:10> , <NUM_LIT:0> ) , new Vec ( <NUM_LIT:8> , <NUM_LIT:1> ) , new Vec ( <NUM_LIT:9> , <NUM_LIT:1> ) , new Vec ( <NUM_LIT:10> , <NUM_LIT:1> ) , new Vec ( <NUM_LIT:8> , <NUM_LIT:2> ) , new Vec ( <NUM_LIT:9> , <NUM_LIT:2> ) , new Vec ( <NUM_LIT:10> , <NUM_LIT:2> ) ) ; } public void scenario3 ( ) { model = new LocalWorldModel ( <NUM_LIT> , <NUM_LIT> , WorldModel . agsByTeam , null ) ; model . setCorral ( new Location ( <NUM_LIT:8> , <NUM_LIT:0> ) , new Location ( <NUM_LIT:12> , <NUM_LIT:2> ) ) ; model . wall ( <NUM_LIT:7> , <NUM_LIT:0> , <NUM_LIT:7> , <NUM_LIT:2> ) ; cowboy = new Vec ( <NUM_LIT:10> , <NUM_LIT:12> ) ; model . add ( WorldModel . AGENT , cowboy . getLocation ( model ) ) ; addCowsToModel ( new Vec ( <NUM_LIT:1> , <NUM_LIT:16> ) , new Vec ( <NUM_LIT:2> , <NUM_LIT> ) , new Vec ( <NUM_LIT:3> , <NUM_LIT> ) , new Vec ( <NUM_LIT:5> , <NUM_LIT> ) , new Vec ( <NUM_LIT:6> , <NUM_LIT:12> ) , new Vec ( <NUM_LIT:6> , <NUM_LIT> ) , new Vec ( <NUM_LIT:20> , <NUM_LIT:2> ) , new Vec ( <NUM_LIT:20> , <NUM_LIT:3> ) , new Vec ( <NUM_LIT:20> , <NUM_LIT:4> ) ) ; } public void scenario4 ( ) { addFenceToModel ( new Vec ( <NUM_LIT> , <NUM_LIT:0> ) , new Vec ( <NUM_LIT> , <NUM_LIT:1> ) , new Vec ( <NUM_LIT> , <NUM_LIT:2> ) , new Vec ( <NUM_LIT> , <NUM_LIT:3> ) , new Vec ( <NUM_LIT> , <NUM_LIT:4> ) , new Vec ( <NUM_LIT> , <NUM_LIT:5> ) , new Vec ( <NUM_LIT> , <NUM_LIT:6> ) ) ; model . add ( WorldModel . SWITCH , <NUM_LIT> , <NUM_LIT> ) ; } @ Test public void bigCluster ( ) throws Exception { for ( int x = <NUM_LIT:10> ; x < <NUM_LIT:30> ; x ++ ) { for ( int y = <NUM_LIT:5> ; y < <NUM_LIT:20> ; y ++ ) { addCowsToModel ( new Vec ( model , x , y ) ) ; } } List < Location > cowsl = cluster . getCluster ( model , WorldModel . cowPerceptionRatio , null ) ; assertEquals ( cluster . MAXCLUSTERSIZE , cowsl . size ( ) ) ; } private void addCowsToModel ( Vec ... cows ) { for ( int i = <NUM_LIT:0> ; i < cows . length ; i ++ ) { Location l = cows [ i ] . getLocation ( model ) ; model . addKnownCow ( l . x , l . y ) ; } } private void addFenceToModel ( Vec ... fences ) { for ( int i = <NUM_LIT:0> ; i < fences . length ; i ++ ) { Location l = fences [ i ] . getLocation ( model ) ; model . add ( WorldModel . CLOSED_FENCE , l . x , l . y ) ; } } @ Test public void testVec ( ) { scenario1 ( ) ; assertEquals ( new Location ( <NUM_LIT:3> , <NUM_LIT> ) , cowboy . getLocation ( model ) ) ; assertEquals ( new Location ( <NUM_LIT:1> , <NUM_LIT> ) , model . getCorral ( ) . center ( ) ) ; assertEquals ( new Vec ( <NUM_LIT:3> , <NUM_LIT:2> ) , new Vec ( <NUM_LIT:6> , <NUM_LIT:7> ) . sub ( cowboy ) ) ; Vec v = new Vec ( <NUM_LIT:3> , <NUM_LIT:2> ) ; assertEquals ( v , v . newAngle ( v . angle ( ) ) ) ; } @ Test public void testOtherSideFence ( ) throws Exception { scenario4 ( ) ; assertTrue ( model . hasObject ( WorldModel . FENCE , new Vec ( <NUM_LIT> , <NUM_LIT:2> ) . getLocation ( model ) ) ) ; Vec start = new Vec ( model , <NUM_LIT:15> , <NUM_LIT> ) ; Vec fence = new Vec ( model , <NUM_LIT> , <NUM_LIT> ) ; Vec target = new other_side_fence ( ) . computesOtherSide ( model , start , fence ) ; assertEquals ( new Location ( <NUM_LIT> , <NUM_LIT> ) , target . getLocation ( model ) ) ; start = new Vec ( model , <NUM_LIT:10> , <NUM_LIT> ) ; fence = new Vec ( model , <NUM_LIT> , <NUM_LIT> ) ; target = new other_side_fence ( ) . computesOtherSide ( model , start , fence ) ; assertEquals ( new Location ( <NUM_LIT> , <NUM_LIT> ) , target . getLocation ( model ) ) ; start = new Vec ( model , <NUM_LIT> , <NUM_LIT> ) ; fence = new Vec ( model , <NUM_LIT> , <NUM_LIT> ) ; target = new other_side_fence ( ) . computesOtherSide ( model , start , fence ) ; assertEquals ( new Location ( <NUM_LIT> , <NUM_LIT> ) , target . getLocation ( model ) ) ; } @ Test public void testVecSort ( ) { scenario1 ( ) ; List < Vec > cowsl = new ArrayList < Vec > ( model . getKnownCows ( ) ) ; Collections . sort ( cowsl ) ; assertEquals ( new Vec ( <NUM_LIT:2> , <NUM_LIT:0> ) , cowsl . get ( <NUM_LIT:0> ) ) ; assertEquals ( new Vec ( <NUM_LIT:4> , <NUM_LIT:8> ) , cowsl . get ( <NUM_LIT:1> ) ) ; assertEquals ( new Vec ( <NUM_LIT:6> , <NUM_LIT:7> ) , cowsl . get ( <NUM_LIT:2> ) ) ; assertEquals ( new Vec ( <NUM_LIT:5> , <NUM_LIT:10> ) , cowsl . get ( <NUM_LIT:3> ) ) ; assertEquals ( new Vec ( <NUM_LIT:5> , <NUM_LIT:30> ) , cowsl . get ( <NUM_LIT:4> ) ) ; } @ Test public void testCowsRepMat ( ) throws Exception { scenario1 ( ) ; assertEquals ( <NUM_LIT:2> , model . getCowsRep ( <NUM_LIT:5> , <NUM_LIT> ) ) ; assertEquals ( <NUM_LIT:1> , model . getCowsRep ( <NUM_LIT:5> , <NUM_LIT> ) ) ; assertEquals ( <NUM_LIT:0> , model . getCowsRep ( <NUM_LIT:5> , <NUM_LIT> ) ) ; assertEquals ( <NUM_LIT:5> , model . getCowsRep ( <NUM_LIT:5> , <NUM_LIT> ) ) ; } @ Test public void testAgsRepMat ( ) throws Exception { scenario1 ( ) ; model . add ( WorldModel . ENEMY , <NUM_LIT:4> , <NUM_LIT> ) ; model . remove ( WorldModel . ENEMY , <NUM_LIT:4> , <NUM_LIT> ) ; assertEquals ( <NUM_LIT:2> , model . getObsRep ( <NUM_LIT:6> , <NUM_LIT> ) ) ; assertEquals ( <NUM_LIT:1> , model . getObsRep ( <NUM_LIT:7> , <NUM_LIT> ) ) ; assertEquals ( <NUM_LIT:0> , model . getObsRep ( <NUM_LIT:5> , <NUM_LIT> ) ) ; } @ Test public void testAStar1 ( ) throws Exception { scenario1 ( ) ; Search s = new Search ( model , cowboy . getLocation ( model ) , new Location ( <NUM_LIT:8> , <NUM_LIT> ) , null , true , true , true , false , false , false , null ) ; Nodo path = s . search ( ) ; assertEquals ( <NUM_LIT> , Search . normalPath ( path ) . size ( ) ) ; } @ Test public void testAStar2 ( ) throws Exception { scenario1 ( ) ; model . add ( WorldModel . CLOSED_FENCE , <NUM_LIT:0> , <NUM_LIT> ) ; model . add ( WorldModel . CLOSED_FENCE , <NUM_LIT:1> , <NUM_LIT> ) ; model . add ( WorldModel . CLOSED_FENCE , <NUM_LIT:2> , <NUM_LIT> ) ; model . add ( WorldModel . CLOSED_FENCE , <NUM_LIT:3> , <NUM_LIT> ) ; model . add ( WorldModel . CLOSED_FENCE , <NUM_LIT:4> , <NUM_LIT> ) ; Search s = new Search ( model , cowboy . getLocation ( model ) , new Location ( <NUM_LIT:8> , <NUM_LIT> ) , null , true , true , true , false , false , true , null ) ; Nodo path = s . search ( ) ; assertEquals ( <NUM_LIT:11> , Search . normalPath ( path ) . size ( ) ) ; s = new Search ( model , cowboy . getLocation ( model ) , new Location ( <NUM_LIT:8> , <NUM_LIT> ) , null , true , true , true , false , false , false , null ) ; path = s . search ( ) ; assertEquals ( <NUM_LIT:11> , Search . normalPath ( path ) . size ( ) ) ; } @ Test public void testAStarPathInEnemyCorral ( ) throws Exception { scenario3 ( ) ; model . add ( WorldModel . ENEMYCORRAL , <NUM_LIT:10> , <NUM_LIT:7> ) ; model . add ( WorldModel . ENEMYCORRAL , <NUM_LIT:11> , <NUM_LIT:7> ) ; model . add ( WorldModel . ENEMYCORRAL , <NUM_LIT:12> , <NUM_LIT:7> ) ; Search s = new Search ( model , new Location ( <NUM_LIT:12> , <NUM_LIT:12> ) , new Location ( <NUM_LIT:10> , <NUM_LIT:1> ) , null , true , false , true , false , true , false , null ) ; Nodo path = s . search ( ) ; assertTrue ( Search . normalPath ( path ) . size ( ) > <NUM_LIT:10> ) ; } @ Test public void moveCows2 ( ) throws Exception { scenario1 ( ) ; List < Location > clusterLocs = cluster . getCluster ( model , WorldModel . cowPerceptionRatio , null ) ; List < Vec > cowsl = cluster . location2vec ( model , clusterLocs ) ; assertEquals ( <NUM_LIT:3> , cowsl . size ( ) ) ; Vec mean = Vec . mean ( cowsl ) ; assertEquals ( new Vec ( <NUM_LIT:5> , <NUM_LIT:8> ) , mean ) ; int stepsFromCenter = ( int ) Math . round ( Vec . max ( cowsl ) . sub ( mean ) . magnitude ( ) ) + <NUM_LIT:1> ; assertEquals ( <NUM_LIT:3> , stepsFromCenter ) ; herd_position hp = new herd_position ( ) ; hp . setModel ( model ) ; Location byIA = hp . getAgTarget ( clusterLocs , Formation . one , cowboy . getLocation ( model ) ) ; assertEquals ( new Location ( <NUM_LIT:6> , <NUM_LIT> ) , byIA ) ; assertEquals ( "<STR_LIT>" , hp . formationPlaces ( clusterLocs , Formation . five ) . toString ( ) ) ; byIA = hp . getAgTarget ( clusterLocs , Formation . six , cowboy . getLocation ( model ) ) ; assertEquals ( new Location ( <NUM_LIT:8> , <NUM_LIT> ) , byIA ) ; assertEquals ( "<STR_LIT>" , hp . formationPlaces ( clusterLocs , Formation . six ) . toString ( ) ) ; } @ Test public void moveCows3 ( ) throws Exception { scenario2 ( ) ; model . add ( WorldModel . ENEMY , <NUM_LIT:11> , <NUM_LIT> ) ; List < Location > clusterLocs = cluster . getCluster ( model , WorldModel . cowPerceptionRatio , null ) ; List < Vec > cowsl = cluster . location2vec ( model , clusterLocs ) ; assertEquals ( <NUM_LIT:9> , cowsl . size ( ) ) ; herd_position hp = new herd_position ( ) ; hp . setModel ( model ) ; Location byIA = hp . getAgTarget ( clusterLocs , Formation . one , cowboy . getLocation ( model ) ) ; assertEquals ( new Location ( <NUM_LIT:11> , <NUM_LIT> ) , byIA ) ; List < Location > form = hp . formationPlaces ( clusterLocs , Formation . four ) ; assertTrue ( form . contains ( new Location ( <NUM_LIT:11> , <NUM_LIT> ) ) ) ; assertTrue ( form . contains ( new Location ( <NUM_LIT:6> , <NUM_LIT> ) ) ) ; } @ Test @ Ignore public void formationSc3 ( ) throws Exception { scenario3 ( ) ; List < Location > clusterLocs = cluster . getCluster ( model , WorldModel . cowPerceptionRatio , null ) ; assertEquals ( <NUM_LIT:6> , clusterLocs . size ( ) ) ; herd_position hp = new herd_position ( ) ; hp . setModel ( model ) ; List < Location > form = hp . formationPlaces ( clusterLocs , Formation . four ) ; assertTrue ( form . contains ( new Location ( <NUM_LIT:0> , <NUM_LIT:4> ) ) || form . contains ( new Location ( <NUM_LIT:0> , <NUM_LIT:3> ) ) ) ; assertTrue ( form . contains ( new Location ( <NUM_LIT:0> , <NUM_LIT:8> ) ) ) ; assertTrue ( form . contains ( new Location ( <NUM_LIT:0> , <NUM_LIT:1> ) ) || form . contains ( new Location ( <NUM_LIT:0> , <NUM_LIT:0> ) ) ) ; assertTrue ( form . contains ( new Location ( <NUM_LIT:4> , <NUM_LIT:11> ) ) ) ; } @ Test public void scouterPos ( ) throws Exception { scenario1 ( ) ; Location byIA = new scouter_pos ( ) . getScouterTarget ( model , new Location ( <NUM_LIT:2> , <NUM_LIT> ) , new Location ( <NUM_LIT:5> , <NUM_LIT> ) ) ; assertEquals ( new Location ( <NUM_LIT:6> , <NUM_LIT> ) , byIA ) ; byIA = new scouter_pos ( ) . getScouterTarget ( model , new Location ( <NUM_LIT:9> , <NUM_LIT> ) , new Location ( <NUM_LIT:9> , <NUM_LIT> ) ) ; assertEquals ( new Location ( <NUM_LIT> , <NUM_LIT> ) , byIA ) ; } } </s>
|
<s> package test ; import static org . junit . Assert . assertFalse ; import static org . junit . Assert . assertTrue ; import jason . environment . grid . Location ; import org . junit . Before ; import org . junit . Test ; import arch . LocalWorldModel ; import env . WorldModel ; public class TestWorldModel { LocalWorldModel model ; @ Before public void scenario ( ) { model = new LocalWorldModel ( <NUM_LIT> , <NUM_LIT> , WorldModel . agsByTeam , null ) ; } @ Test public void testIsFree ( ) { Location l = new Location ( <NUM_LIT:10> , <NUM_LIT:10> ) ; assertTrue ( model . isFree ( l ) ) ; model . add ( WorldModel . OBSTACLE , l ) ; assertFalse ( model . isFree ( l ) ) ; model . add ( WorldModel . ENEMYCORRAL , l ) ; assertFalse ( model . isFree ( l ) ) ; l = new Location ( <NUM_LIT:10> , <NUM_LIT:11> ) ; assertTrue ( model . isFree ( l ) ) ; model . add ( WorldModel . ENEMYCORRAL , l ) ; assertTrue ( model . hasObject ( WorldModel . ENEMYCORRAL , l ) ) ; assertFalse ( model . isFree ( l ) ) ; model . add ( WorldModel . OBSTACLE , l ) ; assertFalse ( model . isFree ( l ) ) ; assertTrue ( model . hasObject ( WorldModel . OBSTACLE , l ) ) ; assertTrue ( model . hasObject ( WorldModel . ENEMYCORRAL , l ) ) ; } } </s>
|
<s> package test ; import static org . junit . Assert . assertEquals ; import jason . asSyntax . Literal ; import org . junit . Test ; import agent . UniqueBelsBB ; public class TestUniqueBB { @ Test public void removeOldBB ( ) { UniqueBelsBB bb = new UniqueBelsBB ( ) ; bb . add ( Literal . parseLiteral ( "<STR_LIT>" ) ) ; bb . add ( Literal . parseLiteral ( "<STR_LIT>" ) ) ; bb . add ( Literal . parseLiteral ( "<STR_LIT>" ) ) ; bb . remove_old_bels ( Literal . parseLiteral ( "<STR_LIT>" ) , "<STR_LIT>" , <NUM_LIT:4> , <NUM_LIT:11> ) ; assertEquals ( <NUM_LIT:2> , bb . size ( ) ) ; bb . remove_old_bels ( Literal . parseLiteral ( "<STR_LIT>" ) , "<STR_LIT>" , <NUM_LIT:4> , <NUM_LIT:12> ) ; bb . remove_old_bels ( Literal . parseLiteral ( "<STR_LIT>" ) , "<STR_LIT>" , <NUM_LIT:4> , <NUM_LIT:15> ) ; assertEquals ( <NUM_LIT:1> , bb . size ( ) ) ; } } </s>
|
<s> package test ; import jason . util . asl2html ; import java . awt . BorderLayout ; import java . awt . Dimension ; import java . awt . FlowLayout ; import java . awt . Toolkit ; import java . awt . event . ActionEvent ; import java . awt . event . ActionListener ; import java . io . File ; import javax . swing . BorderFactory ; import javax . swing . JButton ; import javax . swing . JFrame ; import javax . swing . JPanel ; import javax . swing . JScrollPane ; import javax . swing . JSlider ; import javax . swing . JTextPane ; import javax . swing . SwingUtilities ; import javax . swing . border . TitledBorder ; import javax . swing . event . ChangeEvent ; import javax . swing . event . ChangeListener ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import javax . xml . parsers . ParserConfigurationException ; import org . w3c . dom . Document ; public class MindView { public static void main ( String [ ] args ) throws Exception { new MindView ( Integer . parseInt ( args [ <NUM_LIT:0> ] ) ) ; } private int step = <NUM_LIT:1> ; private asl2html agTransformerHtml = new asl2html ( "<STR_LIT>" ) ; private DocumentBuilder builder ; public MindView ( int step ) throws ParserConfigurationException { this . step = step ; builder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; initComponents ( ) ; show ( ) ; } JTextPane jTA = null ; JFrame frame ; JSlider jHistory = null ; void initComponents ( ) { frame = new JFrame ( ) ; jTA = new JTextPane ( ) ; jTA . setEditable ( false ) ; jTA . setContentType ( "<STR_LIT:text/html>" ) ; jTA . setAutoscrolls ( false ) ; JPanel spTA = new JPanel ( new BorderLayout ( ) ) ; spTA . add ( BorderLayout . CENTER , new JScrollPane ( jTA ) ) ; spTA . setBorder ( BorderFactory . createTitledBorder ( BorderFactory . createEtchedBorder ( ) , "<STR_LIT>" , TitledBorder . LEFT , TitledBorder . TOP ) ) ; JPanel pAg = new JPanel ( new BorderLayout ( ) ) ; pAg . add ( BorderLayout . CENTER , spTA ) ; JButton jBtNext = new JButton ( "<STR_LIT>" ) ; jBtNext . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { step ++ ; show ( ) ; } } ) ; } } ) ; JButton jBtPrev = new JButton ( "<STR_LIT>" ) ; jBtPrev . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { step -- ; show ( ) ; } } ) ; } } ) ; JPanel pButtons = new JPanel ( new FlowLayout ( FlowLayout . CENTER ) ) ; pButtons . add ( jBtPrev ) ; pButtons . add ( jBtNext ) ; JPanel pHistory = new JPanel ( new BorderLayout ( ) ) ; pHistory . setBorder ( BorderFactory . createTitledBorder ( BorderFactory . createEtchedBorder ( ) , "<STR_LIT>" , TitledBorder . LEFT , TitledBorder . TOP ) ) ; jHistory = new JSlider ( ) ; jHistory . setMaximum ( <NUM_LIT:1> ) ; jHistory . setMinimum ( <NUM_LIT:0> ) ; jHistory . setValue ( <NUM_LIT:0> ) ; jHistory . setPaintTicks ( true ) ; jHistory . setPaintLabels ( true ) ; jHistory . setMajorTickSpacing ( <NUM_LIT:10> ) ; jHistory . setMinorTickSpacing ( <NUM_LIT:1> ) ; setupSlider ( ) ; jHistory . addChangeListener ( new ChangeListener ( ) { public void stateChanged ( ChangeEvent e ) { step = ( int ) jHistory . getValue ( ) ; show ( ) ; } } ) ; pHistory . add ( BorderLayout . CENTER , jHistory ) ; pHistory . add ( BorderLayout . EAST , pButtons ) ; frame . getContentPane ( ) . add ( BorderLayout . SOUTH , pHistory ) ; frame . getContentPane ( ) . add ( BorderLayout . CENTER , pAg ) ; frame . pack ( ) ; Dimension screenSize = Toolkit . getDefaultToolkit ( ) . getScreenSize ( ) ; int height = ( int ) ( screenSize . height * <NUM_LIT> ) ; frame . setBounds ( <NUM_LIT> , <NUM_LIT:30> , ( int ) ( height * <NUM_LIT> ) , height ) ; frame . setVisible ( true ) ; } private void show ( ) { try { frame . setTitle ( "<STR_LIT>" + step + "<STR_LIT>" ) ; Document agState = builder . parse ( "<STR_LIT>" + step + "<STR_LIT>" ) ; jTA . setText ( agTransformerHtml . transform ( agState ) ) ; jHistory . setValue ( step ) ; } catch ( Exception et ) { et . printStackTrace ( ) ; } } private void setupSlider ( ) { int first = - <NUM_LIT:1> ; int size = <NUM_LIT:0> ; for ( String f : new File ( "<STR_LIT>" ) . list ( ) ) { if ( f . endsWith ( "<STR_LIT>" ) ) { f = f . substring ( <NUM_LIT:0> , f . length ( ) - <NUM_LIT:4> ) ; try { int n = Integer . parseInt ( f ) ; if ( first < <NUM_LIT:0> ) first = n ; if ( n > size ) size = n ; } catch ( Exception e ) { } } } step = first ; jHistory . setMinimum ( first ) ; jHistory . setMaximum ( size ) ; jHistory . setValue ( step ) ; } } </s>
|
<s> package runtime ; import java . util . logging . Logger ; import env . ClusterModelFactory ; import env . CowModel ; import env . CowModelFactory ; import alice . cartago . * ; import alice . cartago . tools . * ; import alice . cartago . security . * ; public class StartCartago { private static int port = <NUM_LIT> ; private static String end = "<STR_LIT>" ; private static String wpsName1 = "<STR_LIT>" ; private static String wpsName2 = "<STR_LIT>" ; private static String cartagoRole = "<STR_LIT>" ; private static String artName1 = "<STR_LIT>" ; private static String artName2 = "<STR_LIT>" ; private static String artClass1 = "<STR_LIT>" ; private static String artClass2 = "<STR_LIT>" ; private static Logger logger = Logger . getLogger ( CowModel . class . getName ( ) ) ; public static void main ( String [ ] args ) throws Exception { UserCredential crcred = new UserIdCredential ( cartagoRole ) ; CartagoService . installNode ( port ) ; ICartagoContext ctx = CartagoService . joinWorkspace ( "<STR_LIT:default>" , end , cartagoRole , crcred ) ; ctx . createWorkspace ( wpsName1 ) ; ctx . createWorkspace ( wpsName2 ) ; ICartagoContext cModel = ctx . joinWorkspace ( wpsName1 , end , cartagoRole , crcred ) ; ICartagoContext clModel = ctx . joinWorkspace ( wpsName2 , end , cartagoRole , crcred ) ; if ( ! CowModelFactory . centralized ) cModel . makeArtifact ( artName1 , artClass1 , ArtifactConfig . DEFAULT_CONFIG , - <NUM_LIT:1> ) ; if ( ! ClusterModelFactory . centralized ) clModel . makeArtifact ( artName2 , artClass2 , ArtifactConfig . DEFAULT_CONFIG , - <NUM_LIT:1> ) ; } } </s>
|
<s> package agent ; import jason . asSemantics . Agent ; import jason . asSyntax . ASSyntax ; import jason . asSyntax . InternalActionLiteral ; import jason . asSyntax . Literal ; import jason . asSyntax . Plan ; import jason . asSyntax . PlanBody ; import jason . asSyntax . PlanBodyImpl ; import jason . asSyntax . Pred ; import jason . asSyntax . directives . Directive ; import java . util . logging . Level ; import java . util . logging . Logger ; public class OrgMaintenanceGoal implements Directive { static Logger logger = Logger . getLogger ( OrgMaintenanceGoal . class . getName ( ) ) ; public Agent process ( Pred directive , Agent outerContent , Agent innerContent ) { try { Agent newAg = new Agent ( ) ; newAg . initAg ( ) ; PlanBodyImpl endofplan = null ; Literal goal = null ; for ( Plan p : innerContent . getPL ( ) ) { InternalActionLiteral wait = new InternalActionLiteral ( "<STR_LIT>" ) ; wait . addTerm ( directive . getTerm ( <NUM_LIT:0> ) ) ; endofplan = new PlanBodyImpl ( PlanBody . BodyType . internalAction , wait ) ; goal = p . getTrigger ( ) . getLiteral ( ) . copy ( ) ; endofplan . add ( new PlanBodyImpl ( PlanBody . BodyType . achieveNF , goal ) ) ; p . getBody ( ) . add ( endofplan ) ; newAg . getPL ( ) . add ( p , false ) ; } goal = goal . copy ( ) ; goal . addAnnot ( ASSyntax . parseStructure ( "<STR_LIT>" ) ) ; goal . addAnnot ( ASSyntax . parseStructure ( "<STR_LIT>" ) ) ; String sp = "<STR_LIT>" + goal + "<STR_LIT>" + "<STR_LIT>" + goal . getFunctor ( ) + "<STR_LIT>" + "<STR_LIT>" + endofplan + "<STR_LIT:.>" ; Plan p = ASSyntax . parsePlan ( sp ) ; newAg . getPL ( ) . add ( p ) ; return newAg ; } catch ( Exception e ) { logger . log ( Level . SEVERE , "<STR_LIT>" , e ) ; } return null ; } } </s>
|
<s> package agent ; import jason . asSemantics . Agent ; import jason . asSemantics . Event ; import jason . asSemantics . Unifier ; import jason . asSyntax . Literal ; import jason . asSyntax . Trigger ; import java . util . Iterator ; import java . util . List ; import java . util . Queue ; public class SelectEvent extends Agent { private Trigger cow = Trigger . parseTrigger ( "<STR_LIT>" ) ; private Trigger eos = Trigger . parseTrigger ( "<STR_LIT>" ) ; private Unifier un = new Unifier ( ) ; private boolean cleanCows = false ; public Event selectEvent ( Queue < Event > events ) { Iterator < Event > ie = events . iterator ( ) ; while ( ie . hasNext ( ) ) { un . clear ( ) ; Event e = ie . next ( ) ; if ( un . unifies ( eos , e . getTrigger ( ) ) ) { ie . remove ( ) ; return e ; } } return super . selectEvent ( events ) ; } public void cleanCows ( ) { cleanCows = true ; } @ Override public void buf ( List < Literal > percepts ) { super . buf ( percepts ) ; } } </s>
|
<s> package agent ; import jason . asSemantics . Agent ; import jason . asSyntax . Literal ; import jason . bb . DefaultBeliefBase ; import java . util . HashSet ; import java . util . Set ; public class DiscardBelsBB extends DefaultBeliefBase { Set < String > discartedBels = new HashSet < String > ( ) ; public void init ( Agent ag , String [ ] args ) { for ( int i = <NUM_LIT:0> ; i < args . length ; i ++ ) { discartedBels . add ( args [ i ] ) ; } } @ Override public boolean add ( Literal bel ) { if ( ! discartedBels . contains ( bel . getFunctor ( ) ) ) { return super . add ( bel ) ; } else { return false ; } } } </s>
|
<s> package agent ; import jason . asSemantics . Agent ; import jason . asSemantics . Unifier ; import jason . asSyntax . Literal ; import jason . asSyntax . NumberTerm ; import jason . asSyntax . Structure ; import jason . asSyntax . Term ; import jason . bb . DefaultBeliefBase ; import java . util . ArrayList ; import java . util . HashMap ; import java . util . Iterator ; import java . util . List ; import java . util . Map ; public class UniqueBelsBB extends DefaultBeliefBase { Map < String , Literal > uniqueBels = new HashMap < String , Literal > ( ) ; Unifier u = new Unifier ( ) ; Agent myAgent ; public void init ( Agent ag , String [ ] args ) { this . myAgent = ag ; for ( int i = <NUM_LIT:0> ; i < args . length ; i ++ ) { Literal arg = Literal . parseLiteral ( args [ i ] ) ; uniqueBels . put ( arg . getFunctor ( ) , arg ) ; } } @ Override public boolean add ( Literal bel ) { Literal kb = uniqueBels . get ( bel . getFunctor ( ) ) ; if ( kb != null && kb . getArity ( ) == bel . getArity ( ) ) { u . clear ( ) ; Literal linbb = null ; boolean remove = false ; Iterator < Literal > relevant = getCandidateBeliefs ( bel , null ) ; if ( relevant != null ) { final int kbArity = kb . getArity ( ) ; while ( relevant . hasNext ( ) && ! remove ) { linbb = relevant . next ( ) ; boolean equals = true ; for ( int i = <NUM_LIT:0> ; i < kbArity ; i ++ ) { Term kbt = kb . getTerm ( i ) ; if ( ! kbt . isVar ( ) ) { if ( ! u . unifies ( bel . getTerm ( i ) , linbb . getTerm ( i ) ) ) { equals = false ; break ; } } } if ( equals ) { remove = true ; } } } if ( remove ) { remove ( linbb ) ; } } return super . add ( bel ) ; } public void remove_old_bels ( Literal bel , String timeAnnot , int maxAge , int curAge ) { Iterator < Literal > relevant = getCandidateBeliefs ( bel , null ) ; if ( relevant != null ) { List < Literal > toDel = new ArrayList < Literal > ( ) ; while ( relevant . hasNext ( ) ) { Literal linbb = relevant . next ( ) ; Structure bTime = null ; if ( linbb . hasAnnot ( ) ) { for ( Term t : linbb . getAnnots ( ) ) { if ( t . isStructure ( ) ) { Structure s = ( Structure ) t ; if ( s . getFunctor ( ) . equals ( timeAnnot ) ) { if ( bTime == null ) { bTime = s ; } else if ( bTime . compareTo ( s ) < <NUM_LIT:0> ) { linbb . delAnnot ( bTime ) ; bTime = s ; } } } } if ( bTime != null ) { int age = ( int ) ( ( NumberTerm ) bTime . getTerm ( <NUM_LIT:0> ) ) . solve ( ) ; if ( curAge - age > maxAge ) toDel . add ( linbb ) ; } } } for ( Literal l : toDel ) { myAgent . getLogger ( ) . info ( "<STR_LIT>" + l + "<STR_LIT>" + curAge + "<STR_LIT:)>" ) ; remove ( l ) ; } } } } </s>
|
<s> package env ; import java . util . logging . Logger ; import java . util . HashMap ; import java . util . Map ; import java . util . Iterator ; import java . util . Collections ; public class CowModel implements ICowModel { private Map < Integer , Cow > cows = Collections . synchronizedMap ( new HashMap < Integer , Cow > ( ) ) ; private int [ ] [ ] grid ; private int gH = - <NUM_LIT:1> , gW = - <NUM_LIT:1> ; private Logger logger = Logger . getLogger ( CowModel . class . getName ( ) ) ; private int nop = <NUM_LIT:0> ; public CowModel ( ) { } public synchronized void reset ( ) { cows . clear ( ) ; gH = gW = - <NUM_LIT:1> ; logger . info ( "<STR_LIT>" ) ; } public synchronized void setSize ( int w , int h ) { if ( w == gW && h == gH ) return ; reset ( ) ; gW = w ; gH = h ; grid = new int [ w + <NUM_LIT:1> ] [ h + <NUM_LIT:1> ] ; for ( int i = <NUM_LIT:0> ; i <= w ; i ++ ) for ( int j = <NUM_LIT:0> ; j <= h ; j ++ ) grid [ i ] [ j ] = - <NUM_LIT:1> ; logger . info ( "<STR_LIT>" + gW + "<STR_LIT:U+002CU+0020>" + gH ) ; } public void freePos ( int x , int y ) { synchronized ( cows ) { if ( grid [ x ] [ y ] < <NUM_LIT:0> ) return ; cows . remove ( grid [ x ] [ y ] ) ; grid [ x ] [ y ] = - <NUM_LIT:1> ; } } public void insertCow ( int id , int x , int y , int step ) { synchronized ( cows ) { freePos ( x , y ) ; Cow toRem = cows . get ( id ) ; if ( toRem != null ) { freePos ( toRem . x , toRem . y ) ; } cows . put ( id , new Cow ( id , x , y , step ) ) ; grid [ x ] [ y ] = id ; } } public boolean checkState ( ) { String str = new String ( ) ; int [ ] [ ] mapa = new int [ gW + <NUM_LIT:1> ] [ gH + <NUM_LIT:1> ] ; nop = <NUM_LIT:0> ; for ( int x = <NUM_LIT:0> ; x <= gW ; ++ x ) for ( int y = <NUM_LIT:0> ; y <= gH ; ++ y ) mapa [ x ] [ y ] = - <NUM_LIT:1> ; synchronized ( cows ) { Iterator it = cows . keySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { Cow cw = cows . get ( it . next ( ) ) ; if ( mapa [ cw . x ] [ cw . y ] >= <NUM_LIT:0> ) return false ; mapa [ cw . x ] [ cw . y ] = cw . id ; } for ( int x = <NUM_LIT:0> ; x <= gW ; x ++ ) for ( int y = <NUM_LIT:0> ; y <= gH ; y ++ ) if ( mapa [ x ] [ y ] != grid [ x ] [ y ] ) { logger . info ( "<STR_LIT>" + x + "<STR_LIT:U+002C>" + y + "<STR_LIT>" + mapa [ x ] [ y ] + "<STR_LIT:U+0020>" + grid [ x ] [ y ] + "<STR_LIT>" ) ; return false ; } } return true ; } public Cow [ ] getCows ( ) { Cow [ ] a = new Cow [ cows . size ( ) ] ; return ( Cow [ ] ) ( cows . values ( ) ) . toArray ( a ) ; } public void updateCows ( ) { } public int getSizeh ( ) { return gH ; } public int getSizew ( ) { return gW ; } } </s>
|
<s> package env ; import java . lang . String ; public class CowModelFactory { static private ICowModel cModel ; static public boolean centralized = true ; private static String end = "<STR_LIT>" ; private static String wpsName = "<STR_LIT>" ; private static String cartagoRole = "<STR_LIT>" ; private static String artName = "<STR_LIT>" ; public static ICowModel getModel ( String agName ) { if ( centralized ) { synchronized ( CowModelFactory . class ) { if ( cModel == null ) return cModel = new CowModel ( ) ; else return cModel ; } } else { try { Thread . sleep ( <NUM_LIT:3> ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return new CCowModel ( end , wpsName , cartagoRole , artName , agName + "<STR_LIT>" + System . currentTimeMillis ( ) ) ; } } } </s>
|
<s> package env ; public class configTable extends javax . swing . JFrame { IClusterModel clModel ; public configTable ( ) { super ( "<STR_LIT>" ) ; clModel = ClusterModelFactory . getModel ( "<STR_LIT>" ) ; initComponents ( ) ; } @ SuppressWarnings ( "<STR_LIT:unchecked>" ) private void initComponents ( ) { jTextField1 = new javax . swing . JTextField ( ) ; jTabbedPane1 = new javax . swing . JTabbedPane ( ) ; jPanel1 = new javax . swing . JPanel ( ) ; jPanel2 = new javax . swing . JPanel ( ) ; jComboBox1 = new javax . swing . JComboBox ( ) ; jButton1 = new javax . swing . JButton ( ) ; jLabel1 = new javax . swing . JLabel ( ) ; jComboBox2 = new javax . swing . JComboBox ( ) ; jLabel5 = new javax . swing . JLabel ( ) ; jPanel3 = new javax . swing . JPanel ( ) ; jLabel2 = new javax . swing . JLabel ( ) ; jLabel3 = new javax . swing . JLabel ( ) ; jLabel4 = new javax . swing . JLabel ( ) ; jSlider1 = new javax . swing . JSlider ( <NUM_LIT:1> , <NUM_LIT> , <NUM_LIT:10> ) ; jSlider2 = new javax . swing . JSlider ( <NUM_LIT:1> , <NUM_LIT:100> , <NUM_LIT> ) ; jButton2 = new javax . swing . JButton ( ) ; jLabel8 = new javax . swing . JLabel ( ) ; jPanel4 = new javax . swing . JPanel ( ) ; jLabel6 = new javax . swing . JLabel ( ) ; jLabel7 = new javax . swing . JLabel ( ) ; jSlider3 = new javax . swing . JSlider ( <NUM_LIT:1> , <NUM_LIT> , <NUM_LIT:100> ) ; jButton3 = new javax . swing . JButton ( ) ; jLabel9 = new javax . swing . JLabel ( ) ; jTextField1 . setText ( "<STR_LIT>" ) ; setDefaultCloseOperation ( javax . swing . WindowConstants . DISPOSE_ON_CLOSE ) ; jPanel2 . setBackground ( new java . awt . Color ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ; jComboBox1 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ) ) ; jComboBox1 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jComboBox1ActionPerformed ( evt ) ; } } ) ; jButton1 . setText ( "<STR_LIT>" ) ; jButton1 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton1ActionPerformed ( evt ) ; } } ) ; jLabel1 . setText ( "<STR_LIT>" ) ; jComboBox2 . setModel ( new javax . swing . DefaultComboBoxModel ( new String [ ] { "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" , "<STR_LIT>" } ) ) ; jComboBox2 . setSelectedIndex ( <NUM_LIT:3> ) ; jLabel5 . setText ( "<STR_LIT>" ) ; javax . swing . GroupLayout jPanel2Layout = new javax . swing . GroupLayout ( jPanel2 ) ; jPanel2 . setLayout ( jPanel2Layout ) ; jPanel2Layout . setHorizontalGroup ( jPanel2Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel2Layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( jPanel2Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jComboBox1 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( jLabel5 ) . addComponent ( jLabel1 ) . addGroup ( jPanel2Layout . createSequentialGroup ( ) . addComponent ( jComboBox2 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , <NUM_LIT> , Short . MAX_VALUE ) . addComponent ( jButton1 ) ) ) . addContainerGap ( ) ) ) ; jPanel2Layout . setVerticalGroup ( jPanel2Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel2Layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( jPanel2Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel2Layout . createSequentialGroup ( ) . addComponent ( jLabel1 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jComboBox1 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jLabel5 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jComboBox2 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addGap ( <NUM_LIT:24> , <NUM_LIT:24> , <NUM_LIT:24> ) ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , jPanel2Layout . createSequentialGroup ( ) . addComponent ( jButton1 ) . addContainerGap ( ) ) ) ) ) ; jPanel3 . setBackground ( new java . awt . Color ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ; jLabel2 . setText ( "<STR_LIT>" ) ; jLabel3 . setText ( "<STR_LIT>" ) ; jLabel4 . setText ( "<STR_LIT>" ) ; jSlider1 . addChangeListener ( new javax . swing . event . ChangeListener ( ) { public void stateChanged ( javax . swing . event . ChangeEvent evt ) { jSlider1StateChanged ( evt ) ; } } ) ; jSlider2 . addChangeListener ( new javax . swing . event . ChangeListener ( ) { public void stateChanged ( javax . swing . event . ChangeEvent evt ) { jSlider2StateChanged ( evt ) ; } } ) ; jButton2 . setText ( "<STR_LIT>" ) ; jButton2 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton2ActionPerformed ( evt ) ; } } ) ; jLabel8 . setText ( jSlider1 . getValue ( ) + "<STR_LIT:U+002C>" + jSlider2 . getValue ( ) ) ; javax . swing . GroupLayout jPanel3Layout = new javax . swing . GroupLayout ( jPanel3 ) ; jPanel3 . setLayout ( jPanel3Layout ) ; jPanel3Layout . setHorizontalGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel3Layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jLabel2 ) . addGroup ( jPanel3Layout . createSequentialGroup ( ) . addGap ( <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) . addGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jLabel3 ) . addComponent ( jSlider1 , javax . swing . GroupLayout . PREFERRED_SIZE , <NUM_LIT> , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , <NUM_LIT> , Short . MAX_VALUE ) . addGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING , false ) . addComponent ( jSlider2 , <NUM_LIT:0> , <NUM_LIT> , Short . MAX_VALUE ) . addComponent ( jLabel4 , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , jPanel3Layout . createSequentialGroup ( ) . addComponent ( jLabel8 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jButton2 ) ) ) . addContainerGap ( ) ) ) ; jPanel3Layout . setVerticalGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel3Layout . createSequentialGroup ( ) . addContainerGap ( ) . addComponent ( jLabel2 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( jLabel3 ) . addComponent ( jLabel4 ) ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . TRAILING ) . addComponent ( jSlider2 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addComponent ( jSlider1 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addGroup ( jPanel3Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( jButton2 ) . addComponent ( jLabel8 ) ) . addContainerGap ( ) ) ) ; jPanel4 . setBackground ( new java . awt . Color ( <NUM_LIT> , <NUM_LIT> , <NUM_LIT> ) ) ; jLabel6 . setText ( "<STR_LIT>" ) ; jLabel7 . setText ( "<STR_LIT>" ) ; jSlider3 . addChangeListener ( new javax . swing . event . ChangeListener ( ) { public void stateChanged ( javax . swing . event . ChangeEvent evt ) { jSlider3StateChanged ( evt ) ; } } ) ; jButton3 . setText ( "<STR_LIT>" ) ; jButton3 . addActionListener ( new java . awt . event . ActionListener ( ) { public void actionPerformed ( java . awt . event . ActionEvent evt ) { jButton3ActionPerformed ( evt ) ; } } ) ; jLabel9 . setText ( jSlider3 . getValue ( ) + "<STR_LIT>" ) ; javax . swing . GroupLayout jPanel4Layout = new javax . swing . GroupLayout ( jPanel4 ) ; jPanel4 . setLayout ( jPanel4Layout ) ; jPanel4Layout . setHorizontalGroup ( jPanel4Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel4Layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( jPanel4Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel4Layout . createSequentialGroup ( ) . addGap ( <NUM_LIT:12> , <NUM_LIT:12> , <NUM_LIT:12> ) . addComponent ( jLabel7 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jSlider3 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jLabel9 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jButton3 ) ) . addComponent ( jLabel6 ) ) . addContainerGap ( ) ) ) ; jPanel4Layout . setVerticalGroup ( jPanel4Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel4Layout . createSequentialGroup ( ) . addContainerGap ( ) . addComponent ( jLabel6 ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addGroup ( jPanel4Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jLabel7 ) . addComponent ( jSlider3 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) ) . addContainerGap ( javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) . addGroup ( javax . swing . GroupLayout . Alignment . TRAILING , jPanel4Layout . createSequentialGroup ( ) . addContainerGap ( <NUM_LIT> , Short . MAX_VALUE ) . addGroup ( jPanel4Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . BASELINE ) . addComponent ( jButton3 ) . addComponent ( jLabel9 ) ) . addContainerGap ( ) ) ) ; javax . swing . GroupLayout jPanel1Layout = new javax . swing . GroupLayout ( jPanel1 ) ; jPanel1 . setLayout ( jPanel1Layout ) ; jPanel1Layout . setHorizontalGroup ( jPanel1Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel1Layout . createSequentialGroup ( ) . addContainerGap ( ) . addGroup ( jPanel1Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jPanel4 , javax . swing . GroupLayout . Alignment . TRAILING , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jPanel3 , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) . addComponent ( jPanel2 , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) . addContainerGap ( ) ) ) ; jPanel1Layout . setVerticalGroup ( jPanel1Layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addGroup ( jPanel1Layout . createSequentialGroup ( ) . addContainerGap ( ) . addComponent ( jPanel2 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jPanel3 , javax . swing . GroupLayout . PREFERRED_SIZE , <NUM_LIT> , javax . swing . GroupLayout . PREFERRED_SIZE ) . addPreferredGap ( javax . swing . LayoutStyle . ComponentPlacement . RELATED ) . addComponent ( jPanel4 , javax . swing . GroupLayout . PREFERRED_SIZE , javax . swing . GroupLayout . DEFAULT_SIZE , javax . swing . GroupLayout . PREFERRED_SIZE ) . addContainerGap ( javax . swing . GroupLayout . DEFAULT_SIZE , Short . MAX_VALUE ) ) ) ; jTabbedPane1 . addTab ( "<STR_LIT>" , jPanel1 ) ; javax . swing . GroupLayout layout = new javax . swing . GroupLayout ( getContentPane ( ) ) ; getContentPane ( ) . setLayout ( layout ) ; layout . setHorizontalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jTabbedPane1 , javax . swing . GroupLayout . DEFAULT_SIZE , <NUM_LIT> , Short . MAX_VALUE ) ) ; layout . setVerticalGroup ( layout . createParallelGroup ( javax . swing . GroupLayout . Alignment . LEADING ) . addComponent ( jTabbedPane1 , javax . swing . GroupLayout . DEFAULT_SIZE , <NUM_LIT> , Short . MAX_VALUE ) ) ; pack ( ) ; } private void jComboBox1ActionPerformed ( java . awt . event . ActionEvent evt ) { } private void jButton1ActionPerformed ( java . awt . event . ActionEvent evt ) { int a = jComboBox1 . getSelectedIndex ( ) ; IClusterModel clModel = ClusterModelFactory . getModel ( "<STR_LIT>" ) ; clModel . changeClusterer ( a + <NUM_LIT:1> ) ; int b = jComboBox2 . getSelectedIndex ( ) ; clModel . changeMaxDist ( b + <NUM_LIT:1> ) ; } private void jButton2ActionPerformed ( java . awt . event . ActionEvent evt ) { int a = jSlider1 . getValue ( ) ; int b = jSlider2 . getValue ( ) ; clModel . changeWCprop ( a , b ) ; } private void jButton3ActionPerformed ( java . awt . event . ActionEvent evt ) { int a = jSlider3 . getValue ( ) ; clModel . changePTCprop ( a ) ; } private void jSlider1StateChanged ( javax . swing . event . ChangeEvent evt ) { jLabel8 . setText ( jSlider1 . getValue ( ) + "<STR_LIT:U+002C>" + jSlider2 . getValue ( ) ) ; } private void jSlider2StateChanged ( javax . swing . event . ChangeEvent evt ) { jLabel8 . setText ( jSlider1 . getValue ( ) + "<STR_LIT:U+002C>" + jSlider2 . getValue ( ) ) ; } private void jSlider3StateChanged ( javax . swing . event . ChangeEvent evt ) { jLabel9 . setText ( jSlider3 . getValue ( ) + "<STR_LIT>" ) ; } public static void main ( String args [ ] ) { java . awt . EventQueue . invokeLater ( new Runnable ( ) { public void run ( ) { new configTable ( ) . setVisible ( true ) ; } } ) ; } private javax . swing . JButton jButton1 ; private javax . swing . JButton jButton2 ; private javax . swing . JButton jButton3 ; private javax . swing . JComboBox jComboBox1 ; private javax . swing . JComboBox jComboBox2 ; private javax . swing . JLabel jLabel1 ; private javax . swing . JLabel jLabel2 ; private javax . swing . JLabel jLabel3 ; private javax . swing . JLabel jLabel4 ; private javax . swing . JLabel jLabel5 ; private javax . swing . JLabel jLabel6 ; private javax . swing . JLabel jLabel7 ; private javax . swing . JLabel jLabel8 ; private javax . swing . JLabel jLabel9 ; private javax . swing . JPanel jPanel1 ; private javax . swing . JPanel jPanel2 ; private javax . swing . JPanel jPanel3 ; private javax . swing . JPanel jPanel4 ; private javax . swing . JSlider jSlider1 ; private javax . swing . JSlider jSlider2 ; private javax . swing . JSlider jSlider3 ; private javax . swing . JTabbedPane jTabbedPane1 ; private javax . swing . JTextField jTextField1 ; } </s>
|
<s> package env ; import weka . clusterers . ClusterEvaluation ; import weka . clusterers . Clusterer ; import weka . clusterers . Cobweb ; import weka . clusterers . EM ; import weka . clusterers . FarthestFirst ; import weka . clusterers . XMeans ; import weka . clusterers . sIB ; import java . io . BufferedWriter ; import java . io . File ; import java . io . FileWriter ; import java . io . IOException ; import java . util . logging . Logger ; import java . util . Collections ; import java . util . HashMap ; import java . util . List ; import java . util . Map ; import java . util . Vector ; import java . lang . Math ; import jia . Vec ; public class ClusterModel implements Runnable , IClusterModel { private boolean spc = true ; private boolean useTuner = false ; private int useClusterer = <NUM_LIT:1> ; public static final int CLUSTERER_EM = <NUM_LIT:1> ; public static final int CLUSTERER_XMEANS = <NUM_LIT:2> ; public static final int CLUSTERER_COBWEB = <NUM_LIT:3> ; public static final int CLUSTERER_sIB = <NUM_LIT:4> ; public static final int CLUSTERER_FF = <NUM_LIT:5> ; private int prefRadius = <NUM_LIT:10> , prefnCows = <NUM_LIT> , kPTC = <NUM_LIT:100> ; private int useRadius = <NUM_LIT:4> ; public static final int RADIUS_MAXDIST = <NUM_LIT:1> ; public static final int RADIUS_SD = <NUM_LIT:2> ; public static final int RADIUS_DBLDAVERAGE = <NUM_LIT:3> ; final private static String NAME_FILE = "<STR_LIT>" ; final private static String CENTERS_NAME_FILE = "<STR_LIT>" ; private File file ; private File previous ; private int [ ] [ ] data = new int [ <NUM_LIT:2> ] [ <NUM_LIT:2> ] ; private int dataNumber ; private int [ ] alloc = new int [ <NUM_LIT:2> ] ; private Vec [ ] Center ; private int n ; private int [ ] numcows ; private int [ ] maxDist ; private Logger logger = Logger . getLogger ( ClusterModel . class . getName ( ) ) ; ClusterEvaluation ce ; private Cow [ ] cows ; private int actStep = - <NUM_LIT:1> ; private int clStep ; private int [ ] s ; private int gH = <NUM_LIT:0> ; private int gW = <NUM_LIT:0> ; private int [ ] [ ] cowsCluster ; private boolean [ ] [ ] trees ; final int DOWN = <NUM_LIT:0> , UP = <NUM_LIT:1> , LEFT = <NUM_LIT:2> , RIGHT = <NUM_LIT:3> ; List < Integer > treeToAdd = new Vector < Integer > ( ) ; ICowModel cModel = CowModelFactory . getModel ( "<STR_LIT>" ) ; public ClusterModel ( ) { if ( useTuner ) { configTable . main ( null ) ; } } public synchronized void run ( ) { if ( actStep < clStep ) { actStep = clStep ; alloc = calculate ( ) ; cCenters ( ) ; setMap ( ) ; cMaxDist ( ) ; printClusters ( ) ; } } private void printClusters ( ) { String str = new String ( ) ; str = "<STR_LIT>" + n + "<STR_LIT>" ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { str += "<STR_LIT>" + i + "<STR_LIT>" + Center [ i ] . getX ( ) + "<STR_LIT:U+002C>" + ( gH - Center [ i ] . getY ( ) - <NUM_LIT:1> ) + "<STR_LIT>" + maxDist [ i ] + "<STR_LIT:|>" ; } logger . info ( str ) ; } public int [ ] getMaxDist ( ) { return maxDist ; } public void setStepcl ( int step ) { if ( step > clStep ) clStep = step ; if ( step == - <NUM_LIT:1> ) { clStep = <NUM_LIT:0> ; actStep = - <NUM_LIT:1> ; } } private void cMaxDist ( ) { switch ( useRadius ) { case <NUM_LIT:1> : maxDist = new int [ Center . length ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { int Dist = Math . abs ( Center [ alloc [ i ] ] . getX ( ) - data [ <NUM_LIT:0> ] [ i ] ) ; int Dist2 = Math . abs ( Center [ alloc [ i ] ] . getY ( ) - data [ <NUM_LIT:1> ] [ i ] ) ; Dist = Math . max ( Dist , Dist2 ) ; if ( Dist > maxDist [ alloc [ i ] ] ) maxDist [ alloc [ i ] ] = Dist ; } break ; case <NUM_LIT:2> : maxDist = new int [ Center . length ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { int Dist = Math . abs ( Center [ alloc [ i ] ] . getX ( ) - data [ <NUM_LIT:0> ] [ i ] ) ; int Dist2 = Math . abs ( Center [ alloc [ i ] ] . getY ( ) - data [ <NUM_LIT:1> ] [ i ] ) ; Dist = Math . max ( Dist , Dist2 ) ; maxDist [ alloc [ i ] ] += Dist * Dist ; } for ( int i = <NUM_LIT:0> ; i < maxDist . length ; i ++ ) { maxDist [ i ] = ( int ) Math . sqrt ( ( double ) maxDist [ i ] / ( ( double ) numcows [ i ] - <NUM_LIT:1.0> ) ) ; } break ; case <NUM_LIT:3> : maxDist = new int [ Center . length ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { int Dist = Math . abs ( Center [ alloc [ i ] ] . getX ( ) - data [ <NUM_LIT:0> ] [ i ] ) ; int Dist2 = Math . abs ( Center [ alloc [ i ] ] . getY ( ) - data [ <NUM_LIT:1> ] [ i ] ) ; Dist = Math . max ( Dist , Dist2 ) ; maxDist [ alloc [ i ] ] += Dist ; } for ( int i = <NUM_LIT:0> ; i < maxDist . length ; i ++ ) { maxDist [ i ] = <NUM_LIT:2> * maxDist [ i ] / numcows [ i ] ; } break ; case <NUM_LIT:4> : Vec [ ] CenterTemp = new Vec [ Center . length ] ; for ( int i = <NUM_LIT:0> ; i < CenterTemp . length ; i ++ ) { CenterTemp [ i ] = new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ; } float [ ] distOut = new float [ Center . length ] ; Vector < Vector < Integer > > temp = new Vector < Vector < Integer > > ( ) ; Vector < Vector < Integer > > temp2 = new Vector < Vector < Integer > > ( ) ; for ( int j = <NUM_LIT:0> ; j < Center . length ; j ++ ) { temp . add ( new Vector < Integer > ( ) ) ; temp2 . add ( new Vector < Integer > ( ) ) ; } maxDist = new int [ Center . length ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { int Dist = Math . abs ( Center [ alloc [ i ] ] . getX ( ) - data [ <NUM_LIT:0> ] [ i ] ) ; int Dist2 = Math . abs ( Center [ alloc [ i ] ] . getY ( ) - data [ <NUM_LIT:1> ] [ i ] ) ; Dist = Math . max ( Dist , Dist2 ) ; temp . get ( alloc [ i ] ) . add ( Dist ) ; } for ( int i = <NUM_LIT:0> ; i < temp . size ( ) ; i ++ ) { Collections . sort ( temp . get ( i ) ) ; if ( temp . get ( i ) . size ( ) <= <NUM_LIT:3> ) distOut [ i ] = <NUM_LIT:0> ; else { int pos3Quartil = Math . round ( ( float ) <NUM_LIT> * ( temp . get ( i ) . size ( ) + <NUM_LIT:1> ) ) - <NUM_LIT:1> ; int pos1Quartil = Math . round ( ( float ) <NUM_LIT> * ( temp . get ( i ) . size ( ) + <NUM_LIT:1> ) ) - <NUM_LIT:1> ; distOut [ i ] = temp . get ( i ) . get ( pos3Quartil ) + ( float ) <NUM_LIT> * ( temp . get ( i ) . get ( pos3Quartil ) - temp . get ( i ) . get ( pos1Quartil ) ) ; } } for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { int Dist = Math . abs ( Center [ alloc [ i ] ] . getX ( ) - data [ <NUM_LIT:0> ] [ i ] ) ; int Dist2 = Math . abs ( Center [ alloc [ i ] ] . getY ( ) - data [ <NUM_LIT:1> ] [ i ] ) ; Dist = Math . max ( Dist , Dist2 ) ; if ( Dist <= distOut [ alloc [ i ] ] || ( distOut [ alloc [ i ] ] <= <NUM_LIT:0> ) ) { temp2 . get ( alloc [ i ] ) . add ( Dist ) ; CenterTemp [ alloc [ i ] ] = CenterTemp [ alloc [ i ] ] . add ( new Vec ( data [ <NUM_LIT:0> ] [ i ] , data [ <NUM_LIT:1> ] [ i ] ) ) ; } } for ( int i = <NUM_LIT:0> ; i < temp2 . size ( ) ; i ++ ) { Collections . sort ( temp2 . get ( i ) ) ; switch ( temp2 . get ( i ) . size ( ) % <NUM_LIT:2> ) { case <NUM_LIT:1> : { maxDist [ i ] = <NUM_LIT:2> * temp2 . get ( i ) . get ( temp2 . get ( i ) . size ( ) / <NUM_LIT:2> ) ; break ; } case <NUM_LIT:0> : { maxDist [ i ] = temp2 . get ( i ) . get ( temp2 . get ( i ) . size ( ) / <NUM_LIT:2> ) ; maxDist [ i ] += temp2 . get ( i ) . get ( temp2 . get ( i ) . size ( ) / <NUM_LIT:2> - <NUM_LIT:1> ) ; break ; } } maxDist [ i ] += <NUM_LIT:1> ; CenterTemp [ i ] = CenterTemp [ i ] . newMagnitude ( CenterTemp [ i ] . magnitude ( ) / ( ( double ) temp2 . get ( i ) . size ( ) ) ) ; } Center = CenterTemp . clone ( ) ; break ; } } public int [ ] getAlloc ( ) { int [ ] al = alloc . clone ( ) ; return al ; } public int getNumberOfCluster ( ) { return n ; } public int [ ] getNumCows ( ) { return numcows ; } private void setMap ( ) { s = new int [ <NUM_LIT:1000> ] ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT> ; i ++ ) s [ i ] = - <NUM_LIT:1> ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { s [ cows [ i ] . id ] = alloc [ i ] ; } } public int [ ] getMap ( ) { return s ; } private void realloc ( ) { cowsCluster = new int [ dataNumber ] [ dataNumber ] ; n = <NUM_LIT:0> ; numcows = new int [ dataNumber ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { if ( alloc [ i ] > dataNumber ) { logger . info ( "<STR_LIT>" ) ; } cowsCluster [ alloc [ i ] ] [ numcows [ alloc [ i ] ] ] = i ; numcows [ alloc [ i ] ] ++ ; if ( alloc [ i ] + <NUM_LIT:1> > n ) { n = alloc [ i ] + <NUM_LIT:1> ; } } int [ ] temp2 = new int [ n ] ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { temp2 [ i ] = numcows [ i ] ; } numcows = temp2 . clone ( ) ; } private void cCenters ( ) { cowsCluster = new int [ dataNumber ] [ dataNumber ] ; n = <NUM_LIT:0> ; Center = new Vec [ dataNumber ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) Center [ i ] = new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ; numcows = new int [ dataNumber ] ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { if ( alloc [ i ] > dataNumber ) { logger . info ( "<STR_LIT>" ) ; } cowsCluster [ alloc [ i ] ] [ numcows [ alloc [ i ] ] ] = i ; numcows [ alloc [ i ] ] ++ ; if ( alloc [ i ] + <NUM_LIT:1> > n ) { n = alloc [ i ] + <NUM_LIT:1> ; } Vec tmp = new Vec ( data [ <NUM_LIT:0> ] [ i ] , data [ <NUM_LIT:1> ] [ i ] ) ; Center [ alloc [ i ] ] = Center [ alloc [ i ] ] . add ( tmp ) ; } for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { Center [ i ] = Center [ i ] . newMagnitude ( Center [ i ] . magnitude ( ) / ( ( double ) numcows [ i ] ) ) ; } Vec [ ] temp = new Vec [ n ] ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { temp [ i ] = ( Vec ) ( Center [ i ] . clone ( ) ) ; } int [ ] temp2 = new int [ n ] ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { temp2 [ i ] = numcows [ i ] ; } numcows = temp2 . clone ( ) ; Center = temp . clone ( ) ; } private void separateClusters ( ) { int [ ] [ ] datatmp ; int [ ] [ ] extremes = new int [ <NUM_LIT:4> ] [ n ] ; if ( data == null ) return ; datatmp = data . clone ( ) ; for ( int i = <NUM_LIT:0> ; i < n ; i ++ ) { Vec cellUp ; Vec cellDown ; extremes [ UP ] [ i ] = extremes [ DOWN ] [ i ] = datatmp [ <NUM_LIT:1> ] [ cowsCluster [ i ] [ <NUM_LIT:0> ] ] ; extremes [ LEFT ] [ i ] = extremes [ RIGHT ] [ i ] = datatmp [ <NUM_LIT:0> ] [ cowsCluster [ i ] [ <NUM_LIT:0> ] ] ; cellUp = cellDown = new Vec ( extremes [ RIGHT ] [ i ] , extremes [ UP ] [ i ] ) ; for ( int j = <NUM_LIT:1> ; j < numcows [ i ] ; j ++ ) { int x = datatmp [ <NUM_LIT:0> ] [ cowsCluster [ i ] [ j ] ] ; int y = datatmp [ <NUM_LIT:1> ] [ cowsCluster [ i ] [ j ] ] ; if ( x > extremes [ RIGHT ] [ i ] ) { extremes [ RIGHT ] [ i ] = x ; } else if ( x < extremes [ LEFT ] [ i ] ) { extremes [ LEFT ] [ i ] = x ; } if ( y > extremes [ UP ] [ i ] ) { extremes [ UP ] [ i ] = y ; cellUp = new Vec ( x , y ) ; } else if ( y < extremes [ DOWN ] [ i ] ) { extremes [ DOWN ] [ i ] = y ; cellDown = new Vec ( x , y ) ; } } List < Integer > Lista = new Vector < Integer > ( ) ; Vec act = cellUp . sub ( cellDown ) ; double mag = act . r ; Vec init = new Vec ( <NUM_LIT:0> , <NUM_LIT:0> ) ; for ( int j = <NUM_LIT:0> ; j < ( int ) mag + <NUM_LIT:1> ; j ++ ) { Vec position = cellDown . add ( act . newMagnitude ( j ) ) ; int posx = ( int ) position . x ; int posy = ( int ) position . y ; if ( trees [ posx ] [ posy ] ) { init = new Vec ( posx , posy ) ; } } int [ ] dx = { <NUM_LIT:0> , <NUM_LIT:1> , - <NUM_LIT:1> } ; int [ ] dy = { - <NUM_LIT:1> , <NUM_LIT:0> , <NUM_LIT:0> } ; Vec Up = goThroughCells ( dx , dy , init , extremes , i ) ; dx [ <NUM_LIT:0> ] = <NUM_LIT:0> ; dx [ <NUM_LIT:1> ] = <NUM_LIT:1> ; dx [ <NUM_LIT:2> ] = - <NUM_LIT:1> ; dy [ <NUM_LIT:0> ] = <NUM_LIT:1> ; dy [ <NUM_LIT:1> ] = <NUM_LIT:0> ; dy [ <NUM_LIT:2> ] = <NUM_LIT:0> ; Vec Down = goThroughCells ( dx , dy , init , extremes , i ) ; dx [ <NUM_LIT:0> ] = <NUM_LIT:1> ; dx [ <NUM_LIT:1> ] = <NUM_LIT:0> ; dx [ <NUM_LIT:2> ] = <NUM_LIT:0> ; dy [ <NUM_LIT:0> ] = <NUM_LIT:0> ; dy [ <NUM_LIT:1> ] = <NUM_LIT:1> ; dy [ <NUM_LIT:2> ] = - <NUM_LIT:1> ; Vec Left = goThroughCells ( dx , dy , init , extremes , i ) ; dx [ <NUM_LIT:0> ] = - <NUM_LIT:1> ; dx [ <NUM_LIT:1> ] = <NUM_LIT:0> ; dx [ <NUM_LIT:2> ] = <NUM_LIT:0> ; dy [ <NUM_LIT:0> ] = <NUM_LIT:0> ; dy [ <NUM_LIT:1> ] = <NUM_LIT:1> ; dy [ <NUM_LIT:2> ] = - <NUM_LIT:1> ; Vec Right = goThroughCells ( dx , dy , init , extremes , i ) ; Vec D2U = Up . sub ( Down ) ; Vec L2R = Right . sub ( Left ) ; for ( int cow : cowsCluster [ i ] ) { if ( D2U . dot ( new Vec ( data [ <NUM_LIT:0> ] [ cow ] , data [ <NUM_LIT:1> ] [ cow ] ) ) < <NUM_LIT:0> ) { Lista . add ( cow ) ; } } if ( Lista . size ( ) > <NUM_LIT:0> && Lista . size ( ) != numcows [ i ] ) { for ( int j = <NUM_LIT:0> ; j < Lista . size ( ) ; j ++ ) { alloc [ Lista . get ( j ) ] = n ; } n ++ ; } realloc ( ) ; for ( int cow : cowsCluster [ i ] ) { if ( L2R . dot ( new Vec ( data [ <NUM_LIT:0> ] [ cow ] , data [ <NUM_LIT:1> ] [ cow ] ) ) < <NUM_LIT:0> ) { Lista . add ( cow ) ; } } if ( Lista . size ( ) > <NUM_LIT:0> && Lista . size ( ) != numcows [ i ] ) { for ( int j = <NUM_LIT:0> ; j < Lista . size ( ) ; j ++ ) { alloc [ Lista . get ( j ) ] = n ; } n ++ ; } } } private Vec goThroughCells ( int dx [ ] , int dy [ ] , Vec beg , int [ ] [ ] extremes , int Cluster ) { Vec cur = beg ; boolean nextOk ; while ( true ) { nextOk = false ; Vec cur2 = cur ; for ( int i = <NUM_LIT:0> ; i < dx . length ; i ++ ) { cur2 = cur . add ( new Vec ( dx [ i ] + <NUM_LIT> , dy [ i ] + <NUM_LIT> ) ) ; if ( isIn ( ( int ) cur2 . x , ( int ) cur2 . y , extremes , Cluster ) && trees [ ( int ) cur2 . x ] [ ( int ) cur2 . y ] ) { nextOk = true ; break ; } } if ( ! nextOk ) { beg = cur ; break ; } else { cur = cur2 ; } } return beg ; } private boolean isIn ( int x , int y , int [ ] [ ] extremes , int Cluster ) { if ( x > extremes [ RIGHT ] [ Cluster ] ) return false ; if ( x < extremes [ LEFT ] [ Cluster ] ) return false ; if ( y > extremes [ UP ] [ Cluster ] ) return false ; if ( y < extremes [ DOWN ] [ Cluster ] ) return false ; return true ; } private void printCenters ( ) { Vec [ ] c = Center . clone ( ) ; String str = new String ( ) ; str += "<STR_LIT:>>" ; for ( int i = <NUM_LIT:0> ; i < c . length ; i ++ ) { logger . info ( str ) ; str += "<STR_LIT>" + i + "<STR_LIT:]>" + "<STR_LIT:(>" + ( int ) c [ i ] . x + "<STR_LIT:U+002C>" + ( int ) c [ i ] . y + "<STR_LIT:)>" ; } logger . info ( str ) ; } public Vec [ ] getCenters ( ) { return Center ; } public int [ ] [ ] getData ( ) { return data . clone ( ) ; } private void createCentersFile ( ) { try { previous = new File ( CENTERS_NAME_FILE ) ; if ( ! previous . exists ( ) ) previous . createNewFile ( ) ; BufferedWriter out = new BufferedWriter ( new FileWriter ( previous , false ) ) ; out . write ( "<STR_LIT>" ) ; out . write ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < Center . length ; i ++ ) { out . write ( Center [ i ] . getX ( ) + "<STR_LIT:U+002C>" + Center [ i ] . getY ( ) + "<STR_LIT:n>" ) ; } out . write ( "<STR_LIT:n>" ) ; out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } private void createFile ( ) { int i ; try { file = new File ( NAME_FILE ) ; if ( ! file . exists ( ) ) file . createNewFile ( ) ; BufferedWriter out = new BufferedWriter ( new FileWriter ( file , false ) ) ; out . write ( "<STR_LIT>" ) ; out . write ( "<STR_LIT>" ) ; for ( i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) out . write ( data [ <NUM_LIT:0> ] [ i ] + "<STR_LIT:U+002C>" + data [ <NUM_LIT:1> ] [ i ] + "<STR_LIT:n>" ) ; out . write ( "<STR_LIT:n>" ) ; out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } private void defineData ( int [ ] [ ] inf ) { data = inf . clone ( ) ; } public void changeClusterer ( int a ) { useClusterer = a ; } public void changeMaxDist ( int a ) { useRadius = a ; } public void changeWCprop ( int radius , int nCows ) { prefRadius = radius ; prefnCows = nCows ; } public int getPrefRadius ( ) { return prefRadius ; } public int getPrefNCows ( ) { return prefnCows ; } public void changePTCprop ( int k ) { kPTC = k ; } public double getPrefkPTC ( ) { return ( double ) kPTC / <NUM_LIT> ; } synchronized public void insertTree ( int x , int y ) { if ( ! ( x >= gW || x < <NUM_LIT:0> || y >= gH || y < <NUM_LIT:0> ) ) { while ( treeToAdd . size ( ) > <NUM_LIT:0> ) { int tmp = treeToAdd . remove ( <NUM_LIT:0> ) ; insertTree ( tmp / <NUM_LIT> , tmp % <NUM_LIT> ) ; } try { trees [ x ] [ - y + gH - <NUM_LIT:1> ] = true ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } else { if ( gW == <NUM_LIT:0> || gH == <NUM_LIT:0> ) { treeToAdd . add ( x * <NUM_LIT> + y ) ; } } } public void setCows ( Cow [ ] c , int H , int W ) { spc = false ; cows = c ; gH = H ; gW = W ; } private int [ ] calculate ( ) { ce = new ClusterEvaluation ( ) ; int countStepsWithProblem = <NUM_LIT:0> ; if ( spc ) { cModel . updateCows ( ) ; cows = cModel . getCows ( ) ; while ( gH <= <NUM_LIT:0> || gW <= <NUM_LIT:0> || clStep == - <NUM_LIT:1> ) { gH = cModel . getSizeh ( ) ; gW = cModel . getSizew ( ) ; if ( countStepsWithProblem ++ > <NUM_LIT:20> ) { break ; } } } if ( cows == null || cows . length <= <NUM_LIT:0> ) { dataNumber = <NUM_LIT:0> ; gH = gW = <NUM_LIT:0> ; } else dataNumber = cows . length ; trees = new boolean [ gW ] [ gH ] ; int [ ] [ ] infos = new int [ <NUM_LIT:2> ] [ dataNumber ] ; if ( dataNumber == <NUM_LIT:0> ) return null ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { infos [ <NUM_LIT:0> ] [ i ] = cows [ i ] . x ; infos [ <NUM_LIT:1> ] [ i ] = gH - <NUM_LIT:1> - cows [ i ] . y ; } defineData ( infos ) ; createFile ( ) ; Clusterer cluster = null ; String [ ] options = null ; switch ( useClusterer ) { case <NUM_LIT:1> : cluster = new EM ( ) ; options = new String [ <NUM_LIT:4> ] ; options [ <NUM_LIT:0> ] = "<STR_LIT>" ; options [ <NUM_LIT:1> ] = file . getAbsolutePath ( ) ; options [ <NUM_LIT:2> ] = "<STR_LIT>" ; options [ <NUM_LIT:3> ] = "<STR_LIT:0>" ; break ; case <NUM_LIT:2> : cluster = new XMeans ( ) ; options = new String [ <NUM_LIT:8> ] ; options [ <NUM_LIT:0> ] = "<STR_LIT>" ; options [ <NUM_LIT:1> ] = file . getAbsolutePath ( ) ; options [ <NUM_LIT:2> ] = "<STR_LIT>" ; options [ <NUM_LIT:3> ] = "<STR_LIT:0>" ; options [ <NUM_LIT:4> ] = "<STR_LIT>" ; options [ <NUM_LIT:5> ] = "<STR_LIT:6>" ; options [ <NUM_LIT:6> ] = "<STR_LIT>" ; options [ <NUM_LIT:7> ] = "<STR_LIT>" ; break ; case <NUM_LIT:3> : cluster = new Cobweb ( ) ; options = new String [ <NUM_LIT:4> ] ; options [ <NUM_LIT:0> ] = "<STR_LIT>" ; options [ <NUM_LIT:1> ] = file . getAbsolutePath ( ) ; options [ <NUM_LIT:2> ] = "<STR_LIT>" ; options [ <NUM_LIT:3> ] = "<STR_LIT:0>" ; break ; case <NUM_LIT:4> : cluster = new sIB ( ) ; options = new String [ <NUM_LIT:4> ] ; options [ <NUM_LIT:0> ] = "<STR_LIT>" ; options [ <NUM_LIT:1> ] = file . getAbsolutePath ( ) ; options [ <NUM_LIT:2> ] = "<STR_LIT>" ; options [ <NUM_LIT:3> ] = "<STR_LIT:0>" ; break ; case <NUM_LIT:5> : cluster = new FarthestFirst ( ) ; options = new String [ <NUM_LIT:4> ] ; options [ <NUM_LIT:0> ] = "<STR_LIT>" ; options [ <NUM_LIT:1> ] = file . getAbsolutePath ( ) ; options [ <NUM_LIT:2> ] = "<STR_LIT>" ; options [ <NUM_LIT:3> ] = "<STR_LIT:0>" ; break ; } try { String str = ClusterEvaluation . evaluateClusterer ( cluster , options ) ; logger . info ( "<STR_LIT>" + useClusterer ) ; int [ ] assign = new int [ dataNumber ] ; String [ ] tmp = str . split ( "<STR_LIT:n>" ) ; for ( int i = <NUM_LIT:0> ; i < dataNumber ; i ++ ) { assign [ i ] = ( int ) ( Double . parseDouble ( tmp [ i ] . split ( "<STR_LIT:U+0020>" ) [ <NUM_LIT:1> ] ) + <NUM_LIT> ) ; } return assign ; } catch ( Exception e ) { e . printStackTrace ( ) ; } return null ; } public void update ( ) { } } </s>
|
<s> package env ; import java . util . logging . Logger ; import alice . cartago . * ; public class ClusterModelArtifact extends Artifact { private Logger logger = Logger . getLogger ( ClusterModelArtifact . class . getName ( ) ) ; private ClusterModel model = ClusterModelFactory . getModelCent ( ) ; @ OPERATION void init ( ) { new Thread ( ( Runnable ) model ) . start ( ) ; defineObsProperty ( "<STR_LIT>" , model . getAlloc ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getCenters ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getData ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getMap ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getMaxDist ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getNumCows ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getNumberOfCluster ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getPrefNCows ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getPrefRadius ( ) ) ; defineObsProperty ( "<STR_LIT>" , model . getPrefkPTC ( ) ) ; logger . info ( "<STR_LIT>" ) ; } @ OPERATION void update ( ) { logger . info ( "<STR_LIT>" ) ; updateObsProperty ( "<STR_LIT>" , model . getAlloc ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getCenters ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getData ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getMap ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getMaxDist ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getNumCows ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getNumberOfCluster ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getPrefNCows ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getPrefRadius ( ) ) ; updateObsProperty ( "<STR_LIT>" , model . getPrefkPTC ( ) ) ; logger . info ( "<STR_LIT>" + model . getPrefkPTC ( ) ) ; } @ OPERATION void updateAlloc ( ) { updateObsProperty ( "<STR_LIT>" , model . getAlloc ( ) ) ; } @ OPERATION void updateCenters ( ) { updateObsProperty ( "<STR_LIT>" , model . getCenters ( ) ) ; } @ OPERATION void updateData ( ) { updateObsProperty ( "<STR_LIT>" , model . getData ( ) ) ; } @ OPERATION void updateMap ( ) { updateObsProperty ( "<STR_LIT>" , model . getMap ( ) ) ; } @ OPERATION void updateRadius ( ) { updateObsProperty ( "<STR_LIT>" , model . getMaxDist ( ) ) ; } @ OPERATION void updateNumCows ( ) { updateObsProperty ( "<STR_LIT>" , model . getNumCows ( ) ) ; } @ OPERATION void updateClusterNumber ( ) { updateObsProperty ( "<STR_LIT>" , model . getNumberOfCluster ( ) ) ; } @ OPERATION void updatePrefNCows ( ) { updateObsProperty ( "<STR_LIT>" , model . getPrefNCows ( ) ) ; } @ OPERATION void updatePrefRadius ( ) { updateObsProperty ( "<STR_LIT>" , model . getPrefRadius ( ) ) ; } @ OPERATION void updatePrefKPTC ( ) { updateObsProperty ( "<STR_LIT>" , model . getPrefkPTC ( ) ) ; } @ OPERATION void clusterCClusterer ( int a ) { model . changeClusterer ( a ) ; } @ OPERATION void clusterInsertTree ( int x , int y ) { model . insertTree ( x , y ) ; } @ OPERATION void clusterSetStep ( int step ) { model . setStepcl ( step ) ; } @ OPERATION void clusterRun ( ) { new Thread ( ( Runnable ) model ) . start ( ) ; } @ OPERATION void clustercMaxDist ( int a ) { model . changeMaxDist ( a ) ; } @ OPERATION void clusterSetCows ( Cow [ ] c , int H , int W ) { logger . info ( "<STR_LIT>" + c . length ) ; model . setCows ( c , H , W ) ; } @ OPERATION void clusterPTCP ( int k ) { model . changePTCprop ( k ) ; } @ OPERATION void clusterWCP ( int radius , int nCows ) { model . changeWCprop ( radius , nCows ) ; } } </s>
|
<s> package env ; public interface ICowModel { public void reset ( ) ; public void setSize ( int w , int h ) ; public void freePos ( int x , int y ) ; public void insertCow ( int id , int x , int y , int step ) ; public void updateCows ( ) ; public Cow [ ] getCows ( ) ; public int getSizeh ( ) ; public int getSizew ( ) ; } </s>
|
<s> package env ; import java . util . logging . Logger ; import alice . cartago . security . * ; import alice . cartago . * ; import java . lang . String ; public class CCowModel implements ICowModel { private Logger logger = Logger . getLogger ( CowModel . class . getName ( ) ) ; private UserCredential cred ; private ICartagoContext cWps ; private ArtifactId cArt ; private String end ; private String wpsName ; private String cartagoRole ; private String artName ; private int gW , gH ; private Cow [ ] cows ; public CCowModel ( String end , String wpsName , String cartagoRole , String artName , String agName ) { this . end = end ; this . wpsName = wpsName ; this . cartagoRole = cartagoRole ; this . artName = artName ; cred = new UserIdCredential ( agName ) ; try { cWps = CartagoService . joinWorkspace ( this . wpsName , this . end , this . cartagoRole , cred ) ; cArt = cWps . lookupArtifact ( this . artName , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; e . printStackTrace ( ) ; } } public synchronized void reset ( ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" ) , null , null , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } logger . info ( "<STR_LIT>" ) ; } public synchronized void setSize ( int w , int h ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , w , h ) , null , null , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } logger . info ( "<STR_LIT>" + w + "<STR_LIT:U+002CU+0020>" + h ) ; } public void freePos ( int x , int y ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , x , y ) , null , null , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } } public void insertCow ( int id , int x , int y , int step ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , id , x , y , step ) , null , null , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } } public void updateCows ( ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" ) , null , null , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } try { gH = cWps . observeProperty ( cArt , "<STR_LIT>" ) . intValue ( ) ; gW = cWps . observeProperty ( cArt , "<STR_LIT>" ) . intValue ( ) ; cows = ( Cow [ ] ) ( cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } } public Cow [ ] getCows ( ) { return cows ; } public int getSizeh ( ) { return gH ; } public int getSizew ( ) { return gW ; } } </s>
|
<s> package env ; import java . util . logging . Logger ; import java . util . HashMap ; import java . util . Map ; import java . util . Iterator ; import java . util . Collections ; import jason . environment . grid . Location ; import alice . cartago . * ; public class CowModelArtifact extends Artifact { CowModel cModel = new CowModel ( ) ; @ OPERATION void init ( ) { cModel . reset ( ) ; defineObsProperty ( "<STR_LIT>" , cModel . getCows ( ) ) ; defineObsProperty ( "<STR_LIT>" , cModel . getSizeh ( ) ) ; defineObsProperty ( "<STR_LIT>" , cModel . getSizew ( ) ) ; } @ OPERATION void cInsertCow ( int id , int x , int y , int step ) { cModel . insertCow ( id , x , y , step ) ; } @ OPERATION void cFreePos ( int x , int y ) { cModel . freePos ( x , y ) ; } @ OPERATION void cSetSize ( int w , int h ) { cModel . setSize ( w , h ) ; } @ OPERATION void updateProperty ( ) { updateObsProperty ( "<STR_LIT>" , cModel . getCows ( ) ) ; updateObsProperty ( "<STR_LIT>" , cModel . getSizeh ( ) ) ; updateObsProperty ( "<STR_LIT>" , cModel . getSizew ( ) ) ; } } </s>
|
<s> package env ; import jason . environment . grid . Area ; import jason . environment . grid . GridWorldModel ; import jason . environment . grid . Location ; import java . util . logging . Logger ; public class WorldModel extends GridWorldModel { public static final int COW = <NUM_LIT:16> ; public static final int CORRAL = <NUM_LIT:32> ; public static final int ENEMY = <NUM_LIT> ; public static final int TARGET = <NUM_LIT> ; public static final int FORPLACE = <NUM_LIT> ; public static final int ENEMYCORRAL = <NUM_LIT> ; public static final int SWITCH = <NUM_LIT> ; public static final int OPEN_FENCE = <NUM_LIT> ; public static final int CLOSED_FENCE = <NUM_LIT> ; public static final int FENCE = OPEN_FENCE + CLOSED_FENCE ; public static final int nbActions = <NUM_LIT:8> ; public static final int agsByTeam = <NUM_LIT:10> ; public int agPerceptionRatio = <NUM_LIT:8> ; public static final int cowPerceptionRatio = <NUM_LIT:4> ; double PSim = <NUM_LIT> ; double PMax = <NUM_LIT> ; Area corral ; int cowsBlue = <NUM_LIT:0> ; int cowsRed = <NUM_LIT:0> ; int initialNbCows = <NUM_LIT:0> ; int maxSteps = <NUM_LIT:0> ; String opponent ; private Logger logger = Logger . getLogger ( "<STR_LIT>" + WorldModel . class . getName ( ) ) ; public enum Move { north , south , east , west , northeast , southeast , northwest , southwest , skip } ; public static WorldModel create ( int w , int h , int nbAg ) { return new WorldModel ( w , h , nbAg ) ; } public WorldModel ( int w , int h , int nbAg ) { super ( w , h , nbAg ) ; } public int getAgsByTeam ( ) { return agsByTeam ; } private static final int OBS_FOR_NOT_FREE = ENEMY + AGENT + COW + CORRAL + ENEMYCORRAL ; @ Override public boolean isFree ( int x , int y ) { return super . isFree ( x , y ) && ! hasObject ( OBS_FOR_NOT_FREE , x , y ) ; } public WorldView getView ( ) { return ( WorldView ) view ; } public int getData ( Location l ) { return data [ l . x ] [ l . y ] ; } public void setCorral ( Location upperLeft , Location downRight ) { for ( int l = upperLeft . y ; l <= downRight . y ; l ++ ) for ( int c = upperLeft . x ; c <= downRight . x ; c ++ ) { data [ c ] [ l ] = CORRAL ; } corral = new Area ( upperLeft , downRight ) ; } public Area getCorral ( ) { return corral ; } public int getCowsBlue ( ) { return cowsBlue ; } public int getCowsRed ( ) { return cowsRed ; } public void setCowsBlue ( int c ) { cowsBlue = c ; } public void setCowsRed ( int c ) { cowsRed = c ; } public void setOpponent ( String o ) { opponent = o ; } public String getOpponent ( ) { return opponent ; } public void setPSim ( double psim ) { PSim = psim ; } public void setPMax ( double pmax ) { PMax = pmax ; } public void setMaxSteps ( int s ) { maxSteps = s ; } public int getMaxSteps ( ) { return maxSteps ; } public void setAgPerceptionRatio ( int ratio ) { agPerceptionRatio = ratio ; } public int getAgPerceptionRatio ( ) { return agPerceptionRatio ; } public void removeAll ( int obj ) { for ( int i = <NUM_LIT:0> ; i < width ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < height ; j ++ ) { if ( hasObject ( obj , i , j ) ) remove ( obj , i , j ) ; } } } synchronized public boolean move ( Move dir , int ag ) throws Exception { if ( ag < <NUM_LIT:0> ) { logger . warning ( "<STR_LIT>" ) ; return false ; } Location l = getAgPos ( ag ) ; if ( l == null ) { logger . warning ( "<STR_LIT>" + ( ag + <NUM_LIT:1> ) + "<STR_LIT:!>" + this ) ; return false ; } Location n = null ; switch ( dir ) { case north : n = new Location ( l . x , l . y - <NUM_LIT:1> ) ; break ; case south : n = new Location ( l . x , l . y + <NUM_LIT:1> ) ; break ; case east : n = new Location ( l . x + <NUM_LIT:1> , l . y ) ; break ; case west : n = new Location ( l . x - <NUM_LIT:1> , l . y ) ; break ; } if ( n != null && canMoveTo ( ag , n ) ) { if ( ! hasObject ( AGENT , n ) || move ( dir , getAgAtPos ( n ) ) ) { setAgPos ( ag , n ) ; return true ; } } return false ; } private boolean canMoveTo ( int ag , Location l ) { return isFreeOfObstacle ( l ) ; } public void wall ( int x1 , int y1 , int x2 , int y2 ) { for ( int i = x1 ; i <= x2 ; i ++ ) { for ( int j = y1 ; j <= y2 ; j ++ ) { add ( OBSTACLE , i , j ) ; ; } } } public String toString ( ) { StringBuilder s = new StringBuilder ( "<STR_LIT:|>" ) ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) { s . append ( '<CHAR_LIT:->' ) ; } s . append ( "<STR_LIT>" ) ; String bar = s . toString ( ) ; for ( int j = <NUM_LIT:0> ; j < getHeight ( ) ; j ++ ) { s . append ( '<CHAR_LIT>' ) ; for ( int i = <NUM_LIT:0> ; i < getWidth ( ) ; i ++ ) { if ( hasObject ( OBSTACLE , i , j ) ) { s . append ( '<CHAR_LIT>' ) ; } else if ( hasObject ( AGENT , i , j ) ) { s . append ( String . valueOf ( getAgAtPos ( i , j ) ) ) ; } else if ( hasObject ( COW , i , j ) ) { s . append ( '<CHAR_LIT:c>' ) ; } else if ( hasObject ( ENEMY , i , j ) ) { s . append ( '<CHAR_LIT>' ) ; } else if ( hasObject ( OPEN_FENCE , i , j ) ) { s . append ( '<CHAR_LIT>' ) ; } else if ( hasObject ( CLOSED_FENCE , i , j ) ) { s . append ( '<CHAR_LIT>' ) ; } else if ( hasObject ( SWITCH , i , j ) ) { s . append ( '<CHAR_LIT>' ) ; } else { s . append ( '<CHAR_LIT:U+0020>' ) ; } } s . append ( "<STR_LIT>" ) ; } s . append ( bar ) ; return s . toString ( ) ; } public static Location getNewLocationForAction ( Location pos , WorldModel . Move action ) { switch ( action ) { case west : return new Location ( pos . x - <NUM_LIT:1> , pos . y ) ; case east : return new Location ( pos . x + <NUM_LIT:1> , pos . y ) ; case north : return new Location ( pos . x , pos . y - <NUM_LIT:1> ) ; case northeast : return new Location ( pos . x + <NUM_LIT:1> , pos . y - <NUM_LIT:1> ) ; case northwest : return new Location ( pos . x - <NUM_LIT:1> , pos . y - <NUM_LIT:1> ) ; case south : return new Location ( pos . x , pos . y + <NUM_LIT:1> ) ; case southeast : return new Location ( pos . x + <NUM_LIT:1> , pos . y + <NUM_LIT:1> ) ; case southwest : return new Location ( pos . x - <NUM_LIT:1> , pos . y + <NUM_LIT:1> ) ; } return null ; } public static int stringToObject ( String o ) { if ( o . equals ( "<STR_LIT>" ) ) return CLOSED_FENCE ; else if ( o . equals ( "<STR_LIT>" ) ) return OPEN_FENCE ; return - <NUM_LIT:1> ; } } </s>
|
<s> package env ; import java . util . logging . Logger ; import java . io . Serializable ; public class Cow implements Serializable { private static final long serialVersionUID = <NUM_LIT> ; public int id ; public int x , y ; public int step ; public int clId ; public Cow ( int id , int x , int y , int step ) { this . id = id ; this . x = x ; this . y = y ; this . step = step ; this . clId = - <NUM_LIT:1> ; } public Cow ( int id , int x , int y ) { this ( id , x , y , <NUM_LIT:0> ) ; } } </s>
|
<s> package env ; import java . io . File ; import java . util . ArrayList ; import java . util . Collections ; import java . util . List ; import java . util . NoSuchElementException ; import java . util . logging . Logger ; import javax . xml . parsers . DocumentBuilder ; import javax . xml . parsers . DocumentBuilderFactory ; import org . w3c . dom . Document ; import org . w3c . dom . Element ; import org . w3c . dom . NodeList ; import org . xml . sax . SAXParseException ; public class ACViewer extends Thread { private static Logger logger = Logger . getLogger ( ACViewer . class . getName ( ) ) ; WorldModel model = null ; WorldView view = null ; DocumentBuilder builder = null ; File massimServerBackupDir ; public ACViewer ( String massimBackDir , int w , int h ) { massimServerBackupDir = new File ( massimBackDir ) ; model = new WorldModel ( w , h , WorldModel . agsByTeam * <NUM_LIT:2> ) ; view = new WorldView ( "<STR_LIT>" , model ) ; model . setView ( view ) ; } File getLastFile ( File dir ) { if ( dir != null ) { File [ ] afiles = dir . listFiles ( ) ; if ( afiles != null && afiles . length > <NUM_LIT:0> ) { List < File > lfiles = new ArrayList < File > ( ) ; for ( File f : dir . listFiles ( ) ) { lfiles . add ( f ) ; } return Collections . max ( lfiles ) ; } else { logger . info ( "<STR_LIT>" + dir ) ; } } return null ; } void updateWorld ( File f ) throws Exception { if ( builder == null ) { builder = DocumentBuilderFactory . newInstance ( ) . newDocumentBuilder ( ) ; } Document doc = builder . parse ( f ) ; Element simulation = ( Element ) doc . getElementsByTagName ( "<STR_LIT>" ) . item ( <NUM_LIT:0> ) ; view . setCycle ( Integer . parseInt ( simulation . getAttribute ( "<STR_LIT>" ) ) ) ; Element team = ( Element ) simulation . getElementsByTagName ( "<STR_LIT>" ) . item ( <NUM_LIT:0> ) ; model . setCowsBlue ( Integer . parseInt ( team . getAttribute ( "<STR_LIT>" ) ) ) ; team = ( Element ) simulation . getElementsByTagName ( "<STR_LIT>" ) . item ( <NUM_LIT:0> ) ; model . setCowsRed ( Integer . parseInt ( team . getAttribute ( "<STR_LIT>" ) ) ) ; clearModel ( ) ; NodeList cows = simulation . getElementsByTagName ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < cows . getLength ( ) ; i ++ ) { Element cow = ( Element ) cows . item ( i ) ; int x = Integer . parseInt ( cow . getAttribute ( "<STR_LIT>" ) ) ; int y = Integer . parseInt ( cow . getAttribute ( "<STR_LIT>" ) ) ; model . add ( WorldModel . COW , x , y ) ; } NodeList ags = simulation . getElementsByTagName ( "<STR_LIT>" ) ; for ( int i = <NUM_LIT:0> ; i < ags . getLength ( ) ; i ++ ) { Element ag = ( Element ) ags . item ( i ) ; int x = Integer . parseInt ( ag . getAttribute ( "<STR_LIT>" ) ) ; int y = Integer . parseInt ( ag . getAttribute ( "<STR_LIT>" ) ) ; if ( ag . getAttribute ( "<STR_LIT>" ) . equals ( "<STR_LIT>" ) ) { model . add ( WorldModel . AGENT , x , y ) ; } else { model . add ( WorldModel . ENEMY , x , y ) ; } } } void clearModel ( ) { for ( int i = <NUM_LIT:0> ; i < model . getWidth ( ) ; i ++ ) { for ( int j = <NUM_LIT:0> ; j < model . getHeight ( ) ; j ++ ) { if ( model . hasObject ( WorldModel . AGENT , i , j ) || model . hasObject ( WorldModel . COW , i , j ) || model . hasObject ( WorldModel . ENEMY , i , j ) ) { model . set ( WorldModel . CLEAN , i , j ) ; } } } } public void addObject ( int object , int x , int y ) { model . add ( object , x , y ) ; } public WorldModel getModel ( ) { return model ; } public void finish ( ) { view . dispose ( ) ; this . interrupt ( ) ; } public void run ( ) { while ( true ) { try { sleep ( <NUM_LIT> ) ; File lastFile = getLastFile ( getLastFile ( massimServerBackupDir ) ) ; if ( lastFile != null ) { logger . info ( "<STR_LIT>" + lastFile ) ; updateWorld ( lastFile ) ; } } catch ( InterruptedException e ) { return ; } catch ( NoSuchElementException e ) { } catch ( SAXParseException e ) { } catch ( Exception e ) { e . printStackTrace ( ) ; } } } public static void main ( String [ ] args ) { new ACViewer ( "<STR_LIT>" , <NUM_LIT> , <NUM_LIT> ) . start ( ) ; } } </s>
|
<s> package env ; import jia . Vec ; import java . util . Map ; public interface IClusterModel { public void setCows ( Cow [ ] c , int H , int W ) ; public void update ( ) ; public int [ ] getAlloc ( ) ; public Vec [ ] getCenters ( ) ; public int [ ] [ ] getData ( ) ; public int [ ] getMap ( ) ; public int [ ] getMaxDist ( ) ; public int getNumberOfCluster ( ) ; public int [ ] getNumCows ( ) ; public void insertTree ( int x , int y ) ; public void setStepcl ( int step ) ; public void changeClusterer ( int clusterer ) ; public void changeMaxDist ( int a ) ; public void changeWCprop ( int radius , int nCows ) ; public int getPrefRadius ( ) ; public int getPrefNCows ( ) ; public void changePTCprop ( int k ) ; public double getPrefkPTC ( ) ; } </s>
|
<s> package env ; public class ClusterModelFactory { static private IClusterModel clModel ; static public boolean centralized = true ; private static String end = "<STR_LIT>" ; private static String wpsName = "<STR_LIT>" ; private static String cartagoRole = "<STR_LIT>" ; private static String artName = "<STR_LIT>" ; private static ClusterModel clModelC = null ; public static IClusterModel getModel ( String agName ) { if ( centralized ) { synchronized ( ClusterModelFactory . class ) { if ( clModel == null ) return clModel = new ClusterModel ( ) ; else return clModel ; } } else { try { Thread . sleep ( <NUM_LIT:3> ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } return new CClusterModel ( end , wpsName , cartagoRole , artName , agName + "<STR_LIT>" + System . currentTimeMillis ( ) ) ; } } public static ClusterModel getModelCent ( ) { synchronized ( ClusterModelFactory . class ) { if ( clModelC == null ) return clModelC = new ClusterModel ( ) ; else return clModelC ; } } } </s>
|
<s> package env ; import jason . environment . grid . GridWorldView ; import java . awt . BorderLayout ; import java . awt . Color ; import java . awt . FlowLayout ; import java . awt . Graphics ; import java . awt . event . MouseEvent ; import java . awt . event . MouseMotionListener ; import java . util . Map ; import javax . swing . BorderFactory ; import javax . swing . BoxLayout ; import javax . swing . JLabel ; import javax . swing . JPanel ; public class WorldView extends GridWorldView { private static final long serialVersionUID = <NUM_LIT:1L> ; JLabel jCycle ; JLabel jCowsC ; JLabel jlMouseLoc ; IClusterModel Cl = ClusterModelFactory . getModel ( "<STR_LIT>" ) ; ICowModel Cm = CowModelFactory . getModel ( "<STR_LIT>" ) ; public void destroy ( ) { setVisible ( false ) ; } public WorldView ( WorldModel model , int windowSize ) { this ( "<STR_LIT>" , model , windowSize ) ; } public WorldView ( String title , WorldModel model ) { this ( title , model , <NUM_LIT> ) ; } public WorldView ( String title , WorldModel model , int windowSize ) { super ( model , title , windowSize ) ; setVisible ( true ) ; repaint ( ) ; } @ Override public void initComponents ( int width ) { super . initComponents ( width ) ; JPanel args = new JPanel ( ) ; args . setLayout ( new BoxLayout ( args , BoxLayout . Y_AXIS ) ) ; JPanel msg = new JPanel ( ) ; msg . setLayout ( new BoxLayout ( msg , BoxLayout . Y_AXIS ) ) ; msg . setBorder ( BorderFactory . createEtchedBorder ( ) ) ; JPanel pmoise = new JPanel ( new FlowLayout ( FlowLayout . CENTER ) ) ; jlMouseLoc = new JLabel ( "<STR_LIT>" ) ; pmoise . add ( jlMouseLoc ) ; pmoise . setBorder ( BorderFactory . createEtchedBorder ( ) ) ; JPanel p = new JPanel ( new FlowLayout ( FlowLayout . CENTER ) ) ; p . add ( new JLabel ( "<STR_LIT>" ) ) ; jCycle = new JLabel ( "<STR_LIT:0>" ) ; p . add ( jCycle ) ; p . add ( new JLabel ( "<STR_LIT>" ) ) ; jCowsC = new JLabel ( "<STR_LIT:0>" ) ; p . add ( jCowsC ) ; msg . add ( p ) ; JPanel s = new JPanel ( new BorderLayout ( ) ) ; s . add ( BorderLayout . WEST , args ) ; s . add ( BorderLayout . CENTER , msg ) ; s . add ( BorderLayout . EAST , pmoise ) ; getContentPane ( ) . add ( BorderLayout . SOUTH , s ) ; getCanvas ( ) . addMouseMotionListener ( new MouseMotionListener ( ) { public void mouseDragged ( MouseEvent e ) { } public void mouseMoved ( MouseEvent e ) { int col = e . getX ( ) / cellSizeW ; int lin = e . getY ( ) / cellSizeH ; if ( col >= <NUM_LIT:0> && lin >= <NUM_LIT:0> && col < getModel ( ) . getWidth ( ) && lin < getModel ( ) . getHeight ( ) ) { String desc ; desc = "<STR_LIT>" + col + "<STR_LIT:U+002C>" + lin ; int ag = model . getAgAtPos ( col , lin ) ; if ( ag ++ >= <NUM_LIT:0> ) desc = "<STR_LIT>" + ag + "<STR_LIT:;U+0020>" + desc ; jlMouseLoc . setText ( desc ) ; } } } ) ; } public void setCycle ( int c ) { Cm . updateCows ( ) ; if ( jCycle != null ) { WorldModel wm = ( WorldModel ) model ; String steps = "<STR_LIT>" ; if ( wm . getMaxSteps ( ) > <NUM_LIT:0> ) { steps = "<STR_LIT:/>" + wm . getMaxSteps ( ) ; } jCycle . setText ( c + steps ) ; jCowsC . setText ( wm . getCowsBlue ( ) + "<STR_LIT>" + wm . getCowsRed ( ) ) ; } } @ Override public void draw ( Graphics g , int x , int y , int object ) { switch ( object ) { case WorldModel . CORRAL : drawCorral ( g , x , y ) ; break ; case WorldModel . COW : drawCow ( g , x , y ) ; break ; case WorldModel . ENEMY : drawEnemy ( g , x , y ) ; break ; case WorldModel . TARGET : drawTarget ( g , x , y ) ; break ; case WorldModel . FORPLACE : drawFormPlace ( g , x , y ) ; break ; case WorldModel . SWITCH : drawSwhitch ( g , x , y ) ; break ; case WorldModel . OPEN_FENCE : drawFence ( g , x , y , false ) ; break ; case WorldModel . CLOSED_FENCE : drawFence ( g , x , y , true ) ; break ; } } @ Override public void drawAgent ( Graphics g , int x , int y , Color c , int id ) { g . setColor ( c ) ; g . fillOval ( x * cellSizeW + <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> , cellSizeW - <NUM_LIT:4> , cellSizeH - <NUM_LIT:4> ) ; } public void drawCorral ( Graphics g , int x , int y ) { g . setColor ( Color . gray ) ; g . fillRect ( x * cellSizeW , y * cellSizeH , cellSizeW , cellSizeH ) ; g . setColor ( Color . pink ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> , cellSizeW - <NUM_LIT:4> , cellSizeH - <NUM_LIT:4> ) ; g . drawLine ( x * cellSizeW + <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> , ( x + <NUM_LIT:1> ) * cellSizeW - <NUM_LIT:2> , ( y + <NUM_LIT:1> ) * cellSizeH - <NUM_LIT:2> ) ; g . drawLine ( x * cellSizeW + <NUM_LIT:2> , ( y + <NUM_LIT:1> ) * cellSizeH - <NUM_LIT:2> , ( x + <NUM_LIT:1> ) * cellSizeW - <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> ) ; } public void drawTarget ( Graphics g , int x , int y ) { g . setColor ( Color . darkGray ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> , cellSizeW - <NUM_LIT:4> , cellSizeH - <NUM_LIT:4> ) ; g . setColor ( Color . white ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:3> , y * cellSizeH + <NUM_LIT:3> , cellSizeW - <NUM_LIT:6> , cellSizeH - <NUM_LIT:6> ) ; g . setColor ( Color . darkGray ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:4> , y * cellSizeH + <NUM_LIT:4> , cellSizeW - <NUM_LIT:8> , cellSizeH - <NUM_LIT:8> ) ; } public void drawFormPlace ( Graphics g , int x , int y ) { g . setColor ( Color . green ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> , cellSizeW - <NUM_LIT:4> , cellSizeH - <NUM_LIT:4> ) ; g . setColor ( Color . lightGray ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:3> , y * cellSizeH + <NUM_LIT:3> , cellSizeW - <NUM_LIT:6> , cellSizeH - <NUM_LIT:6> ) ; g . setColor ( Color . gray ) ; g . drawRect ( x * cellSizeW + <NUM_LIT:4> , y * cellSizeH + <NUM_LIT:4> , cellSizeW - <NUM_LIT:8> , cellSizeH - <NUM_LIT:8> ) ; } public void drawCow ( Graphics g , int x , int y ) { int [ ] alloc = Cl . getMap ( ) ; Cow [ ] c = Cm . getCows ( ) ; int id = - <NUM_LIT:1> ; Color [ ] C = new Color [ <NUM_LIT:6> ] ; C [ <NUM_LIT:0> ] = Color . green ; C [ <NUM_LIT:1> ] = Color . yellow ; C [ <NUM_LIT:2> ] = Color . gray ; C [ <NUM_LIT:3> ] = Color . white ; C [ <NUM_LIT:4> ] = Color . blue ; C [ <NUM_LIT:5> ] = Color . cyan ; for ( int i = <NUM_LIT:0> ; i < c . length ; i ++ ) { if ( c [ i ] == null ) { continue ; } if ( x == c [ i ] . x && y == c [ i ] . y ) { id = c [ i ] . id ; break ; } } int tmp ; if ( id != - <NUM_LIT:1> ) { tmp = alloc [ id ] ; } else { tmp = - <NUM_LIT:1> ; } id = ( int ) tmp ; if ( id < <NUM_LIT:0> || id > <NUM_LIT:4> ) { id = <NUM_LIT:5> ; } g . setColor ( C [ id ] ) ; g . fillRect ( x * cellSizeW + <NUM_LIT:1> , y * cellSizeH + <NUM_LIT:1> , cellSizeW - <NUM_LIT:1> , cellSizeH - <NUM_LIT:1> ) ; } public void drawEnemy ( Graphics g , int x , int y ) { int gw = <NUM_LIT:1> ; g . setColor ( Color . red ) ; g . fillOval ( x * cellSizeW + gw , y * cellSizeH + gw , cellSizeW - gw * <NUM_LIT:2> , cellSizeH - gw * <NUM_LIT:2> ) ; } private void drawFence ( Graphics g , int x , int y , boolean closed ) { g . setColor ( Color . yellow ) ; g . fillRect ( x * cellSizeW , y * cellSizeH , cellSizeW , cellSizeH ) ; if ( closed ) { if ( model . hasObject ( WorldModel . OBSTACLE , x , y ) ) g . setColor ( Color . black ) ; else g . setColor ( Color . red ) ; g . drawLine ( x * cellSizeW + <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> , ( x + <NUM_LIT:1> ) * cellSizeW - <NUM_LIT:2> , ( y + <NUM_LIT:1> ) * cellSizeH - <NUM_LIT:2> ) ; g . drawLine ( x * cellSizeW + <NUM_LIT:2> , ( y + <NUM_LIT:1> ) * cellSizeH - <NUM_LIT:2> , ( x + <NUM_LIT:1> ) * cellSizeW - <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> ) ; } else { if ( model . hasObject ( WorldModel . OBSTACLE , x , y ) ) g . setColor ( Color . black ) ; else g . setColor ( Color . green ) ; g . drawLine ( x * cellSizeW + <NUM_LIT:2> , ( y * cellSizeH ) + ( cellSizeH / <NUM_LIT:2> ) , ( x + <NUM_LIT:1> ) * cellSizeW - <NUM_LIT:2> , ( y * cellSizeH ) + ( cellSizeH / <NUM_LIT:2> ) ) ; } } private void drawSwhitch ( Graphics g , int x , int y ) { g . setColor ( Color . yellow ) ; g . fillRect ( x * cellSizeW , y * cellSizeH , cellSizeW , cellSizeH ) ; g . setColor ( Color . black ) ; g . drawLine ( x * cellSizeW + <NUM_LIT:2> , ( y + <NUM_LIT:1> ) * cellSizeH - <NUM_LIT:2> , ( x + <NUM_LIT:1> ) * cellSizeW - <NUM_LIT:2> , y * cellSizeH + <NUM_LIT:2> ) ; } } </s>
|
<s> package env ; import java . util . Map ; import java . util . Vector ; import java . util . List ; import java . util . logging . Logger ; import alice . cartago . ArtifactId ; import alice . cartago . CartagoException ; import alice . cartago . CartagoService ; import alice . cartago . ICartagoContext ; import alice . cartago . Op ; import alice . cartago . security . UserCredential ; import alice . cartago . security . UserIdCredential ; import jia . Vec ; public class CClusterModel implements IClusterModel , Runnable { private Logger logger = Logger . getLogger ( ClusterModel . class . getName ( ) ) ; private UserCredential cred ; private ICartagoContext cWps ; private ArtifactId cArt ; private String end ; private String wpsName ; private String cartagoRole ; private String artName ; private static class buffer { public int actStep = - <NUM_LIT:1> ; public int clStep ; public int [ ] alloc ; public Vec [ ] Centers ; public int [ ] [ ] data ; public int [ ] map = new int [ <NUM_LIT:1000> ] ; public int [ ] maxDist ; public int [ ] numCows ; public int numberOfCows ; public int prefNCows ; public int prefRadius ; public double prefkPTC ; public ICowModel cowModel = CowModelFactory . getModel ( "<STR_LIT>" ) ; } public static buffer bf = new buffer ( ) ; public void update ( ) { this . run ( ) ; try { int i = <NUM_LIT:0> ; cWps . use ( null , cArt , new Op ( "<STR_LIT>" ) , null , null , - <NUM_LIT:1> ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . alloc = ( int [ ] ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . Centers = ( Vec [ ] ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . data = ( int [ ] [ ] ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . map = ( int [ ] ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . maxDist = ( int [ ] ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . numCows = ( int [ ] ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . numberOfCows = ( Integer ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . prefNCows = ( Integer ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . prefRadius = ( Integer ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; bf . prefkPTC = ( Double ) cWps . observeProperty ( cArt , "<STR_LIT>" ) . getValue ( ) ; logger . info ( "<STR_LIT>" + ( i ++ ) ) ; logger . info ( "<STR_LIT>" + bf . prefkPTC ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } public CClusterModel ( String end , String wpsName , String cartagoRole , String artName , String agName ) { this . end = end ; this . wpsName = wpsName ; this . cartagoRole = cartagoRole ; this . artName = artName ; cred = new UserIdCredential ( agName ) ; try { cWps = CartagoService . joinWorkspace ( this . wpsName , this . end , this . cartagoRole , cred ) ; cArt = cWps . lookupArtifact ( this . artName , - <NUM_LIT:1> ) ; } catch ( Exception e ) { logger . severe ( "<STR_LIT>" + e ) ; } try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public int [ ] getAlloc ( ) { return bf . alloc ; } public Vec [ ] getCenters ( ) { return bf . Centers ; } public int [ ] [ ] getData ( ) { return bf . data ; } public int [ ] getMap ( ) { return bf . map . clone ( ) ; } public int [ ] getMaxDist ( ) { return bf . maxDist ; } public int [ ] getNumCows ( ) { return bf . numCows ; } public int getNumberOfCluster ( ) { return bf . numberOfCows ; } public synchronized void insertTree ( int x , int y ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , x , y ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public void setStepcl ( int step ) { if ( step > bf . clStep ) bf . clStep = step ; try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , step ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public void run ( ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , bf . cowModel . getCows ( ) , bf . cowModel . getSizeh ( ) , bf . cowModel . getSizew ( ) ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } if ( bf . actStep < bf . clStep ) { bf . actStep = bf . clStep ; try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } update ( ) ; } } public void changeClusterer ( int a ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , a ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public void changeMaxDist ( int a ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , a ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public void changePTCprop ( int k ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , k ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public void changeWCprop ( int radius , int nCows ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , radius , nCows ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } public int getPrefNCows ( ) { return bf . prefNCows ; } public int getPrefRadius ( ) { return bf . prefRadius ; } public double getPrefkPTC ( ) { return bf . prefkPTC ; } public void setCows ( Cow [ ] c , int H , int W ) { try { cWps . use ( null , cArt , new Op ( "<STR_LIT>" , c , H , W ) , null , null , - <NUM_LIT:1> ) ; } catch ( CartagoException e ) { e . printStackTrace ( ) ; } catch ( InterruptedException e ) { e . printStackTrace ( ) ; } } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . action ; import java . util . List ; import org . jboss . hibernateUniversity . criteria . domain . User ; import org . jboss . weld . environment . se . Weld ; import org . jboss . weld . environment . se . WeldContainer ; import org . junit . Test ; public class UserManagerTest { @ Test public void testUserCreation ( ) { final Weld weld = new Weld ( ) ; WeldContainer weldContainer = weld . initialize ( ) ; final UserManager userManager = weldContainer . instance ( ) . select ( UserManager . class ) . get ( ) ; userManager . createNewUsers ( ) ; weld . shutdown ( ) ; } @ Test public void testQueries ( ) { final Weld weld = new Weld ( ) ; WeldContainer weldContainer = weld . initialize ( ) ; final UserManager userManager = weldContainer . instance ( ) . select ( UserManager . class ) . get ( ) ; final List < ? > users = userManager . getUsersBetween30And40 ( ) ; for ( Object o : users ) { System . err . println ( o . toString ( ) ) ; } weld . shutdown ( ) ; } @ Test public void testAvgQuery ( ) { final Weld weld = new Weld ( ) ; WeldContainer weldContainer = weld . initialize ( ) ; final UserManager userManager = weldContainer . instance ( ) . select ( UserManager . class ) . get ( ) ; userManager . displayAvgCreditByGender ( ) ; weld . shutdown ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . enterprise . inject . Disposes ; import javax . enterprise . inject . Produces ; import javax . inject . Singleton ; import javax . persistence . EntityManagerFactory ; import javax . persistence . Persistence ; public class EMFProvider { @ Produces @ Singleton public EntityManagerFactory createEMF ( ) { return Persistence . createEntityManagerFactory ( "<STR_LIT>" ) ; } public void close ( @ Disposes EntityManagerFactory factory ) { factory . close ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import java . lang . annotation . Retention ; import java . lang . annotation . Target ; import javax . interceptor . InterceptorBinding ; import static java . lang . annotation . ElementType . * ; import static java . lang . annotation . RetentionPolicy . * ; @ InterceptorBinding @ Target ( { METHOD , TYPE } ) @ Retention ( RUNTIME ) public @ interface Transactional { } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . enterprise . context . Dependent ; import javax . enterprise . inject . Produces ; import javax . inject . Inject ; import javax . inject . Singleton ; import javax . persistence . EntityManager ; import javax . persistence . EntityManagerFactory ; @ Singleton public class TransactionManager { @ Inject private EntityManagerFactory factory ; private ThreadLocal < EntityManager > emHolder = new ThreadLocal < EntityManager > ( ) ; public void begin ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { entityManager = factory . createEntityManager ( ) ; entityManager . getTransaction ( ) . begin ( ) ; emHolder . set ( entityManager ) ; } else { throw new RuntimeException ( "<STR_LIT>" ) ; } } @ Produces @ Dependent public EntityManager getEntityManager ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } else { return entityManager ; } } public void commit ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } else { entityManager . getTransaction ( ) . commit ( ) ; entityManager . close ( ) ; emHolder . set ( null ) ; } } public void rollback ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } else { entityManager . getTransaction ( ) . rollback ( ) ; entityManager . close ( ) ; emHolder . set ( null ) ; } } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . inject . Inject ; import javax . interceptor . AroundInvoke ; import javax . interceptor . Interceptor ; import javax . interceptor . InvocationContext ; @ Transactional @ Interceptor public class TransactionInterceptor { @ Inject TransactionManager manager ; @ AroundInvoke public Object manageTransaction ( InvocationContext ctx ) throws Exception { manager . begin ( ) ; try { final Object result = ctx . proceed ( ) ; manager . commit ( ) ; return result ; } catch ( Exception e ) { manager . rollback ( ) ; throw e ; } } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . ManyToOne ; @ Entity public class Address { public Address ( ) { } public Address ( String street , String city , String zipCode , User owner ) { this . street = street ; this . city = city ; this . zipCode = zipCode ; this . owner = owner ; owner . getAddresses ( ) . add ( this ) ; } @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } private Long id ; public String getStreet ( ) { return street ; } public void setStreet ( String street ) { this . street = street ; } private String street ; public String getCity ( ) { return city ; } public void setCity ( String city ) { this . city = city ; } private String city ; public String getZipCode ( ) { return zipCode ; } public void setZipCode ( String zipCode ) { this . zipCode = zipCode ; } private String zipCode ; @ ManyToOne public User getOwner ( ) { return owner ; } public void setOwner ( User owner ) { this . owner = owner ; } private User owner ; @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) ; sb . append ( "<STR_LIT>" ) . append ( id ) ; sb . append ( "<STR_LIT>" ) . append ( street ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( city ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( zipCode ) . append ( '<STR_LIT>' ) ; sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; public enum Gender { MALE , FEMALE , NOT_SURE } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import javax . persistence . Embeddable ; @ Embeddable public class Login { public Login ( ) { } public Login ( String username , String password ) { this . username = username ; this . password = password ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } private String username ; public String getPassword ( ) { return password ; } public void setPassword ( String password ) { this . password = password ; } private String password ; @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) ; sb . append ( "<STR_LIT>" ) . append ( username ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( password ) . append ( '<STR_LIT>' ) ; sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import java . util . Date ; import java . util . HashSet ; import java . util . Set ; import javax . persistence . CascadeType ; import javax . persistence . Entity ; import javax . persistence . EnumType ; import javax . persistence . Enumerated ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . OneToMany ; import javax . persistence . Persistence ; import javax . persistence . Temporal ; import javax . persistence . TemporalType ; @ Entity public class User { public User ( ) { } public User ( String firstName , String lastName , Date birthDate , Gender gender , int credits , String username , String password ) { this . firstName = firstName ; this . lastName = lastName ; this . birthDate = birthDate ; this . gender = gender ; this . credits = credits ; this . login = new Login ( username , password ) ; } @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } private Long id ; public String getFirstName ( ) { return firstName ; } public void setFirstName ( String firstName ) { this . firstName = firstName ; } private String firstName ; public String getLastName ( ) { return lastName ; } public void setLastName ( String lastName ) { this . lastName = lastName ; } private String lastName ; @ OneToMany ( cascade = CascadeType . PERSIST , mappedBy = "<STR_LIT>" ) public Set < Address > getAddresses ( ) { return addresses ; } public void setAddresses ( Set < Address > addresses ) { this . addresses = addresses ; } private Set < Address > addresses = new HashSet < Address > ( ) ; @ Temporal ( TemporalType . DATE ) public Date getBirthDate ( ) { return birthDate ; } public void setBirthDate ( Date birthDate ) { this . birthDate = birthDate ; } private Date birthDate ; @ Enumerated ( EnumType . STRING ) public Gender getGender ( ) { return gender ; } public void setGender ( Gender gender ) { this . gender = gender ; } private Gender gender ; public int getCredits ( ) { return credits ; } public void setCredits ( int credits ) { this . credits = credits ; } private int credits ; public Login getLogin ( ) { return login ; } public void setLogin ( Login login ) { this . login = login ; } private Login login ; @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) ; sb . append ( "<STR_LIT>" ) . append ( id ) ; sb . append ( "<STR_LIT>" ) . append ( firstName ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( lastName ) . append ( '<STR_LIT>' ) ; if ( Persistence . getPersistenceUtil ( ) . isLoaded ( this , "<STR_LIT>" ) ) { sb . append ( "<STR_LIT>" ) . append ( addresses ) ; } else { sb . append ( "<STR_LIT>" ) . append ( "<STR_LIT>" ) ; } sb . append ( "<STR_LIT>" ) . append ( birthDate ) ; sb . append ( "<STR_LIT>" ) . append ( gender ) ; sb . append ( "<STR_LIT>" ) . append ( credits ) ; sb . append ( "<STR_LIT>" ) . append ( login ) ; sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . action ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Date ; import java . util . List ; import java . util . Random ; import javax . inject . Inject ; import javax . inject . Provider ; import javax . persistence . EntityManager ; import javax . persistence . EntityManagerFactory ; import javax . persistence . Tuple ; import javax . persistence . TypedQuery ; import javax . persistence . criteria . CriteriaBuilder ; import javax . persistence . criteria . CriteriaQuery ; import javax . persistence . criteria . Fetch ; import javax . persistence . criteria . Path ; import javax . persistence . criteria . Root ; import javax . persistence . criteria . Selection ; import javax . persistence . criteria . SetJoin ; import org . jboss . hibernateUniversity . criteria . domain . Address ; import org . jboss . hibernateUniversity . criteria . domain . Address_ ; import org . jboss . hibernateUniversity . criteria . domain . Gender ; import org . jboss . hibernateUniversity . criteria . domain . Login_ ; import org . jboss . hibernateUniversity . criteria . domain . User ; import org . jboss . hibernateUniversity . criteria . domain . User_ ; import org . jboss . hibernateUniversity . criteria . tools . Transactional ; @ Transactional public class UserManager { @ Inject EntityManagerFactory factory ; private Random random = new Random ( ) ; @ Inject Provider < EntityManager > lazyEM ; @ Transactional public List < User > getUsersNamedEmmanuel ( ) { EntityManager em = lazyEM . get ( ) ; CriteriaBuilder cb = em . getCriteriaBuilder ( ) ; final CriteriaQuery < User > query = cb . createQuery ( User . class ) ; final Root < User > u = query . from ( User . class ) ; u . fetch ( User_ . addresses ) ; query . select ( u ) . distinct ( true ) . where ( cb . equal ( u . get ( User_ . firstName ) , "<STR_LIT>" ) ) ; final TypedQuery < User > typedQuery = em . createQuery ( query ) ; typedQuery . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:20> ) ; final List < User > resultList = typedQuery . getResultList ( ) ; return resultList ; } @ Transactional public List < User > getUsersFromParis ( ) { EntityManager em = lazyEM . get ( ) ; CriteriaBuilder cb = em . getCriteriaBuilder ( ) ; final CriteriaQuery < User > query = cb . createQuery ( User . class ) ; final Root < User > u = query . from ( User . class ) ; final SetJoin < User , Address > a = u . join ( User_ . addresses ) ; u . fetch ( User_ . addresses ) ; query . select ( u ) . distinct ( true ) . where ( cb . equal ( a . get ( Address_ . city ) , "<STR_LIT>" ) ) ; final TypedQuery < User > typedQuery = em . createQuery ( query ) ; typedQuery . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:20> ) ; final List < User > resultList = typedQuery . getResultList ( ) ; return resultList ; } @ Transactional public List < User > getUsersBetween30And40 ( ) { EntityManager em = lazyEM . get ( ) ; CriteriaBuilder cb = em . getCriteriaBuilder ( ) ; final CriteriaQuery < User > query = cb . createQuery ( User . class ) ; final Root < User > u = query . from ( User . class ) ; final Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; cal . add ( Calendar . YEAR , - <NUM_LIT:30> ) ; Date end = new Date ( cal . getTimeInMillis ( ) ) ; cal . add ( Calendar . YEAR , - <NUM_LIT:10> ) ; Date begin = new Date ( cal . getTimeInMillis ( ) ) ; query . select ( u ) . where ( cb . between ( u . get ( User_ . birthDate ) , begin , end ) ) ; final TypedQuery < User > typedQuery = em . createQuery ( query ) ; typedQuery . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:20> ) ; final List < User > resultList = typedQuery . getResultList ( ) ; return resultList ; } @ Transactional public void displayAvgCreditByGender ( ) { EntityManager em = lazyEM . get ( ) ; CriteriaBuilder cb = em . getCriteriaBuilder ( ) ; final CriteriaQuery < Tuple > query = cb . createTupleQuery ( ) ; final Root < User > u = query . from ( User . class ) ; final Path < Gender > gender = u . get ( User_ . gender ) ; gender . alias ( "<STR_LIT>" ) ; final Selection < Double > credits = cb . avg ( u . get ( User_ . credits ) ) . alias ( "<STR_LIT>" ) ; query . multiselect ( credits , gender , cb . count ( u ) . alias ( "<STR_LIT>" ) ) . groupBy ( gender ) . having ( cb . in ( gender ) . value ( Gender . FEMALE ) . value ( Gender . MALE ) ) . orderBy ( cb . desc ( gender ) ) ; final TypedQuery < Tuple > typedQuery = em . createQuery ( query ) ; typedQuery . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:20> ) ; final List < Tuple > list = typedQuery . getResultList ( ) ; for ( Tuple tuple : list ) { final Double average = tuple . get ( credits ) ; System . err . println ( "<STR_LIT>" + tuple . get ( credits ) + "<STR_LIT:U+0020>" + tuple . get ( "<STR_LIT>" ) + "<STR_LIT>" + tuple . get ( "<STR_LIT>" ) + "<STR_LIT>" ) ; } } @ Transactional public void createNewUsers ( ) { final EntityManager entityManager = lazyEM . get ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:1000> ; i ++ ) { entityManager . persist ( createNewRandomUser ( ) ) ; } } private User createNewRandomUser ( ) { final Calendar cal = Calendar . getInstance ( ) ; cal . set ( <NUM_LIT> * <NUM_LIT:100> + <NUM_LIT> + random . nextInt ( <NUM_LIT> ) , random . nextInt ( <NUM_LIT:12> ) , random . nextInt ( <NUM_LIT> ) ) ; final int userRand = random . nextInt ( ) ; User user = new User ( userRand % <NUM_LIT:20> == <NUM_LIT:0> ? "<STR_LIT>" : "<STR_LIT>" + userRand , "<STR_LIT>" + random . nextInt ( ) , new Date ( cal . getTimeInMillis ( ) ) , getGender ( ) , random . nextInt ( <NUM_LIT:30> ) , "<STR_LIT:user>" + random . nextInt ( ) , "<STR_LIT>" + random . nextInt ( ) ) ; new Address ( random . nextInt ( ) + "<STR_LIT>" + random . nextInt ( ) , city . get ( random . nextInt ( city . size ( ) ) ) , new Integer ( random . nextInt ( ) % <NUM_LIT> ) . toString ( ) , user ) ; new Address ( random . nextInt ( ) + "<STR_LIT>" + random . nextInt ( ) , city . get ( random . nextInt ( city . size ( ) ) ) , new Integer ( random . nextInt ( ) % <NUM_LIT> ) . toString ( ) , user ) ; new Address ( random . nextInt ( ) + "<STR_LIT>" + random . nextInt ( ) , city . get ( random . nextInt ( city . size ( ) ) ) , new Integer ( random . nextInt ( ) % <NUM_LIT> ) . toString ( ) , user ) ; return user ; } private Gender getGender ( ) { int i = random . nextInt ( <NUM_LIT:10> ) ; if ( i < <NUM_LIT:4> ) { return Gender . MALE ; } else if ( i < <NUM_LIT:8> ) { return Gender . FEMALE ; } else { return Gender . NOT_SURE ; } } private List < String > city = new ArrayList < String > ( <NUM_LIT:10> ) ; public UserManager ( ) { city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . action ; import org . jboss . weld . environment . se . Weld ; import org . jboss . weld . environment . se . WeldContainer ; import org . junit . Test ; public class BookManagerTest { @ Test public void testQuery ( ) { final Weld weld = new Weld ( ) ; WeldContainer weldContainer = weld . initialize ( ) ; final BookManager userManager = weldContainer . instance ( ) . select ( BookManager . class ) . get ( ) ; userManager . getAllBooksWhoseAuthorIsEmmanuel ( ) ; weld . shutdown ( ) ; } @ Test public void testUserCreation ( ) { final Weld weld = new Weld ( ) ; WeldContainer weldContainer = weld . initialize ( ) ; final BookManager userManager = weldContainer . instance ( ) . select ( BookManager . class ) . get ( ) ; userManager . createNewUsers ( ) ; weld . shutdown ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . action ; import java . util . ArrayList ; import java . util . Calendar ; import java . util . Date ; import java . util . List ; import java . util . Random ; import javax . inject . Inject ; import javax . inject . Provider ; import javax . persistence . EntityManager ; import javax . persistence . EntityManagerFactory ; import org . apache . lucene . search . Query ; import org . jboss . hibernateUniversity . criteria . domain . Address ; import org . jboss . hibernateUniversity . criteria . domain . Book ; import org . jboss . hibernateUniversity . criteria . domain . Gender ; import org . jboss . hibernateUniversity . criteria . domain . User ; import org . jboss . hibernateUniversity . criteria . tools . Transactional ; import org . hibernate . CacheMode ; import org . hibernate . Session ; import org . hibernate . search . Search ; import org . hibernate . search . jpa . FullTextEntityManager ; import org . hibernate . search . jpa . FullTextQuery ; import org . hibernate . search . query . dsl . QueryBuilder ; @ Transactional public class BookManager { private Random random = new Random ( ) ; @ Inject Provider < FullTextEntityManager > lazyEM ; public void getAllBooksFrom1977 ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; Calendar pubDate = Calendar . getInstance ( ) ; pubDate . set ( <NUM_LIT> , <NUM_LIT:0> , <NUM_LIT> ) ; Date begin = new Date ( pubDate . getTimeInMillis ( ) ) ; pubDate . set ( <NUM_LIT> , <NUM_LIT:11> , <NUM_LIT:31> ) ; Date end = new Date ( pubDate . getTimeInMillis ( ) ) ; final Query luceneQuery = builder . range ( ) . onField ( "<STR_LIT>" ) . from ( begin ) . to ( end ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } public void getAllBooksStrictlyAbove1000Pages ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; final Query luceneQuery = builder . range ( ) . onField ( "<STR_LIT>" ) . above ( <NUM_LIT:1000> ) . excludeLimit ( ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } public void getAllBooksWhoseAuthorIsEmmanuel ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; final Query luceneQuery = builder . keyword ( ) . onField ( "<STR_LIT>" ) . matching ( "<STR_LIT>" ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } public void getAllBooksWhoseAuthorIsNotEmmanuel ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; final Query luceneQuery = builder . all ( ) . except ( builder . keyword ( ) . onField ( "<STR_LIT>" ) . matching ( "<STR_LIT>" ) . createQuery ( ) ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } public void getAllBooksOnPlantsAndHands ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; final Query luceneQuery = builder . bool ( ) . should ( builder . keyword ( ) . onField ( "<STR_LIT:title>" ) . boostedTo ( <NUM_LIT> ) . andField ( "<STR_LIT:description>" ) . matching ( "<STR_LIT>" ) . createQuery ( ) ) . should ( builder . keyword ( ) . onField ( "<STR_LIT:title>" ) . boostedTo ( <NUM_LIT> ) . andField ( "<STR_LIT:description>" ) . matching ( "<STR_LIT>" ) . createQuery ( ) ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } public void getAllBooksOnPlentsAndHends ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; final Query luceneQuery = builder . bool ( ) . should ( builder . keyword ( ) . onField ( "<STR_LIT>" ) . boostedTo ( <NUM_LIT> ) . andField ( "<STR_LIT>" ) . matching ( "<STR_LIT>" ) . createQuery ( ) ) . should ( builder . keyword ( ) . onField ( "<STR_LIT>" ) . boostedTo ( <NUM_LIT> ) . andField ( "<STR_LIT>" ) . matching ( "<STR_LIT>" ) . createQuery ( ) ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } public void getAllBooksStarred5InTheLast10Years ( ) { FullTextEntityManager em = lazyEM . get ( ) ; final QueryBuilder builder = em . getSearchFactory ( ) . buildQueryBuilder ( ) . forEntity ( Book . class ) . get ( ) ; final Calendar cal = Calendar . getInstance ( ) ; cal . setTimeInMillis ( System . currentTimeMillis ( ) ) ; cal . add ( Calendar . YEAR , - <NUM_LIT:10> ) ; final Query luceneQuery = builder . bool ( ) . must ( builder . range ( ) . onField ( "<STR_LIT>" ) . above ( <NUM_LIT:5> ) . createQuery ( ) ) . must ( builder . range ( ) . onField ( "<STR_LIT>" ) . above ( new Date ( cal . getTimeInMillis ( ) ) ) . createQuery ( ) ) . createQuery ( ) ; System . out . println ( luceneQuery . toString ( ) ) ; final FullTextQuery query = em . createFullTextQuery ( luceneQuery , Book . class ) ; final List < Book > resultList = query . setFirstResult ( <NUM_LIT:0> ) . setMaxResults ( <NUM_LIT:5> ) . getResultList ( ) ; displayListOfBooks ( resultList , query ) ; } private void displayListOfBooks ( List < Book > resultList , FullTextQuery query ) { System . out . println ( "<STR_LIT>" + query . getResultSize ( ) ) ; for ( Book book : resultList ) { System . out . println ( book . toString ( ) ) ; } } @ Transactional public void createNewUsers ( ) { final EntityManager entityManager = lazyEM . get ( ) ; for ( int i = <NUM_LIT:0> ; i < <NUM_LIT:1000> ; i ++ ) { entityManager . persist ( createNewRandomBook ( ) ) ; } } private Book createNewRandomBook ( ) { Calendar cal = Calendar . getInstance ( ) ; cal . set ( <NUM_LIT> * <NUM_LIT:100> + <NUM_LIT> + random . nextInt ( <NUM_LIT> ) , random . nextInt ( <NUM_LIT:12> ) , random . nextInt ( <NUM_LIT> ) ) ; User user = new User ( firstname . get ( random . nextInt ( firstname . size ( ) ) ) , "<STR_LIT>" + random . nextInt ( ) , new Date ( cal . getTimeInMillis ( ) ) , getGender ( ) , random . nextInt ( <NUM_LIT:30> ) , "<STR_LIT:user>" + random . nextInt ( ) , "<STR_LIT>" + random . nextInt ( ) ) ; new Address ( random . nextInt ( ) + "<STR_LIT>" + random . nextInt ( ) , city . get ( random . nextInt ( city . size ( ) ) ) , new Integer ( random . nextInt ( ) % <NUM_LIT> ) . toString ( ) , user ) ; new Address ( random . nextInt ( ) + "<STR_LIT>" + random . nextInt ( ) , city . get ( random . nextInt ( city . size ( ) ) ) , new Integer ( random . nextInt ( ) % <NUM_LIT> ) . toString ( ) , user ) ; new Address ( random . nextInt ( ) + "<STR_LIT>" + random . nextInt ( ) , city . get ( random . nextInt ( city . size ( ) ) ) , new Integer ( random . nextInt ( ) % <NUM_LIT> ) . toString ( ) , user ) ; Book book = new Book ( ) ; book . setAuthor ( user ) ; book . setDescription ( description . get ( random . nextInt ( description . size ( ) ) ) ) ; book . setTitle ( title . get ( random . nextInt ( title . size ( ) ) ) ) ; cal . add ( Calendar . YEAR , random . nextInt ( <NUM_LIT> ) ) ; book . setPublicationDate ( new Date ( cal . getTimeInMillis ( ) ) ) ; book . setNumberOfPages ( random . nextInt ( <NUM_LIT:1000> ) + <NUM_LIT:30> ) ; book . setStarred ( random . nextInt ( <NUM_LIT:5> ) + <NUM_LIT:1> ) ; return book ; } private Gender getGender ( ) { int i = random . nextInt ( <NUM_LIT:10> ) ; if ( i < <NUM_LIT:4> ) { return Gender . MALE ; } else if ( i < <NUM_LIT:8> ) { return Gender . FEMALE ; } else { return Gender . NOT_SURE ; } } private List < String > city = new ArrayList < String > ( <NUM_LIT:10> ) ; private List < String > description = new ArrayList < String > ( <NUM_LIT:10> ) ; private List < String > title = new ArrayList < String > ( <NUM_LIT:10> ) ; private List < String > firstname = new ArrayList < String > ( <NUM_LIT:20> ) ; public BookManager ( ) { city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; city . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; title . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" + "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; description . add ( "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" + "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; description . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; firstname . add ( "<STR_LIT>" ) ; } public void reindexBooks ( ) { FullTextEntityManager em = lazyEM . get ( ) ; try { em . createIndexer ( Book . class ) . batchSizeToLoadObjects ( <NUM_LIT:100> ) . cacheMode ( CacheMode . IGNORE ) . optimizeAfterPurge ( true ) . optimizeOnFinish ( true ) . purgeAllOnStart ( true ) . threadsToLoadObjects ( <NUM_LIT:5> ) . threadsForSubsequentFetching ( <NUM_LIT:5> ) . startAndWait ( ) ; } catch ( InterruptedException e ) { } } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . inject . Inject ; import javax . interceptor . AroundInvoke ; import javax . interceptor . Interceptor ; import javax . interceptor . InvocationContext ; @ Transactional @ Interceptor public class TransactionInterceptor { @ Inject TransactionManager manager ; @ AroundInvoke public Object manageTransaction ( InvocationContext ctx ) throws Exception { manager . begin ( ) ; try { final Object result = ctx . proceed ( ) ; manager . commit ( ) ; return result ; } catch ( Exception e ) { manager . rollback ( ) ; throw e ; } } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . enterprise . context . Dependent ; import javax . enterprise . inject . Produces ; import javax . inject . Inject ; import javax . inject . Singleton ; import javax . persistence . EntityManager ; import javax . persistence . EntityManagerFactory ; @ Singleton public class TransactionManager { @ Inject private EntityManagerFactory factory ; private ThreadLocal < EntityManager > emHolder = new ThreadLocal < EntityManager > ( ) ; public void begin ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { entityManager = factory . createEntityManager ( ) ; entityManager . getTransaction ( ) . begin ( ) ; emHolder . set ( entityManager ) ; } else { throw new RuntimeException ( "<STR_LIT>" ) ; } } @ Produces @ Dependent public EntityManager getEntityManager ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } else { return entityManager ; } } public void commit ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } else { entityManager . getTransaction ( ) . commit ( ) ; entityManager . close ( ) ; emHolder . set ( null ) ; } } public void rollback ( ) { EntityManager entityManager = this . emHolder . get ( ) ; if ( entityManager == null ) { throw new RuntimeException ( "<STR_LIT>" ) ; } else { entityManager . getTransaction ( ) . rollback ( ) ; entityManager . close ( ) ; emHolder . set ( null ) ; } } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import org . apache . solr . analysis . LowerCaseFilterFactory ; import org . apache . solr . analysis . NGramFilterFactory ; import org . apache . solr . analysis . StandardTokenizerFactory ; import org . hibernate . search . annotations . Factory ; import org . hibernate . search . cfg . SearchMapping ; public class HibernateSearchMapping { @ Factory SearchMapping getSearchMapping ( ) { SearchMapping mapping = new SearchMapping ( ) ; mapping . analyzerDef ( "<STR_LIT>" , StandardTokenizerFactory . class ) . filter ( LowerCaseFilterFactory . class ) . filter ( NGramFilterFactory . class ) . param ( "<STR_LIT>" , "<STR_LIT:3>" ) . param ( "<STR_LIT>" , "<STR_LIT:3>" ) ; return mapping ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . enterprise . inject . Produces ; import javax . inject . Inject ; import javax . persistence . EntityManager ; import org . hibernate . search . jpa . FullTextEntityManager ; import org . hibernate . search . jpa . Search ; public class FTEMProvider { @ Inject TransactionManager transactionManager ; @ Produces public FullTextEntityManager getFTEM ( ) { return Search . getFullTextEntityManager ( transactionManager . getEntityManager ( ) ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import java . lang . annotation . Retention ; import java . lang . annotation . Target ; import javax . interceptor . InterceptorBinding ; import static java . lang . annotation . ElementType . * ; import static java . lang . annotation . RetentionPolicy . * ; @ InterceptorBinding @ Target ( { METHOD , TYPE } ) @ Retention ( RUNTIME ) public @ interface Transactional { } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . tools ; import javax . enterprise . inject . Disposes ; import javax . enterprise . inject . Produces ; import javax . inject . Singleton ; import javax . persistence . EntityManagerFactory ; import javax . persistence . Persistence ; public class EMFProvider { @ Produces @ Singleton public EntityManagerFactory createEMF ( ) { return Persistence . createEntityManagerFactory ( "<STR_LIT>" ) ; } public void close ( @ Disposes EntityManagerFactory factory ) { factory . close ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . ManyToOne ; @ Entity public class Address { public Address ( ) { } public Address ( String street , String city , String zipCode , User owner ) { this . street = street ; this . city = city ; this . zipCode = zipCode ; this . owner = owner ; owner . getAddresses ( ) . add ( this ) ; } @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } private Long id ; public String getStreet ( ) { return street ; } public void setStreet ( String street ) { this . street = street ; } private String street ; public String getCity ( ) { return city ; } public void setCity ( String city ) { this . city = city ; } private String city ; public String getZipCode ( ) { return zipCode ; } public void setZipCode ( String zipCode ) { this . zipCode = zipCode ; } private String zipCode ; @ ManyToOne public User getOwner ( ) { return owner ; } public void setOwner ( User owner ) { this . owner = owner ; } private User owner ; } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; public enum Gender { MALE , FEMALE , NOT_SURE } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import javax . persistence . Embeddable ; @ Embeddable public class Login { public Login ( ) { } public Login ( String username , String password ) { this . username = username ; this . password = password ; } public String getUsername ( ) { return username ; } public void setUsername ( String username ) { this . username = username ; } private String username ; public String getPassword ( ) { return password ; } public void setPassword ( String password ) { this . password = password ; } private String password ; @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) ; sb . append ( "<STR_LIT>" ) . append ( username ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( password ) . append ( '<STR_LIT>' ) ; sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import java . util . Date ; import javax . persistence . CascadeType ; import javax . persistence . Column ; import javax . persistence . Entity ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . ManyToOne ; import javax . persistence . Temporal ; import javax . persistence . TemporalType ; import org . hibernate . search . annotations . Analyzer ; import org . hibernate . search . annotations . DateBridge ; import org . hibernate . search . annotations . Field ; import org . hibernate . search . annotations . Fields ; import org . hibernate . search . annotations . Indexed ; import org . hibernate . search . annotations . IndexedEmbedded ; import org . hibernate . search . annotations . NumericField ; import org . hibernate . search . annotations . Resolution ; @ Entity @ Indexed public class Book { @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } private Long id ; @ Fields ( { @ Field , @ Field ( name = "<STR_LIT>" , analyzer = @ Analyzer ( definition = "<STR_LIT>" ) ) } ) public String getTitle ( ) { return title ; } public void setTitle ( String title ) { this . title = title ; } private String title ; @ Fields ( { @ Field , @ Field ( name = "<STR_LIT>" , analyzer = @ Analyzer ( definition = "<STR_LIT>" ) ) } ) @ Column ( length = <NUM_LIT> ) public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } private String description ; @ Temporal ( TemporalType . DATE ) @ Field @ DateBridge ( resolution = Resolution . DAY ) public Date getPublicationDate ( ) { return publicationDate ; } public void setPublicationDate ( Date publicationDate ) { this . publicationDate = publicationDate ; } private Date publicationDate ; @ ManyToOne ( cascade = CascadeType . PERSIST ) @ IndexedEmbedded public User getAuthor ( ) { return author ; } public void setAuthor ( User author ) { this . author = author ; } private User author ; @ Field @ NumericField public int getNumberOfPages ( ) { return numberOfPages ; } public void setNumberOfPages ( int numberOfPages ) { this . numberOfPages = numberOfPages ; } private int numberOfPages ; @ Field @ NumericField public int getStarred ( ) { return starred ; } public void setStarred ( int starred ) { this . starred = starred ; } private int starred ; @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) ; sb . append ( "<STR_LIT>" ) . append ( id ) . append ( "<STR_LIT:n>" ) ; sb . append ( "<STR_LIT>" ) . append ( title ) . append ( '<STR_LIT>' ) . append ( "<STR_LIT:n>" ) ; sb . append ( "<STR_LIT>" ) . append ( description ) . append ( '<STR_LIT>' ) . append ( "<STR_LIT:n>" ) ; sb . append ( "<STR_LIT>" ) . append ( publicationDate ) . append ( "<STR_LIT:n>" ) ; sb . append ( "<STR_LIT>" ) . append ( author ) . append ( "<STR_LIT:n>" ) ; sb . append ( "<STR_LIT>" ) . append ( numberOfPages ) . append ( "<STR_LIT:n>" ) ; sb . append ( "<STR_LIT>" ) . append ( starred ) . append ( "<STR_LIT:n>" ) ; sb . append ( '<CHAR_LIT:}>' ) . append ( "<STR_LIT:n>" ) ; return sb . toString ( ) ; } } </s>
|
<s> package org . jboss . hibernateUniversity . criteria . domain ; import java . util . Date ; import java . util . HashSet ; import java . util . Set ; import javax . persistence . CascadeType ; import javax . persistence . Entity ; import javax . persistence . EnumType ; import javax . persistence . Enumerated ; import javax . persistence . GeneratedValue ; import javax . persistence . Id ; import javax . persistence . OneToMany ; import javax . persistence . Temporal ; import javax . persistence . TemporalType ; import org . hibernate . search . annotations . Field ; import org . hibernate . search . annotations . Indexed ; @ Entity @ Indexed public class User { public User ( ) { } public User ( String firstName , String lastName , Date birthDate , Gender gender , int credits , String username , String password ) { this . firstName = firstName ; this . lastName = lastName ; this . birthDate = birthDate ; this . gender = gender ; this . credits = credits ; this . login = new Login ( username , password ) ; } @ Id @ GeneratedValue public Long getId ( ) { return id ; } public void setId ( Long id ) { this . id = id ; } private Long id ; @ Field public String getFirstName ( ) { return firstName ; } public void setFirstName ( String firstName ) { this . firstName = firstName ; } private String firstName ; @ Field public String getLastName ( ) { return lastName ; } public void setLastName ( String lastName ) { this . lastName = lastName ; } private String lastName ; @ OneToMany ( cascade = CascadeType . PERSIST , mappedBy = "<STR_LIT>" ) public Set < Address > getAddresses ( ) { return addresses ; } public void setAddresses ( Set < Address > addresses ) { this . addresses = addresses ; } private Set < Address > addresses = new HashSet < Address > ( ) ; @ Temporal ( TemporalType . DATE ) public Date getBirthDate ( ) { return birthDate ; } public void setBirthDate ( Date birthDate ) { this . birthDate = birthDate ; } private Date birthDate ; @ Enumerated ( EnumType . STRING ) public Gender getGender ( ) { return gender ; } public void setGender ( Gender gender ) { this . gender = gender ; } private Gender gender ; public int getCredits ( ) { return credits ; } public void setCredits ( int credits ) { this . credits = credits ; } private int credits ; public Login getLogin ( ) { return login ; } public void setLogin ( Login login ) { this . login = login ; } private Login login ; @ Override public String toString ( ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "<STR_LIT>" ) ; sb . append ( "<STR_LIT>" ) . append ( id ) ; sb . append ( "<STR_LIT>" ) . append ( firstName ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( lastName ) . append ( '<STR_LIT>' ) ; sb . append ( "<STR_LIT>" ) . append ( addresses ) ; sb . append ( "<STR_LIT>" ) . append ( birthDate ) ; sb . append ( "<STR_LIT>" ) . append ( gender ) ; sb . append ( "<STR_LIT>" ) . append ( credits ) ; sb . append ( "<STR_LIT>" ) . append ( login ) ; sb . append ( '<CHAR_LIT:}>' ) ; return sb . toString ( ) ; } } </s>
|
<s> package com . jboss . sample . bv ; import java . math . BigDecimal ; import java . util . Set ; import javax . validation . ConstraintViolation ; import javax . validation . Validation ; import javax . validation . Validator ; import com . jboss . sample . bv . domain . Address ; import com . jboss . sample . bv . domain . BlackListStatus ; import com . jboss . sample . bv . domain . Country ; import com . jboss . sample . bv . domain . CreditCard ; import com . jboss . sample . bv . domain . Customer ; import com . jboss . sample . bv . domain . Item ; import com . jboss . sample . bv . domain . Order ; import com . jboss . sample . bv . domain . StraightToOrderValidation ; import com . jboss . sample . bv . domain . constraints . NoDelay ; public class App { public static void main ( String [ ] args ) { final App app = new App ( ) ; app . testGroups ( ) ; } private void testGroups ( ) { System . out . println ( "<STR_LIT>" ) ; Order order = buildValidOrder ( ) ; Validator v = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; Set < ConstraintViolation < Order > > violations = v . validate ( order ) ; displayViolations ( "<STR_LIT>" , violations ) ; violations = v . validate ( order , NoDelay . class ) ; if ( violations . size ( ) == <NUM_LIT:0> ) { } else { } displayViolations ( "<STR_LIT>" , violations ) ; order . getCustomer ( ) . setStatus ( BlackListStatus . GREY ) ; Country country = new Country ( ) ; country . setName ( "<STR_LIT>" ) ; country . setStatus ( BlackListStatus . BLACK ) ; order . getShippingAddress ( ) . setCountry ( country ) ; violations = v . validate ( order , NoDelay . class ) ; displayViolations ( "<STR_LIT>" , violations ) ; } private void testGroupsInheritance ( ) { System . out . println ( "<STR_LIT>" ) ; Customer customer = buildValidCustomer ( ) ; Validator v = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; Set < ConstraintViolation < Customer > > violations = v . validate ( customer ) ; displayViolations ( "<STR_LIT>" , violations ) ; violations = v . validate ( customer , StraightToOrderValidation . class ) ; if ( violations . size ( ) == <NUM_LIT:0> ) { } else { } displayViolations ( "<STR_LIT>" , violations ) ; customer . setDefaultAddress ( null ) ; customer . getDefaultCreditCard ( ) . setNumber ( "<STR_LIT>" ) ; violations = v . validate ( customer , StraightToOrderValidation . class ) ; if ( violations . size ( ) == <NUM_LIT:0> ) { } else { } displayViolations ( "<STR_LIT>" , violations ) ; } private void testComplexConstraint ( ) { System . out . println ( "<STR_LIT>" ) ; Validator v = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; Address address = buildvalidAddress ( ) ; address . setZipCode ( "<STR_LIT>" ) ; Set < ConstraintViolation < Address > > violations = v . validate ( address ) ; displayViolations ( "<STR_LIT>" , violations ) ; } private void testComposition ( ) { System . out . println ( "<STR_LIT>" ) ; Order order = buildValidOrder ( ) ; Validator v = Validation . buildDefaultValidatorFactory ( ) . getValidator ( ) ; order . setOrderNumber ( "<STR_LIT>" ) ; Set < ConstraintViolation < Order > > violations = v . validate ( order ) ; displayViolations ( "<STR_LIT>" , violations ) ; } private < T > void displayViolations ( String message , Set < ConstraintViolation < T > > violations ) { StringBuilder errorReport = new StringBuilder ( "<STR_LIT:n>" ) ; errorReport . append ( message ) . append ( "<STR_LIT:n>" ) ; if ( violations . size ( ) == <NUM_LIT:0> ) { errorReport . append ( "<STR_LIT>" ) ; } else { errorReport . append ( "<STR_LIT>" ) . append ( violations . size ( ) ) . append ( "<STR_LIT>" ) ; if ( violations . size ( ) > <NUM_LIT:1> ) { errorReport . append ( "<STR_LIT:s>" ) ; } for ( ConstraintViolation violation : violations ) { errorReport . append ( "<STR_LIT>" ) . append ( violation . getRootBeanClass ( ) . getName ( ) ) . append ( "<STR_LIT:.>" ) . append ( violation . getPropertyPath ( ) ) ; errorReport . append ( "<STR_LIT>" ) . append ( violation . getMessage ( ) ) . append ( "<STR_LIT:'>" ) ; } } System . out . println ( errorReport . toString ( ) ) ; } private Order buildValidOrder ( ) { Address address = buildvalidAddress ( ) ; CreditCard creditCard = buildValidCreditCard ( ) ; Item item = new Item ( ) ; item . setDescription ( "<STR_LIT>" ) ; item . setPrice ( new BigDecimal ( "<STR_LIT>" ) ) ; item . setStock ( <NUM_LIT:3> ) ; Customer customer = new Customer ( ) ; customer . setFirstname ( "<STR_LIT>" ) ; customer . setLastname ( "<STR_LIT>" ) ; customer . setStatus ( BlackListStatus . OK ) ; Order order = new Order ( ) ; order . setCreditCard ( creditCard ) ; order . setCustomer ( customer ) ; order . setShippingAddress ( address ) ; order . getItems ( ) . add ( item ) ; order . setOrderNumber ( "<STR_LIT>" ) ; return order ; } private Address buildvalidAddress ( ) { Country country = new Country ( ) ; country . setName ( "<STR_LIT>" ) ; country . setStatus ( BlackListStatus . OK ) ; Address address = new Address ( ) ; address . setStreet1 ( "<STR_LIT>" ) ; address . setCity ( "<STR_LIT>" ) ; address . setCountry ( country ) ; address . setZipCode ( "<STR_LIT>" ) ; return address ; } private Customer buildValidCustomer ( ) { Address address = buildvalidAddress ( ) ; CreditCard creditCard = buildValidCreditCard ( ) ; Customer customer = new Customer ( ) ; customer . setDefaultAddress ( address ) ; customer . setDefaultCreditCard ( creditCard ) ; customer . setFirstname ( "<STR_LIT>" ) ; customer . setLastname ( "<STR_LIT>" ) ; customer . setStatus ( BlackListStatus . OK ) ; return customer ; } private CreditCard buildValidCreditCard ( ) { CreditCard creditCard = new CreditCard ( ) ; creditCard . setNumber ( "<STR_LIT>" ) ; creditCard . setOwner ( "<STR_LIT>" ) ; return creditCard ; } } </s>
|
<s> package com . jboss . sample . bv . domain ; public enum BlackListStatus { OK , GREY , BLACK } </s>
|
<s> package com . jboss . sample . bv . domain . constraints ; public interface NoDelay { } </s>
|
<s> package com . jboss . sample . bv . domain . constraints ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import javax . validation . Constraint ; import javax . validation . ConstraintValidator ; import javax . validation . ConstraintValidatorContext ; import javax . validation . Payload ; import org . hibernate . validator . constraints . impl . LuhnValidator ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( { ElementType . METHOD , ElementType . FIELD , ElementType . ANNOTATION_TYPE , ElementType . PARAMETER } ) @ Constraint ( validatedBy = Luhn . Validator . class ) public @ interface Luhn { String message ( ) default "<STR_LIT>" ; Class < ? > [ ] groups ( ) default { } ; Class < ? extends Payload > [ ] payload ( ) default { } ; public class Validator implements ConstraintValidator < Luhn , String > { private LuhnValidator validator = new LuhnValidator ( <NUM_LIT:2> ) ; public void initialize ( Luhn constraintAnnotation ) { } public boolean isValid ( String value , ConstraintValidatorContext context ) { if ( value == null ) { return true ; } return validator . passesLuhnTest ( value ) ; } } } </s>
|
<s> package com . jboss . sample . bv . domain . constraints ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import javax . validation . Constraint ; import javax . validation . OverridesAttribute ; import javax . validation . Payload ; import javax . validation . ReportAsSingleViolation ; import javax . validation . constraints . Size ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( { ElementType . METHOD , ElementType . FIELD , ElementType . ANNOTATION_TYPE , ElementType . PARAMETER } ) @ Constraint ( validatedBy = { } ) @ Size ( min = <NUM_LIT:10> , max = <NUM_LIT:10> , message = "<STR_LIT>" ) @ Luhn ( message = "<STR_LIT>" ) @ ReportAsSingleViolation public @ interface OrderNumber { String message ( ) default "<STR_LIT>" ; Class < ? > [ ] groups ( ) default { } ; Class < ? extends Payload > [ ] payload ( ) default { } ; @ OverridesAttribute . List ( { @ OverridesAttribute ( constraint = Size . class , name = "<STR_LIT>" ) , @ OverridesAttribute ( constraint = Size . class , name = "<STR_LIT>" ) } ) int size ( ) ; } </s>
|
<s> package com . jboss . sample . bv . domain . constraints ; import java . lang . annotation . ElementType ; import java . lang . annotation . Retention ; import java . lang . annotation . RetentionPolicy ; import java . lang . annotation . Target ; import javax . validation . Constraint ; import javax . validation . Payload ; import javax . validation . ReportAsSingleViolation ; import javax . validation . constraints . Size ; import com . jboss . sample . bv . domain . constraints . impl . ZipCodeValidator ; @ Retention ( RetentionPolicy . RUNTIME ) @ Target ( { ElementType . METHOD , ElementType . TYPE , ElementType . ANNOTATION_TYPE , ElementType . PARAMETER } ) @ Constraint ( validatedBy = { ZipCodeValidator . class } ) public @ interface ZipCode { String message ( ) default "<STR_LIT>" ; Class < ? > [ ] groups ( ) default { } ; Class < ? extends Payload > [ ] payload ( ) default { } ; } </s>
|
<s> package com . jboss . sample . bv . domain . constraints ; import java . lang . annotation . Documented ; import java . lang . annotation . Retention ; import java . lang . annotation . Target ; import java . util . ArrayList ; import java . util . List ; import javax . validation . Constraint ; import javax . validation . ConstraintValidator ; import javax . validation . ConstraintValidatorContext ; import javax . validation . Payload ; import com . jboss . sample . bv . domain . BlackListStatus ; import static java . lang . annotation . ElementType . ANNOTATION_TYPE ; import static java . lang . annotation . ElementType . CONSTRUCTOR ; import static java . lang . annotation . ElementType . FIELD ; import static java . lang . annotation . ElementType . METHOD ; import static java . lang . annotation . ElementType . PARAMETER ; import static java . lang . annotation . RetentionPolicy . RUNTIME ; @ Target ( { METHOD , FIELD , ANNOTATION_TYPE , CONSTRUCTOR , PARAMETER } ) @ Retention ( RUNTIME ) @ Documented @ Constraint ( validatedBy = CheckBlackListStatus . Validator . class ) public @ interface CheckBlackListStatus { String message ( ) default "<STR_LIT>" ; Class < ? > [ ] groups ( ) default { } ; Class < ? extends Payload > [ ] payload ( ) default { } ; BlackListStatus [ ] accepted ( ) ; public class Validator implements ConstraintValidator < CheckBlackListStatus , BlackListStatus > { private List < BlackListStatus > accepted ; public void initialize ( CheckBlackListStatus constraintAnnotation ) { final BlackListStatus [ ] statuses = constraintAnnotation . accepted ( ) ; accepted = new ArrayList < BlackListStatus > ( statuses . length ) ; for ( BlackListStatus current : statuses ) { accepted . add ( current ) ; } } public boolean isValid ( BlackListStatus value , ConstraintValidatorContext context ) { return accepted . contains ( value ) ; } } } </s>
|
<s> package com . jboss . sample . bv . domain . constraints . impl ; import javax . validation . ConstraintValidator ; import javax . validation . ConstraintValidatorContext ; import com . jboss . sample . bv . domain . Address ; import com . jboss . sample . bv . domain . constraints . ZipCode ; public class ZipCodeValidator implements ConstraintValidator < ZipCode , Address > { public void initialize ( ZipCode constraintAnnotation ) { } public boolean isValid ( Address value , ConstraintValidatorContext context ) { if ( value == null ) return true ; context . disableDefaultConstraintViolation ( ) ; String countryName = value . getCountry ( ) == null ? null : value . getCountry ( ) . getName ( ) ; boolean result = true ; if ( countryName == null ) { context . buildConstraintViolationWithTemplate ( "<STR_LIT>" ) . addNode ( "<STR_LIT>" ) . addConstraintViolation ( ) ; result = false ; } String zipCode = value . getZipCode ( ) ; if ( zipCode == null ) { context . buildConstraintViolationWithTemplate ( "<STR_LIT>" ) . addNode ( "<STR_LIT>" ) . addConstraintViolation ( ) ; result = false ; } if ( ! result ) return false ; if ( "<STR_LIT>" . equals ( countryName ) ) { return validateFrenchZipCode ( value . getZipCode ( ) , context ) ; } else if ( "<STR_LIT>" . equals ( countryName ) ) { return validateUSAZipCode ( zipCode , context ) ; } return true ; } private boolean validateFrenchZipCode ( String zipCode , ConstraintValidatorContext context ) { if ( zipCode . length ( ) != <NUM_LIT:5> ) { context . buildConstraintViolationWithTemplate ( "<STR_LIT>" ) . addNode ( "<STR_LIT>" ) . addConstraintViolation ( ) ; return false ; } return true ; } private boolean validateUSAZipCode ( String zipCode , ConstraintValidatorContext context ) { if ( zipCode . length ( ) != <NUM_LIT:5> ) { context . buildConstraintViolationWithTemplate ( "<STR_LIT>" ) . addNode ( "<STR_LIT>" ) . addConstraintViolation ( ) ; return false ; } if ( ! isInUSPSDatabase ( zipCode ) ) { context . buildConstraintViolationWithTemplate ( "<STR_LIT>" ) . addNode ( "<STR_LIT>" ) . addConstraintViolation ( ) ; return false ; } return true ; } private boolean isInUSPSDatabase ( String zipCode ) { return true ; } } </s>
|
<s> package com . jboss . sample . bv . domain ; public interface BillableAutomatically { } </s>
|
<s> package com . jboss . sample . bv . domain ; import java . math . BigDecimal ; import javax . validation . constraints . DecimalMax ; import javax . validation . constraints . DecimalMin ; import javax . validation . constraints . Min ; import javax . validation . constraints . NotNull ; import javax . validation . constraints . Size ; import org . hibernate . validator . constraints . NotEmpty ; public class Item { @ NotEmpty @ Size ( max = <NUM_LIT> ) public String getDescription ( ) { return description ; } public void setDescription ( String description ) { this . description = description ; } private String description ; @ DecimalMin ( value = "<STR_LIT>" ) public BigDecimal getPrice ( ) { return price ; } public void setPrice ( BigDecimal price ) { this . price = price ; } private BigDecimal price ; @ NotNull @ Min ( value = <NUM_LIT:0> ) public Integer getStock ( ) { return stock ; } public void setStock ( Integer stock ) { this . stock = stock ; } private Integer stock ; } </s>
|
<s> package com . jboss . sample . bv . domain ; import javax . validation . groups . Default ; public interface StraightToOrderValidation extends ShippableAutomatically , BillableAutomatically , Default { } </s>
|
<s> package com . jboss . sample . bv . domain ; import javax . validation . Valid ; import com . jboss . sample . bv . domain . constraints . ZipCode ; @ ZipCode public class Address { public String getStreet1 ( ) { return street1 ; } public void setStreet1 ( String street1 ) { this . street1 = street1 ; } private String street1 ; public String getCity ( ) { return city ; } public void setCity ( String city ) { this . city = city ; } private String city ; public String getZipCode ( ) { return zipCode ; } public void setZipCode ( String zipCode ) { this . zipCode = zipCode ; } private String zipCode ; @ Valid public Country getCountry ( ) { return country ; } public void setCountry ( Country country ) { this . country = country ; } private Country country ; } </s>
|
<s> package com . jboss . sample . bv . domain ; import javax . validation . Valid ; import javax . validation . constraints . NotNull ; import javax . validation . constraints . Size ; import com . jboss . sample . bv . domain . constraints . CheckBlackListStatus ; import com . jboss . sample . bv . domain . constraints . NoDelay ; import org . hibernate . validator . constraints . NotEmpty ; public class Customer { @ NotEmpty @ Size ( max = <NUM_LIT> ) public String getFirstname ( ) { return firstname ; } public void setFirstname ( String firstname ) { this . firstname = firstname ; } private String firstname ; @ NotEmpty @ Size ( max = <NUM_LIT> ) public String getLastname ( ) { return lastname ; } public void setLastname ( String lastname ) { this . lastname = lastname ; } private String lastname ; @ Valid @ NotNull ( groups = ShippableAutomatically . class , message = "<STR_LIT>" ) public Address getDefaultAddress ( ) { return defaultAddress ; } public void setDefaultAddress ( Address defaultAddress ) { this . defaultAddress = defaultAddress ; } private Address defaultAddress ; @ Valid @ NotNull ( groups = BillableAutomatically . class , message = "<STR_LIT>" ) public CreditCard getDefaultCreditCard ( ) { return defaultCreditCard ; } public void setDefaultCreditCard ( CreditCard defaultCreditCard ) { this . defaultCreditCard = defaultCreditCard ; } private CreditCard defaultCreditCard ; @ CheckBlackListStatus ( accepted = BlackListStatus . OK , message = "<STR_LIT>" , groups = NoDelay . class ) public BlackListStatus getStatus ( ) { return status ; } public void setStatus ( BlackListStatus status ) { this . status = status ; } private BlackListStatus status ; } </s>
|
<s> package com . jboss . sample . bv . domain ; public interface ShippableAutomatically { } </s>
|
<s> package com . jboss . sample . bv . domain ; import com . jboss . sample . bv . domain . constraints . CheckBlackListStatus ; import com . jboss . sample . bv . domain . constraints . NoDelay ; import com . jboss . sample . bv . domain . constraints . ZipCode ; import org . hibernate . validator . constraints . NotEmpty ; public class Country { @ NotEmpty public String getName ( ) { return name ; } public void setName ( String name ) { this . name = name ; } private String name ; @ CheckBlackListStatus ( accepted = BlackListStatus . OK , groups = NoDelay . class , message = "<STR_LIT>" ) public BlackListStatus getStatus ( ) { return status ; } public void setStatus ( BlackListStatus status ) { this . status = status ; } private BlackListStatus status ; } </s>
|
<s> package com . jboss . sample . bv . domain ; import java . util . ArrayList ; import java . util . List ; import javax . validation . Valid ; import javax . validation . constraints . Size ; import com . jboss . sample . bv . domain . constraints . Luhn ; import com . jboss . sample . bv . domain . constraints . OrderNumber ; public class Order { @ OrderNumber ( size = <NUM_LIT:10> ) public String getOrderNumber ( ) { return orderNumber ; } public void setOrderNumber ( String orderNumber ) { this . orderNumber = orderNumber ; } private String orderNumber ; @ Valid public Customer getCustomer ( ) { return customer ; } public void setCustomer ( Customer customer ) { this . customer = customer ; } private Customer customer ; @ Valid public CreditCard getCreditCard ( ) { return creditCard ; } public void setCreditCard ( CreditCard creditCard ) { this . creditCard = creditCard ; } private CreditCard creditCard ; @ Valid public Address getShippingAddress ( ) { return shippingAddress ; } public void setShippingAddress ( Address shippingAddress ) { this . shippingAddress = shippingAddress ; } private Address shippingAddress ; public List < Item > getItems ( ) { return items ; } public void setItems ( List < Item > items ) { this . items = items ; } private List < Item > items = new ArrayList < Item > ( ) ; } </s>
|
<s> package com . jboss . sample . bv . domain ; import javax . validation . constraints . NotNull ; import org . hibernate . validator . constraints . CreditCardNumber ; import org . hibernate . validator . constraints . NotEmpty ; public class CreditCard { @ CreditCardNumber public String getNumber ( ) { return number ; } public void setNumber ( String number ) { this . number = number ; } private String number ; @ NotEmpty public String getOwner ( ) { return owner ; } public void setOwner ( String owner ) { this . owner = owner ; } private String owner ; } </s>
|
<s> import java . awt . Color ; import java . awt . Dimension ; import java . awt . Graphics ; public class Curve { protected final GraphCanvas canvas ; protected Color color ; public Curve ( GraphCanvas canvas , Color color ) { this . canvas = canvas ; this . color = color ; cacheCanvas ( ) ; } public void draw ( Graphics g ) { cacheCanvas ( ) ; g . setColor ( color ) ; } protected double x0 , xScale , y0 , yScale ; protected void cacheCanvas ( ) { Dimension d = canvas . getSize ( ) ; int width = d . width ; int height = d . height ; x0 = width / <NUM_LIT> ; y0 = height / <NUM_LIT> ; xScale = width / ( canvas . getXMax ( ) - canvas . getXMin ( ) ) ; yScale = height / ( canvas . getYMax ( ) - canvas . getYMin ( ) ) ; } protected double unscreenifyX ( int xCoord ) { return ( xCoord - x0 ) / xScale ; } protected double unscreenifyY ( int yCoord ) { return ( y0 - yCoord ) / yScale ; } protected int screenifyX ( double x ) { return ( int ) ( <NUM_LIT> + x0 + x * xScale ) ; } protected int screenifyY ( double y ) { return ( int ) ( <NUM_LIT> + y0 - y * yScale ) ; } } </s>
|
<s> import java . awt . Canvas ; import java . awt . Color ; import java . awt . Graphics ; public class GraphCanvas extends Canvas { private double x0 , x1 , y0 , y1 ; private Curve curve ; public GraphCanvas ( ) { setBackground ( Color . white ) ; x0 = - <NUM_LIT> ; x1 = <NUM_LIT> ; y0 = - <NUM_LIT> ; y1 = <NUM_LIT> ; curve = null ; } public void setCurve ( Curve curve ) { this . curve = curve ; } public void paint ( Graphics g ) { if ( null != curve ) curve . draw ( g ) ; } public double getXMin ( ) { return x0 ; } public double getXMax ( ) { return x1 ; } public double getYMin ( ) { return y0 ; } public double getYMax ( ) { return y1 ; } } </s>
|
<s> import java . awt . Color ; import java . awt . Graphics ; import expr . Expr ; import expr . Variable ; public final class ParametricCurve extends Curve { public ParametricCurve ( GraphCanvas canvas , Color color , Variable tVar , Expr xExpr , Expr yExpr , int steps ) { super ( canvas , color ) ; this . tVar = tVar ; this . xExpr = xExpr ; this . yExpr = yExpr ; this . steps = steps ; } private Variable tVar ; private Expr xExpr , yExpr ; private int steps ; public void draw ( Graphics g ) { super . draw ( g ) ; tVar . setValue ( <NUM_LIT:0.0> ) ; int prevX = screenifyX ( xExpr . value ( ) ) ; int prevY = screenifyY ( yExpr . value ( ) ) ; double dt = <NUM_LIT:1.0> / steps ; for ( int step = <NUM_LIT:1> ; step <= steps ; ++ step ) { tVar . setValue ( step * dt ) ; int x = screenifyX ( xExpr . value ( ) ) ; int y = screenifyY ( yExpr . value ( ) ) ; g . drawLine ( prevX , prevY , x , y ) ; prevY = y ; prevX = x ; } } } </s>
|
<s> public abstract class Scale { public abstract int map ( double mathCoord ) ; public abstract double unmap ( int screenCoord ) ; } </s>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.