method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
a4552a51-af03-45a9-a0c4-960a44e3f1df
| 2
|
@Override
public AbstractConnection toItem( ConnectionData data, DefaultUmlDiagram diagram ) {
AbstractConnection connection = connection( data.getConnectionType(), data.getKey(), diagram );
DefaultBox<?> source = diagram.getDefaultBox( data.getSource() );
DefaultBox<?> target = diagram.getDefaultBox( data.getTarget() );
connection.setSourceItem( source );
connection.setTargetItem( target );
ConnectionableCapability sourceConnectionable = source.getCapability( CapabilityName.CONNECTABLE );
ConnectionableCapability targetConnectionable = target.getCapability( CapabilityName.CONNECTABLE );
ConnectionArray sourceArray = sourceConnectionable.getSourceArray( connection.getFlavor() );
ConnectionArray targetArray = targetConnectionable.getTargetArray( connection.getFlavor() );
sourceArray.add( connection.getSourceEndPoint() );
targetArray.add( connection.getTargetEndPoint() );
return connection;
}
|
a47a11a7-1351-4eaa-b6af-6fc6643947a2
| 7
|
public void correr(JLabel min, JLabel seg, JLabel seg2, float dt) {
segundos2 = (int) dt;
if (segundos2 != segundosViejo) {
segundosViejo = segundos2;
segundos2Cambio = true;
}
if (segundos2 - valorCambioSeg == 10) {
segundos++;
segundos2 = 0;
segundosViejo = 0;
valorCambioSeg += 10;
segundosCambio = true;
}
if (segundos == 6) {
segundos = 0;
minutos++;
minutosCambio = true;
}
if (minutos == 10)
minutos = 0;
if (minutosCambio)
cambiar(min, minutos, minutosCambio);
if (segundosCambio)
cambiar(seg, segundos, segundosCambio);
if (segundos2Cambio)
cambiar(seg2, segundos2 % 10, segundos2Cambio);
}
|
79a7ba40-22f5-4671-8fe4-9c399735843a
| 5
|
private void eat() {
//eat a character
if (state == State.END) {
return;
}
matchFound = false;
if (state == State.EAGER) {
int curStrPosition = strPosition;
int curPtnPosition = ptnPosition;
strPosition++;
ptnPosition++;
if (match()) {
state = State.END;
matchFound = true;
return;
} else {
strPosition = curStrPosition;
ptnPosition = curPtnPosition;
state = State.EAGER;
}
strPosition++;
} else if (state == State.NORMAL) {
if (matchOne()) {
strPosition++;
ptnPosition++;
matchFound = true;
} else {
state = State.END;
}
}
}
|
3c4a03d5-8c0a-44c1-8600-17688ac4f344
| 8
|
protected void handleCommandResultWithoutWaitingForACommand(String commandResult) {
if (commandResult != null) {
if (!resultExpected.get() ) {
if (proxyInjectionMode) {
// This logic is to account for the case where in proxy injection mode, it is possible
// that a page reloads without having been explicitly asked to do so (e.g., an event
// in one frame causes reloads in others).
if (commandResult.startsWith("OK")) {
if (log.isDebugEnabled()) {
log.debug("Saw page load no one was waiting for.");
}
boolean putUnexpectedResult = resultHolder.putResult(commandResult);
if (!putUnexpectedResult) {
throw new IllegalStateException(
"The resultHolder was not empty for this unexpected result");
}
}
} else if (commandResult.startsWith("OK")) {
// there are a couple reasons for this. If a command
// timed out, its response could come in after we're done
// expecting it. A previous reason was the idea that there
// was some confusion as to which frame's command queue was
// to be used. Rather than throwing an IllegalStateException
// as was the previous action, just add a warning statement
// and throw away the unexpected response.
log.warn(getIdentification("resultHolder", uniqueId)
+ " unexpected response: " + commandResult);
}
} else {
boolean putExpectedResult = resultHolder.putResult(commandResult);
if (!putExpectedResult) {
throw new IllegalStateException(
"The resultHolder was not empty and waiting for this expected result");
}
}
}
}
|
8c9abbf7-eb72-48ac-b975-910f8fad8759
| 2
|
public Account getAccount(int index) {
if (index < 0 || index >= accounts.length) {
throw new IllegalArgumentException("Cannot retrieve account #"
+ index);
}
return accounts[index];
}
|
b95f78b8-769f-467f-9131-e4e509d17dc3
| 7
|
public Double[] getConsumption()
{
ArrayList<Double> temp = new ArrayList<Double>();
int times = getOuterN();
if (times == 0)
times = 2;
// Number of repeats
for (int i = 0; i < times; i++) {
// System.out.println("Time: " + i);
// Number of patterns in each repeat
for (int j = 0; j < getPatternN(); j++) {
// System.out.println("Pattern: " + j);
int internalTimes = getN(j);
if (internalTimes == 0)
internalTimes = 2;
// System.out.println("Internal Times: " + k);
for (int k = 0; k < internalTimes; k++) {
ArrayList<Tripplet> tripplets = getPattern(j);
for (int l = 0; l < tripplets.size(); l++) {
// System.out.println("TripletPower: " + l);
for (int m = 0; m < tripplets.get(l).d; m++) {
temp.add(tripplets.get(l).v);
}
}
}
}
}
Double[] result = new Double[temp.size()];
temp.toArray(result);
return result;
}
|
87b6d7c8-0e20-487b-b236-6a11d6995141
| 8
|
private <T> PlaybackOperation generateOperation(Action<T> action) {
switch (action.type) {
case BGPALETTE:
return new WriteBgPaletteDirect(action.position, (Palette)action.value, true);
case OBJPALETTE:
return new WriteObjPaletteDirect(action.position, (Palette)action.value, true);
case HRAM:
return new WriteHByteDirect(action.position, (Integer)action.value, true);
case TILE:
int tileAddress = 0x8000 + (action.position % 0x180) * 0x10;
int tileVramBank = action.position / 0x180;
return new WriteTileDirect(tileAddress, (Tile)action.value, curVramBank != tileVramBank ? curVramBank : -1, true);
case WRAM:
int wramAddress = 0x9800 + action.position % 0x800;
int wramVramBank = action.position / 0x800;
return new WriteByteDirect(wramAddress, (Integer)action.value, curVramBank != wramVramBank ? curVramBank : -1, true);
case OAM:
return new WriteOamDirect(action.position, (OamEntry)action.value, true);
default:
throw new RuntimeException("Unknown action type " + action.type);
}
}
|
7658859a-4b67-41d7-aa32-396cacc4b858
| 5
|
private static boolean isPrimitiveOrString(Object target) {
if (target instanceof String) {
return true;
}
Class<?> classOfPrimitive = target.getClass();
for (Class<?> standardPrimitive : PRIMITIVE_TYPES) {
if (standardPrimitive.isAssignableFrom(classOfPrimitive)) {
return true;
}
}
return false;
}
|
5ab7c133-d2a1-46c3-b6d2-8316b012737d
| 7
|
public CheckResultMessage checkTotal2(int i) {
int r1 = get(6, 5);
int c1 = get(7, 5);
int r2 = get(8, 5);
BigDecimal sum = new BigDecimal(0);
if (checkVersion(file).equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
for (int j = 1; j < r2 - r1; j++) {
sum = sum.add(getValue(r1 + j, c1 + i, 1));
}
if (0 != getValue(r2, c1 + i, 1).compareTo(sum)) {
return error("支付机构汇总报表<" + fileName + ">sheet1-2:"
+ "本月所有日期合计:B0" + (1 + i) + "错误");
}
in.close();
} catch (Exception e) {
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
for (int j = 1; j < r2 - r1; j++) {
sum = sum.add(getValue1(r1 + j, c1 + i, 1));
}
if (0 != getValue1(r2, c1 + i, 1).compareTo(sum)) {
return error("支付机构汇总报表<" + fileName + ">sheet1-2:"
+ "本月所有日期合计:B0" + (1 + i) + "错误");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付机构汇总报表<" + fileName + ">sheet1-2:" + "本月所有日期合计:B0"
+ (1 + i) + "正确");
}
|
db028613-e119-459b-9826-5b4ae2012456
| 8
|
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection conn = null;
Statement stmt = null;
try {
//get a connection from the pool
conn = pool.getConnection();
stmt = conn.createStatement();
String sqlStr = "SELECT DISTINCT author FROM books WHERE quantity > 0";
// System.out.println(sqlStr); // for debugging
ResultSet rset = stmt.executeQuery(sqlStr);
out.println("<html><head><title>Welcome to E-BookShop</title></head><body>");
out.println("<h2>Welcome to E-BookShop</h2>");
// Begin an HTML form
out.println("<form method='get' action='./search'>");
// A pull-down menu of all the authors with a no-selection option
out.println("Choose an Author: <select name='author' size='1'>");
out.println("<option value=''>Select...</option>"); // no-selection
while (rset.next()) { // list all the authors
String author = rset.getString("author");
out.println("<option value='" + author + "'>" + author + "</option>");
}
out.println("</select><br />");
out.println("<p>OR</p>");
// A text field for entering search word for pattern matching
out.println("Search \"Title\" or \"Author\": <input type='text' name='search' />");
// Submit and reset buttons
out.println("<br /><br />");
out.println("<input type='submit' value='SEARCH' />");
out.println("<input type='reset' value='CLEAR' />");
out.println("</form>");
// Show "View Shopping Cart" if the cart is not empty
HttpSession session = request.getSession(false); // check if session exists
if (session != null) {
ShoppingCart cart;
synchronized (session) {
// Retrieve the shopping cart for this session, if any. Otherwise, create one.
cart = (ShoppingCart) session.getAttribute("cart");
if (cart != null && !cart.isEmpty()) {
out.println("<P><a href='cart?todo=view'>View Shopping Cart</a></p>");
}
}
}
out.println("</body></html>");
} catch (SQLException ex) {
out.println("<h3>Service not available. Please try again later!</h3></body></html>");
Logger.getLogger(EntryServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close(); //return the connection to the pool
} catch (SQLException ex) {
Logger.getLogger(EntryServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
c9bdd99f-3bc3-402d-9be3-2148c35f5ca6
| 1
|
public void printContacts(Set<Contact> returnContacts) {
Iterator<Contact> it = returnContacts.iterator();
while (it.hasNext()) {
Contact holder = it.next();
System.out.print("ID: ");
System.out.print(holder.getId());
System.out.print(" Name: ");
System.out.print(holder.getName());
System.out.print(" Notes: ");
System.out.print(holder.getNotes());
System.out.println("");
}
}
|
145ca990-5b7d-42c6-a4c7-9ef8b9c4a02c
| 6
|
@Override
public void run() {
while (this.isRunning()) {
Socket sckt;
try {
sckt = ssckt.accept();
//Check if only local connections are allowed and whether this is a local one or not
if ((this.conMan.getHotkeyServer().getConf().isLocalConnectiosOnly() && (sckt.getInetAddress().isAnyLocalAddress() || sckt.getInetAddress().isLoopbackAddress())) || (!this.conMan.getHotkeyServer().getConf().isLocalConnectiosOnly())) {
this.conMan.addConnection(new PlainTCPConnection(sckt, conMan));
}
else {
System.out.println("Rejected connection due to accept-only-local-connections policy.");
sckt.close();
}
} catch (IOException ex) {
System.out.println("ServerSocket could not accept new connection! " + ex.toString());
}
}
}
|
a709c507-b9d1-4fa6-8ff2-b3e401603f5c
| 7
|
*/
public int getBulletType() {
Element[] elem = getSelectedParagraphs();
if (elem == null || elem.length == 0)
return -1;
StyledDocument doc = getStyledDocument();
Element head = null;
Icon[] icon = new Icon[elem.length];
for (int i = 0; i < elem.length; i++) {
head = doc.getCharacterElement(elem[i].getStartOffset());
icon[i] = StyleConstants.getIcon(head.getAttributes());
if (!(icon[i] instanceof BulletIcon))
return -1;
}
if (icon.length == 1)
return ((BulletIcon) icon[0]).getType();
for (int i = 1; i < icon.length; i++) {
if (((BulletIcon) icon[i]).getType() != ((BulletIcon) icon[0]).getType())
return -1;
}
return ((BulletIcon) icon[0]).getType();
}
|
484d16a5-a6bd-419e-bf6a-5336f9c855a0
| 4
|
private PlayerSelectFrame(String prompt, String[] players) {
super("Quantum Werewolves");
this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.players = players;
this.label = new JLabel(prompt);
JPanel labelPanel = new JPanel();
JPanel buttonPanel = new JPanel();
labelPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
labelPanel.add(label);
buttonPanel.setLayout(new FlowLayout());
JButton[] referenceToButtons = new JButton[this.players.length]; // sizes cannot be calculated until they are visible.
for (int i = 0; i < this.players.length; i++) {
final String j = this.players[i];
JButton button = new JButton(this.players[i]);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
PlayerSelectFrame.this.choose(j);
}
});
buttonPanel.add(button);
referenceToButtons[i] = button;
}
this.add(labelPanel);
this.add(buttonPanel);
this.pack();
// Things are now packed, and getHeight() etc. now work.
// the following calculates how high the frame should be. (Because FlowLayout sucks...)
int remainingWidth = label.getWidth() + 10;
int TotalHeight = referenceToButtons[0].getHeight();
int rowMaxHeight = referenceToButtons[0].getHeight();
for (int i = 0; i < referenceToButtons.length; i++) {
if(remainingWidth < (referenceToButtons[i].getWidth() + 5)){ // button goes on next row
remainingWidth = label.getWidth() + 5 - referenceToButtons[i].getWidth();
rowMaxHeight = referenceToButtons[i].getHeight();
TotalHeight += rowMaxHeight + 5;
} else {
remainingWidth -= (referenceToButtons[i].getWidth() + 5);
if(referenceToButtons[i].getHeight() > rowMaxHeight){
TotalHeight += (referenceToButtons[i].getHeight() - rowMaxHeight);
rowMaxHeight = referenceToButtons[i].getHeight();
}
}
}
buttonPanel.setSize(new Dimension(label.getWidth() + 10, TotalHeight + 20));
buttonPanel.setPreferredSize(new Dimension(label.getWidth() + 10, TotalHeight + 20));
buttonPanel.setMinimumSize(new Dimension(label.getWidth() + 10, TotalHeight + 20));
buttonPanel.setMaximumSize(new Dimension(label.getWidth() + 10, TotalHeight + 20));
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
|
38920cfb-8c52-4d8f-bf03-2f5d4d35f064
| 1
|
public AnnotationVisitor visitAnnotationDefault() {
AnnotationVisitor av = mv.visitAnnotationDefault();
return av == null ? av : new RemappingAnnotationAdapter(av, remapper);
}
|
f577d76c-f956-435f-97fe-4e69fac940e3
| 0
|
public Object get(int index) {
return vertices.get(index);
}
|
085eb0de-e556-4d10-a8d2-9a7779703b80
| 6
|
private boolean numberInUse() {
if (tfEmployeeNumber.getText().isEmpty() || !Utils.isNumeric(tfEmployeeNumber.getText())) {
lblNumberInUse.setVisible(false);
return true;
} else {
Employee existingEmployee = RoosterProgramma.getInstance().getEmployee(Integer.parseInt(tfEmployeeNumber.getText()));
if (existingEmployee != null
&& (isAdd
|| (!existingEmployee.getFirstName().equalsIgnoreCase(employee.getFirstName())
|| !existingEmployee.getFamilyName().equalsIgnoreCase(employee.getFamilyName())))) {
lblNumberInUse.setVisible(true);
return true;
} else {
lblNumberInUse.setVisible(false);
return false;
}
}
}
|
b52611ca-d4eb-4a24-9e68-04ad99eb480e
| 9
|
@Override
public Object getValueAt(Object node, int column){
if (column == 0) return node;
else
{
DefaultMutableTreeTableNode ttNode = (DefaultMutableTreeTableNode) node;
if (ttNode.getUserObject() instanceof Job)
{
Job job = (Job) ttNode.getUserObject();
switch (column) {
case 1:
return job.getJobId();
}
}
else if (ttNode.getUserObject() instanceof OrderDetail)
{
OrderDetail od = (OrderDetail) ttNode.getUserObject();
switch (column) {
case 1:
return od.getProductDetail();
case 2:
return od.getPrintType().getValue();
case 3:
return od.getNumColors();
case 4:
return od.getQuantity();
case 5:
return od.getNumColors() * od.getQuantity();
}
}
}
return null;
}
|
fcfda91f-2861-4ec9-b95f-53b6c34d8742
| 0
|
public synchronized EquationBTreeNode getParent() {return parent;}
|
cf0f8b41-90c8-49d5-9951-ea7e696d8cac
| 2
|
public void setTool(int i) {
tool = i;
if (tool == 3)
l2 = 0;
if (tool == 2)
l = 0;
}
|
d8f6ef20-118f-438a-9bfa-c83100f27a16
| 2
|
public boolean isAlive() {
if (getShip().isDead() || getShip().getId() == null) {
status = PlayerStatus.DEAD;
getShip().die();
ship = null;
shipId = null;
}
return status == PlayerStatus.ALIVE;
}
|
80d46c3f-919b-478a-b1e9-a3297a01fbd9
| 3
|
public static boolean ignoreSQLException(String sqlState) {
if (sqlState == null) {
//System.out.println("The SQL state is not defined!");
return false;
}
// X0Y32: Jar file already exists in schema
if (sqlState.equalsIgnoreCase("X0Y32")) {
return true;
}
// 42Y55: Table already exists in schema
if (sqlState.equalsIgnoreCase("42Y55")) {
return true;
}
return false;
}
|
4e655758-521d-4ee6-8c94-ace1293838e1
| 2
|
void open() {
// File parameters
dirName = Gpr.dirName(fastqFile);
ext = Gpr.extName(fastqFile);
baseName = Gpr.baseName(fastqFile, "." + ext);
// Open files
try {
file = new File(fastqFile);
if (!file.canRead()) error("Cannot read file '" + fastqFile + "'");
raf = new RandomAccessFile(file, "r");
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
|
4a404db9-48d7-4893-ade1-250c68370d15
| 1
|
public void setGuardAngle(float angle) {
if(angle < 0) {
guardAngle = angle + MathUtil.PI * 2;
}
else {
guardAngle = angle;
}
}
|
9a259720-32a0-43f4-a542-8dc1674bf9fe
| 1
|
public void renderObjects(){
for (GameObject gameObject : objectList) {
gameObject.render();
}
}
|
05679bcd-41db-489c-9b21-9622c100a6b2
| 3
|
public void setLogLevel(final String name) {
Level level;
try { level = Level.parse(name); } catch (final Exception e) {
level = CustomPlugin.DEFAULT_LOG;
this.getLogger().warning("Log level defaulted to " + level.getName() + "; Unrecognized java.util.logging.Level: " + name + "; " + e);
}
// only set the parent handler lower if necessary, otherwise leave it alone for other configurations that have set it
for (final Handler h : this.getLogger().getParent().getHandlers())
if (h.getLevel().intValue() > level.intValue()) h.setLevel(level);
this.getLogger().setLevel(level);
this.getLogger().log(Level.CONFIG, "Log level set to: {0} ({1,number,#})"
, new Object[] { this.getLogger().getLevel(), this.getLogger().getLevel().intValue() });
}
|
62204b5c-76e4-4702-9330-4dba49c2d928
| 0
|
public Builder published(Date published) {
this.published = published;
return this;
}
|
b49183c8-c04a-4ce1-9a9a-5f320f24f6c7
| 0
|
protected void initialize() {
Robot.tilter.moveDown();
}
|
c12d2203-414f-48d8-96d5-5b7abbdb3d1f
| 3
|
public void testSimulate(){
DebicccdGA g = new DebicccdGA("");
g.generateInitialPopulation(6);
g.printPopulation();
g.simulatePopulation("");
g.generateNextPopulation("roulette");
System.out.println();
for(Double d : g.fitness)
System.out.print(d + " : ");
for(int i = 0; i < 1000; i++){
g.simulatePopulation("");
g.generateNextPopulation("roulette");
}
System.out.println();
for(Double d : g.fitness)
System.out.print(d + " : ");
System.out.println();
g.printPrevPopulation();
}
|
ad3ceaf0-f419-4f60-998c-09e3cc5db124
| 2
|
public Socket close() {
EventThread.exec(new Runnable() {
@Override
public void run() {
if (Socket.this.readyState == ReadyState.OPENING || Socket.this.readyState == ReadyState.OPEN) {
Socket.this.onClose("forced close");
logger.fine("socket closing - telling transport to close");
Socket.this.transport.close();
}
}
});
return this;
}
|
a3b7a75a-a53a-4b10-a578-9244b634397b
| 9
|
public StraightTrajectory(Lane lane)
{
fLane = lane;
Point2D p1 = lane.getStart().getPosition();
Point2D p2 = lane.getEnd().getPosition();
double deltaX = p2.getX() - p1.getX();
double deltaY = p2.getY() - p1.getY();
if (deltaX != 0)
{
fA = (deltaY) / (deltaX);
fB = p1.getY() - fA * p1.getX();
}
else
{
fA = INT;
}
double angle = Math.abs(Math.atan2(deltaY, deltaX));
fAngle = angle;
if (lane.getType() == ILaneTypes.BEND)
{
if (angle >= Math.PI / 2 && angle <= Math.PI * 6 / 4)
{
fDirection = -1;
if (fA > 0)
{
fAngle = fAngle + Math.PI / 2;
}
}
else
{
fDirection = +1;
if (fA < 0)
{
fAngle = fAngle - Math.PI / 2;
}
}
}
else
{
boolean isSouth = fLane.getDirection(fLane.getEnd()).equals(Tile.COMPASS_POINT_S);
if (fLane.getDirection(fLane.getEnd()).equals(Tile.COMPASS_POINT_W) || isSouth)
{
fDirection = -1;
}
else
{
fDirection = +1;
if (fLane.getDirection(fLane.getEnd()).equals(Tile.COMPASS_POINT_N))
{
fAngle = fAngle + Math.PI;
}
}
}
}
|
10077062-13c6-4565-b792-fd6ce234ee17
| 5
|
public void draw(Graphics2D g) {
for(
int row = rowOffset;
row < rowOffset + numRowsToDraw;
row++) {
if(row >= numRows) break;
for(
int col = colOffset;
col < colOffset + numColsToDraw;
col++) {
if(col >= numCols) break;
if(map[row][col] == 0) continue;
int rc = map[row][col];
int r = rc / numTilesAcross;
int c = rc % numTilesAcross;
g.drawImage(
tiles[r][c].getImage(),
(int)x + col * tileSize,
(int)y + row * tileSize,
null
);
}
}
}
|
97586285-1e89-483d-b71b-fa1ca172765e
| 0
|
@Test
public void runTestHashMapAccess1() throws IOException {
InfoflowResults res = analyzeAPKFile("ArraysAndLists_HashMapAccess1.apk");
Assert.assertEquals(0, res.size());
}
|
797b000b-5b9f-43d2-ad71-a14cd242a8b7
| 7
|
public final boolean equals(Object o)
{
if (!(o instanceof Entry)) return false;
Entry e = (Entry)o;
Object k1 = Long.valueOf(getKey());
Object k2 = Long.valueOf(e.getKey());
if ((k1 == k2) || ((k1 != null) && (k1.equals(k2)))) {
Object v1 = getValue();
Object v2 = e.getValue();
if ((v1 == v2) || ((v1 != null) && (v1.equals(v2)))) return true;
}
return false;
}
|
b07ff022-717a-4dd2-a77d-a9ede36ec6c5
| 1
|
public void testSetIntoIntervalEx_Object_Chronology2() throws Exception {
MutableInterval m = new MutableInterval(-1000L, 1000L);
try {
StringConverter.INSTANCE.setInto(m, "/", null);
fail();
} catch (IllegalArgumentException ex) {}
}
|
8a6444b0-b9b6-4c6e-a745-cfdacfcbe088
| 8
|
protected String fetch(String url, String caller, boolean write) throws IOException
{
// check the database lag
logurl(url, caller);
do // this is just a dummy loop
{
if (maxlag < 1) // disabled
break;
// only bother to check every 30 seconds
if ((System.currentTimeMillis() - lastlagcheck) < 30000) // TODO: this really should be a preference
break;
try
{
// if we use this, this can block unrelated read requests while we edit a page
synchronized(domain)
{
// update counter. We do this before the actual check, so that only one thread does the check.
lastlagcheck = System.currentTimeMillis();
int lag = getCurrentDatabaseLag();
while (lag > maxlag)
{
log(Level.WARNING, "Sleeping for 30s as current database lag (" + lag + ")exceeds the maximum allowed value of " + maxlag + " s", caller);
Thread.sleep(30000);
lag = getCurrentDatabaseLag();
}
}
}
catch (InterruptedException ex)
{
// nobody cares
}
}
while (false);
// connect
URLConnection connection = new URL(url).openConnection();
connection.setConnectTimeout(CONNECTION_CONNECT_TIMEOUT_MSEC);
connection.setReadTimeout(CONNECTION_READ_TIMEOUT_MSEC);
setCookies(connection, cookies);
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
zipped ? new GZIPInputStream(connection.getInputStream()) : connection.getInputStream(), "UTF-8"));
// get the cookies
if (write)
{
grabCookies(connection, cookies2);
cookies2.putAll(cookies);
}
// get the text
String line;
StringBuilder text = new StringBuilder(100000);
while ((line = in.readLine()) != null)
{
text.append(line);
text.append("\n");
}
in.close();
return text.toString();
}
|
cdd7e4d1-b66e-449b-bb32-8b852f8fe78f
| 7
|
public MergerView(Console consoleStream, DefaultListModel currentModel) {
super("CWRC Data Merger");
this.setSize(1024, 768);
this.consoleStream = consoleStream;
this.currentListModel = currentModel;
//Add the console output
console = new JTextArea();
consoleStream.setOutput(console);
Container container = this.getContentPane();
container.setLayout(new GridLayout(0, 1));
JPanel topPanel = new JPanel();
topPanel.setLayout(new GridLayout(0, 3));
topPanel.add(new JScrollPane(console));
//Add the Selectors
currentMerges = new JList(currentModel);
topPanel.add(new JScrollPane(currentMerges));
currentMerges.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent lse) {
if (lse.getFirstIndex() >= currentListModel.getSize()) {
inputNode.setText("");
return;
}
currentMatch = (MultipleMatchModel) currentListModel.getElementAt(lse.getFirstIndex());
inputNode.setText("");
selectPossibleMatches(currentMatch);
}
});
JPanel mergePanel = new JPanel();
mergePanel.setLayout(new BoxLayout(mergePanel, BoxLayout.Y_AXIS));
possibleMatches = new JList();
mergePanel.add(new JScrollPane(possibleMatches));
possibleMatches.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent lse) {
if (currentMatch != null) {
QueryResult result = (QueryResult) possibleMatches.getSelectedValue();
if (result == null) {
mergeNode.setText("");
return;
}
//Create the text for both sections
inputNode.setText(StringUtils.EMPTY);
mergeNode.setText(StringUtils.EMPTY);
for (SectionDiff diff : currentMatch.getPossibleMatchDifference(result)) {
if (diff.isDifference()) {
append(inputNode, Color.RED, diff.getOldStr());
append(mergeNode, Color.GREEN, diff.getNewStr());
} else {
append(inputNode, Color.WHITE, diff.getOldStr());
append(mergeNode, Color.WHITE, diff.getNewStr());
}
}
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
buttonPanel.setMaximumSize(new Dimension(5000, 64));
buttonPanel.add(new JPanel());
mergeButton = new JButton("Merge");
buttonPanel.add(mergeButton);
mergeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container container = ((JButton) e.getSource()).getParent();
int result = JOptionPane.showConfirmDialog(container, "Are you sure you wish to merge these elements?", "Confirm Merge", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
int selectedIndex = currentMerges.getSelectedIndex();
MultipleMatchModel matches = (MultipleMatchModel) currentListModel.getElementAt(selectedIndex);
matches.setSelection((QueryResult) possibleMatches.getSelectedValue());
currentMatch = null;
currentListModel.removeElementAt(selectedIndex);
possibleMatches.setListData(new Object[]{});
}
}
});
newButton = new JButton("New");
buttonPanel.add(newButton);
newButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Container container = ((JButton) e.getSource()).getParent();
int result = JOptionPane.showConfirmDialog(container, "Are you sure you wish to create a new entry to this element?", "Confirm New Entry", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
int selectedIndex = currentMerges.getSelectedIndex();
MultipleMatchModel matches = (MultipleMatchModel) currentListModel.get(selectedIndex);
matches.setSelection(null);
currentMatch = null;
currentListModel.remove(selectedIndex);
possibleMatches.setListData(new Object[]{});
}
}
});
mergePanel.add(buttonPanel);
topPanel.add(mergePanel);
container.add(topPanel);
//Add text output
JPanel selectors = new JPanel();
selectors.setLayout(new GridLayout(0, 2));
inputNode = new JTextPane();
selectors.add(new JScrollPane(inputNode));
mergeNode = new JTextPane();
selectors.add(new JScrollPane(mergeNode));
container.add(selectors);
}
|
7f4e263c-e869-4dc2-bb86-e87598c460e0
| 2
|
public MetricsLite(Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
|
22a81dc4-3722-46e4-8d72-bbc998877b81
| 4
|
@Override
public O_5x_AbstractDataType deserialize(ByteBuf bb) {
String adc = Serialization.getString(bb);
String oadc = Serialization.getString(bb);
String ac = Serialization.getString(bb);
Character nrq = Serialization.getCharacter(bb);
String nadc = Serialization.getString(bb);
Character nt = Serialization.getCharacter(bb);
String npid = Serialization.getString(bb);
Character lrq = Serialization.getCharacter(bb);
String lrad = Serialization.getString(bb);
String lpid = Serialization.getString(bb);
Character dd = Serialization.getCharacter(bb);
String ddt = Serialization.getString(bb);
String vp = Serialization.getString(bb);
String rpid = Serialization.getString(bb);
String scts = Serialization.getString(bb);
Character dst = Serialization.getCharacter(bb);
String rsn = Serialization.getString(bb);
String dscts = Serialization.getString(bb);
Character mt = Serialization.getCharacter(bb);
String nmsg = null;
String amsg = null;
String tmsg = null;
String nb = null;
if (mt != null) {
nb = Serialization.getString(bb);
if('2' == mt) {
nmsg = Serialization.getString(bb);
} else if('3' == mt) {
String amsgIra = Serialization.getString(bb);
amsg = IRA.iraToUnicode(amsgIra);
} else if('4' == mt) {
String tmsgIra = Serialization.getString(bb);
tmsg = IRA.iraToUnicode(tmsgIra);
} else {
throw new IllegalArgumentException("Illegal \"mt\" value: "+ mt);
}
} else {
Serialization.checkSeparator(bb, "nb");
Serialization.checkSeparator(bb, "msg");
}
Character mms = Serialization.getCharacter(bb);
Character pr = Serialization.getCharacter(bb);
Character dc = Serialization.getCharacter(bb);
Character mcl = Serialization.getCharacter(bb);
Character rpi = Serialization.getCharacter(bb);
String cpg = Serialization.getString(bb);
Character rply = Serialization.getCharacter(bb);
String otoa = Serialization.getString(bb);
String hplmn = Serialization.getString(bb);
String xser = Serialization.getString(bb);
String res4 = Serialization.getString(bb);
String res5 = Serialization.getString(bb);
return new O_5x_AbstractDataType(adc, oadc, ac, nrq, nadc, nt, npid, lrq, lrad, lpid, dd, ddt, vp, rpid, scts, dst, rsn, dscts, mt, nmsg, amsg, nb, tmsg, mms, pr, dc, mcl, rpi, cpg, rply, otoa, hplmn, xser, res4, res5);
}
|
f97b8309-aac4-4088-b668-0e408522b643
| 0
|
public void mouseEntered(MouseEvent e) {
mouseMoved(e);
}
|
b5a14fb3-5ce8-435d-a133-0092ed061833
| 1
|
protected void regraph() {
if( site != null ) {
site.regraph();
}
}
|
bfbb4bf2-8ab8-458b-82c7-b0ef47c96c63
| 6
|
@Override
public String saveAnswer(Question question) {
if(question == null){
return "Не передан объект вопроса";
}
if (question.getIdTest() == null){
return "В переданом объекте отсутствует ссылка на тест";
}
if (question.getIdQuestion() == null){
return "В переданом объекте вопроса нет его кода";
}
answer = new Answer();
answer.setQuestion(question);
answer.setIsRightAnswer(this.isRightAnswer());
answer.setNameAnswer(this.getTextAnswer());
try {
int ret = answer.insertInto();
if (ret == -1) {
return "Такой Ответ на вопрос уже есть";
}
} catch (SQLException ex) {
return ex.toString();
}
try {
answer.setIdAnswer(answer.getIdFromDataBase());
} catch (SQLException ex) {
Logger.getLogger(AlternativePanel.class.getName()).log(Level.SEVERE, null, ex);
return ex.toString();
}
return null;
}
|
c3dafb47-465f-407b-b37d-9b9b4d19d1db
| 5
|
public void saveGameState(ArrayList<InfoPacket> packets, String fileName)
{
String output = new String();
Iterator<InfoPacket> packetIter = packets.iterator();
InfoPacket pckt = null;
while(packetIter.hasNext())
{
pckt = packetIter.next();
Iterator<Pair<?>> namedValueIter = pckt.namedValues.iterator();
while(namedValueIter.hasNext())
{
Pair<?> pair = namedValueIter.next();
output += pair.first() + '/' + pair.second().toString() + '\n';
}
}
try {
BufferedWriter out = new BufferedWriter(new FileWriter("test.txt"));
out.write(output);
System.out.println(output);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
}
|
8104d731-976f-4408-a800-ec066725ead3
| 9
|
public void ObtainPHPFileVariables(DatabaseAccess JavaDBAccess, String TargetPHPFileSelected) {
int TARGET_PHP_FILES_ID = 0;
PreparedStatement ps = null;
String PHPFileText = "", PHPFileTextClean = ""; //The text of the PHP file where we want to inject the vulnerabilities
String[] RegExpTextArray = new String[5];
Matcher existMatch = null;
Pattern p = null;
int existMatchStart = 0, existMatchEnd = 0;
ResultSet rs = null;
int count = 0, RegExpTextArrayIndex = 0;
String TargetVariable = "";
Boolean CaseSensitiveOption = false;
Connection conn = null;
try {
if ((conn = JavaDBAccess.setConn()) != null) {
System.out.println("Connected to database " + JavaDBAccess.getDatabaseName());
} else {
throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName());
}
conn.setAutoCommit(false);
// Start a transaction by inserting a record in the TARGET_PHP_FILES table
ps = conn.prepareStatement("SELECT ID,TEXT,CLEANED_TEXT FROM TARGET_PHP_FILES WHERE PATH = ?");
ps.setString(1, TargetPHPFileSelected);
rs = ps.executeQuery();
rs.next();
TARGET_PHP_FILES_ID = rs.getInt(1);
System.out.println("Chave usada: " + TARGET_PHP_FILES_ID);
/*
java.io.InputStream ip = rs.getAsciiStream(2);
int c = ip.read();
PHPFileTextClean = "";
while (c > 0) {
// System.out.print((char) c);
PHPFileTextClean = PHPFileTextClean + (char) c;
c = ip.read();
}
*/
PHPFileText = rs.getString("TEXT");
PHPFileTextClean = rs.getString("CLEANED_TEXT");
rs.close();
// Start a transaction by inserting a record in the TARGET_PHP_FILES_VARIABLES table
ps = conn.prepareStatement("DELETE FROM TARGET_PHP_FILES_SQL_VARIABLES WHERE TARGET_PHP_FILES_VARIABLE IN (SELECT ID FROM TARGET_PHP_FILES_VARIABLES WHERE TARGET_PHP_FILE=?)");
ps.setInt(1, TARGET_PHP_FILES_ID);
ps.executeUpdate();
// Start a transaction by inserting a record in the TARGET_PHP_FILES_VARIABLES table
ps = conn.prepareStatement("DELETE FROM VARIABLES_SQL_VARIABLES WHERE TARGET_PHP_FILES_VARIABLE IN (SELECT ID FROM TARGET_PHP_FILES_VARIABLES WHERE TARGET_PHP_FILE=?) OR TARGET_PHP_FILES_SQL_VARIABLE IN (SELECT ID FROM TARGET_PHP_FILES_VARIABLES WHERE TARGET_PHP_FILE=?)");
ps.setInt(1, TARGET_PHP_FILES_ID);
ps.setInt(2, TARGET_PHP_FILES_ID);
ps.executeUpdate();
ps = conn.prepareStatement("UPDATE TARGET_PHP_FILES_RUNS_FUNCTIONS_VARIABLES SET TARGET_PHP_FILES_VARIABLE=NULL WHERE TARGET_PHP_FILES_VARIABLE IN (SELECT ID FROM TARGET_PHP_FILES_VARIABLES WHERE TARGET_PHP_FILE=?)");
ps.setInt(1, TARGET_PHP_FILES_ID);
ps.executeUpdate();
ps = conn.prepareStatement("DELETE FROM TARGET_PHP_FILES_VARIABLES WHERE TARGET_PHP_FILE=?");
ps.setInt(1, TARGET_PHP_FILES_ID);
ps.executeUpdate();
CaseSensitiveOption = true;
RegExpTextArray[0] = "\\$[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*"; // Using the regex to find all the PHP variables.
RegExpTextArray[1] = "(?<=\\$_GET\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*"; // Using the regex to find all the PHP variables that come from the Superglobal variables $_GET
RegExpTextArray[2] = "(?<=\\$HTTP_GET_VARS\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*"; // Using the regex to find all the PHP variables that come from the Superglobal variables $HTTP_GET_VARS
RegExpTextArray[3] = "(?<=\\$_POST\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*"; // Using the regex to find all the PHP variables that come from the Superglobal variables $_POST
RegExpTextArray[4] = "(?<=\\$_HTTP_POST_VARS\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*"; // Using the regex to find all the PHP variables that come from the Superglobal variables $HTTP_POST_VARS
//Superglobal variables
//$_GET[
//RegExpText = "(?<=\\$_GET\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*";
//$HTTP_GET_VARS[
//RegExpText = "(?<=\\$HTTP_GET_VARS\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*";
//$_POST[
//RegExpText = "(?<=\\$_POST\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*";
//$HTTP_POST_VARS[
//RegExpText = "(?<=\\$_HTTP_POST_VARS\\[')[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*";
//RegExpText = "\\$[a-zA-Z_\\x7f-\\xff][a-zA-Z0-9_\\x7f-\\xff]*"; // using the regex to find all the PHP variables.
// The regex string was found at http://pt2.php.net/language.variables
// RegExpText = "\\$+\\count+"; // using the regex string: \$+\count+ to find all the PHP variables
// for (int FileTextPointer = 0; FileTextPointer < 2; FileTextPointer++) {
// if (FileTextPointer == 0) {
// RegExpText = "\\$+\\b\\count+\\b\\s*(?!\\[)"; // using the regex string: \$+\b\count+\b\s*(?!\[) to find the scalar PHP variables
// } else {
// RegExpText = "\\$+\\b+\\count+\\b\\s*(?=\\[)"; // using the regex string: \$+\b\count+\b\s*(?=\[) to find the PHP variables arrays
// }
RegExpTextArrayIndex = 0;
for (String RegExpText : RegExpTextArray) {
if (CaseSensitiveOption) {
p = Pattern.compile(RegExpText);
} else {
p = Pattern.compile(RegExpText, Pattern.CASE_INSENSITIVE);
}
existMatch = p.matcher(PHPFileTextClean);
while (existMatch.find()) {
existMatchStart = existMatch.start();
existMatchEnd = existMatch.end();
// System.out.println(SubjectString.getText(existMatch.start(), existMatch.end()-existMatch.start()));
//TargetFunction stores the function
if (RegExpTextArrayIndex == 0) {//Regular PHP variables
TargetVariable = PHPFileText.substring(existMatchStart, existMatchEnd).trim();
} else {//PHP variables that come from the Superglobal variables $_GET, $HTTP_GET_VARS, $_POST, $HTTP_POST_VARS
TargetVariable = "$" + PHPFileText.substring(existMatchStart, existMatchEnd).trim();
}
if (!TargetVariable.matches("(\\$_GET|\\$HTTP_GET_VARS|\\$_POST|\\$_HTTP_POST_VARS)")) {//The TargetVariable must not be the Superglobal Variable itself
// Start a transaction by inserting a record in the TARGET_PHP_FILES_VARIABLES table
ps = conn.prepareStatement("SELECT COUNT(*) FROM TARGET_PHP_FILES_VARIABLES WHERE NAME = ? AND TARGET_PHP_FILE=?");
ps.setString(1, TargetVariable);
ps.setInt(2, TARGET_PHP_FILES_ID);
rs = ps.executeQuery();
rs.next();
count = rs.getInt(1);
rs.close();
if (count == 0) {
// Start a transaction by inserting a record in the TARGET_PHP_FILES_VARIABLES table
ps = conn.prepareStatement("INSERT INTO TARGET_PHP_FILES_VARIABLES (ID, TARGET_PHP_FILE, NAME, AFFECT_SQL_STATIC, INPUT_VARIABLE, DEFAULT_TEST_VALUE, DATA_TYPE) VALUES (DEFAULT,?,?,?,?,?,?)");
ps.setInt(1, TARGET_PHP_FILES_ID);
ps.setString(2, TargetVariable);
ps.setString(3, "U"); //Unknow if affects SQL Injection or not
ps.setString(4, "U"); //INPUT_VARIABLE
ps.setNull(5, java.sql.Types.VARCHAR); //DEFAULT_TEST_VALUE
ps.setString(6, "U"); //DATA_TYPE
ps.executeUpdate();
}
}
}
RegExpTextArrayIndex++;
}
ps.close();
conn.commit();
conn.close();
} catch (Throwable e) {
System.out.println("Errors in ObtainPHPFileVariables!");
System.out.println("exception thrown:");
if (e instanceof SQLException) {
JavaDBAccess.printSQLError((SQLException) e);
} else {
e.printStackTrace();
}
}
}
|
994c68e4-c846-4374-92fd-460f166a3c7c
| 6
|
public static int readPackInt(DataInput br) throws IOException {
int prefix = br.readUnsignedByte();
int bytes, value;
if ((prefix & 0x78) == 0x78) {
bytes = 4;
value = (prefix & 0x7) << 32;
} else if ((prefix & 0x70) == 0x70) {
bytes = 3;
value = (prefix & 0xf) << 24;
} else if ((prefix & 0x60) == 0x60) {
bytes = 2;
value = (prefix & 0x1f) << 16;
} else if ((prefix & 0x40) == 0x40) {
bytes = 1;
value = (prefix & 0x3f) << 8;
} else {
bytes = 0;
value = prefix & 0x7f;
}
for (int i = 0; i < bytes; i++) {
value |= br.readUnsignedByte() << (i << 3);
}
if ((prefix & 0x80) == 0x80)
value = ~value;
return value;
}
|
699df9de-5a78-4537-9be8-dc9811d4d674
| 5
|
private void displayValidationErrorDialog(boolean creationAttempted,
List<Invalid> errors) {
if (!errors.isEmpty()) {
JPanel content = new JPanel(new BorderLayout(0, 8));
JLabel label = new JLabel(
(creationAttempted ? "Your game could not be created due to the following "
: "Your game has the following ")
+ errors.size()
+ " "
+ (errors.size() == 1 ? "error" : "errors") + ":");
content.add(label, BorderLayout.NORTH);
DefaultTableModel model = new DefaultTableModel(errors.size(), 2);
model.setColumnIdentifiers(new String[] { "Aspect", "Message" });
JTable table = new JTable(model);
for (int i = 0; i < errors.size(); i++) {
Invalid ve = errors.get(i);
model.setValueAt(ve.aspect, i, 0);
model.setValueAt(ve.message, i, 1);
}
table.setEnabled(false);
table.getColumn("Aspect").setPreferredWidth(100);
table.getColumn("Aspect").setMaxWidth(100);
Dimension oldScrollSize = table
.getPreferredScrollableViewportSize();
oldScrollSize.height = Math.min(table.getPreferredSize().height,
oldScrollSize.height);
table.setPreferredScrollableViewportSize(oldScrollSize);
content.add(new JScrollPane(table), BorderLayout.CENTER);
JOptionPane.showMessageDialog(this, content, "Validation Failed",
JOptionPane.ERROR_MESSAGE);
} else {
if (!creationAttempted) {
JOptionPane
.showMessageDialog(
this,
"The validation completed successfully. Your game has no errors.",
"Validation Successful",
JOptionPane.INFORMATION_MESSAGE);
}
}
}
|
642f45c6-3979-47ce-9b28-4693821a1cb7
| 0
|
@Override
public Station[] getStations() {
return this._stations;
}
|
6a607eff-60d4-40a8-a576-6ea0a847f6c6
| 2
|
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
if(list != null && list.size() > 0){
drawList(g2d, list);
}
}
|
a049b4fd-093d-44a2-a566-a99c3d10326b
| 2
|
public List<Fleet> MyFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.Owner() == 1) {
r.add(f);
}
}
return r;
}
|
3030dee2-3e93-4c88-8da6-6321d61c7988
| 6
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Event other = (Event) obj;
if (eventType == null) {
if (other.eventType != null)
return false;
} else if (!eventType.equals(other.eventType))
return false;
return true;
}
|
e9c5c120-2a37-43de-9898-e38a3a65cf18
| 0
|
public void setValidatorRHS(Validator<T> validatorRHS) {
this.validatorRHS = validatorRHS;
}
|
3b2d1d1c-4918-4df4-9420-1f849dd71a51
| 7
|
public static void paint(Ocean sea) {
if (sea != null) {
int width = sea.width();
int height = sea.height();
/* Draw the ocean. */
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
for (int y = 0; y < height; y++) {
System.out.print("|");
for (int x = 0; x < width; x++) {
int contents = sea.cellContents(x, y);
if (contents == Ocean.SHARK) {
System.out.print('S');
} else if (contents == Ocean.FISH) {
System.out.print('~');
} else {
System.out.print(' ');
}
}
System.out.println("|");
}
for (int x = 0; x < width + 2; x++) {
System.out.print("-");
}
System.out.println();
}
}
|
ad98906f-ac06-483f-8c31-5a0ee2ee3d62
| 7
|
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
}
|
93f664b1-f662-4fb4-ab74-7f5a55a6e319
| 0
|
@Override
public void documentAdded(DocumentRepositoryEvent e) {}
|
cd3100ca-f2a4-47a5-817f-0bd9aabd73bc
| 8
|
public static void main(String[] args) {
int counter = 0;
for (int firstCard = 2; firstCard <= 14; firstCard++) {
for (int secondCard = 2; secondCard <= 14; secondCard++) {
if (secondCard == firstCard)
continue;
for (int firstSuit = 1; firstSuit <= 4; firstSuit++) {
for (int secondSuit = firstSuit + 1; secondSuit <= 4; secondSuit++) {
for (int thirdSuit = secondSuit + 1; thirdSuit <= 4; thirdSuit++) {
for (int forthSuit = 1; forthSuit <= 4; forthSuit++) {
for (int fifthSuit = forthSuit + 1; fifthSuit <= 4; fifthSuit++) {
printCard(firstCard);
printSuit(firstSuit);
printCard(firstCard);
printSuit(secondSuit);
printCard(firstCard);
printSuit(thirdSuit);
printCard(secondCard);
printSuit(forthSuit);
printCard(secondCard);
printSuit(fifthSuit);
System.out.println();
counter++;
}
}
}
}
}
}
}
System.out.println(counter++);
}
|
0427ad71-a5bb-4373-b0f9-76db48a505fe
| 8
|
public MainUserWindow(int a) {
cn = getContentPane();
cn.setLayout(null);
accno = a;
header = new JLabel("CUSTOMER", JLabel.CENTER);
footer = new JLabel("Logged in with Account No : " + accno,
JLabel.LEFT);
bCheck = new JButton("View Customer Profile");
bView = new JButton("View Transactions");
bPass = new JButton("Change Password");
bLogout = new JButton("Logout");
header.setFont(new Font("Copperplate Gothic Bold", Font.PLAIN, 20));
footer.setFont(new Font("Arial", Font.BOLD, 12));
bView.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
new ViewFrame().viewFrame(1, accno, 0, null);
}
});
bCheck.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String sql_query;
sql_query = "select * from customer where accno=" + accno;
int columncount = 8;
String columns[] = { "Account No", "Name", "Address",
"Phone No", "Account Type", "Balance",
"No. of transactions", "Password" };
ResultSet rs = null;
String[][] d = null;
try {
rs = query("select count(*) from customer where accno = "
+ accno);
rs.next();
int rowcount = Integer.parseInt(rs.getString(1));
rs = query(sql_query);
d = new String[rowcount][8];
int jr = 0;
JTable table = new JTable(d, columns) {
DefaultTableCellRenderer renderRight = new DefaultTableCellRenderer();
{// initializer block
renderRight
.setHorizontalAlignment(SwingConstants.CENTER);
}
@Override
public TableCellRenderer getCellRenderer(int arg0,
int arg1) {
return renderRight;
}
};
while (rs.next()) {
for (int i = 1; i <= columncount; ++i) {
d[jr][i - 1] = rs.getString(i);
}
jr++;
}
JScrollPane spTable = new JScrollPane(table);
spTable.setBounds(50, 50, 800, 40);
JLabel tableheader = new JLabel("CUSTOMER PROFILE", JLabel.CENTER);
tableheader.setFont(new Font("Copperplate Gothic Bold",
Font.PLAIN, 20));
tableheader.setBounds(0, 0, 900, 30);
Container frame = new JFrame();
frame.setLayout(null);
frame.add(tableheader);
frame.add(spTable);
frame.setBounds(400, 200, 900, 150);
frame.setVisible(true);
frame = getContentPane();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bPass.addActionListener(new ActionListener() {
@SuppressWarnings("deprecation")
@Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
JPasswordField oldpass = new JPasswordField(10);
panel.add(new JLabel("Enter current password"));
panel.add(oldpass);
JOptionPane.showConfirmDialog(null, panel, "",
JOptionPane.PLAIN_MESSAGE);
panel.removeAll();
ResultSet rs = null;
if (oldpass.getText().trim().length() == 0
|| oldpass.getText() == null)
;
else {
try {
rs = query("select password from customer where accno = "
+ accno);
rs.next();
String password = rs.getString("password");
password.equals(oldpass.getText());
if (password.equals(oldpass.getText())) {
JPasswordField jt1 = new JPasswordField(10), jt2 = new JPasswordField(
10);
panel.add(new JLabel("Enter new password"));
panel.add(jt1);
panel.add(new JLabel("Re-enter new password"));
panel.add(jt2);
JOptionPane.showConfirmDialog(null, panel, "",
JOptionPane.PLAIN_MESSAGE);
if (jt1.getText().equals(jt2.getText())) {
rs = query("update customer set password = '"
+ jt1.getText() + "' where accno="
+ accno);
JOptionPane.showMessageDialog(null,
"Password updated", "",
JOptionPane.PLAIN_MESSAGE);
} else {
JOptionPane.showMessageDialog(null,
"Passwords don't match");
}
} else
JOptionPane.showMessageDialog(null,
"Wrong password entered");
} catch (Exception e1) {
// TODO: handle exception
e1.printStackTrace();
}
}
}
});
bLogout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
new MainWindow();
}
});
header.setBounds(0, 25, 400, 30);
footer.setBounds(20, 240, 280, 30);
bCheck.setBounds(100, 80, 200, 30);
bView.setBounds(100, 120, 200, 30);
bPass.setBounds(100, 160, 200, 30);
bLogout.setBounds(300, 240, 100, 30);
cn.add(header);
cn.add(footer);
cn.add(bView);
cn.add(bCheck);
cn.add(bPass);
cn.add(bLogout);
setVisible(true);
setResizable(false);
setBounds(400, 250, 400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
|
500744d6-5b72-45f0-a43f-af5cae9cdc0b
| 7
|
public Object[] list() {
ArrayList<Object> ret = new ArrayList<Object>();
while(true) {
if(off >= blob.length)
break;
int t = uint8();
if(t == T_END)
break;
else if(t == T_INT)
ret.add(int32());
else if(t == T_STR)
ret.add(string());
else if(t == T_COORD)
ret.add(coord());
else if(t == T_COLOR)
ret.add(color());
}
return(ret.toArray());
}
|
c6c63ff2-3f01-494c-b24a-d18229be5884
| 5
|
@Override
public void create(String name, String author, String website, Path img) throws IOException {
if ((name == null) || name.equals("")) {
IllegalArgumentException iae = new IllegalArgumentException("Name is null or empty!");
Main.handleUnhandableProblem(iae);
}
// Overwrites any existing skin.
Path skinPath = Constants.PROGRAM_TMPSKIN_PATH.resolve(name);
if (Files.exists(skinPath, LinkOption.NOFOLLOW_LINKS)) {
try {
FileUtil.deleteDirectory(skinPath);
} catch (IOException e) {
Main.showProblemMessage(e.getMessage());
}
}
FileUtil.createDirectory(skinPath);
FileUtil.createDirectory(skinPath.resolve(Constants.SKIN_IMGFOLDER));
img = !FileUtil.control(img) ? Constants.SKIN_PREVIEWIMAGE_DEFAULT : img;
SkinPreviewVO preview = new SkinPreviewVO(name, name, author, website, img);
this.props = new SkinPropertiesVO(skinPath.resolve(Constants.SKIN_IMGFOLDER), preview);
}
|
cb390f0b-ad01-4862-8ed7-c34c837213d6
| 4
|
public void food(int count, int recursive, int length) {
while(recursive < 3) {
if(foodSpaceClear == true) {
for(int i = 0; i < length; i++) {
world[randRow+count][i+randCol].setFood(true); //Creates the line in the centre and the lines
world[randRow+count][i+randCol].setFoodAmount(5); //above the centre of the food blob
world[randRow+count][i+randCol].setEmpty(false);
}
for(int j = 0; j < length; j++) {
world[randRow-count][j+randCol].setFood(true); //Creates the line in the centre and the lines
world[randRow-count][j+randCol].setFoodAmount(5); //below the centre of the food blob
world[randRow-count][j+randCol].setEmpty(false);
}
recursive++;
count++;
food(count, recursive, length);
}
}
}
|
edd126eb-09ea-41b1-9a61-0794b03d5b11
| 3
|
public static void main(String[] args) {
double x=0,y=0;
boolean entra=false;
do{
try{
System.out.print("Valor x => ");
x=Double.parseDouble(stdin.readLine());
System.out.print("Valor y => ");
y=Double.parseDouble(stdin.readLine());
entra=false;
}catch(Exception e){
System.out.println("Valor fuera de rango");
entra=true;
}finally{
try {
stdin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}while(entra==true);
DecimalFormat df=new DecimalFormat("0.00");
//metodos de clase
System.out.println("Suma de "+x+" + "+y+" = "+df.format(Calculadora.sumarXconY(x, y)));
System.out.println("Resta de "+x+" - "+y+" = "+df.format(Calculadora.restaXconY(x, y)));
System.out.println("Multiplicación de "+x+" * "+y+" = "+df.format(Calculadora.multiplicarXconY(x, y)));
System.out.println("División de "+x+" / "+y+" = "+df.format(Calculadora.dividirXconY(x, y)));
//metodos de instancia
Calculadora a=new Calculadora(x,y);
System.out.println("Suma de "+x+" + "+y+" = "+df.format(Calculadora.suma()));
System.out.println("Resta de "+x+" - "+y+" = "+df.format(Calculadora.resta()));
System.out.println("Multiplicación de "+x+" * "+y+" = "+df.format(Calculadora.multiplica()));
System.out.println("División de "+x+" / "+y+" = "+df.format(Calculadora.divide()));
}
|
75d24dc6-9376-4063-92f4-76f7634f8f23
| 7
|
@Override
public QL factor(DenseMatrix A) {
if (Q.numRows() != A.numRows())
throw new IllegalArgumentException("Q.numRows() != A.numRows()");
else if (Q.numColumns() != A.numColumns())
throw new IllegalArgumentException(
"Q.numColumns() != A.numColumns()");
else if (L == null)
throw new IllegalArgumentException("L == null");
/*
* Calculate factorisation, and extract the triangular factor
*/
intW info = new intW(0);
LAPACK.getInstance().dgeqlf(m, n, A.getData(), Matrices.ld(m), tau, work,
work.length, info);
if (info.val < 0)
throw new IllegalArgumentException();
L.zero();
for (MatrixEntry e : A)
if (e.row() >= (m - n) + e.column())
L.set(e.row() - (m - n), e.column(), e.get());
/*
* Generate the orthogonal matrix
*/
info.val = 0;
LAPACK.getInstance().dorgql(m, n, k, A.getData(), Matrices.ld(m), tau, workGen,
workGen.length, info);
if (info.val < 0)
throw new IllegalArgumentException();
Q.set(A);
return this;
}
|
a40f666a-f1e4-4180-9aaf-1b2b5aaa7774
| 4
|
public Document toDOM(java.io.Serializable structure) {
LSystem lsystem = (LSystem) structure;
Document doc = newEmptyDocument();
Element se = doc.getDocumentElement();
// Add the axiom.
se.appendChild(createComment(doc, COMMENT_AXIOM));
se.appendChild(createElement(doc, AXIOM_NAME, null,
listAsString(lsystem.getAxiom())));
// Add the rewriting rules.
Set symbols = lsystem.getSymbolsWithReplacements();
Iterator it = symbols.iterator();
if (it.hasNext())
se.appendChild(createComment(doc, COMMENT_RULE));
while (it.hasNext())
se.appendChild(createRuleElement(doc, lsystem, (String) it.next()));
// Add the parameters.
Map parameters = lsystem.getValues();
it = parameters.keySet().iterator();
if (it.hasNext())
se.appendChild(createComment(doc, COMMENT_PARAMETER));
while (it.hasNext()) {
String name = (String) it.next();
String value = (String) parameters.get(name);
Element pe = createElement(doc, PARAMETER_NAME, null, null);
pe.appendChild(createElement(doc, PARAMETER_NAME_NAME, null, name));
pe
.appendChild(createElement(doc, PARAMETER_VALUE_NAME, null,
value));
se.appendChild(pe);
}
// Return the completed document.
return doc;
}
|
29deef9b-2711-4fc3-8ac3-039540898831
| 0
|
public void setRXAxisDeadZone(float zone) {
setDeadZone(rxaxis,zone);
}
|
a8f4fb21-f116-468f-8da8-2e1c053ac21d
| 4
|
public static final String toRoman(int number) {
if (number < 1) {
throw new IllegalArgumentException("Number must be greater than 0"); //$NON-NLS-1$
}
String text = "I"; //$NON-NLS-1$
int closest = 1;
for (int i = 0; i < ROMAN_VALUES.length; i++) {
if (number >= ROMAN_VALUES[i]) {
closest = ROMAN_VALUES[i];
text = ROMAN_TEXT[i];
break;
}
}
return number == closest ? text : text + toRoman(number - closest);
}
|
b020443e-c931-417d-b7c6-89ee7352c594
| 8
|
public MCTSNode UCTSelectChild() {
MCTSNode selected = null;
double best = -1;
for (MCTSNode node : children){
if (node.getMove().getType().equals(MoveType.PASS) && selected == null){
selected = node;
} else {
//disincentivize playing on the edges
double ratio;
if (node.getMove().getX()==0 || node.getMove().getY()==0 ||
node.getMove().getX() == AppRunner.BOARD_SIZE-1 ||
node.getMove().getY() == AppRunner.BOARD_SIZE-1){
ratio = Math.max(0, (node.wins - 6.1)/(epsilon + node.visits));
} else {
ratio = node.wins/(epsilon + node.visits);
}
double V = Math.max(.001, ratio * (1-ratio));
V = 1;
double uctValue = ratio + Math.sqrt(V*Math.log(this.visits + 1)/(epsilon + node.visits)) + random.nextDouble()*epsilon;
if (uctValue > best){
selected = node;
best = uctValue;
}
}
}
return selected;
}
|
0f052565-da80-43a0-b9a6-c17a45179342
| 3
|
public static int PovSwitch(int pov, int playerID) {
if (pov < 0)
return playerID;
if (playerID == pov)
return 1;
if (playerID == 1)
return pov;
return playerID;
}
|
82b0010c-1e65-42e9-a904-ed2918b50e87
| 4
|
private void airfieldJListSelectionChanged(ListSelectionEvent listSelectionEvent)
{
if(airfieldJList.getSelectedIndex() >= 0){
try{
Airfield theAirfield = (Airfield)airfieldJList.getSelectedValue();
currentData.setCurrentAirfield(theAirfield);
currentData.cleafGliderPosition();
currentData.clearRunway();
currentData.clearWinchPosition();
airfieldNameField.setText(theAirfield.getName());
airfieldNameField.setBackground(Color.GREEN);
airfieldNameField.setHorizontalAlignment(JTextField.RIGHT);
designatorField.setText(String.valueOf(theAirfield.getDesignator()));
designatorField.setBackground(Color.GREEN);
designatorField.setHorizontalAlignment(JTextField.RIGHT);
airfieldAltitudeField.setText(String.valueOf(theAirfield.getAltitude() * UnitConversionRate.convertDistanceUnitIndexToFactor(airfieldAltitudeUnitsID)));
airfieldAltitudeField.setBackground(Color.GREEN);
airfieldAltitudeField.setHorizontalAlignment(JTextField.RIGHT);
magneticVariationField.setText(String.valueOf(theAirfield.getMagneticVariation()));
magneticVariationField.setBackground(Color.GREEN);
magneticVariationField.setHorizontalAlignment(JTextField.RIGHT);
airfieldLongitudeField.setText(String.valueOf(theAirfield.getLongitude()));
airfieldLongitudeField.setBackground(Color.GREEN);
airfieldLongitudeField.setHorizontalAlignment(JTextField.RIGHT);
airfieldLatitudeField.setText(String.valueOf(theAirfield.getLatitude()));
airfieldLatitudeField.setBackground(Color.GREEN);
airfieldLatitudeField.setHorizontalAlignment(JTextField.RIGHT);
runwayNameField.setText("No Runway Selected");
runwayNameField.setBackground(Color.WHITE);
//runwayAltitudeField.setText("No Runway Selected");
//runwayAltitudeField.setBackground(Color.WHITE);
magneticHeadingField.setText("No Runway Selected");
magneticHeadingField.setBackground(Color.WHITE);
gliderPosNameField.setText("No Glider Position Selected");
gliderPosNameField.setBackground(Color.WHITE);
gliderPosAltitudeField.setText("No Glider Position Selected");
gliderPosAltitudeField.setBackground(Color.WHITE);
gliderPosLongitudeField.setText("No Glider Position Selected");
gliderPosLongitudeField.setBackground(Color.WHITE);
gliderPosLatitudeField.setText("No Glider Position Selected");
gliderPosLatitudeField.setBackground(Color.WHITE);
winchPosNameField.setText("No Winch Position Selected");
winchPosNameField.setBackground(Color.WHITE);
winchPosAltitudeField.setText("No Winch Position Selected");
winchPosAltitudeField.setBackground(Color.WHITE);
winchPosLongitudeField.setText("No Winch Position Selected");
winchPosLongitudeField.setBackground(Color.WHITE);
winchPosLatitudeField.setText("No Winch Position Selected");
winchPosLatitudeField.setBackground(Color.WHITE);
runwaysModel.removeAllElements();
winchPositionModel.removeAllElements();
gliderPositionModel.removeAllElements();
for(Runway str: runways){
if(str.getParent().equals(theAirfield.getDesignator()))
runwaysModel.addElement(str);
}
runwaysJList.setModel(runwaysModel);
runwaysScrollPane.setViewportView(runwaysJList);
} catch(Exception e) {
//TODO respond to error
}
airfieldEditButton.setEnabled(true);
runwayAddNewButton.setEnabled(true);
}
}
|
a64d4d0d-f037-486e-847a-4b45f7fa09cc
| 2
|
private static String readField(FileInputStream in) throws IOException {
String str = "";
for (char c = (char)in.read(); !Character.isWhitespace(c) && c != '\n'; c = (char)in.read())
str = str.concat(String.valueOf(c));
return str;
}
|
063ef84e-f1df-4ef6-b668-d33a10cc1ad2
| 7
|
public void receiveAcceptRequest(int uniqueId,BallotNumber proposal, double value) {
if(value>0)
senders.add(uniqueId);
if(acceptedValues.containsKey(value)){
acceptedValues.put(value, acceptedValues.get(value)+1);
} else {
acceptedValues.put(value,1);
}
if(acceptedValues.get(value) >= quorumSize) {
ArrayList<Double> tempValue= new ArrayList<Double>();
ArrayList<Integer> ids=new ArrayList<Integer>();
if(OpenBank.isOptimized == false) {
this.value = value;
tempValue.add(value);
ids.add(uniqueId);
acceptedValues.clear();
} else {
if(value < 0 ) {
tempValue.add(value);
ids.add(uniqueId);
} else {
Object[] keys = acceptedValues.keySet().toArray();
for(int i=0; i<acceptedValues.size();++i) {
if((Double)keys[i]>0 ){
tempValue.add((Double)keys[i]);
}
}
ids.addAll(senders);
}
}
NetworkSender.sendDecide(ids,tempValue);
}
}
|
efccf498-3a51-4c1d-815a-920fc245e839
| 7
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
if (colorCode != category.colorCode) return false;
if (id != category.id) return false;
if (headLine != null ? !headLine.equals(category.headLine) : category.headLine != null) return false;
return true;
}
|
25fc878a-0c1c-4b74-8768-4d84693f14d0
| 2
|
@Override
protected List<ByteBuffer> onRelease()
{
List<ByteBuffer> dump = new ArrayList<ByteBuffer>();
ByteBuffer buffer;
// For each pool of buffers...
for (int i = 0; i < pool.length; i++) {
// Pop every buffer off the current stack and add it to the list.
while ((buffer = pool[i].pop()) != null) {
dump.add(buffer);
}
}
return dump;
}
|
fb2470d4-354e-4cde-b99e-f9f475b2e0eb
| 1
|
public Collection pdomChildren(final Block block) {
if (domEdgeModCount != edgeModCount) {
computeDominators();
}
return block.pdomChildren();
}
|
afb77d7b-bcbf-457f-8bbe-cf1b380c6aa8
| 2
|
public int getCellAddress(int n) throws Exception {
if(n >= numSpillCells || n < 0) {
throw new Exception("Invalid spill cell");
}
return freeAddress + (n * Type.getWordSize());
}
|
5926f265-9862-47eb-9704-3c905dc5210a
| 9
|
public double associationClassesAttribute(double[][] counts){
List<Integer> supportSet = new ArrayList<Integer>();
List<Integer> not_supportSet = new ArrayList<Integer>();
double separability = 0;
int numValues = counts.length;
int numClasses = counts[0].length;
int total = 0;
double[] sumRows = new double[numValues];
double[] sumCols = new double[numClasses];
// get the row totals
for (int i = 0; i < numValues; i++) {
sumRows[i] = 0.0;
for (int j = 0; j < numClasses; j++) {
sumRows[i] += counts[i][j];
total += counts[i][j];
}
}
// get the column totals
for (int j = 0; j < numClasses; j++) {
sumCols[j] = 0.0;
for (int i = 0; i < numValues; i++) {
sumCols[j] += counts[i][j];
}
}
for (int i = 0; i < numValues; i++) {
for (int j = 0; j < numClasses; j++) {
//Computing Conditional Probability P(Valuei | Clasej)
double numerator1 = counts[i][j];
double denominator1 = sumCols[j];
double result1;
if(denominator1 != 0)
result1 = numerator1/denominator1;
else
result1 = 0;
//Computing Conditional Probability P(Valuei | ^Clasej)
double numerator2 = sumRows[i] - counts[i][j];
double denominator2 = total - sumCols[j];
double result2;
if(denominator2 != 0)
result2 = numerator2/denominator2;
else
result2 = 0;
if(result1 > result2){
supportSet.add (i);
separability +=result1;
}
else{
not_supportSet.add (i);
separability +=result2;
}
}
}
return separability/numClasses - 1.0;
}
|
79702402-045f-427e-9ada-8445bdc57361
| 2
|
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result + ((source == null) ? 0 : source.hashCode());
return result;
}
|
94da6970-485e-47a1-af6c-473e570176b9
| 5
|
@EventHandler(ignoreCancelled = true)
public void reloader(ChunkLoadEvent event)
{
Chunk c = event.getChunk();
int x = c.getX();
int z = c.getZ();
String world = c.getWorld().getName();
Location loc;
net.minecraft.server.v1_7_R1.World notchWorld;
V10Dragon v10dragon;
for(LivingEntity d: RideThaDragon.dragons.values())
{
loc = d.getLocation();
c = loc.getChunk();
if(c.getWorld().getName().equals(world) &&
c.getX() == x &&
c.getZ() == z)
{
notchWorld = ((CraftWorld)loc.getWorld()).getHandle();
v10dragon = (V10Dragon)((CraftLivingEntity)d).getHandle();
if(!notchWorld.addEntity(v10dragon, SpawnReason.CUSTOM))
plugin.getLogger().info("Can't respawn the dragon of "+v10dragon.player);
}
}
}
|
d203844d-e31e-45d4-b848-77eb32d51b24
| 3
|
public void getAllGenes() throws FileNotFoundException, IOException{
System.out.println("getting all genes from " + bed12Fname);
allTranscr = new ArrayList();
geneLengths = new HashMap<String, Integer>();
TextFile bed12 = new TextFile(bed12Fname, false);
String[] els = bed12.readLineElems(TextFile.tab);
String cur_gene = els[3], lengths = els[10], gene;
int gene_len;
while( (els = bed12.readLineElems(TextFile.tab)) != null){
gene = els[3];
allTranscr.add(gene);
if (cur_gene.equals(gene)){
lengths += els[10];
}
else{
gene_len = 0;
for (String len : lengths.split(","))
gene_len += Integer.parseInt(len);
geneLengths.put(cur_gene, gene_len);
cur_gene = els[3];
lengths = els[10];
}
}
bed12.close();
}
|
21d67546-b453-4a31-a810-c150f0ac11ac
| 1
|
@Override
public IEmailKontakt last() throws NoEmailKontaktFoundException {
EmailKontaktList emailContacts = readContacts();
if (emailContacts.getContactList().size() == 0) {
throw new NoEmailKontaktFoundException("Kein Kontakt gefunden!");
} else
return emailContacts.getContactList().get(
emailContacts.getContactList().size() - 1);
}
|
9a6065e6-95ef-46d9-88e0-10ee2a05e2c8
| 3
|
public static Map<String, PropertyDescriptor> getPropertyDescriptors(Class<?> clazz) throws IntrospectionException {
Map<String, PropertyDescriptor> propertyDescriptors = PROPERTY_DESCRIPTOR_CACHE.get(clazz);
if (propertyDescriptors == null) {
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
propertyDescriptors = new HashMap<String, PropertyDescriptor>();
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descriptor : descriptors) {
String property = descriptor.getName();
propertyDescriptors.put(property, descriptor);
}
}
return propertyDescriptors;
}
|
ce80a243-de14-49c9-ba3b-67368bfe4d14
| 4
|
void sortDescent (int [] items) {
/* Shell Sort from K&R, pg 108 */
int length = items.length;
for (int gap = length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < length; i++) {
for (int j = i - gap; j >= 0; j -= gap) {
if (items [j] <= items [j + gap]) {
int swap = items [j];
items [j] = items [j + gap];
items [j + gap] = swap;
}
}
}
}
}
|
7dce7392-16a4-4fec-8bdb-f66931931788
| 1
|
public synchronized boolean remover(int i)
{
try
{
new InstituicaoCooperadoraDAO().remover(list.get(i));
list = new InstituicaoCooperadoraDAO().listar("");
preencherTabela();
}
catch (Exception e)
{
return false;
}
return true;
}
|
51b7c074-ffb0-4a81-b36c-507558a45584
| 0
|
public void set(Set productions, String variable, String lookahead) {
int[] r = getLocation(variable, lookahead);
entries[r[0]][r[1]].clear();
entries[r[0]][r[1]].addAll(productions);
}
|
6c7dbb73-26bb-485b-b63e-ac8da4e0495c
| 4
|
public void nextMove()
{
int direction = getDirection();
if (isMove && isAValidDirection(direction)) {
progress(PIXELS);
nextPhotogram();
}
if (!isAValidDirection(direction) && nextDirection != direction) {
setDirection(nextDirection);
}
}
|
08e4fdd9-3b0d-4b27-94e7-aa5c0f7b1d10
| 1
|
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("candy")) System.out.print("end candy");
}
|
590779a6-4ad0-465a-ac3c-c6e016e8fcfa
| 2
|
public void add(String tableName, List<String> args) throws DBUnavailabilityException,
DataBaseRequestException, DataBaseTableException {
if (args.isEmpty()) {
throw new DataBaseRequestException("zero args in request list");
}
String key = args.get(0);
if (key == null) {
throw new DataBaseRequestException("key shouldn't be null");
}
String firstCharAtName = key.substring(0, 1);
DataBase db = getDataBaseByKey(firstCharAtName);
db.add(tableName, args);
}
|
c3427a91-c6b7-4a46-ba53-f6a906acd895
| 1
|
@Override
public void actionPerformed(ActionEvent event) {
try {
commitEdit();
} catch (ParseException exception) {
invalidEdit();
}
}
|
9dfb76ce-bc6f-4514-9e04-423653a91a2f
| 3
|
@SuppressWarnings("unchecked")
private static List<Operation> messageToOperationList(Object operationMessagesObj) {
List<?> operationMessages = (List<?>) operationMessagesObj;
List<Operation> operations = new ArrayList<>();
for (Object operationMessage : operationMessages) {
operations.add((Operation) messageToHasEquality((Map<String, Object>) operationMessage));
}
return operations;
}
|
de80373d-f6de-4c73-bbe1-293e37a0e90e
| 3
|
public static String trimLeadingWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
return sb.toString();
}
|
23ff3051-575f-4ca0-ab32-e70ba2033361
| 5
|
public void darBajaUsuario(String nick){
try {
String queryString = "DELETE FROM Usuarios WHERE nick=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, nick);
ptmt.executeUpdate();
System.out.println("Password cambiando");
String queryString2 = "DELETE FROM PeticionAmistad WHERE emisor=? OR receptor=?";
ptmt = connection.prepareStatement(queryString2);
ptmt.setString(1, nick);
ptmt.setString(2, nick);
ptmt.executeUpdate();
String queryString3 = "DELETE FROM SerAmigos WHERE nick1=? OR nick2=?";
ptmt = connection.prepareStatement(queryString3);
ptmt.setString(1, nick);
ptmt.setString(2, nick);
ptmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null) {
ptmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
45497829-e1da-4b0a-b051-340082b761d7
| 6
|
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
|
d6dc7213-4bff-424a-9caf-ac4114c52281
| 7
|
void doStand() {
if (gameInProgress == false) {
message = "Click \"New Game\" to start a new game.";
repaint();
return;
}
gameInProgress = false;
while (dealerHand.getBlackjackValue() <= 16 && dealerHand.getCardCount() < 5)
dealerHand.addCard( deck.dealCard() );
if (dealerHand.getBlackjackValue() > 21)
message = "You win! Dealer has busted with " + dealerHand.getBlackjackValue() + ".";
else if (dealerHand.getCardCount() == 5)
message = "Sorry, you lose. Dealer took 5 cards without going over 21.";
else if (dealerHand.getBlackjackValue() > playerHand.getBlackjackValue())
message = "Sorry, you lose, " + dealerHand.getBlackjackValue()
+ " to " + playerHand.getBlackjackValue() + ".";
else if (dealerHand.getBlackjackValue() == playerHand.getBlackjackValue())
message = "Sorry, you lose. Dealer wins on a tie.";
else
message = "You win, " + playerHand.getBlackjackValue()
+ " to " + dealerHand.getBlackjackValue() + "!";
repaint();
}
|
664ecb77-b8d9-4128-b793-91e0ccec4e47
| 4
|
@Override
public void mouseDragged(MouseEvent evt) {
if (!SwingUtilities.isRightMouseButton(evt)) {
return;
}
Point current = evt.getPoint();
double x = viewer.getCenter().getX() - (current.x - prev.x);
double y = viewer.getCenter().getY() - (current.y - prev.y);
if (!viewer.isNegativeYAllowed()) {
if (y < 0) {
y = 0;
}
}
int maxHeight = (int) (viewer.getTileFactory().getMapSize(viewer.getZoom()).getHeight() * viewer
.getTileFactory().getTileSize(viewer.getZoom()));
if (y > maxHeight) {
y = maxHeight;
}
prev = current;
viewer.setCenter(new Point2D.Double(x, y));
viewer.repaint();
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
|
4e7dbc75-5e47-46a3-a117-1a66a11ecc11
| 8
|
void generateTree(int nNodes) {
boolean [] bConnected = new boolean [nNodes];
// start adding an arc at random
int nNode1 = random.nextInt(nNodes);
int nNode2 = random.nextInt(nNodes);
if (nNode1 == nNode2) {nNode2 = (nNode1 + 1) % nNodes;}
if (nNode2 < nNode1) {int h = nNode1; nNode1 = nNode2; nNode2 = h;}
m_ParentSets[nNode2].addParent(nNode1, m_Instances);
bConnected[nNode1] = true;
bConnected[nNode2] = true;
// Repeatedly, select one of the connected nodes, and one of
// the unconnected nodes and add an arc.
// All arcs point from lower to higher ordered nodes
// so that acyclicity is ensured.
for (int iArc = 2; iArc < nNodes; iArc++ ) {
int nNode = random.nextInt(nNodes);
nNode1 = 0; // one of the connected nodes
while (nNode >= 0) {
nNode1 = (nNode1 + 1) % nNodes;
while (!bConnected[nNode1]) {
nNode1 = (nNode1 + 1) % nNodes;
}
nNode--;
}
nNode = random.nextInt(nNodes);
nNode2 = 0; // one of the unconnected nodes
while (nNode >= 0) {
nNode2 = (nNode2 + 1) % nNodes;
while (bConnected[nNode2]) {
nNode2 = (nNode2 + 1) % nNodes;
}
nNode--;
}
if (nNode2 < nNode1) {int h = nNode1; nNode1 = nNode2; nNode2 = h;}
m_ParentSets[nNode2].addParent(nNode1, m_Instances);
bConnected[nNode1] = true;
bConnected[nNode2] = true;
}
} // GenerateTree
|
6138695e-394c-4690-bd23-0900584f5ba5
| 1
|
public int getX(int index) {
if(index <= this.index)
return line[index][0];
else
return -1;
}
|
b9f8f83b-3b08-411f-9a57-39cc0a457de8
| 0
|
public void setReferenceList(ReferenceList value) {
this.referenceList = value;
}
|
db27fb8f-02fa-47e4-b4de-d7c50850e068
| 8
|
public SOM(GridType gridType, int[] gridParams, Node.CostMethod costMethod, Node.UpdateMethod updateMethod,
Node.NeighborhoodFunction neighborFunction, double initialLearningRate, DistanceFunction distFunction,
double initialRadius, double timescale, int nIterations, TwoMomentEnsemble ensemble, String variableName) {
this.ensemble = ensemble;
this.initialLearningRate = initialLearningRate;
this.initialRadius = initialRadius;
this.timescale = timescale;
this.distFunction = distFunction;
this.nIterations = nIterations;
/*
* Determine SOM grid coordinates
*/
ArrayList<double[]> coordinates = null;
switch (gridType) {
case HEX:
coordinates = determineHexCoords(gridParams[0]);
break;
case RECTANGULAR:
coordinates = determineRectCoords(gridParams);
break;
}
/*
* Initialize nodes
*/
int nNodes = coordinates.size();
this.nodes = new Node[nNodes];
for (int n = 0; n < nNodes; n++) {
EnsembleVariable randomState = ensemble.getVariableRandomTime(variableName);
this.nodes[n] = new Node(coordinates.get(n), randomState.getMean(), randomState.getStdDev(), updateMethod,
costMethod, neighborFunction);
}
/*
* Iterate SOM
*/
for (int i = 0; i < nIterations; i++) {
System.out.println("Computing SOM iteration " + ( i + 1 ) + "/" + nIterations);
EnsembleVariable randomState = ensemble.getVariableRandomTime(variableName);
double learningRate = initialLearningRate * Math.exp(-i / timescale);
double radius = 0.0;
switch (distFunction) {
case LINEAR:
radius = initialRadius - ( i * initialRadius ) / nIterations;
break;
case EXPONENTIAL:
radius = initialRadius * Math.exp(-i / nIterations);
break;
}
ArrayList<Double> costs = new ArrayList<Double>(0);
for (Node node : this.nodes) {
costs.add(node.cost(randomState));
}
Node closestNode = this.nodes[costs.indexOf(Collections.min(costs))];
closestNode.closest();
for (Node node : this.nodes) {
node.updateNode(closestNode, randomState, learningRate, radius);
}
}
}
|
2991209f-7df9-4d09-b70b-6c3db752ae7f
| 2
|
@Override
public void processEntity(Entity entity) {
// Ensure that we also remove any children entites owned by the parent
Children childrenComponent = entity.getComponent(Children.class);
if (childrenComponent != null) {
for (Entity child : childrenComponent.children) {
entityManager.removeEntity(child);
}
}
entityManager.removeEntity(entity);
}
|
628e3dd9-4332-4bd3-99f4-5d419518199a
| 9
|
public static int solution(int[] A) {
if(A.length == 0)
return -1;
int[] temp = new int[A.length];
for(int i = 0; i < A.length; i++)
temp[i] = A[i];
Arrays.sort(temp);
for(int i = 0; i < A.length; i++) {
int index = binarySearch(temp, 0, temp.length-1, A[i]);
if(index == 0) {
if(temp[index] != temp[index+1])
return i;
}
else if (index == temp.length-1) {
if(temp[index] != temp[index-1])
return i;
} else {
if(temp[index] != temp[index+1] && temp[index] != temp[index-1])
return i;
}
}
return -1;
}
|
c4da5560-e656-4a03-80f7-e26a0aaf21b4
| 9
|
protected List<EmoteObj> parseEmotes()
{
if(emotes!=null)
return emotes;
broadcast=false;
emoteType=EMOTE_TYPE.EMOTE_VISUAL;
emotes=new Vector<EmoteObj>();
String newParms=getParms();
char c=';';
int x=newParms.indexOf(c);
if(x<0){ c='/'; x=newParms.indexOf(c);}
if(x>0)
{
final String oldParms=newParms.substring(0,x);
setEmoteTypes(CMParms.parse(oldParms),false);
newParms=newParms.substring(x+1);
}
final EMOTE_TYPE defaultType=emoteType;
final boolean defaultBroadcast=broadcast;
while(newParms.length()>0)
{
String thisEmote=newParms;
x=newParms.indexOf(';');
if(x<0)
newParms="";
else
{
thisEmote=newParms.substring(0,x);
newParms=newParms.substring(x+1);
}
if(thisEmote.trim().length()>0)
{
final Vector<String> V=CMParms.parse(thisEmote);
emoteType=defaultType;
broadcast=defaultBroadcast;
setEmoteTypes(V,true);
thisEmote=CMParms.combine(V,0);
if(thisEmote.length()>0)
{
if(emoteType==EMOTE_TYPE.EMOTE_SMELL)
{
if(smells==null)
smells=new Vector<EmoteObj>();
smells.add(new EmoteObj(emoteType,thisEmote,broadcast));
}
emotes.add(new EmoteObj(emoteType,thisEmote,broadcast));
}
}
}
return emotes;
}
|
9fad878e-158c-4b45-90c6-0c56e1a3da27
| 9
|
public static Keyword oldInterpretOrScores(ControlFrame frame, Keyword lastmove) {
if (lastmove == Logic.KWD_DOWN) {
{ PartialMatchFrame pmf = frame.partialMatchFrame;
if (pmf == null) {
ControlFrame.createAndLinkPartialMatchFrame(frame, Logic.KWD_OR);
}
else {
{
while (frame.partialMatchFrame.argumentScores.length() > frame.argumentCursor) {
frame.partialMatchFrame.popPartialMatchScore();
}
pmf.setDynamicCutoff();
}
}
}
}
else if ((lastmove == Logic.KWD_UP_TRUE) ||
(lastmove == Logic.KWD_UP_FAIL)) {
ControlFrame.recordLatestPartialMatchScore(frame);
if (Stella_Object.traceKeywordP(Logic.KWD_GOAL_TREE)) {
System.out.println(((FloatWrapper)(KeyValueList.dynamicSlotValue(((QueryIterator)(Logic.$QUERYITERATOR$.get())).dynamicSlots, Logic.SYM_LOGIC_LATEST_POSITIVE_SCORE, Stella.NULL_FLOAT_WRAPPER))).wrapperValue + ", " + frame.partialMatchFrame.computeOrScore());
}
if (ControlFrame.computePartialMatchOrSuccessP(frame)) {
lastmove = Logic.KWD_UP_TRUE;
}
else if (((frame.argumentCursor + 1) == frame.proposition.arguments.length()) &&
ControlFrame.computePartialMatchScoreP(frame)) {
lastmove = Logic.KWD_UP_TRUE;
}
else {
lastmove = Logic.KWD_UP_FAIL;
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + lastmove + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (lastmove);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.