method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
23d7d794-cb16-4a00-93f9-5e6d50859e66
| 5 |
public static void drawVerticalLine(int x, int y, int h, int color) {
if (x < startX || x >= endX)
return;
if (y < startY) {
h -= startY - y;
y = startY;
}
if (y + h > endY)
h = endY - y;
int j1 = x + y * width;
for (int k1 = 0; k1 < h; k1++)
pixels[j1 + k1 * width] = color;
}
|
e4db0815-3444-4109-a668-9093eef561fa
| 7 |
public static void avanzar(Cancha cancha, int equipo, int jugador, Pelota pelota){
float avance=cancha.getEquipoX(equipo).getJugadorX(jugador).getVelocidad();
avance=avance*Factorf.factorF();
int posX;
posX=cancha.getEquipoX(equipo).getJugadorX(jugador).getPosX();
int posY;
posY=cancha.getEquipoX(equipo).getJugadorX(jugador).getPosY();
int objX;
objX=cancha.getEquipoX(equipo).getJugadorX(jugador).getObjetivoX();
int objY;
objY=cancha.getEquipoX(equipo).getJugadorX(jugador).getObjetivoY();
int finX,finY;
double angulo=Math.atan2(objY-posY, objX-posX); //calculo angulo entre puntos(radianes)
finX=(int)(Math.cos(angulo)*avance)+posX;
finY=(int)(Math.sin(angulo)*avance)+posY;
if(cancha.getEquipoX(equipo).getJugadorX(jugador).getTipo()!="arquero"){
if(!cancha.getEquipoX(equipo).isLocal()){ // direccion hacia la que avanzan los jugadores
if(finX>objX){
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosX(objX);
}else {
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosX(finX);
}
if(finY>objY){
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosY(objY);
}else{
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosY(finY);
}
}else{
if(finX<objX){
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosX(objX);
}else {
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosX(finX);
}
if(finY<objY){
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosY(objY);
}else{
cancha.getEquipoX(equipo).getJugadorX(jugador).setPosY(finY);
}
}
}
if(cancha.getEquipoX(equipo).getJugadorX(jugador).isTieneBalon()){
pelota.setPosX(finX);
pelota.setPosY(finY);
}
}
|
4cda6e2e-ca1a-4814-a617-362382376f42
| 8 |
public boolean apply_wprime2w_edge_rule()
{
boolean changed = false;
ClosureOperation wop = null;
ClosureOperation wprime_op = null;
// 1) only the master process holds Read operations
for(BasicOperation bop : this.getProcess(masterPid).getOpList())
{
// 2) for each Read operation (R)
if(bop.isReadOp())
{
// 3) look up #opMatrix for all the Write precedences W' of R which is not W = D(R)
for(int row = 0; row < this.totalOpNum; row++)
{
wprime_op = this.opArray[row];
wop = (ClosureOperation) bop.getReadfromWrite();
if(! wprime_op.isReadOp()
&& wprime_op.getVariable().equals(bop.getVariable())
&& ! wprime_op.equals(wop)
&& this.opMatrix[row][((ClosureOperation) bop).getGlobalIndex()]
&& ! this.isReachable(wprime_op, wop))
{
// 4) add edge W' -> W
wprime_op.add_wprimew_order(wop);
this.opMatrix[wprime_op.getGlobalIndex()][wop.getGlobalIndex()] = true;
changed = true;
}
}
}
}
return changed;
}
|
723ab307-4977-458d-833f-c0fcadc7d0af
| 5 |
private static void merge(Comparable[] items, Comparable[] helper, int begin, int mid, int end) {
for (int i = begin; i <= end; i++) {
helper[i] = items[i];
}
int i = begin;
int j = mid + 1;
for (int k = begin; k <= end; k++) {
if (i > mid) {
items[k] = helper[j++];
} else if (j > end) {
items[k] = helper[i++];
} else if (helper[i].compareTo(helper[j]) < 0) {
items[k] = helper[i++];
} else {
items[k] = helper[j++];
}
}
}
|
dcb28520-2418-44ff-b10e-299584e1f9af
| 2 |
private static void recibirCanales() {
try {
AudioChatService.recibirObjeto(getIn().readObject());
} catch (IOException e) {
throw new ConexionException("Error al recibir el objeto: "
+ e.getMessage(), e);
} catch (ClassNotFoundException e) {
throw new ConexionException("Error al recibir el objeto: "
+ e.getMessage(), e);
}
}
|
873ac796-ec65-46da-879d-c71863a3669f
| 2 |
public static void renderText(String text, float x, float y, float width, float z){
if(USED_FONT == null){
OutputUtility.outputLine("GameFontRender Error: font not set");
}
OpenGLTexture[] textures = USED_FONT.getText(text);
float char_width = width/((float)textures.length);
float char_height = char_width * CHAR_HEIGHT_RATIO;
for(int i = 0; i < textures.length; i++){
float posX = x + (i * char_width);
float posY = y;
textures[i].setRGBAOverlay(r, g, b, a);
textures[i].draw(posX, posY, char_width, char_height, z);
}
}
|
863702f9-d268-4bec-a03a-dd1ff6c5378e
| 9 |
public static void loadText(String file) {
Scanner s = null;
InputStream is = Text.class.getResourceAsStream("/shoddybattleclient/languages/" + file);
try {
s = new Scanner(is);
} catch (Exception e) {
System.err.println("Failed to load language file");
return;
}
int category = -1;
int lineNumber = 0;
while (s.hasNextLine()) {
lineNumber++;
String line = s.nextLine();
line = line.trim();
if ("".equals(line)) continue;
int pos = line.indexOf("//");
if (pos == 0) continue;
if (pos != -1) {
line = line.substring(0, pos - 1);
}
if (line.charAt(0) == '[') {
if (line.indexOf(']') == -1) {
informError(lineNumber);
continue;
}
category++;
m_text.add(new HashMap<Integer, String>());
continue;
}
pos = line.indexOf(':');
if (pos == -1) {
informError(lineNumber);
continue;
}
int id;
try {
id = Integer.parseInt(line.substring(0, pos));
} catch (NumberFormatException e) {
informError(lineNumber);
continue;
}
String str = line.substring(pos + 1).trim();
m_text.get(category).put(id, str);
}
}
|
4b1c0cf5-a7ce-4266-b6d4-39bbeee72f52
| 2 |
@Override
public void changedMostRecentDocumentTouched(DocumentRepositoryEvent e) {
if (e.getDocument() == null) {
setEnabled(false);
} else {
JoeTree tree = e.getDocument().getTree();
if (tree.getComponentFocus() == OutlineLayoutManager.ICON) {
setEnabled(true);
} else {
setEnabled(false);
}
}
}
|
020fd1d2-8b09-43df-b2a8-92594643c6fd
| 7 |
@Override
public void OpenDoors() {
int dir = getMyDirection();
int flr = getFloor();
if (dir == DIRECTION_UP && myUpBarriers[flr].waiters() > 0) {
// System.out.println("Waking up " + myUpBarriers[flr].waiters() +
// " on floor " + myFloor);
myUpBarriers[flr].raise();
}
if (dir == DIRECTION_DOWN && myDownBarriers[flr].waiters() > 0) {
myDownBarriers[flr].raise();
}
// Elevator is in neutral and there is someone waiting to go up. Consider
// the edge cases. If there are people waiting to go up and down, the
// elevator will take the person going up first.
if (dir == DIRECTION_NEUTRAL) {
if (myUpBarriers[flr].waiters() == 0) myDownBarriers[flr].raise();
else myUpBarriers[flr].raise();
}
if (myOutBarriers[flr].waiters() > 0) myOutBarriers[flr].raise();
write("E" + elevatorId + " has opened on floor " + this.myFloor);
}
|
0f03f478-0b7e-4447-969a-6952fcda6c54
| 6 |
public void load(TaggedStorageChunk chunk)
{
this.cookedTime = chunk.getInteger("cookedTime");
this.burnTime = chunk.getInteger("burnTime");
if(chunk.hasTag("inID") && chunk.hasTag("innbr"))
{
this.in = new ItemStack(Item.get(chunk.getString("inID")), chunk.getInteger("innbr"));
}
if(chunk.hasTag("outID") && chunk.hasTag("outnbr"))
{
this.out = new ItemStack(Item.get(chunk.getString("outID")), chunk.getInteger("outnbr"));
}
if(chunk.hasTag("fireID") && chunk.hasTag("firenbr"))
{
this.fire = new ItemStack(Item.get(chunk.getString("fireID")), chunk.getInteger("firenbr"));
}
super.load(chunk);
}
|
06a1da30-8d8a-473b-889f-8820d85a6c40
| 6 |
@Override
public void actionPerformed(ActionEvent e) {
if (mIsRunning) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
repaint();
}
});
mAngle += 3;
if (mAngle >= 360) {
mAngle = 0;
}
if (mIsFadingOut) {
if (--mFadeCount == 0) {
mIsRunning = false;
mTimer.stop();
if (isWaiting) {
latch.countDown();
}
isWaiting = false;
latch = new CountDownLatch(1);
}
} else if (mFadeCount < mFadeLimit) {
mFadeCount++;
}
}
}
|
7fef4107-fbfe-4ea6-b8ff-c254a0338525
| 7 |
public void multiplyBy(double factor, int cx, int cy, int radius) {
int ci = getI(cx);
int cj = getJ(cy);
int iradius = getI(radius);
for (int i = ci - iradius; i < ci + iradius; i++) {
for (int j = cj - iradius; j < cj + iradius; j++) {
if (i < 0 || j < 0 || i >= voxels.length
|| j >= voxels[0].length)
continue;
double di = i - ci;
double dj = j - cj;
double idist = Math.sqrt(di * di + dj * dj);
if (idist < iradius)
voxels[i][j] *= factor;
}
}
}
|
bef5a4ff-785e-47d4-8b93-b4c3e604bac9
| 8 |
private static String encode(String value) {
String encoded = null;
try {
encoded = URLEncoder.encode(value, HTTP_ENCODING);
} catch (UnsupportedEncodingException ignore) {
}
StringBuilder buffer = new StringBuilder(encoded.length());
char focus;
for (int i = 0; i < encoded.length(); i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buffer.append("%2A");
} else if (focus == '+') {
buffer.append("%20");
} else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7' && encoded.charAt(i + 2) == 'E') {
buffer.append('~');
i += 2;
} else {
buffer.append(focus);
}
}
return buffer.toString();
}
|
1544a451-3c50-4574-9a4d-d52389b41547
| 2 |
public double maxProbability(int x_i) {
int n = potentials.chainLength();
int k = potentials.numXValues();
double best = Double.NEGATIVE_INFINITY;
double current = 0;
for (int v = 1 ; v <= k ; v++) {
current = messageFactor2Node(n,n,v) + messageFactor2Node(2*n-1,n,v);
if (current > best) {
best = current;
assignments[n] = v;
}
}
// normalize
SumProduct sp = new SumProduct(potentials);
sp.marginalProbability(1);
return best - Math.log(sp.sum);
}
|
4dfe4c14-00de-400d-9e8a-b155b56ce7a3
| 0 |
public void setMsgContent(byte[] msgContent) {
MsgContent = msgContent;
}
|
29361d52-ddbe-4026-b820-5ba046af5dbd
| 8 |
public boolean pickAndExecuteAnAction() {
synchronized (indecisiveCustomers) {
for (DavidCustomerRole cust : indecisiveCustomers) {
cust.msgAvailability(getAvailability());
indecisiveCustomers.remove(cust);
return true;
}
}
for (Table table : DavidRestaurant.tables) {
if (!table.isOccupied() && !waitingCustomers.isEmpty()
&& !waiters.isEmpty()) {
MyWaiter waiterToUse = getWaiter();
waiterToUse.numCustomers++;
seatCustomer(waitingCustomers.get(0), table, waiterToUse.w);
return true;
}
}
synchronized (waiters) {
for (MyWaiter myw : waiters) {
if (myw.state == WaiterState.BreakRequested) {
if (workingWaiters > 1) {
myw.state = WaiterState.OnBreak;
workingWaiters--;
myw.w.msgBreakReply(true);
return true;
} else {
myw.w.msgBreakReply(false);
return true;
}
}
}
}
return false;
}
|
2484bf5f-cd71-469c-91e8-a4aab7c7c697
| 9 |
public String getLecturaPrimitivaJava() {
if (nombre.equals("String")) {
return "in.nextLine()";
}
if (nombre.equals("int")) {
return "in.nextInt()";
}
if (nombre.equals("float")) {
return "in.nextFloat()";
}
if (nombre.equals("double")) {
return "in.nextDouble()";
}
if (nombre.equals("char")) {
return "in.nextLine().charAt(0)";
}
if (nombre.equals("boolean")) {
return "in.nextBoolean()";
}
if (nombre.equals("long")) {
return "in.nextLong()";
}
if (nombre.equals("byte")) {
return "in.nextByte()";
}
if (nombre.equals("short")) {
return "in.nextShort()";
}
return "";
}
|
7cd9c0ad-6e45-4a7e-a2c9-68203c04642e
| 0 |
public int getRandomNumber(int min, int max) {
return (int) Math.floor(Math.random() * (max - min + 1)) + min;
}
|
b81877ad-5bcf-4b0b-994b-d527cf763c76
| 2 |
@Override
public boolean verificaAcesso(Funcionario funcionario) {
try {
conn = ConnectionFactory.getConnection();
String sql = "SELECT * "
+ " FROM funcionario "
+ " JOIN acesso ON funcionario.idacesso = acesso.id "
+ " WHERE acesso.tipo = 'Gerente' "
+ " AND funcionario.cpf = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, funcionario.getCpf());
rs = ps.executeQuery();
return rs.next();
} catch (SQLException e){
throw new RuntimeException("Erro " + e.getSQLState()
+ " ao atualizar o objeto: "
+ e.getLocalizedMessage());
} catch (ClassNotFoundException e){
throw new RuntimeException("Erro ao conectar ao banco: "
+ e.getMessage());
} finally {
close();
}
}
|
945165c9-c087-4969-8e0e-a24e1615a90c
| 2 |
public RaavareBatchDTO getRaavareBatch(int rbId) throws DALException {
ResultSet rs = Connector.doQuery("SELECT * FROM raavarebatch WHERE rb_id = " + rbId);
try {
if (!rs.first()) throw new DALException("Raavarebatchen " + rbId + " findes ikke");
return new RaavareBatchDTO (rs.getInt(1), rs.getInt(2), rs.getDouble(3));
}
catch (SQLException e) {throw new DALException(e); }
}
|
dc14bcdd-6162-488d-b37a-1a192495def3
| 8 |
public double side(Box box) {
final Point2DInt corners[] = box.getCorners();
final double s0 = side(corners[0]);
final double s1 = side(corners[1]);
final double s2 = side(corners[2]);
final double s3 = side(corners[3]);
if (s0 > 0 && s1 > 0 && s2 > 0 && s3 > 0) {
return 1;
}
if (s0 < 0 && s1 < 0 && s2 < 0 && s3 < 0) {
return -1;
}
return 0;
}
|
ee1026ad-5682-4323-b445-6f626c6633cc
| 9 |
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
if (name.equalsIgnoreCase("gameName")) {
gameName = currentValue;
}
if (isAchievement) {
if (name.equalsIgnoreCase("iconClosed")) {
currentA.setIconOpenURLPath(currentValue);
}
if (name.equalsIgnoreCase("iconOpen")) {
currentA.setIconClosedURLPath(currentValue);
}
if (name.equalsIgnoreCase("name")) {
currentA.setName(currentValue);
}
if (name.equalsIgnoreCase("description")) {
currentA.setDescription(currentValue);
}
if (name.equalsIgnoreCase("unlockTimeStamp")){
if(currentA.convertNSetTimeStamp(currentValue)){
currentA.setTimeStamp(currentA.getUnixTimeStamp());
}
}
if (name.equalsIgnoreCase("achievement")) {
String gName = currentA.getGame().getFriendlyName();
currentA.setIconClosedPath(DataPath.gameDir + DataPath.sep + gName
+ DataPath.sep + "achievements" + DataPath.sep + DataPath.getImageName(currentA.getIconClosedURLPath()));
currentA.setIconOpenPath(DataPath.gameDir + DataPath.sep + gName
+ DataPath.sep + "achievements" + DataPath.sep + DataPath.getImageName(currentA.getIconOpenURLPath()));
achievements.add(currentA);
}
}
}
|
775696d8-970f-4377-8bfd-6bd64a2a726e
| 4 |
public void saveWorldInfoAndPlayer(WorldInfo var1, List var2) {
NBTTagCompound var3 = var1.getNBTTagCompoundWithPlayer(var2);
NBTTagCompound var4 = new NBTTagCompound();
var4.setTag("Data", var3);
try {
File var5 = new File(this.saveDirectory, "level.dat_new");
File var6 = new File(this.saveDirectory, "level.dat_old");
File var7 = new File(this.saveDirectory, "level.dat");
CompressedStreamTools.writeGzippedCompoundToOutputStream(var4, new FileOutputStream(var5));
if(var6.exists()) {
var6.delete();
}
var7.renameTo(var6);
if(var7.exists()) {
var7.delete();
}
var5.renameTo(var7);
if(var5.exists()) {
var5.delete();
}
} catch (Exception var8) {
var8.printStackTrace();
}
}
|
f56b561f-5728-4369-bd76-dfda0053f2e0
| 3 |
@Override
public EntidadBancaria get(int id) {
PreparedStatement preparedStatement;
EntidadBancaria entidadBancaria;
ResultSet resultSet;
Connection connection = connectionFactory.getConnection();
try {
preparedStatement = connection.prepareStatement("SELECT * FROM entidadbancaria WHERE idEntidadBancaria = ?");
preparedStatement.setInt(1, id);
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
entidadBancaria = new EntidadBancaria();
entidadBancaria.setNombre(resultSet.getString("nombre"));
entidadBancaria.setFechaCreacion(resultSet.getDate("fechaCreacion"));
entidadBancaria.setCodigoEntidad(resultSet.getString("codigoEntidad"));
entidadBancaria.setIdEntidad(resultSet.getInt("idEntidadBancaria"));
if (resultSet.next()) {
throw new RuntimeException("Devuelve mas de una fila");
}
} else {
entidadBancaria = null;
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
connectionFactory.closeConnection();
return entidadBancaria;
}
|
07dc1e41-e860-4ee1-a2d2-65ab54b219a4
| 7 |
public static Message parse(String message) {
switch(Message.parseType(message)) {
case ID_REQUEST:
return new IdRequestMessage().decode(message);
case ID_RESPONSE:
return new IdResponseMessage().decode(message);
case SPAWN:
return new SpawnMessage().decode(message);
case DESPAWN:
return new DespawnMessage().decode(message);
case MOVE:
return new MoveMessage().decode(message);
case BUMP:
return new BumpMessage().decode(message);
case SYNC:
return new SyncMessage().decode(message);
default:
return null;
}
}
|
ead7632d-7a3b-4f6e-8935-e82616b169c8
| 0 |
public boolean getObtained() {
return this.obtained;
}
|
4ecfbcab-2848-4c76-8367-336f54e4a4d9
| 1 |
public boolean writeStore(ReservationStation resStation, String result) {
if (resStation.getQk() == null) {
String b = resStation.getDest();
ROB.updateValue(Integer.parseInt(b), result);
return true;
}
return false;
}
|
6021c58a-5f92-4093-9767-c80b142bf475
| 1 |
protected static BmUrlManager getBmUrlManager() {
if (bmUrlManager == null)
bmUrlManager = new BmUrlManager();
return bmUrlManager;
}
|
0f7b411c-2de6-4154-bdec-cb650911045a
| 5 |
@Override
public void onUpdate(World apples) {
if (!apples.inBounds(X, Y)||life--<0)
{
alive = false;
//apples.explode(X, Y, 32, 8, 16);
}
if (!apples.isSolid(X, Y-10))
{
Y-=10;
}
for (int i = 1; i < 10; i++)
{
if (!apples.isSolid(X, Y+i))
{
Y+=i;
}
}
/*if (yspeed<12)
{
yspeed++;
}*/
}
|
3b926d00-9507-4d76-8280-6cad03ad2a68
| 2 |
@Override
public void end(String nick){
if(end == false){
end = true;
if(!nick.equals("computer")) {
Player p = em.find(Player.class, nick);
p.setScore();
em.merge(p);
}
}
}
|
67978c07-8ac9-4134-9736-9239865b063a
| 4 |
public static boolean intersects( String rng, int[] rc )
{
int[] rc2 = getRangeCoords( rng );
if( (rc[0] >= rc2[0]) && (rc[2] <= rc2[2]) && (rc[1] >= rc2[1]) && (rc[3] <= rc2[3]) )
{
return true;
}
return false;
}
|
43af9069-0af2-43b5-8584-3f765d565137
| 2 |
public List<Cliente> listar() {
String sql = "SELECT * FROM CLIENTE";
try {
conn = GerenciaConexaoBD.getInstance().getConnection();
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<Cliente> listaCliente = new ArrayList<Cliente>();
while (rs.next()) {
Cliente cliente = new Cliente();
cliente.setIdCliente(rs.getInt("idCliente"));
cliente.setNome(rs.getString("nome"));
cliente.setCpf(rs.getString("cpf"));
cliente.setEmail(rs.getString("email"));
listaCliente.add(cliente);
}
stmt.close();
return listaCliente;
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
|
9285976e-c0bd-4c4b-b35c-12ec81e80fcb
| 7 |
public double calcUntersumme()
{
double hoehe, erg;
erg = 0.0;
for(double i=intervalLeft; i<=intervalRight-dx+(dx/4); i+=dx)
{
int j1, j2;
j1 = 0;
while(points.get(j1).getX()<=i && j1 < points.size()-1)
{
j1++;
}
j2 = j1;
while(points.get(j2).getX()<=i+dx && j2 < points.size()-1)
{
j2++;
}
hoehe = points.get(j1).getY();
for(int j=j1; j<=j2; j++)
{
if(points.get(j).getY()<hoehe)
{
hoehe = points.get(j).getY();
}
}
erg += dx*hoehe;
}
return erg;
}
|
de44d922-dd94-4177-b8ed-514072fdb8d0
| 0 |
public CheckboxListener(JCheckBox checkbox, Preference pref) {
setCheckBox(checkbox);
setPreference(pref);
}
|
ae5b2134-a448-460c-8b3f-3263ace62eb1
| 6 |
public void tableau_manuel_suivant()
{
tcon.gridy=tcompteur++;
float max =0;
for(int i=1;i<data.get(0).size();i++)
{
if(Float.parseFloat(data.lastElement().get(i))>max)
max = Float.parseFloat(data.lastElement().get(i));
}
if(iteration==0)
{
jPanel2.add(new JLabel("Tableau initial "+((max==0)?"& final":"") +":"),tcon);
}
else if(max==0){
jPanel2.add(new JLabel("Tableau final :"),tcon);
}
else
{
jPanel2.add(new JLabel("Tableau "+iteration+" :"),tcon);
}
tcon.gridy=tcompteur++;
TableIT tableit = new TableIT(data,(max==0),false);
tables.add(tableit);
jPanel2.add(tables.lastElement(),tcon);
if(max!=0)
{
JButton btn = new JButton("Calculer");
btn_tables.add(btn);
tcon.gridy=tcompteur++;
jPanel2.add(btn_tables.lastElement(),tcon);
btn_tables.lastElement().addActionListener(this);
}
iteration++;
jPanel2.setVisible(false);
jPanel2.setVisible(true);
}
|
a5d99951-7932-4bcd-b38c-9391c24024e5
| 9 |
@Override
public void setMiscText(String newText)
{
super.setMiscText(newText);
operation = null;
mask=null;
selfXP=false;
String s=newText.trim();
int x=s.indexOf(';');
if(x>=0)
{
mask=CMLib.masking().getPreCompiledMask(s.substring(x+1).trim());
s=s.substring(0,x).trim();
}
x=s.indexOf("SELF");
if(x>=0)
{
selfXP=true;
s=s.substring(0,x)+s.substring(x+4);
}
operationFormula="Amount "+s;
if(s.startsWith("="))
operation = CMath.compileMathExpression(translateNumber(s.substring(1)).trim());
else
if(s.startsWith("+"))
operation = CMath.compileMathExpression("@x1 + "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("-"))
operation = CMath.compileMathExpression("@x1 - "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("*"))
operation = CMath.compileMathExpression("@x1 * "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("/"))
operation = CMath.compileMathExpression("@x1 / "+translateNumber(s.substring(1)).trim());
else
if(s.startsWith("(")&&(s.endsWith(")")))
{
operationFormula="Amount ="+s;
operation = CMath.compileMathExpression(s);
}
else
operation = CMath.compileMathExpression(translateNumber(s.trim()));
operationFormula=CMStrings.replaceAll(operationFormula, "@x1", "Amount");
}
|
625cae09-3120-4e1c-ac68-d8f34bde7e73
| 8 |
@Override
public Rectangle getBoundingBox() {
int smallestx = Integer.MAX_VALUE;
int smallesty = Integer.MAX_VALUE;
int biggesty = Integer.MIN_VALUE;
int biggestx = Integer.MIN_VALUE;
for (int i = 0; i <= px.length - 1; i++) {
if (px[i] < smallestx) {
smallestx = px[i];
}
}
for (int i = 0; i <= py.length - 1; i++) {
if (py[i] < smallesty) {
smallesty = py[i];
}
}
for (int i = 0; i <= px.length - 1; i++) {
if (px[i] > biggestx) {
biggestx = px[i];
}
}
for (int i = 0; i <= py.length - 1; i++) {
if (py[i] > biggesty) {
biggesty = py[i];
}
}
p1 = new Point(smallestx, smallesty);
p2 = new Point(biggestx, biggesty);
return new Rectangle(p1, p2);
}
|
2a7f7b77-3d6c-47de-a122-c267b767d313
| 1 |
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
// Notify method splash that the window
// has been painted.
// Note: To improve performance we do not enter
// the synchronized block unless we have to.
if (! paintCalled) {
paintCalled = true;
synchronized (this) { notifyAll(); }
}
}
|
f71e9d31-e4b4-4424-af29-7f88f3981e04
| 4 |
private final static BitPayResponse toBitPayResponse(Invoice invoice) {
BitPayResponse response = new BitPayResponse();
if (invoice == null) return response;
response.btcPrice = invoice.getBtcPrice();
response.status = invoice.getStatus();
response.price = invoice.getPrice();
response.currency = invoice.getCurrency();
response.url = invoice.getUrl();
response.currentTime = invoice.getCurrentTime();
response.rate = invoice.getRate();
response.exceptionStatus = invoice.hasExceptionStatus();
response.expirationTime = invoice.getExpirationTime();
response.btcPaid = invoice.getBtcPaid();
response.invoiceTime = invoice.getInvoiceTime();
response.id = invoice.getId();
try {
Document url = Jsoup.connect(response.url).get();
for (Element elm : url.select("a")) {
if (elm.attr("href").toString().contains("bitcoin:")) {
String href = elm.attr("href");
response.address = href.substring(href.indexOf(":") + 1, href.indexOf("?"));
break;
}
}
} catch (IOException ie) {
System.out.println("EXCEPTION REQUESTING URL : "+ response.url);
System.out.println(ie);
}
return response;
}
|
26034a68-8004-4d7d-9df2-fd56b7c85c67
| 6 |
public static void addBuff(Unit owner, Unit target, Buff buff) {
if (owner != null && target != null && buff != null) {
// check if buff already had a target -> if so then remove the buff from the current target
if (buff.getTarget() != null)
GameLogic.INSTANCE.removeBuff(buff.getTarget(), buff);
// set buff owner to have a correct reference to the source unit of the buff
buff.setOwner(owner);
buff.setTarget(target);
Set<Buff> currentBuffs = target.getBuffs();
if (currentBuffs == null) {
// unit does not have a buff yet
currentBuffs = new HashSet<Buff>();
target.setBuffs(currentBuffs);
}
currentBuffs.add(buff);
// buff was successfully added to the target unit
// create event for gameEventController
Map<GameEventParameter, Object> eventParams = new HashMap<GameEventParameter, Object>();
eventParams.put(GameEventParameter.TRIGGERING_UNIT, owner);
eventParams.put(GameEventParameter.TARGET_UNIT, target);
eventParams.put(GameEventParameter.TRIGGERING_BUFF, buff);
GameEventHandler.INSTANCE.createAndDispatchEvent(GameEventType.UNIT_ADD_BUFF, owner, eventParams);
if (LOGGER.isDebugEnabled())
LOGGER.debug("Successfully added buff '" + buff + "' to target unit '" + target + "'");
}
}
|
3001ef5a-ba93-4c08-8e4a-bb8069ec6e36
| 8 |
* @param sizecutoff
*/
public static void printExtensionSizes(Module module, int sizecutoff) {
if (sizecutoff == Stella.NULL_INTEGER) {
sizecutoff = 10;
}
if (module == null) {
module = ((Module)(Stella.$MODULE$.get()));
}
{ List descriptions = List.newList();
String size = null;
{ NamedDescription d = null;
Iterator iter000 = Logic.allNamedDescriptions(module, false);
Cons collect000 = null;
while (iter000.nextP()) {
d = ((NamedDescription)(iter000.value));
if ((d.extension != null) &&
(d.extension.estimatedLength() >= sizecutoff)) {
if (collect000 == null) {
{
collect000 = Cons.cons(d, Stella.NIL);
if (descriptions.theConsList == Stella.NIL) {
descriptions.theConsList = collect000;
}
else {
Cons.addConsToEndOfConsList(descriptions.theConsList, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(d, Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
}
descriptions.sort(Native.find_java_method("edu.isi.powerloom.logic.Description", "descriptionExtensionL", new java.lang.Class [] {Native.find_java_class("edu.isi.powerloom.logic.Description"), Native.find_java_class("edu.isi.powerloom.logic.Description")}));
{ NamedDescription desc = null;
Cons iter001 = descriptions.reverse().theConsList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
desc = ((NamedDescription)(iter001.value));
size = Native.integerToString(((long)(desc.extension.estimatedLength())));
size = Native.makeString(8 - size.length(), ' ') + size;
System.out.println(size + " : " + desc.descriptionName());
}
}
}
}
|
164ffeb2-36c4-4fdc-90d8-6128b742a75f
| 8 |
static void next_move(int posr, int posc, int dimh, int dimw, String[] board) {
char[][] chars = new char[board.length][board[0].length()];
for (int i = 0; i < board.length; i++) {
chars[i] = board[i].toCharArray();
}
String ret = null;
if (chars[posr][posc] == 'd') {
ret = "CLEAN";
chars[posr][posc] = '-';
board[posr] = new String(chars[posr]);
} else {
for (int i = 1; i < (board.length - 1) * 2; i++) {
int[] next = findNextD(posr, posc, chars, i);
if (next != null) {
if (next[0] < posr) {
ret = "UP";
} else if (next[0] > posr) {
ret = "DOWN";
} else {
if (next[1] < posc) {
ret = "LEFT";
} else if (next[1] > posc) {
ret = "RIGHT";
}
}
break;
}
}
}
System.out.println(ret);
}
|
77ea77e5-400b-441a-b253-ef417e8cd18d
| 3 |
public static Mask buildLogMask(int size, double sigma) {
if (size % 2 == 0) {
size++;
}
Mask mask = new Mask(size);
for (int i = -mask.getWidth() / 2; i <= mask.getWidth() / 2; i++) {
for (int j = -mask.getHeight() / 2; j <= mask.getHeight() / 2; j++) {
//1/(sqrt(2*pi)*sigma^3)
double factor = Math.pow(
Math.sqrt(2 * Math.PI) * Math.pow(sigma, 3), -1);
//e^(-(x^2+y^2)/(2*sigma^2))
double exp = -(Math.pow(i, 2) + Math.pow(j, 2))
/ (2 * Math.pow(sigma, 2));
//2-((x^2+y^2)/(sigma^2))
double term = 2 - (Math.pow(i, 2) + Math.pow(j, 2))
/ Math.pow(sigma, 2);
double pixelValue = -1 * factor * term * Math.pow(Math.E, exp);
mask.setPixel(i, j, pixelValue);
}
}
return mask;
}
|
35fb3889-4379-489b-85e2-424f43f1e238
| 5 |
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
frame.setTitle("AsteroidTester");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Random r = new Random();
ArrayList<Asteroid> asteroidList = new ArrayList<Asteroid>();
ArrayList<Drawable> drawableList = new ArrayList<Drawable>();
for (int i = 1; i <= 10; i++)
{
double angle = r.nextDouble() * 359;
int size = r.nextInt(3) + 1;
asteroidList.add(new Asteroid(frame.getWidth() / 2, frame.getHeight() / 2, angle, size, WIDTH,HEIGHT ));
}
//Creates the drawing component and adds it to the frame.
AsteroidsComponent component = new AsteroidsComponent(drawableList);
component.setDoubleBuffered(true);
frame.add(component);
frame.setVisible(true);
boolean gameOver = false;
while(!gameOver)
{
for (Asteroid asteroid : asteroidList)
asteroid.move();
//Pause.pause(10);
int listSize = drawableList.size();
for (int k = 0; k < listSize; k++)
drawableList.remove(0);
for (Asteroid asteroid : asteroidList)
drawableList.add(asteroid);
component.paintImmediately(0,0,frame.getWidth(),frame.getHeight());
}
}
|
72e67271-cad2-46aa-a3a2-0e1b88f4e183
| 9 |
public static void addItem(Hero owner, Item item) {
if (owner != null && item != null && !owner.equals(item.getOwner())) {
item.setOwner(owner);
switch (item.getCategory()) {
case CONSUMABLE: {
// add item to pouch
owner.getPouch().add(item);
if (LOGGER.isDebugEnabled())
LOGGER.debug("Successfully added consumable item '" + item + "' to hero " + owner);
break;
}
case QUEST: {
// add item to inventory
owner.getInventory().add(item);
if (LOGGER.isDebugEnabled())
LOGGER.debug("Successfully added QUEST item '" + item + "' to inventory of hero " + owner);
break;
}
default: {
// add item to current equipment or inventory of owner
// try if item can be equipped
if (!equipItem(owner, item)) {
// item level requirement to high OR
// item bearable maximum of this type already reached
// --> put item in inventory for later use
owner.getInventory().add(item);
if (LOGGER.isDebugEnabled())
LOGGER.debug("Successfully added inventory item '" + item + "' to hero " + owner);
}
break;
}
}
// create event for gameEventController
Map<GameEventParameter, Object> eventParams = new HashMap<GameEventParameter, Object>();
eventParams.put(GameEventParameter.TRIGGERING_UNIT, owner);
eventParams.put(GameEventParameter.TRIGGERING_ITEM, item);
GameEventHandler.INSTANCE.createAndDispatchEvent(GameEventType.UNIT_ADD_ITEM, owner, eventParams);
}
}
|
2a80036d-d3ee-4da9-976f-691ef470ab92
| 3 |
private void report(String name, double value, Hashtable attributes) {
Frame frame = new Frame(name);
Label label = null;
// Resize the frame so it can contain all the text.
// XXXX Ideally we need to find the longest property and resize horizontally as well.
if (attributes != null) {
frame.setSize(200, (attributes.size()*50 + 100));
} else {
frame.setSize(200,100);
}
GridBagLayout gridBag = new GridBagLayout();
frame.setLayout(gridBag);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(5, 5, 5, 5);
c.ipadx = 2;
c.ipady = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
label = new Label("value = " + Double.toString(value));
gridBag.setConstraints(label, c);
frame.add(label);
// Add the properties.
if (attributes != null) {
String attributeString = (attributes.toString()).trim();
attributeString = attributeString.substring(1,attributeString.length()-1);
StringTokenizer st = new StringTokenizer(attributeString,", ");
while (st.hasMoreTokens()) {
c.gridy++;
label = new Label(st.nextToken());
gridBag.setConstraints(label, c);
frame.add(label);
}
}
frame.setLocation(350,350);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
((Frame)e.getComponent()).setVisible(false);
}
});
frame.setVisible(true);
} // End of report.
|
122fe66c-7944-4080-8f0a-96557699f3e2
| 4 |
public Expression(String expression) {
this.expression = expression;
addOperator(new Operator("+", 20, true) {
@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.add(v2, mc);
}
});
addOperator(new Operator("-", 20, true) {
@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.subtract(v2, mc);
}
});
addOperator(new Operator("*", 30, true) {
@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.multiply(v2, mc);
}
});
addOperator(new Operator("/", 30, true) {
@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.divide(v2, mc);
}
});
addOperator(new Operator(">", 10, false) {
@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.compareTo(v2) == 1 ? BigDecimal.ONE : BigDecimal.ZERO;
}
});
addOperator(new Operator("<", 10, false) {
@Override
public BigDecimal eval(BigDecimal v1, BigDecimal v2) {
return v1.compareTo(v2) == -1 ? BigDecimal.ONE : BigDecimal.ZERO;
}
});
addFunction(new Function("MAX", 2) {
@Override
public BigDecimal eval(List<BigDecimal> parameters) {
BigDecimal v1 = parameters.get(0);
BigDecimal v2 = parameters.get(1);
return v1.compareTo(v2) > 0 ? v1 : v2;
}
});
addFunction(new Function("MIN", 2) {
@Override
public BigDecimal eval(List<BigDecimal> parameters) {
BigDecimal v1 = parameters.get(0);
BigDecimal v2 = parameters.get(1);
return v1.compareTo(v2) < 0 ? v1 : v2;
}
});
variables.put("TRUE", BigDecimal.ONE);
variables.put("FALSE", BigDecimal.ZERO);
}
|
91cbb231-d1c6-4b95-9808-b42f16eb5ce2
| 9 |
private void initialize( String h, int p, String n )
{
if ( h == null )
{
throw new IllegalArgumentException( "Hostname cannot be null" );
}
if ( "".equals( h ) )
{
throw new IllegalArgumentException( "Hostname cannot be empty" );
}
if ( h.indexOf( " " ) > -1 )
{
throw new IllegalArgumentException( "Hostname may not contain spaces" );
}
if ( h.indexOf( "_" ) > -1 )
{
throw new IllegalArgumentException( "Hostname may not contain underscores" );
}
host = h;
if ( p < 0 )
{
throw new IllegalArgumentException( "Port may not be negative" );
}
if ( p < 1024 )
{
throw new IllegalArgumentException( "Port may not be privileged (less than 1024)" );
}
if ( p > 65535 )
{
throw new IllegalArgumentException( "Port may not be greater than 65535" );
}
port = p;
// just make sure name isn't null or empty
if ( n == null || "".equals( n ) )
{
name = "Unknown";
}
else
{
name = n;
}
}
|
51f4641c-ccd1-4d6a-8959-319f64b24726
| 7 |
public static void numDecodingsHelper(String s, int[] helper, String last) {
if (s.length() == 0)
return;
boolean flag = false;
String newLast;
if (s.length() >= 2) {
if (Integer.parseInt(s.substring(1, 2)) == 0) {
helper[0]++;
numDecodingsHelper(s.substring(2), helper, s.substring(1, 2));
} else if (Integer.parseInt(s.substring(0, 2)) > 26) {
helper[0]++;
numDecodingsHelper(s.substring(2), helper, s.substring(1, 2));
} else {
helper[0]++;
helper[0]++;
numDecodingsHelper(s.substring(2), helper,s.substring(1, 2));
}
}else if(s.length() >=1 && s.length() <2){
if(s.substring(0, 1) != "0"){
helper[0]++;
numDecodingsHelper(s.substring(1), helper,s.substring(0, 1));
}else{
numDecodingsHelper(s.substring(1), helper,s.substring(0, 1));
}
}
}
|
257d7079-396a-4b4a-968d-6cb2a77b9fc3
| 0 |
public void setIdTpv(int idTpv) {
this.idTpv = idTpv;
}
|
63821ac1-680a-4c59-a7c3-8b4d0a6539b3
| 7 |
void menuOpenURL() {
animate = false; // stop any animation in progress
// Get the user to choose an image URL.
TextPrompter textPrompter = new TextPrompter(shell, SWT.APPLICATION_MODAL | SWT.DIALOG_TRIM);
textPrompter.setText(bundle.getString("OpenURLDialog"));
textPrompter.setMessage(bundle.getString("EnterURL"));
String urlname = textPrompter.open();
if (urlname == null) return;
Cursor waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
shell.setCursor(waitCursor);
imageCanvas.setCursor(waitCursor);
ImageLoader oldLoader = loader;
try {
URL url = new URL(urlname);
InputStream stream = url.openStream();
loader = new ImageLoader();
if (incremental) {
// Prepare to handle incremental events.
loader.addImageLoaderListener(new ImageLoaderListener() {
public void imageDataLoaded(ImageLoaderEvent event) {
incrementalDataLoaded(event);
}
});
incrementalThreadStart();
}
// Read the new image(s) from the chosen URL.
long startTime = System.currentTimeMillis();
imageDataArray = loader.load(stream);
loadTime = System.currentTimeMillis() - startTime;
stream.close();
if (imageDataArray.length > 0) {
currentName = urlname;
fileName = null;
// If there are multiple images (typically GIF)
// then enable the Previous, Next and Animate buttons.
previousButton.setEnabled(imageDataArray.length > 1);
nextButton.setEnabled(imageDataArray.length > 1);
animateButton.setEnabled(imageDataArray.length > 1 && loader.logicalScreenWidth > 0 && loader.logicalScreenHeight > 0);
// Display the first image.
imageDataIndex = 0;
displayImage(imageDataArray[imageDataIndex]);
}
} catch (Exception e) {
showErrorDialog(bundle.getString("Loading_lc"), urlname, e);
loader = oldLoader;
} catch (OutOfMemoryError e) {
showErrorDialog(bundle.getString("Loading_lc"), urlname, e);
loader = oldLoader;
} finally {
shell.setCursor(null);
imageCanvas.setCursor(crossCursor);
waitCursor.dispose();
}
}
|
2723983c-0fb8-4e66-b8b2-13d7f2846f10
| 4 |
public void scoreCountCorrelate() {
double totalScore = 0;
int totalBusinessCnt = 0;
Map<Double, List<Integer>> businessScoreCountMap = new TreeMap<Double, List<Integer>>();
for (Business business:businessMap.values()) {
//System.out.println("hello");
totalBusinessCnt += 1;
double star = business.stars;
totalScore += star;
if (!businessScoreCountMap.containsKey(star)) {
businessScoreCountMap.put(star,new ArrayList<Integer> ());
}
businessScoreCountMap.get(star).add(business.review_count);
}
// DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();
// for (Double d:businessScoreCountMap.keySet()) {
// System.out.println(Collections.max(businessScoreCountMap.get(d)));
// System.out.println(businessScoreCountMap.get(d));
// dataset.add(businessScoreCountMap.get(d),String.valueOf(d),String.valueOf(d));
// }
// CategoryAxis xAxis = new CategoryAxis("Business Score");
// final NumberAxis yAxis = new NumberAxis("Review Count");
// yAxis.setAutoRangeIncludesZero(false);
// final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
// renderer.setFillBox(false);
// renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
// final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);
//
// final JFreeChart chart = new JFreeChart(
// "Review Count vs Business Score Box Plot",
// new Font("SansSerif", Font.BOLD, 14),
// plot,
// true
// );
XYSeries series = new XYSeries("XYGraph");
XYSeries series2 = new XYSeries("XYGraph2");
XYSeries series3 = new XYSeries("XYGraph3");
for (Double d:businessScoreCountMap.keySet()) {
//series.add(d,Collections.max(businessScoreCountMap.get(d)));
//series2.add(d,Collections.min(businessScoreCountMap.get(d)));
series3.add(d, new Double(calculateAverage(businessScoreCountMap.get(d))));
//series3.add(d,avg);
//series3.add(d,avg);
}
// Add the series to your data set
XYSeriesCollection dataset = new XYSeriesCollection();
//dataset.addSeries(series);
//dataset.addSeries(series2);
dataset.addSeries(series3);
// Generate the graph
JFreeChart chart = ChartFactory.createXYLineChart(
"Review Count vs Business Score Plot",
"Business Score",
"Review Count",
dataset,
PlotOrientation.VERTICAL, // Plot Orientation
true, // Show Legend
true, // Use tooltips
false // Configure chart to generate URLs?
);
try {
ChartUtilities.saveChartAsJPEG(new File("maxplot.jpg"), chart, 800, 400);
} catch (IOException e) {
System.err.println("Problem occurred creating chart.");
}
}
|
f833b6db-2606-4703-9ce4-d94431d80d03
| 6 |
public ListNode rotateRight(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if (n == 0 || head == null || head.next == null)
return head;
ListNode firstNode = head;
ListNode secNode = head;
while (n > 0) {
n--;
firstNode = firstNode.next;
if (firstNode == null)
firstNode = head; // 循环到头结点
}
while (firstNode.next != null) {
firstNode = firstNode.next;
secNode = secNode.next;
}
firstNode.next = head; // 三个操作
head = secNode.next;
secNode.next = null;
return head;
}
|
2cc9cf4a-ff5b-42ff-9237-1aa7606a3da0
| 0 |
public void setVersion(String value) {
this.version = value;
}
|
13b54761-7526-4d60-9a35-129a2def8bdf
| 1 |
public boolean isAValidMethod(Request request) {
return isAURIMatch(request) && getRoutesMap(request).get(request.getURI()).containsKey(request.getHTTPMethod());
}
|
5c061e83-8f49-41d3-b50e-02b750ca1d41
| 7 |
public boolean hit(ArrayList<Bullet> bullets,int damage){
if( this.isAlive() ){
for(Bullet b:bullets){
//ӵŵʱɱ
if( b.isAlive() && b.getId()!=id ){
if(inside(b)){
//HP
if( hp>0 ){
hp = hp - damage;
}
if( hp<=0 ){
this.setAlive(false);
cx = this.x;
cy = this.y;
cwidth = WIDTH;
cheight = HEIGHT;
deadStatus = DEAD_1;
}
return true;
}
}
}
}
return false;
}
|
a5083e75-1ccb-40d8-98dd-4ed49ba7b1cc
| 6 |
* @param arguments
* @return int
*/
public static int applyIntegerMethod(java.lang.reflect.Method code, Cons arguments) {
switch (arguments.length()) {
case 0:
throw ((StellaException)(StellaException.newStellaException("Can't call method code on 0 arguments.").fillInStackTrace()));
case 1:
return (((Integer)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{}))).intValue());
case 2:
return (((Integer)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value}))).intValue());
case 3:
return (((Integer)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value, arguments.nth(2)}))).intValue());
case 4:
return (((Integer)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value, arguments.nth(2), arguments.nth(3)}))).intValue());
case 5:
return (((Integer)(edu.isi.stella.javalib.Native.funcall(code, arguments.value, new java.lang.Object []{arguments.rest.value, arguments.nth(2), arguments.nth(3), arguments.nth(4)}))).intValue());
default:
throw ((StellaException)(StellaException.newStellaException("Too many function arguments in `apply'. Max is 5.").fillInStackTrace()));
}
}
|
5ff7223b-cca2-414a-a77e-c0fdccd43fb2
| 7 |
@Override
public void paint(Graphics g) {
//if in fog draw the foggy images
if (tower.isInFog()) {
if (getTower() instanceof DefTower)
g.drawImage(defFog, x, y, null);
else if (getTower() instanceof DmgTower)
g.drawImage(dmgFog, x, y, null);
else if (getTower() instanceof SpdTower)
g.drawImage(spdFog, x, y, null);
} else {
//else the normal ones
if (getTower() instanceof DefTower)
g.drawImage(defImage, x, y, null);
else if (getTower() instanceof DmgTower)
g.drawImage(dmgImage, x, y, null);
else if (getTower() instanceof SpdTower)
g.drawImage(spdImage, x, y, null);
}
}
|
146c95eb-9916-441a-8642-595f0118452a
| 8 |
public static boolean batch( WebSocketImpl ws, ByteChannel sockchannel ) throws IOException {
ByteBuffer buffer = ws.outQueue.peek();
WrappedByteChannel c = null;
if( buffer == null ) {
if( sockchannel instanceof WrappedByteChannel ) {
c = (WrappedByteChannel) sockchannel;
if( c.isNeedWrite() ) {
c.writeMore();
}
}
} else {
do {// FIXME writing as much as possible is unfair!!
/*int written = */sockchannel.write( buffer );
if( buffer.remaining() > 0 ) {
return false;
} else {
ws.outQueue.poll(); // Buffer finished. Remove it.
buffer = ws.outQueue.peek();
}
} while ( buffer != null );
}
if( ws.outQueue.isEmpty() && ws.isFlushAndClose() /*&& ( c == null || c.isNeedWrite() )*/) {
synchronized ( ws ) {
ws.closeConnection();
}
}
return c != null ? !( (WrappedByteChannel) sockchannel ).isNeedWrite() : true;
}
|
b86b88cd-97a4-40e4-a3c4-1567f5a1e6e1
| 9 |
public void paperRankInCluster(int iteratorNum, int cluster) {
String path = "";
if (cluster == k)
path = "";
else
path = "iteration" + iteratorNum + "//cluster" + cluster;
if (!FileUtil.isFileExist(path + "//" + FileUtil.FILE_PAPER)) {
HashMap<Integer, Double> rankMap = new HashMap<Integer, Double>();
Iterator<String> paperIdSet_it = Store.getInstance().vertex_p
.keySet().iterator();
while (paperIdSet_it.hasNext()) {
double rank = 1;
int paperid = Store.getInstance().vertex_p.get(paperIdSet_it
.next()).id;
// get paper's neighborhood
HashMap<Integer, Double> authorsMap = Store.getInstance().pa
.get(paperid);
if (authorsMap != null)// some paper has no author record
// paperid: 162636
{
// get authors
Iterator<Integer> authorsMap_it = authorsMap.keySet()
.iterator();
while (authorsMap_it.hasNext()) {
int author = authorsMap_it.next();
double w = authorsMap.get(author);
// if (clusterList.get(cluster).rank_author_map
// .containsKey(author)) {
double authorRank = clusterList.get(cluster).rank_author_map
.get(author);
rank = rank * Math.pow(authorRank, w);
// }
}
}
// get terms
HashMap<Integer, Double> termsMap = Store.getInstance().pt
.get(paperid);
if (termsMap != null) {
Iterator<Integer> termsMap_it = termsMap.keySet()
.iterator();
while (termsMap_it.hasNext()) {
int term = termsMap_it.next();
double w = termsMap.get(term);
// if (clusterList.get(cluster).rank_term_map
// .containsKey(term)) {
double termRank = clusterList.get(cluster).rank_term_map
.get(term);
rank = rank * Math.pow(termRank, w);
// }
}
}
// get confs
HashMap<Integer, Double> confsMap = Store.getInstance().pc
.get(paperid);
if (confsMap != null) {
Iterator<Integer> confsMap_it = confsMap.keySet()
.iterator();
while (confsMap_it.hasNext()) {
int conf = confsMap_it.next();
double w = confsMap.get(conf);
// if (clusterList.get(cluster).rank_conf_map
// .containsKey(conf)) {
double confRank = clusterList.get(cluster).rank_conf_map
.get(conf);
rank = rank * Math.pow(confRank, w);
// }
}
}
// if (rank != 1)// if rank = 1 , 那么该paper在此cluster中的rank 为 0
rankMap.put(paperid, rank);
// else
// rankMap.put(paperid, 0.0);
}
// clusterList.get(cluster).rank_paper_map = rankMap;
clusterList.get(cluster).rank_paper_map = matrixUtil
.normlize1DHashMap(rankMap);
// write to file, in order to avoid compute again.
FileUtil.write(path, FileUtil.FILE_PAPER,
clusterList.get(cluster).rank_paper_map);
} else {
// read file
clusterList.get(cluster).rank_paper_map = FileUtil.readFile(path
+ "//" + FileUtil.FILE_PAPER);
// // 测试是否和为1
// double sum1 = 0;
// Iterator<Double> it1 =
// clusterList.get(cluster).rank_paper_map.values()
// .iterator();
// while (it1.hasNext()) {
// sum1 += it1.next();
// }
// System.out.println("---------------cluster k:"
// + " rank_paper sum:" + sum1);
}
clusterList.get(cluster).rank_paper = matrixUtil
.HashMapToArrayList(clusterList.get(cluster).rank_paper_map);
// for(int i = 0 ; i < clusterList.get(cluster).rank_paper.size(); i++)
// {
// if(i < 10)
// System.out.println( clusterList.get(cluster).rank_paper.get(i).Rank);
// }
System.gc();
}
|
bdfc5da0-6b3f-4717-b8a7-e7b525602baa
| 6 |
public String getDayZone(){
int hour = this.validTime.get(Calendar.HOUR_OF_DAY)+2;
String result;
if(hour >= 5 && hour < 12){
result = "morning";
} else if(hour >= 12 && hour < 18){
result = "afternoon";
} else if(hour >= 18 && hour < 22){
result = "evning";
} else {
result = "night";
}
return result;
}
|
d065c114-bdc6-40be-9644-688d3ff9ea3a
| 6 |
public void adjustWeights(double[] vector, double koef)
{
// if ((Double.isInfinite(koef))||(Double.isNaN(koef))|| (koef > 1))
// System.out.println("WRONG");
double diffCoor = 0;
for (int i = 0; i < inN; i++){
double check = (vector[i] - weights[i]) * a * koef;
if (Double.isNaN(check) || (Double.isInfinite(check)))
System.out.println("WRONG");
double oldCoor = weights[i];
weights[i] += (vector[i] - weights[i]) * a * koef;
diffCoor += (weights[i] - oldCoor)*(weights[i] - oldCoor) ;
if (Double.isNaN(weights[i]) || (Double.isInfinite(weights[i])))
System.out.println("WRONG");
}
a -= deltaAlpha;
//a -= 0.001 * stepNum;
//if (a < 0)
// a = 0.001;
diffCoor = Math.sqrt(diffCoor);
System.out.print("in neuron");
System.out.println(id);
System.out.println(diffCoor);
weightsDiffHistory.add(diffCoor);
if (weightsDiffHistory.size() > 20)
weightsDiffHistory.remove(0);
stepNum ++;
}
|
8b4b2ff9-22f4-4cff-b368-5c666b0ef714
| 5 |
private void addAllUniforms(String shaderText)
{
HashMap<String, ArrayList<GLSLStruct>> structs = findUniformStructs(shaderText);
final String UNIFORM_KEYWORD = "uniform";
int uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD);
while(uniformStartLocation != -1)
{
if(!(uniformStartLocation != 0
&& (Character.isWhitespace(shaderText.charAt(uniformStartLocation - 1)) || shaderText.charAt(uniformStartLocation - 1) == ';')
&& Character.isWhitespace(shaderText.charAt(uniformStartLocation + UNIFORM_KEYWORD.length()))))
continue;
int begin = uniformStartLocation + UNIFORM_KEYWORD.length() + 1;
int end = shaderText.indexOf(";", begin);
String uniformLine = shaderText.substring(begin, end).trim();
int whiteSpacePos = uniformLine.indexOf(' ');
String uniformName = uniformLine.substring(whiteSpacePos + 1, uniformLine.length()).trim();
String uniformType = uniformLine.substring(0, whiteSpacePos).trim();
resource.getUniformNames().add(uniformName);
resource.getUniformTypes().add(uniformType);
addUniform(uniformName, uniformType, structs);
uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD, uniformStartLocation + UNIFORM_KEYWORD.length());
}
}
|
e2803afb-b053-4a25-ac61-9380159f0419
| 3 |
protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
int c;
int[] lookup = BYTE_TO_CHAR; // getfield bytecode optimization
int remaining = in.remaining();
while (remaining-- > 0) {
if (out.remaining() < 1)
return CoderResult.OVERFLOW; // we need exactly one char per byte
c = lookup[in.get() & 0xFF];
if (c == -1) {
in.position(in.position() - 1);
return CoderResult.malformedForLength(1);
}
out.put((char)c);
}
return CoderResult.UNDERFLOW;
}
|
0b6206a2-ca68-4e77-a67b-006ca6d1ae49
| 2 |
@Override
public void registerDeleted(IDomainObject domainObject) {
assert domainObject.getId() != null : "id not null";
if (newObjects.remove(domainObject)) {
return;
}
dirtyObjects.remove(domainObject);
if (!removedObjects.contains(domainObject)) {
removedObjects.add(domainObject);
}
}
|
12b3b30f-13b8-46fe-92e5-06873894ddcc
| 6 |
public static void STARTUP_FETCH_DEMO_CONTENT() {
{ Object OLD_$MODULE$_000 = Stella.$MODULE$.get();
Object OLD_$CONTEXT$_000 = Stella.$CONTEXT$.get();
try {
Native.setSpecial(Stella.$MODULE$, Stella.getStellaModule("/STELLA/XML-OBJECTS/FETCH-CONTENT", Stella.$STARTUP_TIME_PHASE$ > 1));
Native.setSpecial(Stella.$CONTEXT$, ((Module)(Stella.$MODULE$.get())));
if (Stella.currentStartupTimePhaseP(2)) {
FetchContent.SGT_FETCH_CONTENT_arg0 = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("arg0", null, 1)));
FetchContent.SGT_FETCH_CONTENT_arg1 = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("arg1", null, 1)));
FetchContent.SYM_FETCH_CONTENT_item = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("item", null, 0)));
FetchContent.SGT_FETCH_CONTENT_item = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("item", null, 1)));
FetchContent.SYM_FETCH_CONTENT_key = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("key", null, 0)));
FetchContent.SYM_FETCH_CONTENT_val = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("val", null, 0)));
FetchContent.SGT_FETCH_CONTENT_key = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("key", null, 1)));
FetchContent.SGT_FETCH_CONTENT_value = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("value", null, 1)));
FetchContent.SGT_FETCH_CONTENT_arg2 = ((Surrogate)(GeneralizedSymbol.internRigidSymbolWrtModule("arg2", null, 1)));
FetchContent.SYM_FETCH_CONTENT_STARTUP_FETCH_DEMO_CONTENT = ((Symbol)(GeneralizedSymbol.internRigidSymbolWrtModule("STARTUP-FETCH-DEMO-CONTENT", null, 0)));
}
if (Stella.currentStartupTimePhaseP(5)) {
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("arg0", "(DEFCLASS arg0 (XMLObject) :PUBLIC-SLOTS ((/STELLA/XML-OBJECTS/XSI/type :TYPE STRING :INITIALLY \"XSD:string\")))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.arg0", "new_arg0", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.arg0", "access_arg0_Slot_Value", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.examples.fetchcontent.arg0"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("arg1", "(DEFCLASS arg1 (XMLObject) :PUBLIC-SLOTS ((item :TYPE item)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.arg1", "new_arg1", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.arg1", "access_arg1_Slot_Value", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.examples.fetchcontent.arg1"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("item", "(DEFCLASS item (XMLObject) :PUBLIC-SLOTS ((key :TYPE key) (val :TYPE value)))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.item", "new_item", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.item", "access_item_Slot_Value", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.examples.fetchcontent.item"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("key", "(DEFCLASS key (XMLObject) :PUBLIC-SLOTS ((/STELLA/XML-OBJECTS/XSI/type :TYPE STRING :INITIALLY \"XSD:string\")))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.key", "new_key", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.key", "access_key_Slot_Value", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.examples.fetchcontent.key"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("value", "(DEFCLASS value (XMLObject) :PUBLIC-SLOTS ((/STELLA/XML-OBJECTS/XSI/type :TYPE STRING :INITIALLY \"XSD:string\")))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.value", "new_value", new java.lang.Class [] {});
renamed_Class.classSlotAccessorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.value", "access_value_Slot_Value", new java.lang.Class [] {Native.find_java_class("edu.isi.webtools.examples.fetchcontent.value"), Native.find_java_class("edu.isi.stella.Symbol"), Native.find_java_class("edu.isi.stella.Stella_Object"), java.lang.Boolean.TYPE});
}
{ Stella_Class renamed_Class = Stella.defineClassFromStringifiedSource("arg2", "(DEFCLASS arg2 (XMLObject))");
renamed_Class.classConstructorCode = Native.find_java_method("edu.isi.webtools.examples.fetchcontent.arg2", "new_arg2", new java.lang.Class [] {});
}
}
if (Stella.currentStartupTimePhaseP(6)) {
Stella.finalizeClasses();
}
if (Stella.currentStartupTimePhaseP(7)) {
Stella.defineFunctionObject("STARTUP-FETCH-DEMO-CONTENT", "(DEFUN STARTUP-FETCH-DEMO-CONTENT () :PUBLIC? TRUE)", Native.find_java_method("edu.isi.webtools.examples.fetchcontent._StartupFetchDemoContent", "STARTUP_FETCH_DEMO_CONTENT", new java.lang.Class [] {}), null);
{ MethodSlot function = Symbol.lookupFunction(FetchContent.SYM_FETCH_CONTENT_STARTUP_FETCH_DEMO_CONTENT);
KeyValueList.setDynamicSlotValue(function.dynamicSlots, edu.isi.webtools.examples.sample.Sample.SYM_STELLA_METHOD_STARTUP_CLASSNAME, StringWrapper.wrapString("_StartupFetchDemoContent"), Stella.NULL_STRING_WRAPPER);
}
}
if (Stella.currentStartupTimePhaseP(8)) {
Stella.finalizeSlots();
Stella.cleanupUnfinalizedClasses();
}
if (Stella.currentStartupTimePhaseP(9)) {
Stella_Object.inModule(((StringWrapper)(Stella_Object.copyConsTree(StringWrapper.wrapString("FETCH-CONTENT")))));
XmlObjects.$NAMESPACE_PREFIX_URI_TABLE$.insertAt(StringWrapper.wrapString("FETCH-CONTENT"), StringWrapper.wrapString("urn:fetchDemoContent"));
XmlObjects.$NAMESPACE_URI_PREFIX_TABLE$.insertAt(StringWrapper.wrapString("urn:fetchDemoContent"), StringWrapper.wrapString("FETCH-CONTENT"));
XmlObjects.$INVISIBLE_NAMESPACES_ON_OUTPUT$ = Cons.cons(StringWrapper.wrapString("FETCH-CONTENT"), XmlObjects.$INVISIBLE_NAMESPACES_ON_OUTPUT$);
}
} finally {
Stella.$CONTEXT$.set(OLD_$CONTEXT$_000);
Stella.$MODULE$.set(OLD_$MODULE$_000);
}
}
}
|
2a4adbd8-3620-4e30-8486-8c28d34c4d5a
| 4 |
@Override
protected void dispatchMessage(ICallbackEnum message, IEvent object) {
// Iterate methods
for(Binding binding : this.callbackBindings.get(message))
{
try
{
// Dispatch
if(object == null)
binding.invoke(this);
else
{
// Set session
object.setSession(this);
// Invoke
binding.invoke(object);
}
}catch(Exception e)
{
// Error out
if(JeTT.isDebugging())
{
System.err.println("Received message event handling failed: " + message.name());
e.printStackTrace();
}else
System.err.println(String.format("Received message event %s failed: %s", message.name(), e.getMessage()));
}
}
}
|
2cee8a70-bc56-439b-b864-a7b72fa5a26c
| 6 |
private void doUpdateTrafficMask() {
if (trafficControllingSessions.isEmpty())
return;
for (;;) {
SocketSessionImpl session = trafficControllingSessions.poll();
if (session == null)
break;
SelectionKey key = session.getSelectionKey();
// Retry later if session is not yet fully initialized.
// (In case that Session.suspend??() or session.resume??() is
// called before addSession() is processed)
if (key == null) {
scheduleTrafficControl(session);
break;
}
// skip if channel is already closed
if (!key.isValid()) {
continue;
}
// The normal is OP_READ and, if there are write requests in the
// session's write queue, set OP_WRITE to trigger flushing.
int ops = SelectionKey.OP_READ;
Queue<WriteRequest> writeRequestQueue = session
.getWriteRequestQueue();
synchronized (writeRequestQueue) {
if (!writeRequestQueue.isEmpty()) {
ops |= SelectionKey.OP_WRITE;
}
}
// Now mask the preferred ops with the mask of the current session
int mask = session.getTrafficMask().getInterestOps();
key.interestOps(ops & mask);
}
}
|
8f1b5d27-698f-4537-a965-80b4500a7cd4
| 8 |
@Override
public boolean controls(ChessCoord coord) {
if (!super.controls(coord)) {
return false;
}
// Here we are sure we are not at the coordinate ourselves
final int currentRank = this.getCoord().getRank();
final int currentFile = this.getCoord().getFile();
final int destFile = coord.getFile();
final int destRank = coord.getRank();
// First check the rook possibilities
/*
* Now check if we are either on the same file or rank. Afterwards check
* where the coordinate is relative to us (right/left, above/below) and
* set the step accordingly. Afterwards loop to we can see whether
* something is in our way. If not, we control the piece.
*/
if (currentRank == destRank) {
final int stepFile = currentFile < destFile ? STEP_RIGHT
: STEP_LEFT;
return this.controls(coord, stepFile, STEP_STAY);
} else if (currentFile == destFile) {
final int stepRank = currentRank < destRank ? STEP_UP : STEP_DOWN;
return this.controls(coord, STEP_STAY, stepRank);
}
// The rook moving did not yield results, check for the Bishop moves
// instead.
if ((Math.abs(currentFile - destFile) == Math.abs(currentRank
- destRank))) {
final int stepFile = currentFile < destFile ? STEP_RIGHT
: STEP_LEFT;
final int stepRank = currentRank < destRank ? STEP_UP : STEP_DOWN;
return this.controls(coord, stepFile, stepRank);
}
// Nothing found
return false;
}
|
7bf45a0f-64f7-438c-a95f-b43c73f8d92a
| 2 |
public void loadFavoriteServersList(List<Server> servers) {
favoritesMenu.removeAll();
if ( servers.size() > 0 ) {
for (final Server s : servers) {
JMenuItem item = new JMenuItem( s.get("title") );
item.addActionListener( new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ConnectionDetails cd = ConnectionDetails.fromServer(s);
MainWindow.getInstance().createServerTab(cd);
}
});
favoritesMenu.add(item);
}
favoritesMenu.addSeparator();
}
favoritesMenu.add(editFavorites);
}
|
74ca6762-21a0-4a38-9601-8d1bf37bafcd
| 8 |
protected Registration readName (Input input) {
int nameId = input.readInt(true);
if (nameIdToClass == null) nameIdToClass = new IntMap();
Class type = nameIdToClass.get(nameId);
if (type == null) {
// Only read the class name the first time encountered in object graph.
String className = input.readString();
if (nameToClass != null) type = nameToClass.get(className);
if (type == null) {
try {
type = Class.forName(className, false, kryo.getClassLoader());
} catch (ClassNotFoundException ex) {
throw new KryoException("Unable to find class: " + className, ex);
}
if (nameToClass == null) nameToClass = new ObjectMap();
nameToClass.put(className, type);
}
nameIdToClass.put(nameId, type);
if (TRACE) trace("kryo", "Read class name: " + className);
} else {
if (TRACE) trace("kryo", "Read class name reference " + nameId + ": " + className(type));
}
return kryo.getRegistration(type);
}
|
4ffd9608-08bd-42e8-8a78-cac035b90985
| 5 |
private void ParseAttack(Node parentElement) {
Node child = parentElement.getFirstChild();
while (child != null) {
if (! handleGeneralProperty(child)) {
String nodeName = child.getNodeName();
// Can contain conditions, a print, and actions
if (nodeName == "print") {
attackMessage = child.getFirstChild().getNodeValue();
}
else if (nodeName == "action") {
attackActions.add(child.getFirstChild().getNodeValue());
}
else if (nodeName == "condition") {
attackConditions.add(new Condition(child));
}
}
child = child.getNextSibling();
}
}
|
1b24d055-cf2e-4749-9713-bd175eba5e33
| 1 |
@Override
public void setDefaultGraph(String graph) {
if(graph == null){
((SPARQLConnection) this.con).setDefaultGraphs(null);
}
LinkedList<String> graphs = new LinkedList<String>();
graphs.add(graph);
((SPARQLConnection) this.con).setDefaultGraphs(graphs);
}
|
5c75f891-5be8-43b8-b8fb-1511c41af6eb
| 6 |
public char[] determineText(){
int sz = 0;
if(isUpper){
sz+= upperCase.length;
}
if(isLower){
sz+= lowerCase.length;
}
if(isNumbers) {
sz+= numbers.length;
}
char chars[] = new char[sz];
int offset = 0;
if(isUpper){
System.arraycopy(upperCase,0,chars,offset,upperCase.length);
offset+=upperCase.length;
}
if(isLower){
System.arraycopy(lowerCase,0,chars,offset,lowerCase.length);
offset+=lowerCase.length;
}
if(isNumbers){
System.arraycopy(numbers,0,chars,offset,numbers.length);
offset+=numbers.length;
}
return chars;
}
|
fb1be570-33b1-40dc-bf8a-ad718ecc1cd8
| 2 |
public void update() {
Window window = device.getFullScreenWindow();
if (window != null) {
BufferStrategy strategy = window.getBufferStrategy();
if (!strategy.contentsLost()) {
strategy.show();
}
}
// Sync the display on some systems.
// (on Linux, this fixes event queue problems)
Toolkit.getDefaultToolkit().sync();
}
|
c1ed8be0-e42e-4ccb-b7b4-7169b5ff46ba
| 5 |
public void loadState(Session s) throws Exception {
for (int n = s.loadInt() ; n-- > 0 ;) {
final Target t = s.loadTarget() ;
final List <Action> l = new List <Action> () ;
s.loadObjects(l) ;
actions.put(t, l) ;
//
// Safety checks for can't-happen events-
if (! t.inWorld()) {
I.say(t+" IS NOT IN WORLD ANY MORE!") ;
}
for (Action a : l) {
if (! a.actor.inWorld()) {
I.say(" "+a+" BELONGS TO DEAD ACTOR!") ;
l.remove(a) ;
}
}
}
for (int n = s.loadInt() ; n-- > 0 ;) {
final Behaviour b = (Behaviour) s.loadObject() ;
behaviours.put(b, b) ;
}
}
|
9901ba13-5be4-4fc9-8c9a-45269453d2b8
| 8 |
protected Method findMethod(String name, Class<?> clazz, Class<?> returnType, Class<?>[] paramTypes) {
Method method = null;
try {
method = clazz.getMethod(name, paramTypes);
} catch (NoSuchMethodException e) {
throw new MethodNotFoundException(LocalMessages.get("error.property.method.notfound", name, clazz));
}
method = findAccessibleMethod(method);
if (method == null) {
throw new MethodNotFoundException(LocalMessages.get("error.property.method.notfound", name, clazz));
}
if (!ignoreReturnType && returnType != null && !returnType.isAssignableFrom(method.getReturnType())) {
throw new MethodNotFoundException(LocalMessages.get("error.property.method.returntype", method.getReturnType(), name, clazz, returnType));
}
return method;
}
|
205ceaa3-8f64-49d8-a81b-595f24c61eda
| 8 |
private boolean jj_3R_38() {
Token xsp;
xsp = jj_scanpos;
if (jj_3_23()) {
jj_scanpos = xsp;
if (jj_3_24()) {
jj_scanpos = xsp;
if (jj_3_25()) {
jj_scanpos = xsp;
if (jj_3_26()) {
jj_scanpos = xsp;
if (jj_3_27()) {
jj_scanpos = xsp;
if (jj_3_28()) {
jj_scanpos = xsp;
if (jj_3_29()) {
jj_scanpos = xsp;
if (jj_3_30()) return true;
}
}
}
}
}
}
}
return false;
}
|
65265834-4164-4dd5-8d93-efd89db3d959
| 0 |
public int hashCode() {
int code = super.hashCode() ^ toRead.hashCode() ^ toWrite.hashCode()
^ direction.hashCode();
return code;
}
|
38c4f2a6-47ba-492b-ad56-e7d8a7daf937
| 5 |
public void bajaDeLicencia(int numero) {
EntityManager manager = verificarConexion();
if (numero <= 0) {
System.out.println("Se introdulo una licencia nula, no se puedo ejecutar la peticion");
return;
}
if (manager.find(LicenciaConductor.class, numero) != null) {
try {
LicenciaConductor mergedMember = manager.merge(manager.find(LicenciaConductor.class, numero));
if (manager.find(LicenciaConductor.class, numero).getDepartamento() != null) {
if (manager.find(Departamento.class, mergedMember.getDepartamento().getId()) == null) {
mergedMember.setDepartamento(null);
manager.getTransaction().begin();
manager.persist(mergedMember);
manager.getTransaction().commit();
}
}
manager.getTransaction().begin();
manager.remove(mergedMember);
manager.getTransaction().commit();
System.out.println("La eliminacion de la licencia " + numero + " se realizo correctamente");
} catch (Exception e) {
throw new PersistenciaException(e.getMessage(), e);
} finally {
manager.close();
setEm(null);
}
} else {
throw new PersistenciaException("No existe en la base de datos la licencia a eliminar");
}
}
|
9582e721-15c6-4964-a59e-e02380566651
| 5 |
public void paint(Graphics2D g, Component component, int width, int height) {
MacWidgetsPainter<Component> painterToUse;
Window activeAncestor = null;
Window active = KeyboardFocusManager.getCurrentKeyboardFocusManager()
.getActiveWindow();
if (active != null) {
activeAncestor = SwingUtilities.getWindowAncestor(active);
}
Window componentAncestor = SwingUtilities.getWindowAncestor(component);
if (component.hasFocus() || componentAncestor.equals(activeAncestor)) {
painterToUse = fComponentFocusedPainter;
} else if (WindowUtils.isParentWindowFocused(component)
|| componentAncestor.equals(activeAncestor)) {
painterToUse = fWindowFocusedPainter;
} else {
painterToUse = fWindowUnfocusedPainter;
}
painterToUse.paint(g, component, width, height);
}
|
078b78ba-b1b7-4e13-b607-a02aea1e9b37
| 0 |
public static PermissionMethodParser fromFile(String fileName) throws IOException {
PermissionMethodParser pmp = new PermissionMethodParser();
pmp.readFile(fileName);
return pmp;
}
|
ec7c09ba-af74-4fd5-ba8f-4c409a1d0780
| 8 |
public static String rowConverter(int row) {
switch (row) {
case 0:
return "A";
case 1:
return "B";
case 2:
return "C";
case 3:
return "D";
case 4:
return "E";
case 5:
return "F";
case 6:
return "G";
case 7:
return "H";
}
return "Failed";
}
|
f11a58a1-17f9-4f06-bc97-edbd9522e455
| 3 |
public static int findNumDays(String fileName)
{
int lineNumber = 0;
String line;
try {
BufferedReader br = new BufferedReader( new FileReader(fileName));
while( (line = br.readLine()) != null)
{
lineNumber++; //counts number of entries in file
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return lineNumber;
}
|
d0d60daf-c5e1-48ba-b623-3fa908cf7d17
| 3 |
public void save(){
List<TreeItem> items = getItems();
items.remove(0); //Remove the tree root ("Project")
for(TreeItem item : items){
DatabaseTreeItem dataItem = (DatabaseTreeItem) item;
if(dataItem.gameData != null){
File file = new File(ProjectMgr.getDataGamePath(), "Map" + dataItem.gameData.getIdName() + "." + AppMgr.getExtension("data file"));
DataMgr.dump(dataItem.gameData, file.getAbsolutePath());
dataItem.gameData = null;
}
}
DataEditorMap rootMapEditorData = (DataEditorMap) rootItem.editorData;
File file = new File(ProjectMgr.getDataEditorPath(), "MapInfos" + "." + AppMgr.getExtension("data file"));
DataMgr.dump(rootMapEditorData, file.getAbsolutePath());
for(DatabaseTreeItem item : deletedItems){
file = new File(ProjectMgr.getDataGamePath(), "Map" + item.editorData.getIdName() + "." + AppMgr.getExtension("data file"));
file.delete();
}
deletedItems.clear();
}
|
fa4977aa-f0db-4240-aaad-b5872fb1451d
| 6 |
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Bookingclass other = (Bookingclass) obj;
if (clas == null) {
if (other.clas != null)
return false;
} else if (!clas.equals(other.clas))
return false;
return true;
}
|
75edabbb-f126-4074-be7c-7f2108e962d4
| 6 |
private void checkStaleHosts() {
long currTime = System.currentTimeMillis();
List<String> staleHostsToRemove = new ArrayList<String>();
for(TaskTrackerHB lastHB : lastHeartbeat.values()) {
if( currTime - lastHB.getSendTime() > 8*TaskTracker.JOB_TRACKER_HB_TIME) {
//This task tracker missed more than allowed heartbeats.
staleHostsToRemove.add(lastHB.getTaskTrackerId());
System.out.println("Task Tracker " + lastHB.getTaskTrackerId() + " died");
for(Task t : lastHB.getTasksSnapshot()) {
t.setState(TaskState.PENDING);
t.setPercentComplete(0);
if(t.getTaskType() == TaskType.MAP) {
pendingMapTasks.add(t);
System.out.println("Adding task " + t.getTaskId() +
" back to the queue");
} else if (t.getTaskType() == TaskType.REDUCE) {
System.out.println("Adding task " + t.getTaskId() +
" back to the queue");
pendingReduceTasks.add(t);
}
}
}
}
//Clean up stale hosts.
for(String id : staleHostsToRemove) {
lastHeartbeat.remove(id);
}
}
|
e5c2bb47-7d1a-4db3-a7b4-68b3706b797e
| 1 |
public String getURL()
{
String queryString = getQueryString();
return (queryString != null ? this.uri + "?" + queryString : this.uri);
}
|
d4e53b94-bbf8-4cc3-b140-ab3056cccf35
| 4 |
private static void panelProperties(Node node, StringBuilder code) {
GObject gObj = (GObject) node;
for (PanelProperty property : gObj.getPanelProperties()) {
String javaCode = property.getJavaCode();
if (!javaCode.isEmpty()) {
code.append(" ").append(javaCode.replace("\n", "\n ")).append("\n");
}
}
code.append('\n');
if (node instanceof Pane) {
for (Node node2 : ((Pane) node).getChildren()) {
panelProperties(node2, code);
}
}
}
|
1bd9ff94-1ccf-4536-ac0e-e7b7a69473c0
| 8 |
public void deserializeFromStream(DataInputStream index) throws IOException {
int magic = index.readShort();
if (magic != MAGIC) {
throw new IOException("invalid magic at " + getPos());
}
nodeWeight = index.readInt();
int nodes = index.readShort();
if (nodes < 0) {
throw new IOException("bad file nodes less then zero");
}
for (int i = 0; i < nodes; ++i) {
char ch = index.readChar();
long pointer = PointerUtils.readPointer(index);
if (pointer == 0) {
throw new IndexOutOfBoundsException("readed zero pointer");
}
ensureSubNodesExists();
subNodes.put(ch, new Node(getFileSpaceManager(), this, pointer));
}
int queueItems = index.read();
if (queueItems < 0) {
throw new IOException("bad file queue size less then zero");
}
if (queueItems > 0) {
ensureQueueExists();
queue.deserializeFromStream(index, queueItems);
}
int originalNameItems = index.readShort();
if (originalNameItems < 0) {
throw new IOException("bad file originalNameItems less then zero");
}
if (originalNameItems > 0) {
ensureOriginalNamesExists();
originalNames.deserializeFromStream(index, originalNameItems);
}
}
|
2afc8901-e98f-4cf3-9b8d-8185a970f15d
| 2 |
public String join(String separator) throws JSONException {
int len = length();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i += 1) {
if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
}
return sb.toString();
}
|
748fae95-ea1b-4e28-a613-850eb91d615f
| 5 |
public static void saveImage(BufferedImage img, ImageViewer imViewer, ImageMapper imMapper, String path, int mode, boolean rle)
throws CantSaveException
{
String fn = generateCleanFileName(path);
StringBuffer output = new StringBuffer();
//print data on the buffer
printData(output, fn, img, mode, rle);
//if it's a map, print also the map
if (imMapper.isActive())
printMap(output, fn, imMapper);
//cleans the filename
int i = path.lastIndexOf(".");
if (i > 0 && i < path.length())
path = path.substring(0, i);
File file = new File(path+".h");
//try to create it
try {
if (!file.exists())
file.createNewFile();
FileWriter fstream = new FileWriter(path+".h");
BufferedWriter out = new BufferedWriter(fstream);
out.write(output.toString());
out.close();
} catch (Exception e) {
throw new CantSaveException();
}
}
|
6098b06b-8b2e-40e4-a769-fdfddbb5f158
| 1 |
@Override
public int valueCount() {
return value == null? 0:value.length;
}
|
e22f719e-cc12-491b-a0e5-f9b584af7937
| 9 |
public boolean step(){
// NETWORK: transmit any current data in the network, then signal the source UAV and queuing ground station if it finished
PointCloud finishedCloud = network.step(currentTime);
if(finishedCloud != null){
//System.out.println("UAV #" + finishedCloud.getSrc().getID() + " finished transmitting with time " + (currentTime - finishedCloud.getTransmitTime())); // DEBUGSTATEMENT: finished transmitting
finishedCloud.getSrc().networkFinish(currentTime); // tell the UAV that it is done transmitting
groundStation.receive(finishedCloud, currentTime); // enqueue at the ground station
}
// UAV: check UAVs for transmissions attempts and respond to those requests
int networkStatus = network.getStatus();
LinkedList<PointCloud> toTransmitList = new LinkedList<PointCloud>();
for(UAV u : UAVs){ // get a list of point clouds to be transmitted
PointCloud newCloud = u.step(currentTime);
if(newCloud != null){
toTransmitList.add(newCloud);
}
}
// respond to the requests; if the network is free, accept a random cloud and retry on the rest
if(networkStatus == Network.NET_IDLE && toTransmitList.size() > 0){
PointCloud toTransmit = toTransmitList.remove((int)Math.floor((toTransmitList.size() * Math.random())));
//System.out.println("UAV #" + toTransmit.getSrc().getID() + " transmitting, service time " + (currentTime - toTransmit.getDetectTime())); // DEBUGSTATEMENT: start transmitting
network.startTransmit(toTransmit, currentTime); // start the tranmission
toTransmit.getSrc().networkRespond(currentTime, true); // tell the UAV that it is transmitting
}
for(PointCloud p : toTransmitList)
p.getSrc().networkRespond(currentTime, false); // tell the UAV to retry
// GROUND: perform ground processing
groundStation.step(currentTime);
// terminate the simulation after the time horizon and when all point clouds are processed
if(currentTime > timesteps && groundStation.getQueueSize() == 0 && toTransmitList.size() == 0)
return false;
// increment the next time step
currentTime++;
return true;
}
|
ca84c71c-174a-4fbd-afbb-123cdf4a50f3
| 2 |
void invalidAction(JSONObject action){
try {
JSONObject errorMessage
= new JSONObject().put("error", "Invalid action: " + action.get("type"));
sendMessage(errorMessage);
} catch (JSONException f){}
catch (IOException g){}
}
|
86ce3129-a63f-43ec-84c0-66d9d2210bd2
| 4 |
public boolean canMove(int oldX, int oldY, int newX, int newY, boolean isNewSpotEmpty) {
int deltaX;
int deltaY;
deltaX = Math.abs(newX-oldX);
deltaY = Math.abs(newY-oldY);
if (deltaX == 0 && deltaY != 0){
return true;
} else if (deltaX != 0 && deltaY == 0) {
return true;
}
return false;
}
|
53f460e0-8892-4f42-a074-4980c3d60972
| 1 |
public ArrayList<String> listFilesFromSourceNotInTargets() throws IOException{
ArrayList<String> strings = new ArrayList<String>();
for(int i=0;i<targetDirs.size();i++){
strings.add(listFilesFromSourceNotInTarget(i));
}
return strings;
}
|
be806e8e-2622-4669-809b-cf0dca350a66
| 9 |
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
switch (cmd) {
case "EnterButton":
// first the driver presses the enter button, this creates a ticket
// need to get the next available ticket number from the garage
int ticketNumber;
try {
ticketNumber = garage.getNextTicketID();
} catch (RemoteException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
ticketNumber = 9999;
}
// if the rate changes, this driver only has to pay the rate at the time
// that the ticket is tendered, therefore, we store this on / with the ticket
BigDecimal currentRate;
try {
currentRate = garage.getRate();
} catch (RemoteException e2) {
e2.printStackTrace();
currentRate = new BigDecimal("2.50");
}
currentTicket = new Ticket(ticketNumber, currentRate);
Date timeIn = currentTicket.getTimeIn();
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM yyyy HH:mm z");
String dateOut = dateFormatter.format(timeIn);
String entryMessage = "Time is " + dateOut;
String entryMessage2 = " License: " +
currentTicket.getVehicle().getLicensePlate();
entryUI.setMessage1(entryMessage);
entryUI.setMessage2(entryMessage2);
entryUI.enableTicketButtons(true);
entryUI.enableEnterButton(false);
break;
case "DispenseTicketButton":
// this dispenses an actual ticket, shows in the printedTicket UI
entryUI.enableTicketButtons(false);
entryUI.enableEnterButton(true);
ticketLevel--;
@SuppressWarnings("unused")
PhysicalTicketUI printedTicket = new PhysicalTicketUI(currentTicket);
ticketLevel--;
if (ticketLevel < TICKET_LEVEL_WARNING) {
// warn someone that the physical ticket level is low
// maybe with a notification to the garage
}
entryUI.setMessage1("Press Top Button to Enter");
entryUI.setMessage2("");
entryGate.openGateForCar();
// add to the list of tickets current outstanding
try {
garage.addTicket(currentTicket);
garage.updateOccupancy("entry");
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case "VirtualTicketButton":
entryUI.enableTicketButtons(false);
entryUI.enableEnterButton(true);
entryUI.setMessage1("Press Top Button to Enter");
entryUI.setMessage2("");
entryGate.openGateForCar();
// add to the list of tickets current outstanding
try {
garage.addTicket(currentTicket);
garage.updateOccupancy("entry");
} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
case "NoThanks":
entryUI.enableTicketButtons(false);
entryUI.enableEnterButton(true);
entryUI.setMessage1("Press Top Button to Enter");
entryUI.setMessage2("");
break;
}
}
|
9fd606a1-a616-4417-980f-d5efea4f2554
| 2 |
public void updatePathField(Path text, boolean colorReset) {
String replace = text == null ? "" : text.toString();
this.path.setText(replace);
this.path.setToolTipText(replace);
if (colorReset) {
this.path.setForeground(Color.BLACK);
}
}
|
2770389b-762d-44d2-a827-f9a8c45ec44f
| 9 |
public int compareTo( Object obj ) {
if( obj == null ) {
return( -1 );
}
else if( obj instanceof GenKbGelExpansionBuff ) {
GenKbGelExpansionBuff rhs = (GenKbGelExpansionBuff)obj;
int retval = super.compareTo( rhs );
if( retval != 0 ) {
return( retval );
}
{
int cmp = getRequiredMacroName().compareTo( rhs.getRequiredMacroName() );
if( cmp != 0 ) {
return( cmp );
}
}
return( 0 );
}
else if( obj instanceof GenKbGelInstructionPKey ) {
GenKbGelInstructionPKey rhs = (GenKbGelInstructionPKey)obj;
if( getRequiredCartridgeId() < rhs.getRequiredCartridgeId() ) {
return( -1 );
}
else if( getRequiredCartridgeId() > rhs.getRequiredCartridgeId() ) {
return( 1 );
}
if( getRequiredGelInstId() < rhs.getRequiredGelInstId() ) {
return( -1 );
}
else if( getRequiredGelInstId() > rhs.getRequiredGelInstId() ) {
return( 1 );
}
return( 0 );
}
else {
int retval = super.compareTo( obj );
return( retval );
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.