method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
3bf7eb59-3628-46c6-8311-09da2514db7a
| 1
|
public Monitor(String xmlPath, String dbUrl) throws Exception, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IllegalAccessException, InstantiationException {
File xml = new File(xmlPath);
if (!xml.exists()) throw new IllegalArgumentException("XML file with monitor description is not found");
SingleStatProcessorFactory factory = new SingleStatProcessorFactory();
Connector conn = new Connector(dbUrl);
final StatDB db = SqlProxy.produceSqlFacade(StatDB.class, conn);
AutoUpdateableStatConfig config = new AutoUpdateableStatConfig(xml, db, factory);
MonitorTask task = new MonitorTask(config);
Timer t = new Timer();
t.schedule(task, new Date(), DELAY);
}
|
9b281419-2878-4947-9091-7bce523904ad
| 3
|
public boolean canPlaceAnywhere() {
// check still playable
for (int y = 0; y < BOARD_LENGTH; y++) {
for (int x = 0; x < BOARD_LENGTH; x++) {
if (canPlace(y, x)) {
return true;
}
}
}
return false;
}
|
5fc054b3-f71f-4bc3-af0e-a538d8f2b898
| 0
|
public Status getStatus() {
return status;
}
|
92b85d2a-36aa-40d3-a2a9-ddbc5efda9a1
| 9
|
public static void analyzeListStability(){
TreeMap<Long, Class<?>> map = new TreeMap<Long, Class<?>>();
List<Class<?>> sorts = getSorts();
for(Class<?> clazz : sorts){
sampleListTest(clazz, false);
System.out.println("--------");
}
for(Class<?> clazz : sorts){
long time = listStabilityTest(clazz, false);
System.out.println("--------");
map.put(time, clazz);
}
for(Map.Entry<Long, Class<?>> entry : map.entrySet()){
System.out.println(entry.getValue().getSimpleName() + " sort: "
+ entry.getKey() + " ns");
}
}
|
d5ab9ebb-e0b4-4131-8b8c-b59424be016e
| 3
|
public Cellule plusProche (List<Cellule> l){
Cellule c = null;
int d = Integer.MAX_VALUE;
for(int i = 0 ; i < l.size() ; i++){
if(l.get(i) != this){
int di = l.get(i).distance(this);
if(di < d){
c = l.get(i);
d = di;
}
}
}
return c;
}
|
5084fe8b-59cd-451f-a1c4-cbd638bc8996
| 5
|
public void onEnable() {
checkFiles();
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(new FAAPlayerListener(this), this);
getCommand("account").setExecutor(new AccountCommand(this));
server = getServer();
Class<? extends ForumHandler> fh = null;
try {
fh = Class.forName(getConfig().getString("Forum.Type")).asSubclass(
ForumHandler.class);
} catch (ClassNotFoundException e1) {
logError(getConfig().getString("Forum.Type")
+ " is not a valid forum type! Make sure config.yml is setup properly.");
setEnabled(false);
}
try {
handler = fh.newInstance();
} catch (InstantiationException e1) {
logError(getConfig().getString("Forum.Type")
+ " is not a valid forum type! Make sure config.yml is setup properly.");
setEnabled(false);
} catch (IllegalAccessException e) {
logError(getConfig().getString("Forum.Type")
+ " is not a valid forum type! Make sure config.yml is setup properly.");
setEnabled(false);
}
handler.url = getConfig().getString("Database.URL");
handler.port = getConfig().getString("Database.Port");
handler.username = getConfig().getString("Database.Username");
handler.password = getConfig().getString("Database.Password");
handler.tablePref = getConfig().getString("Database.Table_Prefix");
handler.database = getConfig().getString("Database.Database");
handler.customField = getConfig().getString("Optional.Custom_Field_ID");
getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {
public void run() {
setEnabled(checkSql());
}
});
try {
Metrics metrics = new Metrics(this);
metrics.start();
} catch (IOException e) {
logInfo("PluginMetrics could not start.");
}
}
|
2d2bcb7a-7a3b-4221-adfe-74bb0c8ebd2a
| 3
|
public void update(MouseEvent e, mxCellState targetState, double x, double y)
{
mxGraph graph = graphComponent.getGraph();
mxICell cell = (mxICell) previewState.getCell();
mxRectangle dirty = graphComponent.getGraph().getPaintBounds(
new Object[] { previewState.getCell() });
if (cell.getTerminal(false) != null)
{
cell.getTerminal(false).removeEdge(cell, false);
}
if (targetState != null)
{
((mxICell) targetState.getCell()).insertEdge(cell, false);
}
mxGeometry geo = graph.getCellGeometry(previewState.getCell());
geo.setTerminalPoint(startPoint, true);
geo.setTerminalPoint(transformScreenPoint(x, y), false);
revalidate(previewState);
fireEvent(new mxEventObject(mxEvent.CONTINUE, "event", e, "x", x, "y",
y));
// Repaints the dirty region
// TODO: Cache the new dirty region for next repaint
Rectangle tmp = getDirtyRect(dirty);
if (tmp != null)
{
graphComponent.getGraphControl().repaint(tmp);
}
else
{
graphComponent.getGraphControl().repaint();
}
}
|
c7e7c91f-4cf1-47df-92be-1e3d3026cef7
| 2
|
public float[][] getM()
{
float[][] res = new float[4][4];
for ( int i = 0; i < 4; i++ )
for ( int j = 0; j < 4; j++ )
res[i][j] = m[i][j];
return res;
}
|
fc61d207-d826-46af-a3ae-76c05061d0ed
| 6
|
public String addINode(String resource_id, String inode_id)
{
String node_id = null;
int count = 0;
try
{
while((node_id == null) && (count != retryCount))
{
if(count > 0)
{
Thread.sleep((long)(Math.random() * 1000)); //random wait to prevent sync error
}
node_id = IaddINode(resource_id, inode_id);
count++;
}
if((node_id == null) && (count == retryCount))
{
System.out.println("GraphDBEngine : addINode : Failed to add node in " + count + " retrys");
}
}
catch(Exception ex)
{
System.out.println("GraphDBEngine : addINode : Error " + ex.toString());
}
return node_id;
}
|
2c608e39-3ac4-4c85-83bd-ebff4262935a
| 5
|
public static String extractLCS(String s1, String s2, int[][] lcs){
int i = lcs.length-1;
int j = lcs[0].length-1;
int length = lcs[s1.length()][s2.length()];
char[] chars = new char[length];
int index = length - 1;
while(i > 0 && j > 0 && index >= 0){
if(s1.charAt(i-1) == s2.charAt(j-1)){
chars[index] = s1.charAt(i-1);
index --;
i --;
j --;
}else if(lcs[i-1][j] > lcs[i][j-1]){
i --;
}else{
j --;
}
}
return new String(chars, 0, length);
}
|
67f5b159-0a3d-4bf6-958d-6fef12976a22
| 8
|
public static MavenRelationships getByName(String name) {
if (name.equalsIgnoreCase("COMPILE")) {
return COMPILE;
} else if (name.equalsIgnoreCase("PROVIDED")) {
return PROVIDED;
} else if (name.equalsIgnoreCase("RUNTIME")) {
return RUNTIME;
} else if (name.equalsIgnoreCase("TEST")) {
return TEST;
} else if (name.equalsIgnoreCase("SYSTEM")) {
return SYSTEM;
} else if (name.equalsIgnoreCase("PLUGIN")) {
return PLUGIN;
} else if (name.equalsIgnoreCase("IMPORT")) {
return IMPORT;
} else if (name.equalsIgnoreCase("PARENT")) {
return PARENT;
} else {
return UNKONWN;
}
}
|
a8bacfbb-c2af-4698-a4f4-49f03cba8f8f
| 8
|
@Override
public int posicionFichaY(int nivel) {
return nivel == 1 ? 260
: nivel == 2 ? 233
: nivel == 3 ? 206
: nivel == 4 ? 179
: nivel == 5 ? 152
: nivel == 6 ? 125
: nivel == 7 ? 98
: nivel == 8 ? 71
: 0;
}
|
72a7e297-6093-42f0-8b8c-0b7af1f96ce2
| 9
|
private void setPesoLlaveEntera(int llave, double valor){
switch (llave) {
case 0:
this.setPeso(THRESHOLD, valor);
break;
case 1:
this.setPeso(EMBARAZOS, valor);
break;
case 2:
this.setPeso(CONCENTRACION_GLUCOSA, valor);
break;
case 3:
this.setPeso(PRESION_ARTERIAL, valor);
break;
case 4:
this.setPeso(GROSOR_TRICEPS, valor);
break;
case 5:
this.setPeso(INSULINA, valor);
break;
case 6:
this.setPeso(MASA_CORPORAL, valor);
break;
case 7:
this.setPeso(FUNCION, valor);
break;
case 8:
this.setPeso(EDAD, valor);
break;
}
}
|
c07df34c-af89-43e5-8486-235d3658331a
| 0
|
public int getHeight() {
return height;
}
|
6d070109-8221-42f6-a9c9-7a4c15d6c05d
| 3
|
public void removeElement(ZElement element)
{
enleverFocus();
Iterator<ZLien> e = zliens.iterator();
List<ZLien> supp = new ArrayList<ZLien>();
while (e.hasNext()) {
ZLien l = (ZLien) (e.next());
if (l.getElement(Constantes.MCDENTITE1).equals(element)
|| l.getElement(Constantes.MCDENTITE2).equals(element))
supp.add(l);
}
removeLiens(supp);
zelements.remove(element);
repaint();
}
|
ca040ea4-2ecf-4f7c-94ed-24b904faf438
| 5
|
public static TreeMap<Long, IpEntity> getLastConnections() {
TreeMap<Long, IpEntity> treeMap = new TreeMap<>();
TreeMap<Long, IpEntity> resMap = new TreeMap<>();
for (IpEntity ip : requestEntityMap.values()) {
for (UrlEntity url : ip.getUrlSet()) {
System.out.println("for (UrlEntity url : ip.getUrlSet()): " + url);
treeMap.put(url.getLastTime().get(), ip);
}
}
int size = treeMap.size();
if (size <= 16) {
for (int i = 0; i < size; i++) {
Map.Entry<Long, IpEntity> entry = treeMap.pollLastEntry();
resMap.put(entry.getKey(), entry.getValue());
}
} else {
for (int i = 0; i < 16; i++) {
Map.Entry<Long, IpEntity> entry = treeMap.pollLastEntry();
resMap.put(entry.getKey(), entry.getValue());
}
}
return resMap;
}
|
cb1a151a-2926-4c18-a586-142353032b34
| 5
|
public boolean isRestricted(xAuthPlayer player, Event event) {
if (!player.isProtected())
return false;
boolean restrict = true;
String[] split = event.getEventName().split("\\.");
String eventName = split[split.length - 1];
split = eventName.split("(?=\\p{Upper})");
// first element (0) will always be empty for whatever reason
String type = split[1].toLowerCase(); //player, block, entity
String action = split[2].toLowerCase(); // move, place, target, etc.
String restrictNode = String.format("restrict.%s.%s", type, action);
String allowNode = String.format("allow.%s.%s", type, action);
if (plugin.getConfig().contains("guest." + restrictNode)) {
if (!plugin.getConfig().getBoolean("guest." + restrictNode))
restrict = false;
if (xPermissions.has(player.getPlayer(), "xauth." + restrictNode))
restrict = true;
else if (xPermissions.has(player.getPlayer(), "xauth." + allowNode))
restrict = false;
}
return restrict;
}
|
a8c5476f-8273-40f5-97c5-de2c4f613d0e
| 6
|
public String getTooltipExtraText(final Province current) {
final int id = current.getId();
if (!editor.Main.map.isLand(id))
return "";
final String rel = Text.getText(mapPanel.getModel().getHistString(id, "religion"));
if (rel.length() == 0)
return "";
String owner = mapPanel.getModel().getHistString(id, "owner");
String ctryRel = null;
if (owner != null) {
owner = owner.toUpperCase();
if (Utilities.isNotACountry(owner) /*noCountryPattern.matcher(owner).matches()*/) {
// don't add anything
owner = "-";
} else {
ctryRel = Text.getText(mapPanel.getModel().getHistString(owner, "religion"));
}
} else {
owner = "-";
}
final StringBuilder text = new StringBuilder("Owner: ");
if (!owner.equals("-"))
text.append(Text.getText(owner)).append(" ").append("(").append(owner).append(")<br />");
text.append("Religion: ").append(rel);
if (ctryRel != null)
text.append("<br />Owner's religion: ").append(ctryRel);
return text.toString();
}
|
812ac2ba-c28c-48d6-bce7-16644455af77
| 5
|
public ListNode rotateRight(ListNode head, int n) {
if (head == null) {
return null;
}
ListNode n1 = head;
ListNode n2 = head;
//n2 move length - n steps
while (n > 0) {
n2 = n2.getNext();
n--;
//in case n > the length of list
if (n2 == null) {
n2 = head;
}
}
//n = 0
if (n1 == n2) {
return n1;
}
//n1 move n steps
while (n2.getNext() != null) {
n1 = n1.getNext();
n2 = n2.getNext();
}
//n1 points the end of the new list, n2 used to connect the new list
ListNode temp = n1.getNext();
n2.setNext(head);
n1.setNext(null);
return temp;
}
|
8a48ab20-1fe8-4c06-9f8c-6261899802d9
| 6
|
public Object getParameter(String key) {
if (key.contains(GameSocketServer.BLACKHAND_KEY))
return blackhand;
if (key.contains(GameSocketServer.SURRENDER_KEY))
return surrender;
if (key.contains(GameSocketServer.TEAMS))
return teams;
if (key.contains(GameSocketServer.CARD_SWAP))
return cardswap;
if (key.contains(BriscaGameFactory.TOURNAMENT_GAME))
return tournament;
if (key.contains(GameSocketServer.LIFECARD_KEY))
return life;
return null;
}
|
7c185a26-5696-4dc4-bfa4-2f437aa2692a
| 8
|
public void testSetValue() {
int scalar = 0;
int[] array = { 1, 2, 3 };
ArrayELResolver resolver = new ArrayELResolver();
ArrayELResolver resolverReadOnly = new ArrayELResolver(true);
// base == null --> unresolved
context.setPropertyResolved(false);
resolver.setValue(context, null, "foo", -1);
assertFalse(context.isPropertyResolved());
// base is scalar --> unresolved
context.setPropertyResolved(false);
resolver.setValue(context, scalar, "foo", -1);
assertFalse(context.isPropertyResolved());
// base is array, property == 1 --> ok
context.setPropertyResolved(false);
resolver.setValue(context, array, 1, 999);
assertEquals(999, array[1]);
assertTrue(context.isPropertyResolved());
// base is array, bad property --> exception
try {
resolver.setValue(context, array, null, 999);
fail();
} catch (IllegalArgumentException e) {
// fine
}
try {
resolver.setValue(context, array, "foo", 999);
fail();
} catch (IllegalArgumentException e) {
// fine
}
try {
resolver.setValue(context, array, -1, 999);
fail();
} catch (PropertyNotFoundException e) {
// fine
}
try {
resolver.setValue(context, array, array.length, 999);
fail();
} catch (PropertyNotFoundException e) {
// fine
}
// base is array, property == 1, bad value --> exception
try {
resolver.setValue(context, array, 1, null);
fail();
} catch (IllegalArgumentException e) {
// fine
}
try {
resolver.setValue(context, array, 1, "foo");
fail();
} catch (ClassCastException e) {
// fine, according to the spec...
} catch (IllegalArgumentException e) {
// violates the spec, but we'll accept this...
}
// read-only resolver
try {
resolverReadOnly.setValue(context, array, 1, 999);
fail();
} catch (PropertyNotWritableException e) {
// fine
}
}
|
84bf8e5a-de19-48c0-aa63-eb002e924c5b
| 5
|
public static void main(String[] args)
{
int secretNumber;
Scanner input = new Scanner(System.in);
int guess;
int num = 1;
while(num < 4)
{
secretNumber = (int)(Math.random() * 999 + 1);
System.out.print("Guess a number: ");
guess = input.nextInt();
System.out.printf("Your guess is %d.\n", guess);
System.out.printf("The secret number is %d.\n", secretNumber);
if((guess > secretNumber) && (guess > secretNumber + 10))
System.out.println("Your guess is more than 10 too big!");
else if((guess < secretNumber) || (guess == secretNumber))
System.out.println("Your guess is less than or equal to the secret number!");
else
System.out.println("Your guess is correct!");
num++;
}
}
|
2dd44611-b44d-41e0-94a2-9035cafaec02
| 8
|
protected boolean computeCell(int col, int row)
{
boolean liveCell = getCell(col, row);
int neighbours = countNeighbours(col, row);
boolean nextCell = false;
if (neighbours < 2) nextCell = false;
if (liveCell && (neighbours == 2 || neighbours == 3)) nextCell = true;
if (liveCell && neighbours > 3) nextCell = false;
if (!liveCell && neighbours == 3) nextCell = true;
return nextCell;
}
|
a1601d91-f3c6-4308-91d3-eb9b30e8c934
| 0
|
public FinalData(String id) {
this.id = id;
}
|
048aa293-6d68-444c-b17a-fb4ff1f451ab
| 0
|
public Autorize()
{
this.setSize(100,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c=this.getContentPane();
c.setLayout(new GridLayout(2,1));
port=new JLabel("Port:");
adress=new JLabel("Adress:");
name=new JLabel("Name:");
_port=new JTextField("8080");
_adress=new JTextField("127.0.0.1");
_name=new JTextField("Name");
action=new JButton("Ok");
JPanel p=new JPanel();
p.setLayout(new GridLayout(3,3));
p.add(port);
p.add(_port);
p.add(adress);
p.add(_adress);
p.add(name);
p.add(_name);
c.add(p);
c.add(action);
}
|
c9db52aa-8d37-4c92-8fd8-64b5915faa5a
| 0
|
@Override
public void keyPressed(KeyEvent e) {
}
|
a9a8a93f-738e-484c-9b18-d2d956efbe53
| 7
|
@Override
public boolean execute(MOB mob, List<String> commands, int metaFlags)
throws java.io.IOException
{
final Room room=mob.location();
if(room==null)
return false;
if((commands.size()>1)&&((room.domainType()&Room.INDOORS)==0)&&(commands.get(1).equalsIgnoreCase("WORLD")))
{
final StringBuffer tellMe=new StringBuffer("");
for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();)
{
final Area A=a.nextElement();
if((CMLib.flags().canAccess(mob,A))
&&(!CMath.bset(A.flags(),Area.FLAG_INSTANCE_CHILD)))
tellMe.append(CMStrings.padRight(A.name(),20)+": "+A.getClimateObj().weatherDescription(room)+"\n\r");
}
mob.tell(tellMe.toString());
return false;
}
mob.tell(room.getArea().getClimateObj().weatherDescription(room));
return false;
}
|
cca2307d-6a3a-4c85-84fa-d1c284eeec5f
| 4
|
private static void binarySort(int[] array){
for (int i=0;i<array.length - 1;++i){
int temp=array[i];
int left=0;
int right=i;
while (left<right){
int middle=(left+right)/2;
if (temp>=array[middle])
left=right+1;
else
right=middle;
}
for (int j=i;j>left;--j){
swap(array,j-1,j);
}
}
}
|
e1c25bca-e014-476a-8f29-469be6a186eb
| 4
|
private void checkIfCanCreate() {
boolean canCreate = false;
synchronized (this) {
if (matchingItems != null) {
if (matchingItems.size() > 0) {
String item = matchingItems.get(currentItem);
if (canCreate(item)) {
canCreate = true;
}
}
}
if (canCreate) {
getHUDAreaByType("create").setImage("HUD/Master/CreateOn");
} else {
getHUDAreaByType("create").setImage("HUD/Master/Create");
}
}
}
|
a64ebe9a-b74e-4c70-bad5-440b13635d31
| 2
|
public Turnstile getTurnstile(int id) {
if (id < 0 || id >= turnstiles.size()) {
return null;
} else {
return turnstiles.get(id);
}
}
|
f7163806-a1de-4a33-9921-918ac7dd333e
| 3
|
public String writeVerbose(Puzzle p) {
StringBuilder sb = new StringBuilder();
appendLine(sb, p);
sb.append("\n");
for (int r = 0; r < p.getSide(); r++) {
if (r > 0 && r % p.getBoxSize() == 0) {
appendDivisor(sb, p);
}
appendRow(sb, p, r);
}
appendLine(sb, p);
return sb.toString();
}
|
28223746-be35-4d37-bc1a-708a38752314
| 1
|
private String[] getCustomFilterPropertyValue(final Properties properties) {
String values = this.getPropertyValue(properties, CUSTOM_FILTER_TAG, null);
if (values == null) {
return null;
}
return values.split(PARAM_SEPARATOR);
}
|
a72cf488-f334-44f3-a6db-f21736e80130
| 8
|
public void onLoad() {
plugin = this;
PluginManager pm = getServer().getPluginManager();
// Make sure we haven't already been added
try {
@SuppressWarnings("unchecked")
Map<Pattern, PluginLoader> map = (Map<Pattern, PluginLoader>) Reflection.getPrivateValue(pm, "fileAssociations");
if (map != null && map.containsKey(PythonLoader.PATTERNS[0])) {
getLogger().info("MiniPython was already loaded, aborting");
return;
}
} catch (Exception ex) {
getLogger().severe("Failed to ensure MiniPython isn't already loaded");
return;
}
// Add to Bukkit
pm.registerInterface(PythonLoader.class);
// Must manually load plugins to avoid reloading existing Java plugins
File[] list = this.getFile().getParentFile().listFiles();
if (list == null) {
getLogger().severe("Failed to search for Python plugins");
return;
}
for (File file : list) {
for (Pattern filter : PythonLoader.PATTERNS) {
if (filter.matcher(file.getName()).find()) {
try {
getLogger().info("Loading " + file.getName());
pm.loadPlugin(file);
} catch (Exception e) {
getLogger().log(Level.SEVERE, "Could not load Python plugin " + file.getName(), e);
e.printStackTrace();
}
}
}
}
}
|
b00cd910-4adf-404d-83be-d2d52f84b6c1
| 0
|
public YamlConfiguration getConfig() {
return config;
}
|
71eb560a-2ee5-4218-af11-2502bf7d7836
| 4
|
@Override
public Connection openConnection() throws SQLException,
ClassNotFoundException {
if (checkConnection()) {
return connection;
}
if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs();
}
File file = new File(plugin.getDataFolder(), dbLocation);
if (!(file.exists())) {
try {
file.createNewFile();
} catch (IOException e) {
plugin.getLogger().log(Level.SEVERE,
"Unable to create database!");
}
}
Class.forName("org.sqlite.JDBC");
connection = DriverManager
.getConnection("jdbc:sqlite:"
+ plugin.getDataFolder().toPath().toString() + "/"
+ dbLocation);
return connection;
}
|
8bf316f4-7211-46ed-9c9e-8e8eae737da0
| 2
|
private static void sameArrayLen(double[]... arr) {
int len = arr[0].length;
for (double[] a : arr) {
if (a.length != len) {
throw new IllegalArgumentException("obs and sim data have not same size (" + a.length + "/" + len + ")");
}
}
}
|
2f657b67-4f96-486a-98c0-4b3c43dfcc0d
| 1
|
private JTextField getJTextField1() {
if (jTextField1 == null) {
jTextField1 = new JTextField();
}
return jTextField1;
}
|
86d0e574-8a45-4e5d-8e4b-3ee6f573fe6f
| 3
|
public int playDichotomy(User user, int left, int right) {
assert (left <= right) : "left > right";
if (left == right) {
return user.theNumberIs(left) ? left : UNDEFINED;
} else {
final int middle = (left + right) >>> 1;
final int leftBranchTry = playDichotomy(user, left, middle);
return (leftBranchTry != UNDEFINED) ? leftBranchTry : playDichotomy(user, middle + 1, right);
}
}
|
3b789a8a-ded8-40a8-a5f1-71f6b26cc5b3
| 1
|
public void addStock(Stock stock) {
if (!this.stocks.contains(stock)) {
this.stocks.add(stock);
stock.addSubProcess(this);
}
}
|
c62691e2-091d-490f-921a-c9e1e6aebc97
| 2
|
@Override
void draw(Graphics g, int xSize, int ySize) {
xPixels = col*xSize;
yPixels = row*ySize;
if (color.equals(Color.RED)) {
g.setColor(Color.RED);
g.fillRect(xPixels, yPixels, xSize, ySize);
}
else if (color.equals(Color.CYAN)) {
g.setColor(Color.CYAN);
g.fillRect(xPixels, yPixels, xSize, ySize);
}
g.setColor(Color.BLACK);
g.drawRect(xPixels, yPixels, xSize, ySize);
}
|
cf25382a-9150-4bd8-8b13-be00cbe3e0b1
| 9
|
public void tick()
{
for (int menu = 0; menu < menus.size(); menu++)
{
//if (!main.enabled) break;
if (menus.get(menu).active())
{
//System.out.println("Menu " + menu);
for (int i = clicks.size() - 1; i >= 0; i--)
{
String command = menus.get(menu).click(clicks.get(i).mouseX, clicks.get(i).mouseY);
if (command != null && !command.equals(""))
{
menuActivated = true;
//Replace with function that returns true if the menu resetting should happen
if (executeAction(command))
{
main.resetCamera();
}
}
}
}
if (menus.get(menu).active() && !menus.get(menu).noShortcuts)
makeShortcut(menus.get(menu));
}
if (techMenu.active())
makeShortcut(techMenu);
clicks.clear();
/*
//main.textFont(arial);
//main.resetShader();
main.hint(PApplet.DISABLE_DEPTH_TEST);
//main.textSize(20);
//main.background(255,255,255,0);
main.camera();
main.perspective();
main.resetShader();
main.noLights();
main.noStroke();
main.textSize(12);
lastHighlighted = highlighted;
lastMouseHighlighted = mouseHighlighted;
//System.out.println(menus.get(0).findButtonByCommand("markTile").posX);
//System.out.println(menus.get(0).findButtonByCommand("markTile").posY);
//System.out.println("======");
main.textAlign(main.CENTER);
//main.text("When selecting a unit, hold Q to bring out the quick menu. Drag with right click to the desired tile.", 500, 80);
//main.image(EntityData.iconMap.get("CopperWeapons"),200,200,200,200);
if (minimapMode == 1 || minimapMode == 2)
{
//main.rect(0, 700, 50, 50);
int con = 1;
main.noFill();
float sX = main.width - 300; float sY = main.height - 600; float widthX = 250; float widthY = 250;
main.rect(sX, sY, widthX, widthY);
//System.out.println(rbox[0] + " " + rbox[1] + " " + rbox[2] + " " + rbox[3]);
if (minimapMode == 2)
{
for (int r = rbox[0]; r <= rbox[0] + rbox[2]; r += con)
{
for (int c = rbox[1]; c <= rbox[1] + rbox[3]; c += con)
{
Tile t = main.grid.getTile(r,c);
if (t == null) continue;
minimapFill(t);
//main.rect(sX + (main.grid.rows-r)/(float)main.grid.rows*widthX,sY + c/(float)main.grid.cols*widthY,widthX*con/main.grid.rows,widthY*con/main.grid.cols);
//System.out.println(sX + r/(float)main.grid.rows*widthX);
main.rect(sX + (r-rbox[0])/(float)rbox[2]*widthX, sY + (1 - (c-rbox[1])/(float)(rbox[3]))*widthY, widthX*con/(float)rbox[2], widthY*con/(float)rbox[3]);
}
}
}
else //if (minimapMode == 1) by disjunctive syllogism
{
int rr = 0, cc = 0;
if (highlighted != null)
{
for (int r = highlighted.row - sight; r <= highlighted.row + sight; r++)
{
for (int c = highlighted.col - sight; c <= highlighted.col + sight; c++)
{
Tile t = main.grid.getTile(r,c);
if (t == null) {cc++; continue;}
float wX = widthX/(sight*2 + 1), wY = widthY/(sight*2 + 1);
//minimapFill(t);
if (main.grid.civs[0].revealed[r][c] == 0 && !main.showAll)
{
main.fill(0);
main.rect(sX + rr*wX,sY + (sight*2 + 1 - cc)*wY,wX,wY);
cc++;
continue;
}
if (t.biome == -1)
main.fill(150,225,255,150);
else if (t.owner == null)
main.fill(150,255);
else
main.fill(t.owner.r, t.owner.g, t.owner.b, 255);
main.stroke(0);
main.rect(sX + rr*wX,sY + (sight*2 + 1 - cc)*wY,wX,wY);
ArrayList<PImage> images = icon(t);
if (images.size() > 0)
for (int i = images.size() - 1; i >= 0; i--)
if (images.get(i) != null)
{
if (t.occupants.get(i).owner != null)
main.tint(t.occupants.get(i).owner.r, t.occupants.get(i).owner.g, t.occupants.get(i).owner.b);
else
main.tint(150);
main.image(images.get(i),sX + (rr+0.25F)*wX,sY + (sight*2 + 1 - cc + 0.25F - 0.25F*i)*wY,wX/2F,wY/2F); //Flip cols
}
cc++;
}
rr++;
cc = 0;
}
}
}
}
if (info)
{
main.fill(0);
main.rect(100,130,200,100);
main.fill(255);
main.textAlign(PApplet.LEFT);
main.text("Seed: " + main.seed, 115, 150);
}
if (textboxes.get(4).active)
{
updateCivStats();
}
if (console != null)
{
textboxes.get(8).active = true;
textboxes.get(8).display.clear();
textboxes.get(8).display.add(console);
}
else
{
textboxes.get(8).active = false;
}
//menus.get(6).active = ledgerMenu;
//System.out.println(loadout + " " + loadoutDisplay);
//Render the cursor
if (!menus.get(7).active && !menus.get(9).active)
{
int width = 6;
main.stroke(255);
main.fill(0);
main.rect((main.width - width)/2, (main.height - width)/2, width, width);
}
main.noStroke();
ArrayList<String> hintText = textboxes.get(0).display;
//hintText.clear();
if (mouseHighlighted != null)
{
String stringy = (main.grid.cols - mouseHighlighted.col) + " " + mouseHighlighted.row;
if (mouseHighlighted.owner != null)
stringy += " (" + mouseHighlighted.owner.name + ")";
hintText.add(stringy);
//else
//hintText.add("Terra nullius");
String biomeText = "";
if (mouseHighlighted.biome >= 4 && mouseHighlighted.biome <= 6)
if (mouseHighlighted.forest)
biomeText += EntityData.getBiomeName(mouseHighlighted.biome) + " (fertile)";
else
biomeText += EntityData.getBiomeName(mouseHighlighted.biome);
else
biomeText += EntityData.getBiomeName(mouseHighlighted.biome);
if (mouseHighlighted.shape == 1)
biomeText += ", Hill";
else if (mouseHighlighted.shape == 2)
biomeText += ", Mountain";
hintText.add(biomeText);
if (mouseHighlighted.improvement != null)
{
hintText.add(mouseHighlighted.improvement.name + ", " + mouseHighlighted.improvement.id);
}
else
hintText.add("Pristine");
if (mouseHighlighted.city != null)
{
if (mouseHighlighted.city.owner != null)
{
double[] data = mouseHighlighted.city.evaluate(mouseHighlighted, -1);
hintText.add((int)data[0] + " F, " + (int)data[1] + " G, " + (int)data[2] + " M, " + (int)data[3] + " R");
}
}
else //A rough estimate that does not take the city into account
{
double[] data = City.staticEval(mouseHighlighted);
hintText.add((int)data[0] + " F, " + (int)data[1] + " G, " + (int)data[2] + " M, " + (int)data[3] + " R");
}
//Same check as above, really
if (mouseHighlighted.owner != null)
hintText.add("Relations: " + mouseHighlighted.owner.opinions[0]);
if (main.grid.irrigated(mouseHighlighted.row, mouseHighlighted.col))
hintText.add("Fresh Water");
if (mouseHighlighted.occupants.size() > 0)
{
//String stringy;
stringy = "";
if (mouseHighlighted.occupants.size() > 3)
{
stringy += "Stack (" + mouseHighlighted.occupants.size() + ")";
}
else
{
for (int i = 0; i < mouseHighlighted.occupants.size(); i++)
{
GameEntity en = mouseHighlighted.occupants.get(i);
stringy += en.name + " (" + en.owner + "); ";
}
//if (!stringy.equals(""))
hintText.add(stringy.substring(0,stringy.length()-2));
}
}
String resource = EntityData.getResourceName(mouseHighlighted.resource);
if (resource != null)
hintText.add(resource);
hintText.add(" ");
if (mouseHighlighted != null)
{
ArrayList<String> conditions;
if (mouseHighlighted.improvement != null)
conditions = City.staticEvalReasons(mouseHighlighted, mouseHighlighted.improvement.name);
else
conditions = City.staticEvalReasons(mouseHighlighted, null);
ArrayList<String> text6 = textboxes.get(6).display;
ArrayList<String> text7 = textboxes.get(7).display;
int[] bYield = {0,0,0,0};
for (int i = 0; i < conditions.size(); i++)
{
text6.add(conditions.get(i));
int[] yield = EntityData.yield.get(conditions.get(i));
String s = "";
for (int j = 0; j < yield.length; j++)
{
bYield[j] += yield[j];
if (yield[j] == 0) s += " ";
else if (yield[j] > 0) s += "+" + yield[j];
else s += yield[j];
s += " ";
}
text7.add(s);
}
String s = "";
for (int j = 0; j < bYield.length; j++)
{
if (bYield[j] == 0) s += " ";
else if (bYield[j] > 0) s += "+" + bYield[j];
else s += bYield[j];
s += " ";
}
text6.add("TOTAL YIELD");
text7.add(s);
s = "";
if (mouseHighlighted.improvement == null)
{
String impr = EntityData.optimalImpr(mouseHighlighted);
if (impr != null)
text6.add("With " + impr.toLowerCase());
double[] aYield = City.staticEval(mouseHighlighted, impr);
for (int j = 0; j < aYield.length; j++)
{
if (aYield[j] - bYield[j] == 0) s += " ";
else if (aYield[j] - bYield[j] > 0) s += "+" + (int)(aYield[j] - bYield[j]);
else s += (int)(aYield[j] - bYield[j]);
s += " ";
}
text7.add(s);
}
}
}
Tile h = highlighted;
MouseHelper mh = main.inputSystem.mouseHelper;
main.noStroke();
if (selected != null) //Allow GUI to show elements specific to selected unit
{
if (selected.owner != null && !(selected instanceof City))
{
main.fill(255);
//main.textSize(14);
ArrayList<String> temp = textboxes.get(1).display;
//temp.clear();
temp.add(selected.name + " " + ((GameEntity)selected).action*2 + "/" + ((GameEntity)selected).maxAction*2);
//temp.add(selected.health + "<!health!>/" + selected.maxHealth + " health");
temp.add(selected.health + "/" + selected.maxHealth + " health");
temp.add(selected.offensiveStr + " offensive, " + selected.rangedStr + " ranged,");
temp.add(selected.defensiveStr + " defensive");
if (!typeOfLastSelected.equals(selected.name))
{
updateUnitMenu((GameEntity)selected);
}
if (!menus.get(1).active())
menus.get(1).activate(true);
//main.text("Test", main.width*5/6 + 15, main.height*5/6 + 15);
}
else
{
if (menus.get(1).active())
menus.get(1).activate(false);
}
if ((getSelected() instanceof City || getSelected() instanceof Settler || getSelected() instanceof Worker) && h != null &&
(main.grid.civs[0].revealed[h.row][h.col] != 0 || main.showAll) && main.player.posY < height)
{
for (int r = 0; r < mh.guiPositions.length; r++)
{
for (int c = 0; c < mh.guiPositions[0].length; c++)
{
float[] pos = mh.positionGui(r,c);
if (pos != null)
{
if (!main.newMenuSystem.notOverlapping(pos[0], pos[1])) continue;
main.textAlign(main.CENTER);
main.textSize(18);
main.fill(255,0,0);
int dC = r - (mh.guiPositions.length-1)/2;
int dR = c - (mh.guiPositions[0].length-1)/2;
//float[] disp = mh.center();
float dX = main.width/2 - highlightDispX, dY = main.height/2 - highlightDispY;
//float dX = 0, dY = 0;
//System.out.println(dX + " " + dY + " " + highlightDispX + " " + highlightDispY);
Tile t = main.grid.getTile(h.row + dR, h.col - dC);
if (t != null)
{
if (t.biome == -1 && main.grid.adjacentLand(t.row, t.col).size() == 0 ||
main.grid.civs[0].revealed[t.row][t.col] == 0 && !main.showAll)
continue;
//if (movementChoices.contains(t))
//main.text(">", pos[0] - dX,pos[1] - dY + 10);
if (!(getSelected() instanceof City) && pathToHighlighted != null)
{
int index = pathToHighlighted.indexOf(t);
if (index != -1)
main.text(pathToHighlighted.size() - index, pos[0] - dX,pos[1] - dY + 20);
}
if (movementChoices.size() > 0) continue;
//main.text(t.row + "," + t.col, pos[0], pos[1]);
if (!main.tacticalView)
{
double[] y = City.staticEval(t);
//float height = pos[1]-dY+(5-dC)*8;
float height = pos[1]-dY+25;
//if (dC >= 1)
//height += 20*dC; //height = pos[1]-dY;
main.newMenuSystem.tileIcon(pos[0]-dX, height, (int)y[0], (int)y[1], (int)y[2], (int)y[3], t.harvest);
//main.rect(pos[0]-dX-5, height-5+25, 10, 10);
PImage img = EntityData.iconMap.get(EntityData.getBiomeName((t.biome)));
int len = 20;
float iX = pos[0]-dX-len/2, iY = pos[1]-dY+10;
main.tint(255,255,255,100);
//Make way for the appropriate GUIs
if (t.forest || t.freshWater)
{
if (img != null)
{
main.image(img, iX, iY, len, len);
iX = pos[0]-dX+len/2; //iY = pos[1]-dY+20-len/2;
}
}
else
{
iX = pos[0]-dX;
}
img = EntityData.iconMap.get(EntityData.getResourceName(t.resource));
if (img != null)
{
main.tint(255,255,255,255);
main.pushStyle();
if (t.owner != null)
{
main.strokeWeight(3);
main.noFill();
main.stroke(t.owner.r, t.owner.g, t.owner.b);
main.rect(iX, iY, len, len);
}
main.image(img, iX, iY + 2*len, len, len);
main.popStyle();
//iX = pos[0]-dX-len/2; iY = pos[1]-dY+20-len/2;
}
main.tint(255,255,255,255);
//main.rect(pos[0]-dX, pos[1]-dY, 10, 10);
int n = 0;
for (int i = 0; i < y.length; i++)
if (y[i] > 0)
n++;
int iter = 1;
for (int i = 0; i < y.length; i++)
if (y[i] > 0)
{
main.newMenuSystem.tileIcon(pos[0] - dX,pos[1] - dY,i,(int)y[i],n,iter);
iter++;
}
}
}
}
}
}
}
}
else
menus.get(1).activate(false);
menus.get(14).activate(main.tacticalView);
if (requestFieldsUpdate)
{
menus.get(14).buttons.clear();
}
main.strokeWeight(1);
if (h != null && main.player.posY < height)
{
for (int r = 0; r < mh.guiPositions.length; r++)
{
for (int c = 0; c < mh.guiPositions[0].length; c++)
{
float[] pos = mh.positionGui(r,c);
if (pos != null)
{
if (!main.newMenuSystem.notOverlapping(pos[0], pos[1])) continue;
main.textAlign(main.CENTER);
main.textSize(18);
main.fill(255,0,0);
int dC = r - (mh.guiPositions.length-1)/2;
int dR = c - (mh.guiPositions[0].length-1)/2;
float dX = main.width/2 - highlightDispX, dY = main.height/2 - highlightDispY;
Tile t = main.grid.getTile(h.row + dR, h.col - dC);
if (t != null)
{
if (t.biome == -1 && main.grid.adjacentLand(t.row, t.col).size() == 0 && t.resource == 0 ||
main.grid.civs[0].revealed[t.row][t.col] == 0 && !main.showAll)
continue;
if (markedTiles[h.row + dR][h.col - dC])
main.text("X", pos[0] - dX,pos[1] - dY + 20);
if (t.improvement != null)
{
if (t.improvement instanceof City)
{
//main.rectMode(main.LEFT);
City city = (City)t.improvement;
//Growth GUI
main.fill(0);
//main.rectMode(main.CENTER);
main.rect(pos[0] - dX - 50, pos[1] - dY - 10, 100, 20);
main.fill(0,255,0);
//System.out.println((float)city.percentGrowth*100);
main.rect(pos[0] - dX - 50, pos[1] - dY - 10, 100F*(float)city.percentGrowth, 20);
main.fill(255);
main.textAlign(main.CENTER);
main.text(city.name + " <" + ((int)(city.percentGrowth*10000F)/100) + "% >", pos[0] - dX, pos[1] - dY + 3);
//Queue GUI
if (city.queue != null)
{
main.fill(0, 100);
main.rect(pos[0] - dX - 50, pos[1] - dY + 10, 100, 20);
float[] cost = EntityData.getCost(city.queue);
main.fill(0,255,0,255);
main.rect(pos[0] - dX - 50, pos[1] - dY + 10, (float)Math.min(100F, 100F*(1 - city.queueFood/cost[0])), 10);
main.fill(255,150,0,255);
main.rect(pos[0] - dX - 50, pos[1] - dY + 20, (float)Math.min(100F, 100F*(1 - city.queueMetal/cost[2])), 10);
main.fill(255,255);
main.textAlign(main.CENTER);
//main.text(city.name + " <" + ((int)(city.percentGrowth*10000F)/100) + "% >", pos[0] - dX, pos[1] - dY + 3);
}
main.textAlign(main.LEFT);
//main.rectMode(main.LEFT);
}
}
//if (!main.tacticalView)
if (true)
{
float len = 30; boolean cityGui = false;
if (t.improvement != null)
{
if (t.improvement instanceof City)
{
City city = (City)t.improvement;
main.tint(t.improvement.owner.r, t.improvement.owner.g, t.improvement.owner.b);
PImage image = city.owner.id >= main.grid.barbarians ? EntityData.iconMap.get("CityIcon") : EntityData.iconMap.get("Barbarian");
if (t.improvement.owner.capital != null)
if (t.improvement.owner.capital.equals(t.improvement))
image = EntityData.iconMap.get("Capital");
main.image(image, pos[0] - dX - 3*len/2, pos[1] - dY - 30 - len/2, len, len);
int i = 0;
main.image(image, pos[0] - dX - len/2 - len, pos[1] - dY - 30 - i*30 - len/2, len, len);
main.image(EntityData.iconMap.get("population"), pos[0] - dX - len/2, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.image(EntityData.iconMap.get("defense"), pos[0] - dX - len/2, pos[1] - dY - 30 - i*30, len/2, len/2);
main.image(EntityData.iconMap.get("ranged"), pos[0] - dX - len/2 + len, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.image(EntityData.iconMap.get("cityhealth"), pos[0] - dX - len/2 + len, pos[1] - dY - 30 - i*30, len/2, len/2);
main.fill(0);
main.rect(pos[0] - dX, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.rect(pos[0] - dX, pos[1] - dY - 30 - i*30, len/2, len/2);
main.rect(pos[0] - dX + len, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.rect(pos[0] - dX + len, pos[1] - dY - 30 - i*30, len/2, len/2);
main.textAlign(main.LEFT, main.TOP);
main.fill(255);
main.text((int)city.population, pos[0] - dX, pos[1] - dY - 30 - i*30 - len/2);
main.text((int)city.defensiveStr, pos[0] - dX, pos[1] - dY - 30 - i*30);
main.text((int)city.rangedStr, pos[0] - dX + len, pos[1] - dY - 30 - i*30 - len/2);
main.text((int)city.health, pos[0] - dX + len, pos[1] - dY - 30 - i*30);
cityGui = true;
}
}
if (t.occupants.size() > 0)
{
//for (int i = 0; i < t.occupants.size(); i++)
if (!(selected instanceof City) && !(getSelected() instanceof Settler))
{
for (int i = t.occupants.size() - 1; i >= 0; i--)
{
GameEntity en = t.occupants.get(i);
main.fill(en.owner.r, en.owner.g, en.owner.b);
//main.rectMode(main.CENTER);
//main.rect(pos[0] - dX - len/2, pos[1] - dY - 60 - i*10 - len/2, len, len);
PImage image = EntityData.iconMap.get(en.name);
float iX, iY;
//ArrayList<PImage> images = icon(t);
if (image != null)
{
main.pushStyle();
main.tint(en.owner.r, en.owner.g, en.owner.b);
//main.rectMode(main.LEFT);
if (en.mode != 0)
{
//TODO
//Redefine this type of unit stat rendering
//as a function which accepts a unit and some of its stat types as input
//and renders in correct order at the appropriate location
//4*len to compensate for unit strength GUI
iX = pos[0] - dX - len/2 - len; iY = pos[1] - dY - (i+1)*len - len/2;
if (cityGui)
iY -= len;
unitStats(en, iX, iY, len);
main.image(image, iX, iY, len, len);
main.image(EntityData.iconMap.get("attack"), pos[0] - dX - len/2, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.image(EntityData.iconMap.get("defense"), pos[0] - dX - len/2, pos[1] - dY - 30 - i*30, len/2, len/2);
main.image(EntityData.iconMap.get("ranged"), pos[0] - dX - len/2 + len, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.image(EntityData.iconMap.get("health"), pos[0] - dX - len/2 + len, pos[1] - dY - 30 - i*30, len/2, len/2);
main.fill(0);
main.rect(pos[0] - dX, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.rect(pos[0] - dX, pos[1] - dY - 30 - i*30, len/2, len/2);
main.rect(pos[0] - dX + len, pos[1] - dY - 30 - i*30 - len/2, len/2, len/2);
main.rect(pos[0] - dX + len, pos[1] - dY - 30 - i*30, len/2, len/2);
main.textAlign(main.LEFT, main.TOP);
main.fill(255);
main.text((int)en.offensiveStr, pos[0] - dX, pos[1] - dY - 30 - i*30 - len/2);
main.text((int)en.defensiveStr, pos[0] - dX, pos[1] - dY - 30 - i*30);
main.text((int)en.rangedStr, pos[0] - dX + len, pos[1] - dY - 30 - i*30 - len/2);
main.text((int)en.health, pos[0] - dX + len, pos[1] - dY - 30 - i*30);
//image = EntityData.iconMap.get("CopperWeapons");
//main.image(image, iX + len*0.6F, iY + len*0.6F, len*0.4F, len*0.4F);
}
else
{
iX = pos[0] - dX - len/2; iY = pos[1] - dY - 30 - i*30 - len/2;
main.image(image, iX, iY, len, len);
}
main.popStyle();
if (en.unitImprovement != null)
{
image = null; image = EntityData.iconMap.get(en.unitImprovement.name);
if (image != null)
main.image(image, iX + len*0.6F, iY, len*0.4F, len*0.4F);
}
}
}
}
else
{
for (int i = t.occupants.size() - 1; i >= 0; i--)
{
GameEntity en = t.occupants.get(i);
if (main.grid.civs[0].isWar(en.owner))
main.fill(255,0,0);
else
main.fill(150,225,255);
float iX = pos[0] - dX - len/2, iY = pos[1] - dY - 60 - i*10 - len/2;
main.stroke(en.owner.r, en.owner.g, en.owner.b);
main.rect(iX + len/4, iY + len/4, len/2, len/2);
main.noStroke();
}
}
}
}
if (main.tacticalView)
{
int len = 8;
//main.fill(t.owner.r, t.owner.g, t.owner.b);
//main.rect(pos[0] - dX - len/2, pos[1] - dY - len/2, len, len);
//Replace with for loop //done
if (requestFieldsUpdate)
{
//requestFieldsUpdate = false;
main.newMenuSystem.largeFieldIcon(pos[0]-dX,pos[1]-dY + len*1.5F,t,(int)(len*1.5));
if (Math.random() < 0.01)
System.out.println(t.maxFields);
}
for (int i = 0; i <= 3; i++)
{
if (t.maxFields > i)
{
main.newMenuSystem.fieldIcon(pos[0]-dX,pos[1]-dY + len*1.5F,t,i,len,(int)(len*1.5F));
}
}
}
}
}
}
}
}
if (requestFieldsUpdate) requestFieldsUpdate = false;
main.textSize(12);
if (mouseHighlighted != null && selected instanceof GameEntity)
{
GameEntity atk = (GameEntity)selected;
if (mouseHighlighted.occupants.size() > 0)
{
BaseEntity def = mouseHighlighted.occupants.get(0);
if (def == null && mouseHighlighted.improvement instanceof City)
def = mouseHighlighted.improvement;
if (atk.owner.isWar(def.owner))
{
if (atk.mode != 0)
{
//Preview of calculated damage
int[] offensiveDamage = main.grid.conflictSystem.attackNoRandomness(atk.offensiveStr, def.defensiveStr);
int[] defensiveDamage = main.grid.conflictSystem.attackNoRandomness(def.offensiveStr, atk.defensiveStr);
//All numbers, great
float iX = 150, iY = main.height - 150, len = 40;
main.pushStyle();
main.textAlign(main.CENTER, main.TOP);
main.fill(0);
main.rect(iX, iY - 30, 340, 30);
main.fill(255);
main.text(atk.name + " (" + atk.owner.name + ") vs " + def.name + " (" + def.name + ")", iX + 170, iY - 30);
main.tint(atk.owner.r, atk.owner.g, atk.owner.b);
unitStats(atk, iX, iY, len);
main.fill(0);
main.rect(iX, iY + len, 160, 150 - len);
main.rect(iX + 180, iY + len, 160, 150 - len);
main.fill(255);
ArrayList<String> text1 = new ArrayList<String>();
text1.add("If I attacked...");
text1.add("Damage inflicted: " + offensiveDamage[0]);
text1.add("Damage taken: " + offensiveDamage[1]);
for (int i = 0; i < text1.size(); i++)
main.text(text1.get(i), iX, iY + len + 14*i);
if (def instanceof GameEntity)
{
main.tint(def.owner.r, def.owner.g, def.owner.b);
unitStats((GameEntity)def, iX + 220, iY, len);
ArrayList<String> text2 = new ArrayList<String>();
text2.add("If I attacked...");
text2.add("Damage inflicted: " + defensiveDamage[0]);
text2.add("Damage taken: " + defensiveDamage[1]);
for (int i = 0; i < text2.size(); i++)
main.text(text2.get(i), iX + 180, iY + len + 14*i);
}
main.popStyle();
}
}
}
}
//Show the possible tiles that a unit can move to
//Make this a function to stop code repeats
//System.out.println(movementChoices.size());
for (int i = 0; i < movementChoices.size(); i++)
{
Tile t = movementChoices.get(i);
//System.out.println((t.row - h.row - (mh.guiPositions.length-1)/2) + " " + (t.col - h.col + (mh.guiPositions[0].length-1)/2));
float[] pos = mh.positionGui(t.col - h.col + (mh.guiPositions[0].length-1)/2, t.row - h.row + (mh.guiPositions.length-1)/2);
if (pos != null && t != null)
{
if (t.biome == -1 && main.grid.adjacentLand(t.row, t.col).size() == 0 ||
main.grid.civs[0].revealed[t.row][t.col] == 0 && !main.showAll)
continue;
main.textAlign(main.CENTER);
main.fill(255,0,0);
float dX = main.width/2 - highlightDispX, dY = main.height/2 - highlightDispY;
main.text("1", pos[0] - dX,pos[1] - dY);
}
}
//Show the city queue food/metal menu and associated UI
//More repeating code
if (h != null)
{
for (int r = 0; r < mh.guiPositions.length; r++)
{
for (int c = 0; c < mh.guiPositions[0].length; c++)
{
float[] pos = mh.positionGui(r,c);
if (pos != null)
{
int dC = r - (mh.guiPositions.length-1)/2;
int dR = c - (mh.guiPositions[0].length-1)/2;
float dX = main.width/2 - highlightDispX, dY = main.height/2 - highlightDispY;
Tile t = main.grid.getTile(h.row + dR, h.col - dC);
if (t != null)
{
if (t.improvement != null)
{
if (t.improvement instanceof City)
{
//TODO Show the city GUI/label
}
}
}
}
}
}
}
if (menus.get(2).active())
menus.get(2).activate(false);
if (selected != null)
{
if (selected.owner != null)
if (selected.owner.equals(main.grid.civs[0]) && selected instanceof City)
{
City citySelected = (City)selected; //to work with old code
displayCity(citySelected);
}
}
else if (mouseHighlighted != null)
{
if (mouseHighlighted.improvement != null)
if (mouseHighlighted.improvement instanceof City)
{
City citySelected = (City)mouseHighlighted.improvement;
displayCity(citySelected);
}
}
if (messages.size() > 0)
{
int len = Math.min(6,messages.size());
for (int i = 0; i < len; i++)
{
textboxes.get(2).display.add(messages.get(i));
}
}
main.noStroke();
Civilization c = main.grid.civs[0];
textboxes.get(3).display.add(c.name + "; Health: " + c.health + "; Gold: " + c.gold + "; Research: " + c.research);
//textboxes.get(3).display.add("Health: " + c.health);
if (c.researchTech == null)
textboxes.get(3).display.add("No research");
else
textboxes.get(3).display.add("Researching " + c.researchTech + " at " + (int)((c.researchProgress()*1000/1000)*100) + "%");
//Manual textbox; does not use class
main.fill(0);
main.rect(0,0,main.width/6,50);
main.textSize(20);
main.fill(main.grid.civs[0].r, main.grid.civs[0].g, main.grid.civs[0].b);
main.text(main.civChoice,main.width/6/2,25);
int s = 5;
main.rect(s, s, 50 - 2*s, 50 - 2*s);
main.rect(main.width/6 - 50 + s, s, 50 - 2*s, 50 - 2*s);
main.textSize(12);
updateMessages();
for (int menu = 0; menu < menus.size(); menu++)
{
displayMenu(menu);
}
for (int i = 0; i < textboxes.size(); i++)
{
TextBox b = textboxes.get(i);
if (b.active)
{
main.fill(b.r, b.g, b.b, b.alpha);
strokeTextbox(b.borderR, b.borderG, b.borderB);
if (b.shape == 0)
main.rect(b.posX, b.posY, b.sizeX, b.sizeY);
else if (b.shape == 1)
main.ellipse(b.posX, b.posY, b.sizeX, b.sizeY);
else
System.out.println("Invalid button shape: " + b.shape);
//main.textAlign(PApplet.LEFT, PApplet.UP);
main.fill(255);
if (i == 7) //Monospaced GUI?
{
main.pushStyle();
main.textFont(main.dvs, 18);
main.textAlign(main.LEFT, main.TOP);
for (int j = 0; j < textboxes.get(7).display.size(); j++)
{
String stringy = textboxes.get(7).display.get(j);
main.text(stringy, b.posX, b.posY + 15*j + 5);
}
main.popStyle();
}
else
{
main.textAlign(main.CENTER, main.TOP);
displayText(b);
}
if (b.autoClear)
b.display.clear(); //Clear them to be refilled next frame
}
}
tooltip.active = false;
TextBox hover = findButtonWithin(main.mouseX, main.mouseY);
tooltip.active = false;
if (hover != null)
{
if (hover.tooltip != null)
if (hover.tooltip.size() > 0)
if (!hover.tooltip.get(0).isEmpty())
{
//TODO: Word wrap if the text goes off the screen
tooltip.active = true;
int[] d = hover.dimTooltip();
tooltip.sizeX = d[0];
tooltip.sizeY = d[1];
tooltip.posX = main.mouseX;
tooltip.posY = main.mouseY;
if (hover instanceof Button)
{
Button b = (Button)hover;
if (b.menu != null)
if (b.menu.name.equals("MainMenu") ||
b.menu.name.equals("UnitMenu") ||
b.menu.name.equals("TechMenu") ||
b.menu.name.equals("CityMenu") ||
b.menu.name.equals("CreateFieldMenu") ||
b.menu instanceof TechMenu)
{
tooltip.posX = hover.posX + hover.sizeX;
tooltip.posY = hover.posY;
//System.out.println("---_>");
}
}
main.fill(0);
main.stroke(255);
main.rect(tooltip.posX, tooltip.posY, tooltip.sizeX, tooltip.sizeY);
main.fill(255);
main.noStroke();
main.textAlign(main.CENTER);
//if (hover.tooltip.size() == 0)
for (int i = 0; i < hover.tooltip.size(); i++)
main.text(hover.tooltip.get(i), tooltip.posX + tooltip.sizeX/2, tooltip.posY + 10 + 14*i);
}
}
else //Show the tooltip for a unit being hovered over
{
if (mouseHighlighted != null)
{
if (mouseHighlighted.occupants.size() > 0)
{
//if (tooltip.display.size() != 0)
{
//if (!tooltip.display.get(0).equals(""))
{
tooltip.active = true;
tooltip.posX = main.mouseX;
tooltip.posY = main.mouseY;
tooltip.dimTooltip(mouseHighlighted.occupants, mouseHighlighted.improvement);
main.fill(0);
main.stroke(255);
main.rect(tooltip.posX, tooltip.posY, tooltip.sizeX, tooltip.sizeY);
main.fill(255);
main.noStroke();
main.textAlign(main.CENTER);
BaseEntity impr = mouseHighlighted.improvement;
if (impr != null)
main.text(impr.name + " (" + impr.owner + ")", tooltip.posX + tooltip.sizeX/2, tooltip.posY + 10);
for (int i = 0; i < mouseHighlighted.occupants.size(); i++)
{
GameEntity en = mouseHighlighted.occupants.get(i);
if (i != mouseHighlighted.occupants.size() - 1)
main.text(en.name + "(" + en.owner + ")", tooltip.posX + tooltip.sizeX/2, tooltip.posY + tooltip.sizeY/2 + 14*i);
else
if (impr != null)
main.text(en.name + " (" + en.owner + ")", tooltip.posX + tooltip.sizeX/2, tooltip.posY + 10 + 14*(i+1));
else
main.text(en.name + " (" + en.owner + ")", tooltip.posX + tooltip.sizeX/2, tooltip.posY + 10 + 14*i);
}
}
}
}
}
}
//Update the rectangular regions where there will be no extra elements shown
noOverlap.clear();
for (int i = 0; i < menus.size(); i++)
{
if (menus.get(i).active())
{
for (int j = 0; j < menus.get(i).buttons.size(); j++)
{
TextBox t = menus.get(i).buttons.get(j);
if (t.active && t.noOverlap)
noOverlap.add(t);
}
}
}
for (int i = 0; i < textboxes.size(); i++)
{
TextBox t = textboxes.get(i);
if (t.active && t.noOverlap)
noOverlap.add(t);
}
menuActivated = false;
for (int menu = 0; menu < menus.size(); menu++)
{
if (!main.enabled) break;
if (menus.get(menu).active())
{
for (int i = clicks.size() - 1; i >= 0; i--)
{
if (clicks.get(i).click)
{
String command = menus.get(menu).click(clicks.get(i).mouseX, clicks.get(i).mouseY);
if (command != null && !command.equals(""))
{
menuActivated = true;
//Replace with function that returns true if the menu resetting should happen
if (executeAction(command))
{
//main.menuSystem.select(null);
//below was derived from the original expression to calculate rotY & rotVertical
//main.centerX = main.mouseX/(1 - main.player.rotY/(float)Math.PI);
//main.centerY = main.mouseY/(1 + 4*main.player.rotVertical/(float)Math.PI);
main.resetCamera();
}
}
}
else
{
if (menu == 0 || menu == 5)
{
boolean[] activeMenus = new boolean[menus.size()];
for (int j = 0; j < activeMenus.length; j++)
{
activeMenus[j] = menus.get(j).active();
}
menus.get(menu).pass(activeMenus, clicks.get(i).mouseX, clicks.get(i).mouseY);
}
}
}
menus.get(menu).origPosIfNoMouse();
for (int i = 0; i < menus.get(menu).buttons.size(); i++)
{
main.fill(0);
Button b = menus.get(menu).buttons.get(i);
main.rect(b.posX, b.posY, b.sizeX, b.sizeY);
main.textAlign(PApplet.CENTER, PApplet.CENTER);
main.fill(255);
main.text(b.display, b.posX + b.sizeX/2, b.posY + b.sizeY/2);
}
for (int i = 0; i < menus.get(menu).buttons.size(); i++)
{
TextBox b = menus.get(menu).buttons.get(i);
b.tick();
}
for (int i = 0; i < textboxes.size(); i++)
{
textboxes.get(i).tick();
}
}
if (menus.get(menu).requestUpdate && menu != 0 && menu != 14)
{
menus.get(menu).requestUpdate = false;
//System.out.println("Clear shortcuts");
shortcuts = new Button[10];
//System.out.println(menu);
if (menus.get(menu).active() && !menus.get(menu).noShortcuts)
makeShortcut(menus.get(menu));
}
}
if (techMenu.active())
makeShortcut(techMenu);
clicks.clear();
menuHighlighted = false;
for (int index = 0; index < menus.size(); index++)
if (menus.get(index).active())
if (menus.get(index).within(main.mouseX, main.mouseY) != null)
{
menuHighlighted = true;
break;
}
if (main.testing)
{
MouseHelper mouseh = main.inputSystem.mouseHelper;
for (int i = 0; i < mouseh.horizonLines.size(); i++)
{
main.strokeWeight(5);
main.stroke(255,0,0);
MouseHelper.Line l = mouseh.horizonLines.get(i);
main.line((float)l.xPoint - 1000, (float)l.yPoint - 1000*l.slope, (float)l.xPoint + 1000, (float)l.yPoint + 1000*l.slope);
}
for (int i = 0; i < mouseh.vertLines.size(); i++)
{
main.strokeWeight(5);
main.stroke(255,0,0);
MouseHelper.Line l = mouseh.vertLines.get(i);
main.line((float)l.xPoint - 200, (float)l.yPoint - 200*l.slope, (float)l.xPoint + 200, (float)l.yPoint + 200*l.slope);
}
for (int i = 0; i < mouseh.intersections.length; i++)
{
for (int j = 0; j < mouseh.intersections[0].length; j++)
{
Point p = mouseh.intersections[i][j];
main.fill(0);
main.rect(p.x, p.y, 10, 10);
}
}
}
MouseHelper mouseHelper = main.inputSystem.mouseHelper;
for (int row = 0; row < mouseHelper.shapes.length; row++)
{
for (int col = 0; col < mouseHelper.shapes[0].length; col++)
{
//if (r != activeX || c != activeY) continue;
Shape shape = mouseHelper.shapes[row][col];
//if (s == null) continue;
main.fill(150*col/15,225*row/15,255*row/15);
main.beginShape(main.QUADS);
for (int i = 0; i < shape.x.length; i++)
{
main.vertex(shape.x[i],shape.y[i]);
}
main.vertex(shape.x[0],shape.y[0]);
main.endShape();
}
}
MouseHelper mouseh = main.inputSystem.mouseHelper;
for (int i = 0; i < mouseh.rHorizonLines.size(); i++)
{
main.strokeWeight(5);
main.stroke(255,0,0);
MouseHelper.Line l = mouseh.rHorizonLines.get(i);
main.line(0F, (float)l.yPoint - 200*l.slope, 1000F, (float)l.yPoint + 200*l.slope);
}
for (int i = 0; i < mouseh.rVertLines.size(); i++)
{
main.strokeWeight(5);
main.stroke(255,0,0);
MouseHelper.Line l = mouseh.rVertLines.get(i);
main.line((float)l.xPoint - 200, (float)l.yPoint - 200*l.slope, (float)l.xPoint + 200, (float)l.yPoint + 200*l.slope);
}
for (int i = 0; i < mouseh.guiPositions.length; i++)
{
for (int j = 0; j < mouseh.guiPositions[0].length; j++)
{
Point p = mouseh.guiPositions[i][j];
main.fill(0);
main.rect(p.x, p.y, 10, 10);
}
}
main.strokeWeight(1);*/
}
|
21296da2-2b82-43d8-868b-3994efb7e6a5
| 0
|
private int readUInt16(byte[] uint16, int offset) throws IOException {
int b0 = uint16[0 + offset] & 0x000000FF;
int b1 = uint16[1 + offset] & 0x000000FF;
return (b1 << 8) + b0;
}
|
6902d7f6-511d-4d6c-8376-abf0d00f69f2
| 6
|
private void loadSkipLevels() throws IOException {
numberOfSkipLevels = docCount == 0 ? 0 : (int) Math.floor(Math.log(docCount) / Math.log(skipInterval[0]));
if (numberOfSkipLevels > maxNumberOfSkipLevels) {
numberOfSkipLevels = maxNumberOfSkipLevels;
}
skipStream[0].seek(skipPointer[0]);
int toBuffer = numberOfLevelsToBuffer;
for (int i = numberOfSkipLevels - 1; i > 0; i--) {
// the length of the current level
long length = skipStream[0].readVLong();
// the start pointer of the current level
skipPointer[i] = skipStream[0].getFilePointer();
if (toBuffer > 0) {
// buffer this level
skipStream[i] = new SkipBuffer(skipStream[0], (int) length);
toBuffer--;
} else {
// clone this stream, it is already at the start of the current level
skipStream[i] = (IndexInput) skipStream[0].clone();
if (inputIsBuffered && length < BufferedIndexInput.BUFFER_SIZE) {
((BufferedIndexInput) skipStream[i]).setBufferSize((int) length);
}
// move base stream beyond the current level
skipStream[0].seek(skipStream[0].getFilePointer() + length);
}
}
// use base stream for the lowest level
skipPointer[0] = skipStream[0].getFilePointer();
}
|
5344803d-6036-46c9-a714-b4b645c317be
| 0
|
@Override
public boolean setDefault(boolean def) {
return (defaultGroup = def);
}
|
374ad65d-2f13-49d5-859c-cdd764d744f9
| 9
|
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption("min", options);
if (tmpStr.length() != 0)
setMinThreshold(Double.parseDouble(tmpStr));
else
setMinThreshold(-Double.MAX_VALUE);
tmpStr = Utils.getOption("min-default", options);
if (tmpStr.length() != 0)
setMinDefault(Double.parseDouble(tmpStr));
else
setMinDefault(-Double.MAX_VALUE);
tmpStr = Utils.getOption("max", options);
if (tmpStr.length() != 0)
setMaxThreshold(Double.parseDouble(tmpStr));
else
setMaxThreshold(Double.MAX_VALUE);
tmpStr = Utils.getOption("max-default", options);
if (tmpStr.length() != 0)
setMaxDefault(Double.parseDouble(tmpStr));
else
setMaxDefault(Double.MAX_VALUE);
tmpStr = Utils.getOption("closeto", options);
if (tmpStr.length() != 0)
setCloseTo(Double.parseDouble(tmpStr));
else
setCloseTo(0);
tmpStr = Utils.getOption("closeto-default", options);
if (tmpStr.length() != 0)
setCloseToDefault(Double.parseDouble(tmpStr));
else
setCloseToDefault(0);
tmpStr = Utils.getOption("closeto-tolerance", options);
if (tmpStr.length() != 0)
setCloseToTolerance(Double.parseDouble(tmpStr));
else
setCloseToTolerance(1E-6);
tmpStr = Utils.getOption("R", options);
if (tmpStr.length() != 0)
setAttributeIndices(tmpStr);
else
setAttributeIndices("first-last");
setInvertSelection(Utils.getFlag("V", options));
setIncludeClass(Utils.getFlag("include-class", options));
tmpStr = Utils.getOption("decimals", options);
if (tmpStr.length() != 0)
setDecimals(Integer.parseInt(tmpStr));
else
setDecimals(-1);
super.setOptions(options);
}
|
282ddbe8-a264-4943-bd99-5e32ebdc1abf
| 8
|
public void setSpawnPoint(ArmyType type) {
switch(type) {
case PLAYER_FRONT: break;
case PLAYER_MAIN: spawnPoint = new Point2D.Double(380, 540); break;
case PLAYER_LEFTWING: break;
case PLAYER_RIGHTWING: break;
case ENEMY_FRONT: break;
case ENEMY_MAIN: spawnPoint = new Point2D.Double(380, 50); break;
case ENEMY_LEFTWING: break;
case ENEMY_RIGHTWING: break;
}
}
|
ed9671a1-5b80-4e7a-91a8-2b2fa2628c37
| 4
|
public Student search(int id) throws UnknownStudent {
Student s = null;
boolean found = false;
int i = 0;
while (i < getList().size() && !found) {
s = getList().get(i);
if (s.getId() == id)
found = true;
i++;
}
if (!found) {
throw new UnknownStudent("No student with an id " + id
+ " in the Promotion " + name + " !");
} else {
return s;
}
}
|
90f7d8c9-2545-41c7-b3e9-a5eae7dcd5e6
| 9
|
public void setNamespaces(NodeInfo node) {
namespaces.clear();
int kind = node.getNodeKind();
if (kind == Type.ATTRIBUTE || kind == Type.TEXT ||
kind == Type.COMMENT || kind == Type.PROCESSING_INSTRUCTION ||
kind == Type.NAMESPACE) {
node = node.getParent();
}
if (node == null) {
return;
}
AxisIterator iter = node.iterateAxis(Axis.NAMESPACE);
while (true) {
NodeInfo ns = (NodeInfo)iter.next();
if (ns == null) {
return;
}
String prefix = ns.getLocalPart();
if ("".equals(prefix)) {
setDefaultElementNamespace(ns.getStringValue());
} else {
declareNamespace(ns.getLocalPart(), ns.getStringValue());
}
}
}
|
fb5f4247-20a0-435c-ab2a-bae162f1c202
| 8
|
private double findSplitNumericNumeric(int index) throws Exception {
double bestVal = Double.MAX_VALUE, currVal, currCutPoint;
int numMissing = 0;
double[] sumsSquares = new double[3], sumOfWeights = new double[3];
double[][] bestDist = new double[3][1];
double totalSum = 0, totalSumOfWeights = 0;
// Compute counts for all the values
for (int i = 0; i < m_Instances.numInstances(); i++) {
Instance inst = m_Instances.instance(i);
if (!inst.isMissing(index)) {
m_Distribution[1][0] += inst.classValue() * inst.weight();
sumsSquares[1] += inst.classValue() * inst.classValue()
* inst.weight();
sumOfWeights[1] += inst.weight();
} else {
m_Distribution[2][0] += inst.classValue() * inst.weight();
sumsSquares[2] += inst.classValue() * inst.classValue()
* inst.weight();
sumOfWeights[2] += inst.weight();
numMissing++;
}
totalSumOfWeights += inst.weight();
totalSum += inst.classValue() * inst.weight();
}
// Check if the total weight is zero
if (totalSumOfWeights <= 0) {
return bestVal;
}
// Sort instances
m_Instances.sort(index);
// Make split counts for each possible split and evaluate
for (int i = 0; i < m_Instances.numInstances() - (numMissing + 1); i++) {
Instance inst = m_Instances.instance(i);
Instance instPlusOne = m_Instances.instance(i + 1);
m_Distribution[0][0] += inst.classValue() * inst.weight();
sumsSquares[0] += inst.classValue() * inst.classValue() * inst.weight();
sumOfWeights[0] += inst.weight();
m_Distribution[1][0] -= inst.classValue() * inst.weight();
sumsSquares[1] -= inst.classValue() * inst.classValue() * inst.weight();
sumOfWeights[1] -= inst.weight();
if (inst.value(index) < instPlusOne.value(index)) {
currCutPoint = (inst.value(index) + instPlusOne.value(index)) / 2.0;
currVal = variance(m_Distribution, sumsSquares, sumOfWeights);
if (currVal < bestVal) {
m_SplitPoint = currCutPoint;
bestVal = currVal;
for (int j = 0; j < 3; j++) {
if (sumOfWeights[j] > 0) {
bestDist[j][0] = m_Distribution[j][0] / sumOfWeights[j];
} else {
bestDist[j][0] = totalSum / totalSumOfWeights;
}
}
}
}
}
m_Distribution = bestDist;
return bestVal;
}
|
917476a3-1475-48b4-9ec0-8b0b42ecd63e
| 5
|
private void calculateSpikeTrain(SpikingNeuronPhenotype pheno){
double v = -60.0;
double u = 0.0;
double[] voltageArray = new double[target.length];
voltageArray[0] = v;
for (int j = 1; j < target.length; j++){
if (v >= 35.0){
v = pheno.c;
u += pheno.d;
}
double vd = ((pheno.k * Math.pow(v, 2.0)) + 5.0*v + 140.0 - u + I) / T;
double ud = (pheno.a / T) * (pheno.b * v - u);
u += ud;
v += vd;
if (v >= 35.0) voltageArray[j] = 35.0;
else voltageArray[j] = v;
}
pheno.spiketrain = voltageArray;
pheno.distance = sdm.calculateDistance(target, voltageArray);
if (pheno.distance < 0) System.out.println("ERROR, distance negative");
if (pheno.distance > longestDistance) longestDistance = pheno.distance;
}
|
4e003234-3b6b-481a-9959-d802cb39b29a
| 5
|
private void updateGate(String CLK, String SHLD, String CLKINH, String SER, String A, String B, String C, String D, String E, String F, String G, String H, String QH, String nQH) throws InvalidPinException {
if (this.isLow(SHLD)) {
this.a = this.getPinState(A);
this.b = this.getPinState(B);
this.c = this.getPinState(C);
this.d = this.getPinState(D);
this.e = this.getPinState(E);
this.f = this.getPinState(F);
this.g = this.getPinState(G);
if (this.isHigh(H)) {
this.setPin(nQH, Pin.PinState.LOW);
this.setPin(QH, Pin.PinState.HIGH);
} else {
this.setPin(nQH, Pin.PinState.HIGH);
this.setPin(QH, Pin.PinState.LOW);
}
} else if (this.isRisingEdge(CLK) && this.isLow(CLKINH)) {
if (this.g.equals(Pin.PinState.HIGH)) {
this.setPin(QH, Pin.PinState.HIGH);
this.setPin(nQH, Pin.PinState.LOW);
} else {
this.setPin(QH, Pin.PinState.LOW);
this.setPin(nQH, Pin.PinState.HIGH);
}
this.g = this.f;
this.f = this.e;
this.e = this.d;
this.d = this.c;
this.c = this.b;
this.b = this.a;
this.a = this.getPinState(SER);
}
}
|
8dd123c0-964d-4395-b0d3-372aeb24d671
| 4
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (critical ? 1231 : 1237);
result = prime * result
+ ((manufacturer == null) ? 0 : manufacturer.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((origin == null) ? 0 : origin.hashCode());
result = prime * result + price;
return result;
}
|
5f5969bf-488e-4c8c-b1c1-af89ffb364fc
| 7
|
public int read(int width) throws IOException {
if (width == 0) {
return 0;
}
if (width < 0 || width > 32) {
throw new IOException("Bad read width.");
}
int result = 0;
while (width > 0) {
if (this.available == 0) {
this.unread = this.in.read();
if (this.unread < 0) {
throw new IOException("Attempt to read past end.");
}
this.available = 8;
}
int take = width;
if (take > this.available) {
take = this.available;
}
result |= ((this.unread >>> (this.available - take)) &
((1 << take) - 1)) << (width - take);
this.nrBits += take;
this.available -= take;
width -= take;
}
return result;
}
|
c5de849f-a50a-41e2-932a-01ae417e600e
| 4
|
public static PackedImage read(String filename) throws IOException {
FileInputStream in = new FileInputStream(filename);
if (!readField(in).equals("P6")) throw new IOException("Not a P6 PPM file");
int nc = Integer.parseInt(readField(in));
int nr = Integer.parseInt(readField(in));
int maxint = Integer.parseInt(readField(in));
PackedImage img = new PackedImage(nr, nc);
for (int r = 0; r < nr; r++)
for (int c = 0; c < nc; c++)
for (int ch = 0; ch < 3; ch++)
img.set(r, c, ch, in.read());
in.close();
return img;
}
|
630a780a-0a47-440a-90ca-b729c562e40d
| 6
|
public boolean isIsomorphic(String a, String b) {
if(a.length() != b.length()) {
return false;
}
List<Mapping> aMappings = getMappings(a);
List<Mapping> bMappings = getMappings(b);
if(aMappings.size() != bMappings.size()){
return false;
}
for(int i = 0;i < aMappings.size(); i++) {
Mapping amap = aMappings.get(i);
Mapping bmap = bMappings.get(i);
if(amap.positions.size() != bmap.positions.size()){
return false;
}
for( int j = 0; j< amap.positions.size(); j++){
if(amap.positions.get(i) != bmap.positions.get(i)){
return false;
}
}
}
return true;
}
|
7a8134ef-f4a3-4cdf-869d-a2d227b7a194
| 7
|
private void compileFunctionDeclarations(Program program)
throws ParseException, IOException
{
// function
while ((tokenizer.tokenType() == Tokenizer.KEYWORD) &&
(tokenizer.keyword() == Tokenizer.KW_FUNCTION)) {
advance("program not ended");
// <data-type>
Type returnType = compileDataType();
// <function-name>
if (tokenizer.tokenType() != Tokenizer.IDENTIFIER) {
throw new ParseException("function name is excepted after type",
tokenizer.lineNumber());
}
new Function(tokenizer.getIdentifier(), returnType);
// (
getSymbol('(',
"( is excepted after function name " +
tokenizer.getIdentifier());
advance("program not ended");
// <arguments-list>
compileArgumentsList();
// )
if ((tokenizer.tokenType() != Tokenizer.SYMBOL) ||
(tokenizer.symbol() != ')')) {
throw new ParseException(") is excepted in the end of arguments",
tokenizer.lineNumber());
}
// {
getSymbol('{', "{ is excepted after )");
advance("program not ended");
// <var declarations>
compileVarDeclarations();
// <function body>
compileFunctionBody();
// }
if ((tokenizer.tokenType() != Tokenizer.SYMBOL) ||
(tokenizer.symbol() != '}')) {
throw new ParseException("} is excepted at end of function",
tokenizer.lineNumber());
}
advance("program not ended");
program.addFunction(Function.currentFunction);
}
}
|
97b00b81-40fe-43a0-90fa-d9c45cfd7fad
| 0
|
public void setParams(Object params) {
this.params = params;
}
|
d8f52182-430d-479d-9835-2a0d3120ab6d
| 7
|
final public Attribute parseAttr() throws ParseException {
String name;
Attribute.Type type;
int length = -1;
String constraint = "";
name = getTokenImage();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case KW_INT:
jj_consume_token(KW_INT);
type = Attribute.Type.INT;
break;
case KW_CHAR:
jj_consume_token(KW_CHAR);
jj_consume_token(52);
jj_consume_token(INT_LITERAL);
length=Integer.parseInt(token.image);
jj_consume_token(53);
type = Attribute.Type.CHAR;
break;
case KW_DECIMAL:
jj_consume_token(KW_DECIMAL);
type = Attribute.Type.DECIMAL;
break;
default:
jj_la1[9] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case KW_CHECK:
jj_consume_token(KW_CHECK);
jj_consume_token(52);
constraint = Expression();
jj_consume_token(53);
break;
default:
jj_la1[10] = jj_gen;
;
}
{if (true) return new Attribute(type, name, length, constraint);}
throw new Error("Missing return statement in function");
}
|
26645a2d-26ff-49cc-9ca9-e80f278370c0
| 1
|
public String outerClass(int nth) {
int i = outerClassIndex(nth);
if (i == 0)
return null;
else
return constPool.getClassInfo(i);
}
|
c196b536-2b19-4c5d-b0a1-37d3fe285201
| 9
|
private File findIndexFile(String bamFilename) {
File bam = new File(bamFilename);
if (!bam.exists()) {
System.err.println("BAM file does not exist : " + bam.getAbsolutePath() + ".");
System.exit(1);
}
File index1 = new File( bamFilename+".bai" );
File index2 = new File( bamFilename.substring(0, bamFilename.lastIndexOf("."))+".bai" );
File index = null;
if (!index1.exists() && !index2.exists()) {
System.err.println("BAM index file does not exist for " + bamFilename + ".");
System.err.println("Socrates is creating one for you.");
BuildBamIndex.createIndex(new SAMFileReader(new File(bamFilename)), index2);
index = index2;
} else if (index1.exists() && !index2.exists()) {
index = index1;
} else if (!index1.exists() && index2.exists()) {
index = index2;
} else {
if (index1.lastModified() > index2.lastModified())
index = index1;
else
index = index2;
}
// RESOLVED: when index is older than the BAM file, record seeking can go out of range.
if (index.lastModified() < bam.lastModified()) {
System.err.println("BAM index file for " + bamFilename + " is out of date.");
System.err.println("Socrates is rebuilding one for you.");
BuildBamIndex.createIndex(new SAMFileReader(new File(bamFilename)), index);
}
return index;
}
|
0bc44da4-7cb6-4595-804a-1dae00b7f0ea
| 9
|
public void paint(java.awt.Graphics g) {
// g.drawLine (0, 50, 50, 0);
//System.out.println ("paint called");
try {
synchronized (repaintLock) {
ApplicationManager manager = ApplicationManager.manager;
//java.awt.Dimension d = getSize();
if (manager.offscreen == null) {
manager.offscreen =
ApplicationManager.manager.awtContainer.createImage(
manager.screenWidth,
manager.screenHeight);
}
if (repaintPending) {
Graphics mg =
new Graphics(
canvas,
null,
manager.offscreen.getGraphics());
if (mg != null) {
repaintPending = false; // moved up here to allow the request of a repaint in paint
Log.log(Log.DRAW_EVENTS, "ScmCanvas.paint() entering");
if(canvas.oldW != canvas.getWidth() || canvas.oldH != canvas.getHeight()){
try{
canvas.sizeChanged(canvas.getWidth(), canvas.getHeight());
canvas.oldW = canvas.getWidth();
canvas.oldH = canvas.getHeight();
}
catch(Exception e){
e.printStackTrace();
}
}
canvas.paint(mg); // thanks for the fix to Steven Lagerweij
Log.log(Log.DRAW_EVENTS, "ScmCanvas.paint() left");
// mg.stale = true;
if (canvas.videoFrameImage != null)
mg.drawImage(canvas.videoFrameImage,
canvas.videoFrameX, canvas.videoFrameY,
Graphics.TOP | Graphics.LEFT);
}
else repaint ();
}
//TODO: Clarify under which circumstances g may be null ...
if(g != null){
g.drawImage(
manager.offscreen,
0,
0,
manager.awtContainer);
}
repaintLock.notify();
}
}
catch (Exception e) {
e.printStackTrace();
}
//System.out.println ("paint left");
//g.drawLine (0, 0, 999, 999);
}
|
29d77b9a-4a85-4452-bf5f-1b6652efcb9f
| 5
|
public void edgeCollisions(){
Coordinate ballCoord = ball.getCurrentCoordinate();
if (ball.getxSpeed() + ballCoord.getX() + ball.getSize() >= windowWidth){ //Checks if ball hits right edge
changeBallDirection('r');
}else if (ballCoord.getX()+ball.getxSpeed() <= 0){ //Checks if ball hits left edge
changeBallDirection('l');
}else if (ballCoord.getY() - ball.getySpeed() + ball.getSize() > windowHeight+ball.getSize()){ //Checks if ball hitslower edge
killBall();
restorePaddle();
lives--;
if (lives <= 0)
gameover = true;
} else if (ballCoord.getY() - ball.getySpeed() <= 0){ //Checks if ball hits upper edge
changeBallDirection('u');
}
}
|
5e9a649a-bf01-4597-921a-e7b4f29211ca
| 6
|
@Override
public AbstractComponent parse(String string) throws BookParseException {
if (string == null) {
throw new BookParseException("String is null");
}
try {
TextComponent component = (TextComponent) factory
.newComponent(EComponentType.LEXEM);
String word = "";
for (String s : string.split("")) {
if (Pattern.matches(PUNCTUATION_REGEX, s)) {
if (!word.equals("")) {
component.addComponent(wordParser.parse(word));
word = "";
}
component.addComponent(characterParser.parse(s));
} else {
word += s;
}
}
if (!word.equals("")) {
component.addComponent(wordParser.parse(word));
word = "";
}
return component;
} catch (ComponentException e) {
throw new BookParseException("Lexem parser failed", e);
}
}
|
2a1bc97c-1eb2-45e4-8149-9b9e4c1deece
| 3
|
public String name(final PrintType pt) {
final String name = name().toLowerCase();
switch (pt) {
case START_UP:
return name.toUpperCase().substring(0, 1) + name.substring(1);
case NORMAL:
return name;
case UP:
return name.toUpperCase();
default:
return null;
}
}
|
c4a7dc85-25a6-4a57-ac81-6ab56d09e5a1
| 6
|
@Override
public List<AccessPoint> list() {
Process p;
ProcessBuilder pb = new ProcessBuilder("netsh", "wlan", "show", "networks");
List<AccessPoint> result = new ArrayList<AccessPoint>();
try {
p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while (null != (line = br.readLine())) {
sb.append(line);
}
String[] networks = sb.toString().split("\n \n");
for (int i = 1, j = networks.length; i < j; i++) {
Matcher ssidMatch = SSID_PATTERN.matcher(networks[i]);
Matcher macMatch = MAC_PATTERN.matcher(networks[i]);
Matcher strengthMatch = STRENGTH_PATTERN.matcher(networks[i]);
if (ssidMatch.find() && macMatch.find() && strengthMatch.find()) {
result.add(new AccessPoint(ssidMatch.group(1), macMatch.group(0), Integer
.parseInt(strengthMatch.group(1))));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
|
152dcd72-03d4-4f1f-ae16-8cfe454becf7
| 1
|
public AnnotationVisitor visitAnnotation(final String desc,
final boolean visible) {
return new SAXAnnotationAdapter(getContentHandler(), "annotation",
visible ? 1 : -1, null, desc);
}
|
0a651b58-6ebd-4ca6-b532-1bb48345066d
| 0
|
public double getMass() { return mass; }
|
66e45d4c-f3c5-4224-8e78-46a053c68973
| 1
|
public void initSpeicher() {
for(int i = 0; i < SPEICHERGROESSE; i++) {
speicherZellen[i] = new Speicherzelle(new Integer(0));
}
}
|
f019c77f-505b-4270-9e35-cf0a5e877464
| 3
|
@Override
public void caseADoopExp(ADoopExp node)
{
inADoopExp(node);
if(node.getAssgnfrom() != null)
{
node.getAssgnfrom().apply(this);
}
if(node.getOp() != null)
{
node.getOp().apply(this);
}
if(node.getAssgnto() != null)
{
node.getAssgnto().apply(this);
}
outADoopExp(node);
}
|
7659584e-ab74-454b-8c66-b2e8f76ca320
| 4
|
@Override
public void handle(HttpExchange exchange) throws IOException {
System.out.println("In Load Game handler.");
String responseMessage = "";
if(exchange.getRequestMethod().toLowerCase().equals("post")) {
exchange.getResponseHeaders().set("Content-Type", "appliction/json");
BufferedReader in = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
String inputLine;
StringBuffer requestJson = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
requestJson.append(inputLine);
}
in.close();
System.out.println(requestJson);
LoadGameRequest request = (LoadGameRequest) translator.translateFrom(requestJson.toString(), LoadGameRequest.class);
exchange.getRequestBody().close();
try{
int id = gamesFacade.loadGame(request.getName());
responseMessage = "Successfully loaded game: " + request.getName() + " with id " + id;
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0);
log.Store(new LoadCommand(gamesFacade, request.getName()));
}catch(IOException e){
System.out.println("Error reading file. IOException");
responseMessage = e.getMessage();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
}
else {
// unsupported request method
responseMessage = "Error: \"" + exchange.getRequestMethod() + "\" is not supported!";
exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, 0);
}
if (!responseMessage.isEmpty()) {
//send failure response message
OutputStreamWriter writer = new OutputStreamWriter(
exchange.getResponseBody());
writer.write(responseMessage);
writer.flush();
writer.close();
}
exchange.getResponseBody().close();
}
|
ec853a15-87ed-4867-9db9-a53b8bf01c8f
| 9
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PosEnvioAPosEntityPK that = (PosEnvioAPosEntityPK) o;
if (pepIdElemento != that.pepIdElemento) return false;
if (pepMoaConsec != that.pepMoaConsec) return false;
if (pepMoaTipo != null ? !pepMoaTipo.equals(that.pepMoaTipo) : that.pepMoaTipo != null) return false;
if (pepPosId != null ? !pepPosId.equals(that.pepPosId) : that.pepPosId != null) return false;
return true;
}
|
05ece3f6-80a3-4990-bd97-84ca8498fbb7
| 0
|
@Override
public void startAddSubContainer(Container c) {
containerStack.add(c);
}
|
eae68a87-3055-4923-8dd0-02c037561b81
| 6
|
private void updateCamera() {
Vector temp = Vector.add(cameraPosition,cameraVelocity);
if (temp.x < 0 || temp.x + screenDims.width > mapDims.width) {
cameraVelocity.x = 0F;
temp.x = (temp.x < 0)?0:mapDims.width - screenDims.width;
}
if (temp.y < 0 || temp.y + screenDims.height > mapDims.height) {
cameraVelocity.y = 0F;
temp.y = (temp.y < 0)?0:mapDims.height - screenDims.height;
}
cameraPosition = temp;
cameraVelocity = Vector.scalar(.75F,cameraVelocity);
}
|
7e415567-6255-4e3e-be35-4d0892adbae0
| 4
|
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if(this.x + this.width - 34 <= x && this.y + scrollPerc*this.height + borderWidth - 3 <= y &&
this.x + this.width - 1 > x && this.y + scrollPerc*this.height + borderWidth - 3 + scrollButtonHeight - borderWidth > y) {
scrolling = true;
startScrollingPerc = scrollPerc;
startScrolling = y;
}
}
|
025e7593-ef24-4b64-8d86-1f1cfedd8896
| 1
|
public void update(long dt) {
if (mapview == null)
last_newwidget_time = System.currentTimeMillis();
root.update(dt);
}
|
02716b21-2e5a-48be-8462-a292b336d893
| 2
|
public RPTreeNodeItem getItem(int index) {
if (index < 0 || index >= childItems.size())
return null;
else {
RPTreeChildNodeItem item = childItems.get(index);
return (RPTreeNodeItem) item;
}
}
|
db64c6cc-7a70-4d60-8a9d-be883c85f635
| 4
|
public void updateMaxMin(int frameNo, int max, int min) {
switch (frameNo) {
case 1:
minValue1.setText("" + max);
maxValue1.setText("" + min);
break;
case 2:
minValue2.setText("" + max);
maxValue2.setText("" + min);
break;
case 3:
minValue3.setText("" + max);
maxValue3.setText("" + min);
break;
case 4:
minValue4.setText("" + max);
maxValue4.setText("" + min);
break;
default:
break;
}
}
|
5c952dc7-5708-4122-b67e-5dfe7591f0ca
| 2
|
public TreeRoot getTreeRoot() {
TreeRow row = this;
while (row != null) {
if (row instanceof TreeRoot) {
return (TreeRoot) row;
}
row = row.mParent;
}
return null;
}
|
61f96402-d438-4a4b-b068-33b742d28ea9
| 6
|
final void method1346(int i, int i_4_) {
anInt2322++;
if (Class103.aClass345_1607 != null) {
for (Class348_Sub42_Sub9 class348_sub42_sub9
= (Class348_Sub42_Sub9) aClass107_2316.getFirst();
class348_sub42_sub9 != null;
class348_sub42_sub9
= ((Class348_Sub42_Sub9)
aClass107_2316.next())) {
if (class348_sub42_sub9.method3206((byte) -124)) {
if (class348_sub42_sub9.method3205(i + 67027) == null) {
class348_sub42_sub9.removeNode();
class348_sub42_sub9.removeSubnode();
anInt2311
+= (((Class348_Sub42_Sub9) class348_sub42_sub9)
.anInt9556);
}
} else if (((long) i_4_ ^ 0xffffffffffffffffL)
> (++((SubNode) class348_sub42_sub9)
.subnodeKey
^ 0xffffffffffffffffL)) {
Class348_Sub42_Sub9 class348_sub42_sub9_5_
= Class103.aClass345_1607
.method2694(-1, class348_sub42_sub9);
aClass356_2312.putNode((((Node) class348_sub42_sub9)
.nodeKey),
class348_sub42_sub9_5_);
Class59_Sub2_Sub2.method573(class348_sub42_sub9_5_,
class348_sub42_sub9,
(byte) 63);
class348_sub42_sub9.removeNode();
class348_sub42_sub9.removeSubnode();
}
}
}
if (i != -1491)
method1342(null, (byte) 51);
}
|
2951b645-f0a0-48fa-9a9e-5fe96da5fb67
| 1
|
public boolean started(){
if(IP == ""){
return false;
}else{
return true;
}
}
|
ea0d9cbc-5311-4b01-8082-33c2b02d728a
| 1
|
public static void main(String[] args) throws FileNotFoundException {
/*
Identifying exception categories
* Exceptions can be divided into three main categories:
- Checked exceptions
- Runtime exceptions
- Errors
* Checked exceptions require most of your attention when it comes to coding and using methods.
* You should not normally try to catch runtime exceptions, and there are few options you can use for errors,
as they're thrown by the JVM.
* All three categories are related to one another as they're subclasses of java.lang.Exception.
Checked Exceptions
* Checked exceptions take up most of our attention.
* A checked exception is an unacceptable condition foreseen by the author of a method but outside the
immediate control of the code.
* For example, FileNotFoundException is a checked exception. This exception is thrown if the file that the
code is trying to access can't be found.
* A checked exception is a subclass of java.lang.Exception, but it's not a subclass of java.lang.RunTimeException.
* If a method uses another method that may throw a checked exception, one of two of the following things should
be true
- The method should be enclosed within a try-catch block, or
- The method should specify this exception to be thrown in its method signature.
* A checked exception is an unacceptable condition that a programmer foresees at the time of writing a method.
By declaring these exceptions as checked exceptions, the author of the method makes its users aware of the
exceptional conditions that can arise from its use.
* Checked Exceptions
- Exception
- IOException
- FileNotFoundException
- ParseException
- ClassNotFoundException
- CloneNotSupportedException
- InstantiationException
- InterruptedException
- NoSuchMethodException
- NoSuchFieldException
*/
// Unchecked Exceptions
try {
String[] usernames = {"BOFlaherty", "JBloggs"};
System.out.println(usernames[3].toString());
} catch (ArrayIndexOutOfBoundsException e) {
/*
Should we catch RunTimeExceptions, it depends. An argument is that if unchecked exceptions are programmer
foreseen errors, should we catch the exception, or simply fix root of the problem. How can we prevent an
ArrayIndexOutOfBoundsException from being thrown?
*/
e.printStackTrace();
}
// throws an checked exception via the method signature (They have no catch or finally clauses)
FileInputStream fileInputStream = new FileInputStream("testing.text");
/*
Runtime Exceptions (aka - an unchecked Exceptions)
* A runtime exception is a representation of a programming error. These occur from inappropriate use of
another piece of code. For example, NullPointerException is a runtime exception that occurs when a piece of
code tries to execute some code on a variable that hasn't been assigned an object and points to null.
* A runtime exception is a subclass of java.lang.RunTimeException.
* A runtime exception may not be a part of the method signature, even if a method may throw it.
Unchecked Exceptions
- ArrayIndexOutOfBoundsException
- ClassCastException
- IllegalArgumentException
- IllegalStateException
- NullPointerException
- NumberFormatException
- AssertionError
- ExceptionInInitializerError
- StackOverflowError
- NoClassDefFoundError
*/
}
|
dfe398f1-49fb-4761-9ded-acd5ff412b14
| 8
|
public static double bruteForce(double[] Ow, double[] Op, int w){
double res = 0;
int size = Op.length;
int[] A = new int[size];
for(int i=0;i<size;i++)
A[i] = 0;
for(int i=0;;i++){
int j = size;
double tempW = 0;
double tempV = 0;
int k = 1;
for(j=0;j<size;j++){
A[j]+=k;
k = A[j]/2;
A[j] = A[j]%2;
}
if(k>0)
break;
for(k=0;k<size;k++){
if(A[k]==1){
tempW += (double)Ow[k];
tempV += (double)Op[k];
}
}
if(tempW<=w && res<=tempV)
res = tempV;
}
return res;
}
|
1b6c7c29-af66-4b7a-8182-115cddeb2465
| 3
|
private static String executeAddCommand(DataBaseManager dbManager, Command command) {
List<String> args = command.getArgs();
String tableName = args.get(0);
List<String> params = args.subList(1, args.size());
String msg;
try {
dbManager.save(tableName, params);
msg = "data saved";
} catch (DBUnavailabilityException e) {
msg = e.getMessage();
} catch (DataBaseTableException e) {
msg = e.getMessage();
} catch (DataBaseRequestException e) {
msg = e.getMessage();
}
return msg;
}
|
e30bf73c-31cc-4fcd-82b3-6973be02507f
| 9
|
public boolean canSnowAt(int par1, int par2, int par3)
{
BiomeGenBase var4 = this.getBiomeGenForCoords(par1, par3);
float var5 = var4.getFloatTemperature();
if (var5 > 0.15F)
{
return false;
}
else
{
if (par2 >= 0 && par2 < 256 && this.getSavedLightValue(EnumSkyBlock.Block, par1, par2, par3) < 10)
{
int var6 = this.getBlockId(par1, par2 - 1, par3);
int var7 = this.getBlockId(par1, par2, par3);
if (var7 == 0 && Block.snow.canPlaceBlockAt(this, par1, par2, par3) && var6 != 0 && var6 != Block.ice.blockID && Block.blocksList[var6].blockMaterial.blocksMovement())
{
return true;
}
}
return false;
}
}
|
dfb82016-acb4-4af2-8bbb-d94c3723ec6a
| 4
|
public int maxPathNotRoot2(treeNode curRoot,
HashMap<treeNode, Integer> node_notRootMax) {
this.running_time_NotRoot2++;
if (node_notRootMax.containsKey(curRoot))
return node_notRootMax.get(curRoot);
if (curRoot.leftLeaf == null && curRoot.rightLeaf == null) {
node_notRootMax.put(curRoot, curRoot.value);
return curRoot.value;
}
int leftMax = maxPathNotRoot(curRoot.leftLeaf);
int rightMax = maxPathNotRoot(curRoot.rightLeaf);
int curMax = (leftMax >= rightMax ? (leftMax + curRoot.value)
: (rightMax + curRoot.value));
node_notRootMax.put(curRoot, curMax);
return curMax;
}
|
3941c2b6-ad46-4d18-9bcb-7315843d2db7
| 6
|
@Override
public void happens() {
Character character = Game.getInstance().getCurrentCharacter();
int rollResult = 0;
if (character.getCurrentRoom().getNameEnum() == RoomName.CHAPEL){
rollResult = Game.getInstance().rollDice(2);
}else{
rollResult = Game.getInstance().rollDice(1);
}
if(rollResult == 4){
character.incrementMight();
Character char2 = character.getNearestCharacter();
char2.incrementMight();
} else if (rollResult == 3){
character.incrementMight();
Character char2 = character.getNearestCharacter();
char2.decrementSanity();
} else if (rollResult == 2){
character.decrementSanity();
} else if (rollResult == 1){
character.decrementSpeed();
} else {
ArrayList<Character> characters = Game.getInstance().getCharacters();
for (Character ch: characters){
Trait chosenTrait = Game.getInstance().chooseATrait();
ch.decrementTrait(chosenTrait, 1);
}
}
}
|
d0198f5d-1cf3-4ae6-9f06-9abc323a1e6b
| 7
|
private List<QCFile> dirjavaFind(File f) {
List<QCFile> result = new ArrayList<>();
if (!f.exists()) {
return result;
}
if (!f.isDirectory()) {
String type = GetIndexableFileType(f);
if (type != null) {
result.add(new QCFile(f, type));
}
return result;
}
if (f.isDirectory() && !IsIgnorableDirectory(f)) {
String[] chld = f.list();
if (chld != null) {
for (String s : chld) {
result.addAll(dirjavaFind(new File(f.getAbsolutePath() + '\\' + s)));
}
}
return result;
}
return result;
}
|
b4679807-beba-46d7-b0d5-87d747b4fdfb
| 7
|
public void printScene(Entity player) {
boolean leftOpen;
boolean frontOpen;
boolean rightOpen;
switch (player.movementDirection) {
case MainSystem.NORTH:
leftOpen = (this.maps.mapChars[this.map][this.arrayY][this.arrayX-1]==' ');
frontOpen = (this.maps.mapChars[this.map][this.arrayY-1][this.arrayX]==' ');
rightOpen = (this.maps.mapChars[this.map][this.arrayY][this.arrayX+1]==' ');
break;
case MainSystem.EAST:
leftOpen = (this.maps.mapChars[this.map][this.arrayY-1][this.arrayX]==' ');
frontOpen = (this.maps.mapChars[this.map][this.arrayY][this.arrayX+1]==' ');
rightOpen = (this.maps.mapChars[this.map][this.arrayY+1][this.arrayX]==' ');
break;
case MainSystem.SOUTH:
leftOpen = (this.maps.mapChars[this.map][this.arrayY][this.arrayX+1]==' ');
frontOpen = (this.maps.mapChars[this.map][this.arrayY+1][this.arrayX]==' ');
rightOpen = (this.maps.mapChars[this.map][this.arrayY][this.arrayX-1]==' ');
break;
case MainSystem.WEST:
leftOpen = (this.maps.mapChars[this.map][this.arrayY+1][this.arrayX]==' ');
frontOpen = (this.maps.mapChars[this.map][this.arrayY][this.arrayX-1]==' ');
rightOpen = (this.maps.mapChars[this.map][this.arrayY-1][this.arrayX]==' ');
break;
default:
leftOpen=false;
frontOpen=false;
rightOpen=false;
}
int scene = leftOpen ? 1 : 0;
scene += frontOpen ? 2 : 0;
scene += rightOpen ? 4 : 0;
this.scenes.printMap(scene);
}
|
cb55ec93-f652-4e33-ba8d-6a1af64f5934
| 6
|
private int loadCommands()
{
ArrayList<Command> _commands = new ArrayList<Command>();
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader(dictFile));
while ((line = br.readLine()) != null) {
String tabLine[];
tabLine = line.split(";");
String tabArgs[];
int no = 0;
int noArg = 0;
try
{
tabArgs = tabLine[1].split("#");
no = Integer.parseInt(tabArgs[0]);
if(tabArgs.length > 1)
{
noArg = Integer.parseInt(tabArgs[1]);
}
}
catch(Exception e)
{
no = Integer.parseInt(tabLine[1]);
}
_commands.add(new Command(tabLine[0], no, noArg));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
commands = _commands.toArray(new Command[0]);
return commands.length;
}
|
2d3b06f0-2dcf-4ea3-96eb-b94810b97c60
| 0
|
public List<Speaker> findSpeakersBySpecialityId(final Long specialityId) {
return new ArrayList<Speaker>();
}
|
d834cb8c-627b-44f5-9b65-cee30a652370
| 2
|
public boolean isDomainRegistered(final String domainName) {
boolean registered = checkDomainRegistered(domainName);
boolean unregistered = checkDomainUnregistered(domainName);
try {
assert registered != unregistered : "Domain check failed for Domain: " + domainName + "; reg: " + registered + "; unreg: " + unregistered;
} catch (AssertionError e) {
Logger log = LoggerCollection.getLogger("DomainLister");
log.log(Level.INFO, "Domain " + domainName + " got error finding out if domain is taken: " + e.toString());
String text = getWhois(domainName);
Matcher m = whoisUnregisteredPattern.matcher(text);
while (m.find()) {
log.log(Level.INFO, m.start() + ": " + m.group());
}
}
return registered;
}
|
307849d0-80dd-4043-80f5-21d206d5d87a
| 0
|
public SHSManagerBean() {
}
|
b88eed69-623f-405d-9513-00a338d0223a
| 8
|
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0)
&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS))
&&((msg.amITarget(affected))))
{
final MOB target=(MOB)msg.target();
if((!target.isInCombat())
&&(CMLib.flags().isUndead(msg.source()))
&&(msg.source().location()==target.location())
&&(msg.source().getVictim()!=target))
{
msg.source().tell(L("You don't see @x1",target.name(msg.source())));
if(target.getVictim()==msg.source())
{
target.makePeace(true);
target.setVictim(null);
helpProficiency((MOB)affected, 0);
}
return false;
}
}
return super.okMessage(myHost,msg);
}
|
522e681d-5b13-4c06-97f2-f4e63e87abcd
| 1
|
public Lohko nykyinenLohko() {
if (this.eiAvoimiaLohkoja()) {
return paalohko;
}
return lohkot.get(lohkot.size() - 1);
}
|
d4783d10-7b2b-4216-9a71-2aa9428b25df
| 3
|
public void disableSensor(String sensor_id) throws NotFoundException, IllegalAccessError, SocketTimeoutException {
try {
clientSocket.Escribir("OFF " + sensor_id + '\n');
serverAnswer = clientSocket.Leer();
} catch (IOException e) {
throw new SocketTimeoutException();
}
if(serverAnswer.contains("527 ERR")) {
throw new NotFoundException();
} else if(serverAnswer.contains("529 ERR")) {
throw new IllegalAccessError();
}
System.out.println(serverAnswer);
}
|
9f149f7f-b585-4330-9269-318e0c4b4688
| 0
|
private Point2D.Float transformPoint(Point p1) throws NoninvertibleTransformException {
// System.out.println("Model -> Screen Transformation:");
// showMatrix(coordTransform);
AffineTransform inverse = coordTransform.createInverse();
// System.out.println("Screen -> Model Transformation:");
// showMatrix(inverse);
Point2D.Float p2 = new Point2D.Float();
inverse.transform(p1, p2);
return p2;
}
|
c2a351ca-25e2-4a0c-a10b-66c8d847d053
| 0
|
private void setQuest(String id,QuestPoint quest, String title,
ArrayList<String> imageList, ArrayList<Boolean> imageInventoryList,
ArrayList<String> soundList, ArrayList<Boolean> soundInventoryList,
int narration, String paragraphList, String preNote, String postNote) {
quest.setId(id);
quest.setQuestName(title);
quest.setPicturePaths(imageList);
quest.setPictureInventoryList(imageInventoryList);
quest.setSoundPaths(soundList);
quest.setSoundInventoryList(soundInventoryList);
quest.setSoundNarration(narration);
quest.setParagraph(paragraphList);
quest.setPreNote(preNote);
quest.setPostNote(postNote);
QuestPoint.compareAndChangeId(Integer.parseInt(id));
}
|
11979fa3-3ddc-4a88-9624-0be19605dcb9
| 6
|
public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (end()) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
}
|
e242872d-1aad-4860-9d7f-953a6cc58ad7
| 3
|
protected NoeudArbre recherchePriorite(double priorite, int typeRecherche) throws Exercice1Exception {
NoeudArbre result = NIL;
switch (typeRecherche) {
case SEARCH_LIST:
result = recherchePrioriteList(priorite);
break;
case SEARCH_TREE:
if (root != NIL) {
result = recherchePrioriteArbre(priorite, root);
}
break;
default:
throw new Exercice1Exception("type de recherche inconnu");
}
return result;
}
|
1ef83c6c-0e0d-4ca4-899a-a46c8f00800c
| 4
|
private List<ReducerEstimatedJvmCost> estimateReducersMemory(List<Reducer> eReducers, InitialJvmCapacity gcCap) {
int fReducerNum = finishedConf.getMapred_reduce_tasks();
if(fReducerNum == 0)
return null;
List<ReducerEstimatedJvmCost> reducersJvmCostList = new ArrayList<ReducerEstimatedJvmCost>();
ReducerMemoryEstimator memoryEstimator = new ReducerMemoryEstimator(finishedConf, newConf, gcCap);
ReducerEstimatedJvmCost jvmCost;
//reducer number doesn't change
if(fReducerNum == newConf.getMapred_reduce_tasks()) {
for(int i = 0; i < fReducerNum; i++) {
//use the corresponding finished reducer to estimate the new reducer
//if input data is changed, this model needs modification
//currently, this model assumes the total input data is as same as the finished one
jvmCost = memoryEstimator.esimateJvmCost(job.getReducerList().get(i), eReducers.get(i));
reducersJvmCostList.add(jvmCost);
}
}
//reducer number changes
else {
for(int i = 0; i < newConf.getMapred_reduce_tasks(); i++) {
//use all the finished reducers' infos to estimate the new reducer
jvmCost = memoryEstimator.esimateJvmCost(job.getReducerList(), eReducers.get(i));
reducersJvmCostList.add(jvmCost);
}
}
return reducersJvmCostList;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.