method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
5aff7da2-c687-4440-a4ce-062d30f38eaf
| 3
|
protected void startGame(String sender) {
if (!bot.getNick().equals(name)) {
bot.changeNick(name);
}
if (doBarks)
idleTimer.cancel(); // don't make comments while the game's on.
players2.reset();
players2.start(MAXPLAYERS);
for (int i = 0; i < players2.numPlayers(); i++) {
bot.voice(gameChan, players2.get(i));
bot.sendMessage(gameChan, getFromFile("JOIN", sender, NARRATION));
}
status = GameStatus.PRE;
firstNight = true;
toSee = -1;
bot.sendMessage(gameChan, getFromFile("STARTGAME", sender, joinTime, NARRATION));
sendNotice(gameChan, getFromFile("STARTGAME-NOTICE", sender, NOTICE));
joinGame(sender);
/*
* if (players2.addPlayer(sender)) { bot.setMode(gameChan, "+v " + sender); sendNotice2(sender, getFromFile("ADDED",
* NOTICE)); } else sendNotice2(sender, "Could not add you to player list. Please try again." + " (/msg " +
* bot.getName() + " join.");
*/
waitForOutgoingQueueSizeIsZero();
gameTimer = new Timer();
gameTimer.schedule(new WereTask(), joinTime * 1000);
}
|
8d4dfa21-0917-4a85-8928-87088c433a9a
| 1
|
public static byte[] rotateLeft(byte[] in, int len, int step) {
int numOfBytes = (len - 1) / 8 + 1;
byte[] out = new byte[numOfBytes];
for (int i = 0; i < len; i++) {
int val = getBitInt(in, (i + step) % len);
setBit(out, i, val);
}
return out;
}
|
130ec827-5164-457b-8ef6-d97de977c15e
| 5
|
public void loadHandlers() throws IOException{
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
if (line.contains("#")) {
String thePackage = stringModifier.removeSingleChar(line, line.indexOf("#"));
String name = stringModifier.substringFirstCapitalChar(thePackage);
try {
Class<?> handlerClass = Class.forName(thePackage);
System.out.println(thePackage);
Object handlerInstance = handlerClass.newInstance();
classes.put(name, (ProblemHandler) handlerInstance);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
handlerNames = new String[classes.size()];
int index = 0;
for(String name : classes.keySet())
{
handlerNames[index] = name;
index++;
}
}
|
1a9e82de-faee-47ed-943c-23770179a1bf
| 9
|
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(citation).append(EOL);
if (comments != null ) {
for (Comment comment : comments) {
stringBuilder.append(comment).append(EOL);
}
}
if (xrefs != null ) {
for (Xref xref : xrefs) {
stringBuilder.append(xref).append(EOL);
}
}
if (features != null ) {
for (Feature feature : features) {
stringBuilder.append(feature).append(EOL);
}
}
if (sequence != null) {
stringBuilder.append(sequence).append(EOL);
}
if (evTags != null) {
for (EvidenceTag evidenceTag : evTags) {
stringBuilder.append(evidenceTag).append(EOL);
}
}
stringBuilder.append(curatorEvidence);
return stringBuilder.toString();
}
|
a024e83c-4900-485b-9c23-a04cc14205e2
| 1
|
private ItemIdList() {
ItemIdList.idSIIS = new SIIS();
File datadump = new File("data.dump");
if (!datadump.exists()) {
parse();
// buildFromScratch();
} else {
idSIIS = SIIS.deSerializeFile(datadump);
System.out.println(idSIIS.size());
}
}
|
ebb011fc-4212-49a3-987e-0fba336b114a
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GameFrame().setVisible(true);
}
});
}
|
68bd38a1-82a6-4ee4-968e-22e43e00ada4
| 2
|
public void write(AnnotationsWriter writer) throws IOException {
String typeName = pool.getUtf8Info(typeIndex);
if (members == null) {
writer.annotation(typeName, 0);
return;
}
writer.annotation(typeName, members.size());
Iterator it = members.values().iterator();
while (it.hasNext()) {
Pair pair = (Pair)it.next();
writer.memberValuePair(pair.name);
pair.value.write(writer);
}
}
|
f3ffed3b-ef3f-42ad-a097-9d7cc28af9d8
| 5
|
private void checkWhatLineExpected() throws AssemblerException {
abortMnem = true;
if (atOperandFieldEncodings) {
abortMnem = true;
throw new AssemblerException(
"MnemonicData error: Line format or indentation error, operand field encodings line expected. Line should begin with two tabs.\n"
+ getMnemDataErrorMessage());
}
else if (atLocalFieldEncodings) {
throw new AssemblerException(
"MnemonicData error: Line format or indentation error, local field encodings line expected. Line should begin with two tabs.\n"
+ getMnemDataErrorMessage());
}
else if (atInsFormat) {
throw new AssemblerException(
"MnemonicData error: Line format or indentation error, instruction format line expected. Line should begin with two tabs.\n"
+ getMnemDataErrorMessage());
}
else if (!emptyLine){
throw new AssemblerException(
"MnemonicData error: Line format error, empty line expected.\n"
+ getMnemDataErrorMessage());
}
else if (!foundFormatHeader) {
throw new AssemblerException(
"MnemonicData error: Line format or indentation error, operand format line expected.\nOperand format missing for mnemonic \""
+ currentMnemonic.getMnemonic()
+ "\".\n"
+ getMnemDataErrorMessage());
}
else
throw new AssemblerException("MnemonicData error: Line format or indentation error.");
}
|
baa48474-f2dd-4be2-8a42-86013042e16a
| 0
|
public static void severe(String message)
{
FMLRelaunchLog.log("MattparksCore", Level.ERROR, message);
}
|
f9c20638-c10e-487a-9734-e08840efe9fe
| 1
|
private synchronized boolean contains(Object p){
if(p instanceof Peer)
return peerList.contains((Peer)p);
return false;
}
|
cd389125-db81-4e23-b068-ad0873a78829
| 0
|
public static void before(PrintWriter out){
out.println("<html>"+
head()+
"<body>"+
"<table id=\"hor-minimalist-b\">"+
thead());
}
|
5de55962-93f1-44cc-bd2a-3c3df0e33a09
| 5
|
public CodeMap31 set(final int index, final int value) {
final int i0 = index >>> 24;
int[][] map1;
if (i0 != 0) {
if (map == null)
map = new int[MAX_INDEX_ZERO][][];
map1 = map[i0];
if (map1 == null)
map[i0] = map1 = new int[MAX_INDEX_ONE][];
} else
map1 = map10;
final int i1 = (index >>> 12) & 0xfff;
int[] map2 = map1[i1];
if (map2 == null) {
map1[i1] = map2 = new int[MAX_INDEX_TWO];
for (int i = 0; i < MAX_INDEX_TWO; ++i)
map2[i] = NOT_FOUND;
}
map2[index & 0xfff] = value;
return this;
}
|
ccd43e55-48a9-4596-b496-76cd01afa5b6
| 0
|
public int ID() {
return ID;
}
|
5e4a4974-f799-440f-9c0b-ce41c81e8534
| 8
|
@Override
public void actionPerformed(ActionEvent e)
{
Reference.lastActionMinute = new DateTime().getMinuteOfDay();
if (e.getSource() == overviewButton)
{
Reference.overPanel = new OverPanel();
Reference.saveAndChangePanel(Reference.overPanel, Reference.debtAccountPanel, Reference.DEBT_ACCOUNT);
}
else if (e.getSource() == bankButton)
Reference.saveAndChangePanel(Reference.bankAccountPanel, Reference.debtAccountPanel, Reference.DEBT_ACCOUNT);
else if (e.getSource() == billButton)
Reference.saveAndChangePanel(Reference.billAccountPanel, Reference.debtAccountPanel, Reference.DEBT_ACCOUNT);
else if (e.getSource() == logoutButton)
{
Reference.loginPanel = new LoginPanel();
Reference.ex.shutdownNow();
Reference.saveAndChangePanel(Reference.loginPanel, Reference.debtAccountPanel, Reference.DEBT_ACCOUNT);
}
else if (e.getSource() == saveButton)
Reference.saveAccounts(Reference.DEBTACCOUNT_DATABASE_FILE.toString(), Reference.DEBT_ACCOUNT);
else if (e.getSource() == newButton)
debtAccountTableModel.addNewAccount();
else if (e.getSource() == delButton)
{
if ( Reference.debtAccountTable.getSelectedRow() == -1)
{
JOptionPane
.showMessageDialog(
getRootPane(),
"No account selected: Please click on an account to highlight it and then click the Remove account button.",
"No account selected",
JOptionPane.INFORMATION_MESSAGE);
}else
debtAccountTableModel.removeAccount(Reference.debtAccountTable.getSelectedRow());
}
}
|
7c5dbff6-79ea-4b62-a7f1-4dee022d1d8a
| 8
|
public void registerBookJobs(BookMeta book, Minecart minecart, Player player) {
if (!enable) {
return;
}
if (minecartBookJobMap.get(minecart) != null){
ItemStack bookItemStack = new ItemStack(Material.BOOK_AND_QUILL, 1);
bookItemStack.setItemMeta(getBook(minecart));
minecart.getLocation().getWorld().dropItem(minecart.getLocation(), bookItemStack);
}
List<BookJob> bookJobs = new ArrayList<BookJob>();
List<String> pages = book.getPages();
for (int x = 0; x < pages.size(); x++) {
String[] lines = pages.get(x).split("\n");
for (int y = 0; y < lines.length; y++) {
if (!lines[y].contains("_")) {
continue;
}
String[] lineSplit = lines[y].split("_", 2);
String[] job = {"", ""};
if (lineSplit[1].contains(" ")) {
job = lineSplit[1].split(" ", 2);
} else {
job[0] = lineSplit[1];
}
System.out.println(job[1]);
if (job[1].contains("§")){
job[1] = job[1].split("§", 2)[0];
}
String bookJobName = lineSplit[0];
BookJob bj = new CraftBookJob(bookJobName, job[0], job[1]);
bookJobs.add(bj);
MCLogger.info("add Bookjob: " + bj.toString());
if (!player.hasPermission("minecartcontrol.bookjobs." + lineSplit[0].toLowerCase())) {
bj.setStatus(BookJobStatus.NO_PERMISSIONS);
}
}
}
minecartBookJobMap.put(minecart, bookJobs);
}
|
3ec168f1-e007-4e05-8b64-e346b1e24856
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddPatients.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddPatients.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddPatients.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddPatients.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AddPatients().setVisible(true);
}
});
}
|
ff783152-9fac-4012-ba7e-cfa556584bd9
| 1
|
public JSONObject getJSONObject(int index) throws JSONException {
Object object = this.get(index);
if (object instanceof JSONObject) {
return (JSONObject)object;
}
throw new JSONException("JSONArray[" + index +
"] is not a JSONObject.");
}
|
4fafb297-0c03-47af-967a-6cfdae0f5c93
| 4
|
private int transferFromLargestOverlap(int count, AreaObject[] array) {
int smallestWasted = Integer.MAX_VALUE;
int bestPick = -1;
for (int i = 0; i < count; i++) {
int wasted = areaWasted(mBounds, array[i].getBounds());
if (wasted <= smallestWasted) {
smallestWasted = wasted;
bestPick = i;
}
}
mBounds.union(array[bestPick].getBounds());
mStorage[mStorageCount++] = array[bestPick];
if (!mLeafNode) {
((AreaNode) array[bestPick]).mParent = this;
}
if (bestPick != --count) {
array[bestPick] = array[count];
}
array[count] = null;
return count;
}
|
86c3e818-fbf7-4c9b-8d55-adb85526720b
| 8
|
public boolean saveItemList(ArrayList<Package> packList, Connection con) {
int rowsInserted = 0;
int tal = 0;
String SQLString1 = "insert into pakker values(?,?,?)";
String SQLString2 = "select pakkeseq.nextval from dual";
String SQLString3 = "insert into pakkedetails values(?,?,?)";
PreparedStatement statement = null;
for (int j = 0; j < packList.size(); j++) {
Package ptest = packList.get(j);
if (ptest.getPackageNo() != 0) {
tal++;
}
}
try {
statement = con.prepareStatement(SQLString2);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
for (int j = tal; packList.size() > j; j++) {
Package pk = packList.get(j);
pk.setPakkeNo(rs.getInt(1));
}
}
statement = con.prepareStatement(SQLString1);
for (int j = tal; j < packList.size(); j++) {
Package pk = packList.get(j);
statement.setInt(1, pk.getPackageNo());
statement.setString(2, pk.getPackageName());
statement.setInt(3, pk.getPrice());
rowsInserted += statement.executeUpdate();
}
statement = con.prepareStatement(SQLString3);
for (int i = tal; i < packList.size(); i++) {
Package pk = packList.get(i);
for (int j = 0; j < pk.getItems().size(); j++) {
statement.setInt(2, pk.getItems().get(j).getItemNo());
statement.setInt(1, pk.getPackageNo());
statement.setInt(3, pk.getItems().get(j).getItemAmount());
rowsInserted += statement.executeUpdate();
}
}
} catch (Exception e) {
System.out.println("Fejl i OrdreMapper - SaveNewProject");
e.printStackTrace();
}
return rowsInserted == packList.size();
}
|
6faf277b-86e7-4bac-a19b-61fc5ecce7be
| 7
|
public static char getIndexPos(int index)
{
switch(index)
{
case 0: return '^';
case 1: return 'N';
case 2: return 'V';
case 3: return 'A';
case 4: return 'R';
case 5: return 'O';
case 6: return '.';
}
return ' ';
}
|
b0240693-5ca5-42ac-8b12-efd7e7359c28
| 7
|
@ScriptyCommand(name="map-create")
public static Map mapCreate(Object[] aArgs)
throws CommandException
{
{
Map<Object, Object> lMap = new HashMap<Object, Object>();
for(int i = 1; i < aArgs.length; i++)
{
if(aArgs[i] instanceof String)
{
lMap.put(aArgs[i], null);
}
else if(aArgs[i] instanceof Pair)
{
final Pair lPair = (Pair) aArgs[i];
lMap.put(lPair.getLeft(), lPair.getRight());
}
else if(aArgs[i] instanceof Map)
{
lMap.putAll((Map<?,?>) aArgs[i]);
}
else
{
Object lCulprit = aArgs[i];
throw new CommandException(String.format("Command '%s' expects zero or more string or pairs.\nArgument %d is of type '%s'.", aArgs[0], i, lCulprit==null?"null":lCulprit.getClass().getCanonicalName()));
}
}
return lMap;
}
}
|
2f896a03-6433-47e8-b3f4-abdf84af77aa
| 5
|
private void editarDatosUsuario() throws IOException, ServletException {
String nombre = request.getParameter("nombre");
String apellido = request.getParameter("apellido");
String username = request.getParameter("username");
String email = request.getParameter("mail");
if (apellido != null && nombre != null && username != null
&& email != null) {
Usuario user = new Usuario(nombre, apellido, email, username, "");
if (administrador.editarUsuario(user))
response.sendRedirect("index.html");
else
response.sendRedirect("UsersAdminServlet?editar=EditarDatos&error=error");
} else {
response.sendRedirect("UsersAdminServlet?editar=EditarDatos&error=faltan");
}
}
|
49060334-c4b7-4599-a59d-5a0e0c8da1ff
| 0
|
public void setResponseWrapper(ResponseWrapper responseWrapper) {
this.responseWrapper = responseWrapper;
}
|
0dec4907-9781-41c2-93ca-427edfa534c6
| 9
|
public static final int getMPEaterForJob(final int job) {
switch (job) {
case 210:
case 211:
case 212:
return 2100000;
case 220:
case 221:
case 222:
return 2200000;
case 230:
case 231:
case 232:
return 2300000;
}
return 2100000; // Default, in case GM
}
|
ec14f802-baf6-4641-bd98-a4bcfae70cd0
| 7
|
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case LEFT_RHINO_ID:
return isSetLeftRhinoId();
case LEFT_TITAN_ID:
return isSetLeftTitanId();
case RIGHT_RHINO_ID:
return isSetRightRhinoId();
case RIGHT_TITAN_ID:
return isSetRightTitanId();
case LABEL:
return isSetLabel();
case PROPERTIES:
return isSetProperties();
}
throw new IllegalStateException();
}
|
89d02f41-f3b2-459f-902a-1e579bf3e01e
| 5
|
public void paint(Graphics g) {
int startRow = 0;
int endRow = rows;
int startColumn = 0;
int endColumn = columns;
Rectangle clip = g.getClipRect();
if (clip == null) {
computeVisibleRect(visibleRect);
clip = visibleRect;
}
g.setColor(defaultAttributes.getBackground());
g.fillRect(clip.x, clip.y, clip.width, clip.height);
startRow = clip.y / charHeight;
endRow = Math.min(rows, startRow + (clip.height + charHeight - 1) / charHeight + 1);
startColumn = clip.x / charWidth;
endColumn = Math.min(columns, startColumn + (clip.width + charWidth - 1) / charWidth + 1);
for (int i = startRow; i < endRow; i++) {
int start = startColumn;
TextAttributes currentAttributes = defaultAttributes;
for (int j = startColumn; j < endColumn; j++) {
if (currentAttributes != attributes[i][j]) {
if (start != j)
paintRun(g, i, start, j, currentAttributes);
start = j;
currentAttributes = attributes[i][j];
}
}
paintRun(g, i, start, endColumn, currentAttributes);
}
paintCursor(g);
}
|
9f75bb16-0b6b-4f2c-b262-4d6277cd57bb
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PlayerNames.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PlayerNames.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PlayerNames.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PlayerNames.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PlayerNames().setVisible(true);
}
});
}
|
a835f7d6-c3f9-4be7-83b5-101318c343e9
| 0
|
public void setLastLargest() {
lastLargest = largest;
}
|
def2a9d9-464b-4acf-9ced-8072e16dc8c1
| 8
|
public static void classClass(){
Olive o = new Olive(OliveName.PICHOLINE, OliveColor.GREEN);
// using Class Class
Class<?> c = o.getClass();
System.out.println(c);
System.out.println(c.getName());
System.out.println(c.getSimpleName());
ArrayList<Integer> aa = new ArrayList<>();
Class<?> bb = aa.getClass();
System.out.println(bb);
System.out.println(bb.getName());
System.out.println(bb.getSimpleName());
// instantiating classes dynamically
Constructor<?>[] constructors = c.getConstructors();
System.out.println("Number of constructors " + constructors.length);
Constructor<?> con = constructors[0];
Object obj = null;
try {
obj = con.newInstance(OliveName.PICHOLINE, OliveColor.GREEN);
System.out.println(obj);
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
// Navigating inheritance trees
Object oo = new Ligurio();
Class<?> cc = oo.getClass();
System.out.println("Class name: " + c.getName());
Class<?> sup = cc.getSuperclass();
System.out.println("super name: " + sup.getName());
Class<?> top = sup.getSuperclass();
System.out.println("top name: " + top.getName());
Package p = cc.getPackage();
System.out.println("package: " + p.getName());
}
|
e89a533b-c26b-4da0-8081-a920e66e4484
| 7
|
private static void parseDriverNode(Node node) {
String jdbcDriver = null, jdbcUrl = null, name = null;
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node childNode = nodeList.item(i);
if (childNode.getNodeType() != Node.ELEMENT_NODE) {
continue;
}
if ("driverClass".equals(childNode.getNodeName())) {
jdbcDriver = parseElementNodeValue(childNode);
} else if ("url".equals(childNode.getNodeName())) {
jdbcUrl = parseElementNodeValue(childNode);
} else if ("name".equals(childNode.getNodeName())) {
name = parseElementNodeValue(childNode);
}
}
if (StringUtil.isNotEmpty(jdbcDriver) && StringUtil.isNotEmpty(jdbcUrl)) {
JdbcDrivers.jdbcDriversMap.put(jdbcDriver, new DriverInfo(name, jdbcDriver, jdbcUrl));
}
}
|
f95d1a31-0fd7-45e8-8189-7aaa7d594254
| 2
|
public void mouseReleased(int mouseX, int mouseY) {
//Iterate through each object
for (ImageButton obj : screenObjects) {
obj.mouseReleased(mouseX, mouseY);
}
if(loopMenuOpen){
loopMenu.mouseRelease(mouseX, mouseY);
}
}
|
4adc1ba4-11a8-4372-8ba3-89731bcd5166
| 4
|
public Projectile createProjectile(float direction, Position pos){
if (timeNow()-lastTimeFired>rateOfFire
&& !isReloading()){
if (ammunitionInMagazine==0){
return null;
} else {
ammunitionInMagazine-=1;
lastTimeFired=timeNow();
boolean visible = (getType() == Type.GUN) ? true : false;
return new Projectile(damage, projectileSpeed, range, direction, pos, visible);
}
} else {
return null;
}
}
|
755f63c3-d23c-4d9f-ae35-73808f9aa85e
| 1
|
public void printError(int err)
{
if(err==-1) System.out.println("File not found");
}
|
d55d288f-1333-4fc2-9e0f-b8d9eb7c8bc1
| 0
|
@Override
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
log.debug("before method invoke...");
Object result = arg1.invoke(delegate, arg2);
log.debug("after method invoke...");
return result;
}
|
03e91584-98d1-448f-9b4e-6650f2521453
| 5
|
@Override
public String getPinyin() {
if(getInput().replaceAll("\\d", "").equals(getInput()) || getInput().replaceAll("\\d", "").isEmpty())
return getInput();//just return input if the input is all numbers or no numbers
String unprocessedInput = getInput();
// split up each syllable and then put the string back together
String output = "";
for(String letters : getInput().split("\\d")){
try{
output += new Syllable(unprocessedInput.substring(unprocessedInput.indexOf(letters), unprocessedInput.indexOf(letters) + letters.length() + 1).toLowerCase());
}catch(StringIndexOutOfBoundsException ex){
output += letters;// no pinyin to convert
}
unprocessedInput = unprocessedInput.replace(letters, "");
}
// capitalize first letter if it is capitalized in the input
String firstLetter = getInput().substring(0, 1);
if(firstLetter.toUpperCase().equals(firstLetter))
output = output.substring(0, 1).toUpperCase() + output.substring(1, output.length());
return output;
}
|
77fdef39-0f5a-4ef1-834c-c56c045e5aca
| 6
|
public static List<List<Integer>> subsetsWithDup(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(num, 0, num.length);
res.add(new ArrayList<Integer>());
if (null == num || 0 == num.length) {
return res;
}
int j = 0;
int last = 0;
for (int i = 0; i < num.length; i++) {
if (i != 0 && num[i] == num[i - 1]) {
j = last;
} else {
j = 0;
}
last = res.size();
for (; j < last; j++) {
ArrayList<Integer> t = (ArrayList<Integer>) res.get(j);
t = (ArrayList<Integer>) t.clone();
t.add(num[i]);
res.add(t);
}
}
return res;
}
|
eccda05a-4c39-4a45-9a9e-8703acfc8bfd
| 5
|
public static ArrayList<Member> searchMemberByCity(String city){
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<Member> members = new ArrayList<Member>();
try {
PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM Addresses a, Members m WHERE a.address_id = m.address_id AND a.city LIKE ?");
stmnt.setString(1, city + "%");
ResultSet res;
res = stmnt.executeQuery();
while(res.next()){
adress = AdressDAO.getAdressByID(res.getInt("address_id"));
member = new Member(res.getString("name"),res.getString("first_name"),res.getString("phone_num"),adress,res.getInt("member_id"));
members.add(member);
}
}
catch(SQLException e){
e.printStackTrace();
}
return members;
}
|
9a332dd7-6d35-475a-b968-4965be7fa3a2
| 8
|
@DataProvider
public Collection getChartResult(Map param) throws Exception {
// sql的内容为根据时间的分组,然后分别计算出当月的利润率和从开户到当月截至的利润率
/******
* SQL********* select dm, round(profit/(SELECT profit_ FROM
* accounttransactionsinfo WHERE TYPE_='balance' and SIZE_ in
* ('AddFunds') order by OPENTIME_,TICKET_ limit 1),4) as profitRate,
* round(total/(SELECT profit_ FROM accounttransactionsinfo WHERE
* TYPE_='balance' and SIZE_ in ('AddFunds') order by OPENTIME_,TICKET_
* limit 1),4) as totalRate FROM ( select
* DATE_FORMAT(t1.OPENTIME_,'%Y%m') as dm, round(sum(t1.profit_),4) as
* profit , (select round(sum(t2.PROFIT_),4) from
* accounttransactionsinfo t2 where
* DATE_FORMAT(t2.OPENTIME_,'%Y%m')<=DATE_FORMAT(t1.OPENTIME_,'%Y%m')
* and t2.TYPE_ in ('buy','sell')) as total FROM accounttransactionsinfo
* t1 where t1.TYPE_ in ('buy','sell') group by
* DATE_FORMAT(t1.OPENTIME_,'%Y%m') ) a
*/
String account = (String) param.get("account");
Boolean isRolling = (Boolean) param.get("isRolling");
String sqlFunds = "select * from accountinfo where 1=1";
String sqlDespoit = "SELECT sum(profit_) as profit_ FROM accounttransactionsinfo \n"
+ "WHERE 1=1";
if (StringUtils.isNotEmpty(account)) {
sqlDespoit += " and ACCOUNT_ID_='" + account + "'";
sqlFunds += " and ACCOUNT_='" + account + "'";
}
List<AccountInfo> fundList = this.jdbcTemplate.query(sqlFunds,
new AccountInfoRowMapper());
String funds = "";
if (fundList.size() > 0) {
String[] fund = fundList.get(0).getBalanceSize().split("\\|");
for(int i=0;i<fund.length;i++){
funds+="'"+fund[i]+"'";
if(i+1<fund.length){
funds+=",";
}
}
}
sqlDespoit += " AND TYPE_='balance' and SIZE_ in (" + funds + ")\n"
+ "order by OPENTIME_,TICKET_ limit 1";
String sql = "select \n"
+ "dm,\n"
+ "round(profit/("
+ sqlDespoit
+ "),4) as profitRate,\n"
+ "round(total/("
+ sqlDespoit
+ "),4) as totalRate\n"
+ "FROM (\n"
+ "select DATE_FORMAT(t1.OPENTIME_,'%Y-%m') as dm,\n"
+ "round(sum(COALESCE(t1.profit_,0)+COALESCE(t1.COMMISSION_,0)+COALESCE(t1.SWAP_,0)),4) as profit ,\n"
+ "(select round(sum(COALESCE(t2.PROFIT_,0)+COALESCE(t2.COMMISSION_,0)+COALESCE(t2.SWAP_,0)),4) from accounttransactionsinfo t2 where t2.ACCOUNT_ID_='"
+ account
+ "' AND DATE_FORMAT(t2.OPENTIME_,'%Y%m')<=DATE_FORMAT(t1.OPENTIME_,'%Y%m') and t2.TYPE_ in ('buy','sell')) as total\n"
+ "FROM accounttransactionsinfo t1\n"
+ "where t1.TYPE_ in ('buy','sell') AND t1.ACCOUNT_ID_='"
+ account + "'\n"
+ "group by DATE_FORMAT(t1.OPENTIME_,'%Y%m')\n" + ") a";
if (isRolling != null && isRolling) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
String cudm = String.valueOf(year)
+ "-"
+ (month < 10 ? "0" + String.valueOf(month) : String
.valueOf(month));
cal.add(Calendar.YEAR, -1);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH) + 1;
String lastdm = String.valueOf(year)
+ "-"
+ (month < 10 ? "0" + String.valueOf(month) : String
.valueOf(month));
sql += "\n where dm>='" + lastdm + "' and dm<='" + cudm + "'";
}
return jdbcTemplate.queryForList(sql);
}
|
ad6e9aaf-dfc2-4f97-8c94-7c1b44d68343
| 4
|
public void javaToNative (Object object, TransferData transferData) {
if (!checkMyType(object) || !isSupportedType(transferData)) {
DND.error(DND.ERROR_INVALID_DATA);
}
MyType[] myTypes = (MyType[]) object;
try {
// write data to a byte array and then ask super to convert to pMedium
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream writeOut = new DataOutputStream(out);
for (int i = 0, length = myTypes.length; i < length; i++){
byte[] buffer = myTypes[i].firstName.getBytes();
writeOut.writeInt(buffer.length);
writeOut.write(buffer);
buffer = myTypes[i].firstName.getBytes();
writeOut.writeInt(buffer.length);
writeOut.write(buffer);
}
byte[] buffer = out.toByteArray();
writeOut.close();
super.javaToNative(buffer, transferData);
} catch (IOException e) {
}
}
|
5f307ca1-2754-4832-8621-9b08b2bb985b
| 6
|
public String download(PeerInfo peerInfo, String filename) throws PeerNotConnectedException, TrackingServerNotConnectedException, FileNotFoundException {
if(peerInfo == null) {
peerInfo = getPeerInfoFromPeerSelectionAlgorithm(filename);
}
if(peerInfo == null) {
throw new PeerNotConnectedException("Cannot decide peerInfo for file : " + filename);
}
PeerRMIInterface peerRMIInterfaceImplObject = RMIUtil.getPeerRMIInterfaceImplObject(peerInfo.getIp(), peerInfo.getPort());
if(peerRMIInterfaceImplObject == null) {
throw new PeerNotConnectedException("Cannot connect to peer : " + peerInfo );
}
FileMemoryObject downloadedFileMemoryObject = null;
PeerClient.printOnShell("Calling RMI call for download on " + peerInfo);
try {
downloadedFileMemoryObject = peerRMIInterfaceImplObject.download(Peer.getCurrentPeerInfo(), filename);
} catch (RemoteException e) {
throw new PeerNotConnectedException("Peer not connected");
}
String newFileName = downloadedFileMemoryObject.getFilename();
String writeFileCompletePathName = FileStore.getInstance().getFileStoreDirectory() + newFileName;
FileMemoryObject fileObject = new FileMemoryObject(writeFileCompletePathName, downloadedFileMemoryObject.getBytecontents());
PeerClient.printOnShell("Writing " + writeFileCompletePathName + " to local disk");
try {
FileIOUtil.writeToDisk(fileObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
PeerClient.printOnShell("Adding the filename in tracking server");
// Add the new file to file store as well as the tracking server.
FileStore.getInstance().addFilename(newFileName);
try {
Peer.getTrackingServerRMIObjectHandler().updateFiles(Peer.getCurrentPeerInfo(), FileStore.getInstance().getFilenames());
} catch (RemoteException e) {
throw new TrackingServerNotConnectedException("Tracking server not connected.");
}
PeerClient.printOnShell("Done Download");
return writeFileCompletePathName;
}
|
a7a867eb-4f98-4011-8f14-0802bc66202c
| 5
|
public void sizeline() {
int dumy = 0;
MyDrawing buffer;
if(selectedDrawings.size() != 0){
for(int i=0;i<selectedDrawings.size();i++){
selectedDrawings.elementAt(i).move(selectedDrawings.elementAt(i).getX(), 400 - selectedDrawings.elementAt(i).getH());
}
for(int i=0;i<selectedDrawings.size();i++){
for(int j=i+1;j<selectedDrawings.size();j++){
if(selectedDrawings.elementAt(i).getH() < selectedDrawings.elementAt(j).getH()){
buffer = selectedDrawings.elementAt(i);
selectedDrawings.removeElementAt(i);
selectedDrawings.insertElementAt(selectedDrawings.elementAt(j-1), i);
selectedDrawings.removeElementAt(j);
selectedDrawings.insertElementAt(buffer, j);
dumy = selectedDrawings.elementAt(i).getX();
selectedDrawings.elementAt(i).setX(selectedDrawings.elementAt(j).getX());
selectedDrawings.elementAt(j).setX(dumy);
}
}
}
}
canvas.repaint();
}
|
a1819afa-52a5-4985-8d2d-75e6303814a4
| 4
|
void paintDirect(CPRect srcRect, CPRect dstRect, byte[] brush, int w, int alpha, int color1) {
int[] opacityData = opacityBuffer.data;
int by = srcRect.top;
for (int j = dstRect.top; j < dstRect.bottom; j++, by++) {
int srcOffset = srcRect.left + by * w;
int dstOffset = dstRect.left + j * width;
for (int i = dstRect.left; i < dstRect.right; i++, srcOffset++, dstOffset++) {
int alpha1 = (brush[srcOffset] & 0xff) * alpha / 255;
if (alpha1 <= 0) {
continue;
}
int color2 = opacityData[dstOffset];
int alpha2 = (color2 >>> 24);
int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;
if (newAlpha > 0) {
int realAlpha = alpha1 * 255 / newAlpha;
int invAlpha = 255 - realAlpha;
// The usual alpha blending formula C = A * alpha + B * (1 - alpha)
// has to rewritten in the form C = A + (1 - alpha) * B - (1 - alpha) *A
// that way the rounding up errors won't cause problems
int newColor = newAlpha << 24
| ((color1 >>> 16 & 0xff) + (((color2 >>> 16 & 0xff) * invAlpha - (color1 >>> 16 & 0xff)
* invAlpha) / 255)) << 16
| ((color1 >>> 8 & 0xff) + (((color2 >>> 8 & 0xff) * invAlpha - (color1 >>> 8 & 0xff)
* invAlpha) / 255)) << 8
| ((color1 & 0xff) + (((color2 & 0xff) * invAlpha - (color1 & 0xff) * invAlpha) / 255));
opacityData[dstOffset] = newColor;
}
}
}
}
|
9553b7e5-c915-4afe-b29a-e6d03199cab6
| 5
|
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
SoundManager.playSound(SoundManager.SoundType.BUTTON);
}
//TODO Program functionality of buttons?
if(e.getSource() == home) {
mathGame.showMenu(MathGame.Menu.MAINMENU); // Return to the main menu
// choosefraction();
// startgame();
} else if(e.getSource() == host) {
mathGame.showMenu(MathGame.Menu.HOSTMENU);
// startgame();
} else if(e.getSource() == join) {
// choosedecimal();
// startgame();
}
else if(e.getSource() == refresh) {
refresh();
}
}
|
ce334a48-df47-4857-b742-89a22f5c9a04
| 3
|
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] S) {
result = new ArrayList<ArrayList<Integer>>();
result.add(new ArrayList<Integer>());
Arrays.sort(S);
if ((S.length) == 0)
return result;
put(S[0], 1);
Arrays.sort(S);
int range = result.size() - 1;
for (int i = 1; i < S.length; i++) {
if (S[i] != S[i - 1])
range = result.size();
put(S[i], range);
}
return result;
}
|
cb96b41c-ca22-40b4-8ae6-a3bd0c1e8c8e
| 7
|
@Override
public boolean equals(Object o) {
if (!(o instanceof Matrix)) {
return false; // o is not a matrix
}
Matrix a = (Matrix) o;
if ((!this.isJagged && !a.isJagged) && this.sameOrder(a)) {
for (int row = 0; row < this.rowCount; row++) {
for (int column = 0; column < this.columnCount; column++) {
if (a.elements[row][column] != this.elements[row][column]) {
return false;
}
}
}
return true;
}
return false;
}
|
1b256753-3e1a-458e-9706-43f6d51aba53
| 6
|
public static boolean line_box_xywh(double lx0, double ly0, double lx1, double ly1, double rx0, double ry0, double rWidth, double rHeight) {
int out1, out2;
if ((out2 = outcode(lx1, ly1, rx0, ry0, rWidth, rHeight)) == 0) {
return true;
}
while ((out1 = outcode(lx0, ly0, rx0, ry0, rWidth, rHeight)) != 0) {
if ((out1 & out2) != 0) {
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
double x = rx0;
if ((out1 & OUT_RIGHT) != 0) {
x += rWidth;
}
ly0 = ly0 + (x - lx0) * (ly1 - ly0) / (lx1 - lx0);
lx0 = x;
} else {
double y = ry0;
if ((out1 & OUT_BOTTOM) != 0) {
y += rHeight;
}
lx0 = lx0 + (y - ly0) * (lx1 - lx0) / (ly1 - ly0);
ly0 = y;
}
}
return true;
}
|
d36680d9-0552-4467-93b6-769c3830a4a7
| 6
|
public Object[] toArrays() {
Object objs[] = new Object[count];
int n = 0;
if ((flags&InputFlags.TA_IN_PRICE_OPEN)!=0) {
objs[n++] = getO();
}
if ((flags&InputFlags.TA_IN_PRICE_HIGH)!=0) {
objs[n++] = getH();
}
if ((flags&InputFlags.TA_IN_PRICE_LOW)!=0) {
objs[n++] = getL();
}
if ((flags&InputFlags.TA_IN_PRICE_CLOSE)!=0) {
objs[n++] = getC();
}
if ((flags&InputFlags.TA_IN_PRICE_VOLUME)!=0) {
objs[n++] = getV();
}
if ((flags&InputFlags.TA_IN_PRICE_OPENINTEREST)!=0) {
objs[n++] = getI();
}
return objs;
}
|
3b32be8b-53f8-4618-9cf3-a2857a14c01d
| 9
|
private static String toNumber(String s) {
String result = "";
for (int i =0; i < s.length(); i ++){
if("ABC".indexOf("" + s.charAt(i)) > -1)
result += "" + 2;
if("DEF".indexOf("" + s.charAt(i)) > -1)
result += "" + 3;
if("GHI".indexOf("" + s.charAt(i)) > -1)
result += "" + 4;
if("JKL".indexOf("" + s.charAt(i)) > -1)
result += "" + 5;
if("MNO".indexOf("" + s.charAt(i)) > -1)
result += "" + 6;
if("PQRS".indexOf("" + s.charAt(i)) > -1)
result += "" + 7;
if("TUV".indexOf("" + s.charAt(i)) > -1)
result += "" + 8;
if("WXYZ".indexOf("" + s.charAt(i)) > -1)
result += "" + 9;
}
return result;
}
|
a15fe5f0-7ab7-41ce-ad1a-4fff64b16d89
| 5
|
public ButtonPanel() {
super();
listeners = new EventListenerList();
setLayout(new FlowLayout(FlowLayout.RIGHT));
install = new JButton(Localization.translate("ButtonPanel.install"));
update = new JButton(Localization.translate("ButtonPanel.update"));
uninstall = new JButton(Localization.translate("ButtonPanel.uninstall"));
mods = new JButton(Localization.translate("ButtonPanel.mods"));
config = new JButton(Localization.translate("ButtonPanel.config"));
add(install);
add(update);
add(uninstall);
add(new JSeparator(SwingConstants.VERTICAL));
add(mods);
add(config);
install.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (final ButtonListener l : listeners
.getListeners(ButtonListener.class)) {
l.onInstall();
}
}
});
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (final ButtonListener l : listeners
.getListeners(ButtonListener.class)) {
l.onUpdate();
}
}
});
uninstall.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (final ButtonListener l : listeners
.getListeners(ButtonListener.class)) {
l.onUninstall();
}
}
});
mods.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (final ButtonListener l : listeners
.getListeners(ButtonListener.class)) {
l.onMods();
}
}
});
config.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
for (final ButtonListener l : listeners
.getListeners(ButtonListener.class)) {
l.onConfig();
}
}
});
}
|
5ada1df1-ac73-4368-9fd9-3753a69c8eac
| 7
|
@SuppressWarnings("unchecked")
private void _unload(PythonPlugin pl) throws Exception {
PluginManager man = plugin.getServer().getPluginManager();
if (!(man instanceof SimplePluginManager)) {
throw new ClassCastException("cannot unload plugins from a non-SimplePluginManager");
}
SimplePluginManager pm = (SimplePluginManager) man;
pm.disablePlugin(pl);
HandlerList.unregisterAll(pl);
for (Permission perm : pl.getDescription().getPermissions()) {
pm.removePermission(perm);
}
SimpleCommandMap cmdMap = (SimpleCommandMap) Reflection.getPrivateValue(pm, "commandMap");
Map<String, Command> knownCommands = (Map<String, Command>) Reflection.getPrivateValue(cmdMap, "knownCommands");
if (pl.getDescription().getCommands() != null) {
for (String command : pl.getDescription().getCommands().keySet()) {
Command cmd = cmdMap.getCommand(command);
for (String alias : cmd.getAliases()) {
knownCommands.remove(alias);
}
for (String key : new ArrayList<>(knownCommands.keySet())) {
if (knownCommands.get(key) == cmd) {
knownCommands.remove(key);
}
}
cmd.unregister(cmdMap);
}
}
List<Plugin> pluginList = (List<Plugin>) Reflection.getPrivateValue(pm, "plugins");
pluginList.remove(pl);
Map<String, Plugin> lookupNames = (Map<String, Plugin>) Reflection.getPrivateValue(pm, "lookupNames");
lookupNames.remove(pl.getName());
}
|
c47f130c-acd3-45e0-9065-4b9e32aa33d1
| 6
|
static void printAnalyzerResult(MethodNode method, Analyzer a,
final PrintWriter pw) {
Frame[] frames = a.getFrames();
TraceMethodVisitor mv = new TraceMethodVisitor();
pw.println(method.name + method.desc);
for (int j = 0; j < method.instructions.size(); ++j) {
method.instructions.get(j).accept(mv);
StringBuffer s = new StringBuffer();
Frame f = frames[j];
if (f == null) {
s.append('?');
} else {
for (int k = 0; k < f.getLocals(); ++k) {
s.append(getShortName(f.getLocal(k).toString()))
.append(' ');
}
s.append(" : ");
for (int k = 0; k < f.getStackSize(); ++k) {
s.append(getShortName(f.getStack(k).toString()))
.append(' ');
}
}
while (s.length() < method.maxStack + method.maxLocals + 1) {
s.append(' ');
}
pw.print(Integer.toString(j + 100000).substring(1));
pw.print(" " + s + " : " + mv.buf); // mv.text.get(j));
}
for (int j = 0; j < method.tryCatchBlocks.size(); ++j) {
((TryCatchBlockNode) method.tryCatchBlocks.get(j)).accept(mv);
pw.print(" " + mv.buf);
}
pw.println();
}
|
6865ebe9-395f-477b-8e5c-a17f0d90e99c
| 5
|
public String evaluate(String in){
in = in.trim();
String command = in.substring(0,in.indexOf(" "));
String args = in.substring(in.indexOf(" ")+1);
if(command.equals("help"))
man.get("help");
if(command.equals("save")){
if(man.save())return "Saved successfully!";
else return "Saving failed!";
}if(command.equals("load")){
if(man.load())return "Saved successfully!";
else return "Saving failed!";
}
return "";
}
|
c5fa102c-3835-4c5d-8980-d49dd29f180b
| 6
|
public void parseWrite(StringBuilder code, ApplySentence s, Environment e) {
List<Value> args = s.value;
boolean gr6taken = willPushRegister(6);
takeRegister(code, 6);
boolean gr7taken = willPushRegister(7);
takeRegister(code, 7);
code.append(spc + " LAD GR6, 0" + "\n");
code.append(spc + " LAD GR7, WRBUFFER" + "\n");
for (Value arg : args) {
Type t = arg.type;
if (arg instanceof VariableAssign) {
t = e.find(arg.value).val.type;
}
if (t instanceof ArrayType && t.type.equals("char")) {
ArrayType ta = (ArrayType) t;
boolean sizeRegT = willPushRegister(1);
int sizeReg = takeRegister(code, 1);
code.append(spc + " LAD GR" + sizeReg + ", "
+ (ta.max - ta.min + 1) + "\n");
boolean writeRegT = willPushRegister(2);
int writeReg = takeRegister(code, 2);
int valueReg = parseValue(code, arg, e);
code.append(spc + " LD GR" + writeReg + ", GR" + valueReg
+ "\n");
freeRegister(code);
code.append(spc + " CALL WRTSTR" + "\n");
// if(writeRegT)freeRegister(code);
// if(sizeRegT) freeRegister(code);
freeRegister(code, 2);
freeRegister(code, 1);
} else if (t.type.equals("char")) {
boolean writeRegT = willPushRegister(2);
int writeReg = takeRegister(code, 2);
int valueReg = parseValue(code, arg, e);
code.append(spc + " LD GR" + writeReg + ", GR" + valueReg
+ "\n");
freeRegister(code);
code.append(spc + " CALL WRTCH" + "\n");
freeRegister(code, 2);
} else if (t.type.equals("integer")) {
boolean writeRegT = willPushRegister(2);
int writeReg = takeRegister(code, 2);
int valueReg = parseValue(code, arg, e);
code.append(spc + " LD GR" + writeReg + ", GR" + valueReg
+ "\n");
freeRegister(code);
code.append(spc + " CALL WRTINT" + "\n");
freeRegister(code, 2);
} else {
throw new RuntimeException("unhandled format");
}
}
// code.append(spc + " CALL WRTLN" + "\n");
code.append(spc + " ST GR6, WRBUFLEN" + "\n");
code.append(spc + " OUT WRBUFFER, WRBUFLEN" + "\n");
freeRegister(code, 7);
freeRegister(code, 6);
}
|
348b57b8-1ea8-413a-9eb1-76c88ecd0fae
| 7
|
public Matrix subMatrix(int startRowIndex, int endRowIndex, int startColIndex, int endColIndex) {
if (startRowIndex < 0 || endRowIndex > getNumRows()
|| startColIndex < 0 || endColIndex > getNumCols()) {
throw new IndexOutOfBoundsException("Sub-matrix index out of range");
}
Matrix subMatrix = new Matrix();
for (int i = startColIndex; i < endColIndex; i++) {
ColumnAttributes columnAttributes = getColumnAttributes(i);
subMatrix.addColumn(new ColumnAttributes(columnAttributes));
}
for (int i = startRowIndex; i < endRowIndex; i++) {
List<Double> row = getRow(i);
List<Double> newRow = new ArrayList<Double>();
for (int j = startColIndex; j < endColIndex; j++) {
newRow.add(row.get(j));
}
subMatrix.addRow(newRow);
}
return subMatrix;
}
|
118fb4bd-1a47-4a59-ad85-79231ba636f6
| 8
|
private static void destroy_Launcher(War war) {
LauncherDestroyer destroyer;
EnemyLauncher user_launcher = null;
String launcherId;
int destroyerId = 0;
if (war.getWarLauncherDestroyer().isEmpty()) {
System.out.println("\tNo Destroyer available to hit the launcher");
} else {
System.out.println("Enter destroyer id: ");
for (LauncherDestroyer launcher_destroyer : war
.getWarLauncherDestroyer()) {
System.out.print("\t" + launcher_destroyer.getLauncherType()
+ " id: " + launcher_destroyer.getLauncherId());
}
System.out.println("\n Your selection: ");
while (true) { // check user input
destroyerId = scanner.nextInt();
destroyer = war.findDestroyerById(destroyerId);
if (destroyer != null)
break;
else
System.out.println("Id not found, enter agian ");
}
System.out.println("Choose launcher to destroy");
for (EnemyLauncher launcher : war.getLaunchers()) {
if (launcher.alive())
System.out.print("\t" + launcher.getLauncherId());
}
System.out.println("\n Your selection: ");
while (true) { // check user input
launcherId = scanner.next();
user_launcher = war.findLauncherById(launcherId);
if (user_launcher != null)
break;
else
System.out.println("Id not found, enter agian ");
}
destroyer.addLauncherToDestroy(user_launcher, ""
+ War.DESTROYER_MISSILE_DELAY_TIME);
}
}
|
2f930a0e-2d91-4406-85fb-18d5255a8af1
| 6
|
private void creerTblOffre() {
if (!m_offInit) {
try (BufferedReader br = new BufferedReader(new FileReader(Constant.m_offreList))) {
String sCurrentLine;
m_tblEmplois.clear();
String[] results;
// int i = 0;
while ((sCurrentLine = br.readLine()) != null) {
// System.out.println("22222#####" + sCurrentLine + "\t#####line from offrelist.txt (NoyauOffre)");
// results = sCurrentLine.split(m_itemDelim, -1);
results = sCurrentLine.split(Constant.m_itemDelim, -1);
// Stage has experience -1
if ("-1".equals(results[2])) {
//System.out.println(i + "ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss");
Stage tmpStage = new Stage(sCurrentLine);
String tmpRegStr = tmpStage.getReg().getRegnom();
ArrayList<Stage> lstStage = m_tblStages.get(tmpRegStr);
if (lstStage == null) {
m_tblStages.put(tmpRegStr, lstStage = new ArrayList<Stage>());
}
// System.out.println(tmpStage.toString() + "!!!!!!!!!before add emploi (NoyauOffre)");
lstStage.add(tmpStage);
tmpStage.printOut();
// System.out.println("lstStage size+++++:" + lstStage.size() + " (NoyauOffre)");
// System.out.println("tblStages size+++++:" + m_tblStages.size() + " (NoyauOffre)");
} else {
//System.out.println(i + "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee" + results[2]);
Emploi tmpEmploi = new Emploi(sCurrentLine);
String tmpRegStr = tmpEmploi.getReg().getRegnom();
ArrayList<Emploi> lstEmploi = m_tblEmplois.get(tmpRegStr);
if (lstEmploi == null) {
m_tblEmplois.put(tmpRegStr, lstEmploi = new ArrayList<Emploi>());
}
// System.out.println(tmpEmploi.toString() + "!!!!!!!!!before add emploi (NoyauOffre)");
lstEmploi.add(tmpEmploi);
tmpEmploi.printOut();
// System.out.println("lstEmploi size+++++:" + lstEmploi.size() + " (NoyauOffre)");
// System.out.println("tblEmplois size+++++:" + m_tblEmplois.size() + " (NoyauOffre)");
}
// i++;
}
// System.out.println("tblEmplois size:" + m_tblEmplois.size() + " (NoyauOffre)");
// System.out.println("tblStages size:" + m_tblStages.size() + " (NoyauOffre)");
//System.out.println("regVec size:" + m_regVecNom.size() + " (NoyauOffre)");
m_offInit = true;
} catch (IOException ee) {
ee.printStackTrace();
}
// System.out.println("region map emplois:" + m_tblEmplois + " (NoyauOffre)");
// System.out.println("region map stages:" + m_tblStages + m_tblStages.get("Corse") + " (NoyauOffre)");
}
}
|
636a1c0f-0e26-4f24-9017-19d46ee446d8
| 2
|
public static void setSpeed(int x)
{
if(x < 1 || x > 10)
return;
crawlOff = false;
crawlSpeed = 0.05 / x;
}
|
902e6dd2-5009-4c2a-8505-6c16b000b046
| 2
|
*
* @return <tt>true</tt> iff any ground formula instances exist having the given predicate, and
* the given term in the given argument position
*
* @throws IOException if a data communication error occurs
* @throws CycApiException if the api request results in a cyc server error
*/
public boolean hasSomePredicateUsingTerm(CycConstant predicate,
CycFort term,
Integer argumentPosition,
CycObject mt)
throws IOException, CycApiException {
String command;
if (makeELMt(mt).equals(inferencePSC) || makeELMt(mt).equals(everythingPSC)) {
command = makeSubLStmt(SOME_PRED_VALUE_IN_ANY_MT, term, predicate, argumentPosition);
} else {
command = makeSubLStmt(SOME_PRED_VALUE_IN_RELEVANT_MTS, term, predicate,
makeELMt(mt), argumentPosition);
}
//this.traceOn();
return converseBoolean(command);
}
|
39618037-6c0e-4929-bac3-361ee191aedc
| 3
|
public void newGame()
{
/** Choose mode - Player vs Player or Player vs Computer */
System.out.println("Press Y to play against the AI. \n Alternatively, press any other key to continue with 2 players. \n Confirm your choice by pressing Enter");
Scanner sc = new Scanner(System.in);
String yn = sc.nextLine().toUpperCase(); // Save entire input to String yn
int nb = 2; // nb stores the number of human players - 2 by default
switch(yn) {
case "Y": // If user enters 'Y'
player[1] = new ArtificialPlayer(); // Create a new AI Player
player[1].addFleet(); // Add the AI's ships
nb = 1;
break;
}
/** Instantiate 2 Players and their ships */
for (int i = 0; i<nb; i++){
Game.clearConsole(); // Clear the screen
System.out.print("Player "+(i+1)+", enter your name: "); // Player 1/2 - enter your name
player[i]= new Player(sc.next());
if(nb == 2) // If there are two human players
System.out.println("Captain " +player[i].name+", it is time to deploy your fleet! Press Enter to continue\n");
player[i].addFleet(); // Call addFleet to start placing boats
}
System.out.print(Game.display(player[1].myGrid.displayOwnGrid())); // Show own grid
/** Create "opponent" versions of each grid to display hits and misses only */
player[0].opponentGrid=player[1].myGrid;
player[1].opponentGrid=player[0].myGrid;
/** Start the game by calling the playGame method */
playing = true;
this.playGame();
}
|
b88ba6a1-f9b3-4d62-9995-f8bb0ea54aac
| 5
|
public static void loadConfig() {
// set standard values
config.put("DBURL", "jdbc:mysql://localhost:55555/server");
config.put("DBUSER", "root");
config.put("DBPW", "root");
config.put("PORT", "1234");
// overwrite them with the values from the config file
try (BufferedReader br = new BufferedReader(
new FileReader("config.txt"))) {
String line = br.readLine();
while (line != null) {
String[] in = line.split("=");
config.put(in[0], in[1]);
line = br.readLine();
}
} catch (FileNotFoundException e) {
// write a config file with standard values when no conifg file
// exists
File file = new File("config.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
for (Map.Entry<String, String> entry : config.entrySet()) {
writer.write(entry.getKey() + "=" + entry.getValue());
writer.write(System.getProperty("line.separator"));
writer.flush();
}
writer.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
446fe9a2-4854-4934-98bb-15bf725fb009
| 8
|
private void createSpecies(int num,int inputs,int outputs){
if(species==null){
species=new Species(history);
for(int i=0;i<num;i++)
species.getIndividuals().add(new SpeciationNeuralNetwork(history,inputs,outputs));
if(species2==null)
currentSpecies=species;
}else if(species2==null){
species2=new Species(history);
for(int i=0;i<num;i++)
species2.getIndividuals().add(new SpeciationNeuralNetwork(history,inputs,outputs));
//currentSpecies=species2;
}else if(species==currentSpecies){
species2=null;
species2=new Species(history);
for(int i=0;i<num;i++)
species2.getIndividuals().add(new SpeciationNeuralNetwork(history,inputs,outputs));
}else{ // species2==currentSpecies
species=null;
species=new Species(history);
for(int i=0;i<num;i++)
species.getIndividuals().add(new SpeciationNeuralNetwork(history,inputs,outputs));
}
}
|
62099a18-cbc5-49aa-a712-efdc15cf73e9
| 3
|
public void setCategorie(Categorie categorie) {
if (getCategorie() != null) {
getCategorie().getSujets().remove(this);
getCategorie().ajouterNbreSujets(-1);
getCategorie().ajouterNbreReponses(-(getReponses().size() - 1));
}
this.categorie = categorie;
if (getCategorie() != null && !getCategorie().getSujets().contains(this)) {
getCategorie().getSujets().add(this);
getCategorie().ajouterNbreSujets(1);
getCategorie().ajouterNbreReponses(getReponses().size() - 1);
}
}
|
eb962c80-b502-4e13-bf44-3dc114163785
| 4
|
@Override
public void run() {
boolean fim = false;
LOGGER.info("Cliente Aguardando dados");
while (!fim) {
System.out.println("Cliente Aguardando dados");
System.out.flush();
int read = is.nextInt();
LOGGER.info("Recebido " + read + " do servidor");
switch (read) {
case -1: // mario
cliente.getMario().getPosicao().setX(is.nextInt());
cliente.getMario().getPosicao().setY(is.nextInt());
break;
case -2: // luigi
cliente.getLuigi().getPosicao().setX(is.nextInt());
cliente.getLuigi().getPosicao().setY(is.nextInt());
break;
case -3: // fim
cliente.fim();
fim = true;
break;
default:
LOGGER.info("Valor inesperado, ignorando");
}
LOGGER.info("Cliente Autlaizado:\t" + cliente.toString() );
cliente.update();
}
}
|
dd4de106-d6aa-4fa0-a0e0-84235ac82b25
| 3
|
private void playCard(ICard card, List<ICard> taking) {
if (table.action(card, taking)) {
log("Giocata la carta " + card.getCardStr());
cardsOnHand.remove(card); // rimuove la carta dalla mano
if (taking.size() != 0){
personalDeck.addAll(taking); // Aggiungo le carte al mazzetto
log("Presa: " + cardsListStr(taking));
}
if(table.cardsOnTable().size() == 0)
scopeCount++; //Ho eseguito una scopa;
} else {
log("Impossibile giocare la carta " + card.getCardStr());
throw new IllegalStateException("L'agente " + getName()
+ " sta eseguendo un azione non valida");
}
}
|
3388c4f8-1404-42be-a427-b7404e9f31d0
| 2
|
@Override
public void onCloseDocument(PdfWriter writer, Document document) {
//la cella con il numero totale di pagine avrà le stesse caratteristiche della cella originaria contentente il testo #Page
//ma l'allineamento sarà a sinistra
if (this._TotalNumberOfPageFooter != null) {
ColumnText.showTextAligned(this._TotalNumberOfPageFooter, Element.ALIGN_LEFT, new Phrase(new Chunk(String.valueOf(writer.getPageNumber() - 1), FontFactory.getFont(this._PageNumberBaseFont, this._PageNumberFontSize, this._PageNumberStyle, this._PageNumberBaseColor))), 0, this._PageNumberHeight / 2 - this._PageNumberFontSize / 2, 0);
}
if (this._TotalNumberOfPageHeader != null) {
ColumnText.showTextAligned(this._TotalNumberOfPageHeader, Element.ALIGN_LEFT, new Phrase(new Chunk(String.valueOf(writer.getPageNumber() - 1), FontFactory.getFont(this._PageNumberBaseFont, this._PageNumberFontSize, this._PageNumberStyle, this._PageNumberBaseColor))), 0, this._PageNumberHeight / 2 - this._PageNumberFontSize / 2, 0);
}
}
|
2e0f3866-9b5e-435e-8ea9-736ff58911de
| 5
|
public ContentObjectRelation getParentChildRelation(ContentType childType, String childId) {
if (childType instanceof RegionType)
return null;
else if (childType instanceof LowLevelTextType) { //Text lines, word, glyph
for (int i=0; i<regions.size(); i++) {
Region reg = regions.getAt(i);
if (reg instanceof LowLevelTextContainer) {
ContentObjectRelation rel = getLowLevelTextObject((LowLevelTextContainer)reg, (LowLevelTextType)childType, childId);
if (rel != null)
return rel;
}
}
}
return null;
}
|
b9b80cb1-ad5c-4928-9312-a8189ea98cea
| 4
|
protected String getGasType(int userChoice){
if (userChoice == UNLEAD) return UNLEAD_STR;
else if (userChoice == PLUS_UNLEAD) return PLUS_UNLEAD_STR;
else if (userChoice == PREMIUM_UNLEAD) return PREMIUM_UNLEAD_STR;
else if (userChoice == DIESEL) return DIESEL_STR;
return null;
}
|
c26a057c-a068-4c6a-b624-95f73c78e50a
| 3
|
public void Insert(BinaryNode item)
{
if(item.elementNumber < elementNumber)
if(left != null)
left.Insert(item);
else
setLeft(item);
else
{
if(right != null)
right.Insert(item);
else
setRight(item);
}
}
|
62a28980-5352-4e1b-88ad-eaa08679c99e
| 8
|
public static void main(String args[]) throws Throwable{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
for(String ln;(ln=in.readLine())!=null;){
StringTokenizer st=new StringTokenizer(ln);String a=st.nextToken(),b=st.nextToken();
boolean ws=false;
for(int i=2;i<37&&!ws;i++)
for(int j=2;j<37&&!ws;j++)
try{
ws=parseInt(a,i)==parseInt(b,j);
if(ws)sb.append(a+" (base "+i+") = "+b+" (base "+j+")\n");
}catch(Exception e){}
if(!ws)sb.append(a+" is not equal to "+b+" in any base 2..36\n");
}
System.out.print(new String(sb));
}
|
bb380a0d-8873-4ad9-968d-90737c1555ee
| 3
|
@Override
public void setBuffer()
{
if (isDirty())
{
// calculate how many bytes we need to store all the involved people
int length = 0;
for(InvolvedPerson involvedPerson : involvedPeople)
{
length += stringToBytes(encoding.getCharacterSet(), involvedPerson.getInvolvement()).length;
length += stringToBytes(encoding.getCharacterSet(), involvedPerson.getPerson ()).length;
}
buffer = new byte[1 + length];
buffer[0] = (byte)encoding.ordinal();
int index = 1;
for(InvolvedPerson involvedPerson : involvedPeople)
{
byte[] involvementBytes = stringToBytes(encoding.getCharacterSet(), involvedPerson.getInvolvement());
byte[] personBytes = stringToBytes(encoding.getCharacterSet(), involvedPerson.getPerson ());
System.arraycopy(involvementBytes, 0, buffer, index, involvementBytes.length);
index += involvementBytes.length;
System.arraycopy(personBytes , 0, buffer, index, personBytes .length);
index += personBytes.length;
}
dirty = false;
}
}
|
3f5f38c0-3966-41cd-80e7-77d8e37e35a2
| 5
|
public Load(){
try{
aFileReader = new FileReader(aFilePath);
aBufferedReader = new BufferedReader(aFileReader);
for(;;){
String aString = aBufferedReader.readLine();
if(aString != null){
stringLines.add(aString);
}else{
break;
}
}
}catch(FileNotFoundException error){
error.printStackTrace();
}catch(IOException error){
error.printStackTrace();
}finally{
try{
aBufferedReader.close();
aFileReader.close();
}catch(IOException error){
error.printStackTrace();
}
}
}
|
62da3664-b3d9-4d25-9274-7ab5f23881f2
| 4
|
private static boolean isUpdateAvailable(URI remoteUri, File localFile)
{
URLConnection conn;
try
{
conn = remoteUri.toURL().openConnection();
}
catch (MalformedURLException ex)
{
log.error("An exception occurred", ex);
return false;
}
catch (IOException ex)
{
log.error("An exception occurred", ex);
return false;
}
if (!(conn instanceof HttpURLConnection))
{
// don't bother with non-http connections
return false;
}
long localLastMod = localFile.lastModified();
long remoteLastMod = 0L;
HttpURLConnection httpconn = (HttpURLConnection) conn;
// disable caching so we don't get in feedback loop with ResponseCache
httpconn.setUseCaches(false);
try
{
httpconn.connect();
remoteLastMod = httpconn.getLastModified();
}
catch (IOException ex)
{
// log.error("An exception occurred", ex);();
return false;
}
finally
{
httpconn.disconnect();
}
return (remoteLastMod > localLastMod);
}
|
086830d0-af26-4c52-9806-8fbd111daae2
| 7
|
private static long ageDifferenceInDays(String firstname1 , String surname1,
String firstname2, String surname2)
throws InvalidPersonException {
Person person1 = null;
Person person2 = null;
for (Person person : people){
String firstname = person.getFirstname();
String surname = person.getSurname();
if (firstname.equalsIgnoreCase(firstname1) && surname.equalsIgnoreCase(surname1)){
person1 = person;
} else if (firstname.equalsIgnoreCase(firstname2) && surname.equalsIgnoreCase(surname2)){
person2 = person;
}
}
if (person1 != null && person2 != null){
//find the difference in age in miliseconds between the two Person objects
//what if p1 is younger than p2
long p1 = person1.getDob().getTime();
long p2 = person2.getDob().getTime();
long ageDiff = p2-p1;
//Useful enum from the concurrency package
return TimeUnit.DAYS.convert(ageDiff, TimeUnit.MILLISECONDS);
} else {
throw new InvalidPersonException("Could not find the people with names:["+firstname1+" "+surname1+"] and ["+firstname2+" "+surname2+"]");
}
}
|
1eca65bc-f4df-4295-aa75-f6139521d61b
| 9
|
@Override
public String getOptionsXML()
{
StringBuffer sb = new StringBuffer();
if( anRot != 0 )
{
sb.append( " AnRot=\"" + anRot + "\"" );
}
if( anElev != 15 )
{
sb.append( " AnElev=\"" + anElev + "\"" );
}
if( pcDist != 30 )
{
sb.append( " pcDist=\"" + pcDist + "\"" );
}
if( pcHeight != 100 )
{
sb.append( " pcHeight=\"" + pcHeight + "\"" );
}
if( pcDepth != 100 )
{
sb.append( " pcDepth=\"" + pcDepth + "\"" );
}
if( pcGap != 150 )
{
sb.append( " pcGap=\"" + pcGap + "\"" );
}
if( fPerspective )
{
sb.append( " Perspective=\"true\"" );
}
if( f3dScaling )
{
sb.append( " ThreeDScaling=\"true\"" );
}
if( f2DWalls )
{
sb.append( " TwoDWalls=\"true\"" );
}
// 20070913 KSC: need to track Cluster, whether on or off
sb.append( " Cluster=\"" + fCluster + "\"" );
// sb.append(" formatOptions=\"" + grbit+ "\"");
return sb.toString();
}
|
a604a41a-284d-49ce-9896-8ed4c5c53a19
| 9
|
public void setTimestep(String timestep) {
if ((!timestep.equals(SimConst.DAILY))
&& (!timestep.equals(SimConst.DAILY_MEAN))
&& (!timestep.equals(SimConst.MONTHLY_MEAN))
&& (!timestep.equals(SimConst.MEAN_MONTHLY))
&& (!timestep.equals(SimConst.ANNUAL_MEAN))
&& (!timestep.equals(SimConst.PERIOD_MAXIMUM))
&& (!timestep.equals(SimConst.PERIOD_MININUM))
&& (!timestep.equals(SimConst.PERIOD_MEDIAN))
&& (!timestep.equals(SimConst.PERIOD_STANDARD_DEVIATION))) {
throw new IllegalArgumentException("SetTimeStep: Illegal timestep: " + timestep);
}
this.timestep = timestep;
}
|
6e95b20b-4fab-4995-be5b-0c3592bfea22
| 4
|
public void modifyCountry(Country cnt) {
Connection con = null;
PreparedStatement pstmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
pstmt = con.prepareStatement("Update country Set cnt_code=?, "
+ "cnt_name=? Where cnt_id=?");
pstmt.setString(1, cnt.getCode());
pstmt.setString(2, cnt.getName());
pstmt.setInt(3, cnt.getId());
pstmt.executeUpdate();
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
}
|
55a8d664-0301-4c4f-9107-c6e3888415c3
| 0
|
public long getLastReceiptTime() {
return lastReceiptTime;
}
|
94b6fa1a-2e6e-4a75-9d45-d3f6bdd534d9
| 7
|
private static void mirror() throws Exception {
int initialSize = frames.size();
if (mapCenter == -1) {
throw new Exception("map-center was never declared.");
}
for (int fr = 0; fr < initialSize; fr++) {
if (fr != mapCenter) {
//This loop should be where detailing of red-blue sides should go
//make a new skybox rotated around the mapCenter skybox.
int newX = frames.get(mapCenter).getX() + (frames.get(mapCenter).getX() + frames.get(mapCenter).getXs() - (frames.get(fr).getX() + frames.get(fr).getXs()));
int newY = frames.get(mapCenter).getY() + (frames.get(mapCenter).getY() + frames.get(mapCenter).getYs() - (frames.get(fr).getY() + frames.get(fr).getYs()));
//mid + (mid - skyCoord)
//isFrame as opposed to isSkybox
if (frames.get(fr).isFrame()) {
System.out.println("Mirroring a frame");
frames.add(new Frame(newX, newY, frames.get(fr).getZ(), frames.get(fr).getXs(), frames.get(fr).getYs(), frames.get(fr).getZs()));
} else {
System.out.println("Mirroring a skybox");
frames.add(new Skybox(newX, newY, frames.get(fr).getZ(), frames.get(fr).getXs(), frames.get(fr).getYs(), frames.get(fr).getZs()));
}
int initMirror = frames.get(fr).getComponentSize();
System.out.println("populating new container...");
for (int i = 0; i < initMirror; i++) {
//now take everything inside and mirror it
frames.get(frames.size() - 1).addDrawable(frames.get(fr).getComponents()[i].getMirror(frames.get(mapCenter).getX(), frames.get(mapCenter).getY(), frames.get(mapCenter).getX() + frames.get(mapCenter).getXs(), frames.get(mapCenter).getY() + frames.get(mapCenter).getYs()));
}
if (frames.get(fr).getMirrored()) {
frames.get(frames.size() - 1).setMirror();
}
}
}
//ADD General MIRRORED OBJECTS
System.out.println("Cleaning up mirroring...");
for (Frame frame : frames) {
// if (frame.getMirrored()) {
// for (int i = 0; i < frame.getComponentSize(); i++) {
// frame.addDrawable(frame.getComponents()[i].getMirror(frame.getX(), frame.getY(), frame.getX() + frame.getXs(), frame.getY() + frame.getYs()));
// }
// }
}
}
|
979e5e81-09b0-4fef-9bb0-13d65cd6ee6f
| 0
|
@Basic
@Column(name = "CTR_ID_ELEMENTO")
public int getCtrIdElemento() {
return ctrIdElemento;
}
|
c940802b-c8b4-49fe-98c3-61be04d630ca
| 7
|
public NusmvSTS explore(String nusmvFile) throws IOException {
logger.info("Using NuSMV to retrieve STS from SMV file");
init(nusmvFile);
int iteration = 0;
while (!this.pathsToExplore.isVisited()) {
iteration++;
logger.info("Starting up..");
startNuSMVConsole(nusmvFile);
// sendCommandToConsole("set shown_states 400");
sendCommandToConsole("go");
sendCommandToConsole("build_boolean_model");
sendCommandToConsole("bmc_setup");
if (iteration == 1) {
List<State> newStates = new ArrayList<State>();
String consolePrint = this.sendCommandToConsole("print_reachable_states -v");
newStates = NuSMVOutputHandler.addStatesToSTS(sts, consolePrint, "-------");
logger.info("Nr of reachable states: " + newStates.size());
if (newStates.isEmpty()) {
logger.error("Incorrect specification: the generated NuSMV model has no reachable states");
}
}
int i = 0;
while (!this.pathsToExplore.isVisited() && i < 70) {
i++;
sendCommandToConsole("set nusmv_stdout " + outFile);
String consolePrint = console.pickInitialState(pathsToExplore);
logger.trace(consolePrint);
sendCommandToConsole("set nusmv_stdout " + outFile);
consolePrint = console.simulateInteractively();
logger.trace(consolePrint + "\n");
exploredPaths++;
logger.info("Explored path " + this.exploredPaths);
}
console.execCommand("quit");
console.closeConsole();
input.setRun(false);
}
if (!sts.getStates().isEmpty()) {
logger.debug("Obtained STS:\n" + sts.toDot());
}
if (!Boolean.getBoolean(ConfigUtils.getProperty("intermediaryFiles"))) {
File nusmvOutput = new File(outFile);
nusmvOutput.deleteOnExit();
}
return sts;
}
|
50c3f847-d114-470f-9793-0be01e6f8fe1
| 7
|
private void read(){
try{
String str = "";
String seqstr = "";
Sequence curseq = new Sequence();
while((str=input.readLine())!=null){
if(str.startsWith(">")){
if(seqstr.compareTo("")!=0&&curseq!=null){
curseq.seqSeq(seqstr);
seqstr = "";
seqs.add(curseq);
}
curseq = new Sequence();
str = str.substring(1).trim();
curseq.setID(str);
}else{
seqstr += str.trim();
}
}
//this would be for the last seq
if(seqstr.compareTo("")!=0&&curseq!=null){
curseq.seqSeq(seqstr);
seqs.add(curseq);
}
}catch(IOException ioe){
System.out.println("there was a problem reading your file (FastaReader.java)");
}
}
|
820893f3-1d36-4943-9c0a-ad516d4a0d93
| 5
|
public boolean move(int newBase)
{
//Save the registers if we're the currently running process
if(this == m_currProcess)
save(m_CPU);
//Get the relative locations to make for easier moving based on newBase
int relLIM = registers[CPU.LIM] - registers[CPU.BASE];
int relPC = registers[CPU.PC] - registers[CPU.BASE];
int relSP = registers[CPU.SP] - registers[CPU.BASE];
//Verify that the new location is ok
if (newBase < 0 || newBase + relLIM > m_MMU.getSize())
return false;
//Copy the given program into the new RAM location.
//for(int i = 0; i < relLIM; ++i)
//m_MMU.write(newBase + i, m_MMU.read(registers[CPU.BASE] + i));
//Move around the page numbers as needed
int currPageIndex = registers[CPU.BASE] / m_MMU.getPageSize();
int newPageIndex = newBase / m_MMU.getPageSize();
for (int i = 0; i < (registers[CPU.LIM] - registers[CPU.BASE]) / m_MMU.getPageSize(); ++i)
{
int temp = m_MMU.read(newPageIndex + i);
m_RAM.write(newPageIndex + i, m_MMU.read(currPageIndex + i));
m_RAM.write(currPageIndex + i, temp);
}
//Move the three registers from before based on their relative locations to the base
int oldBase = registers[CPU.BASE];
registers[CPU.BASE] = newBase;
registers[CPU.LIM] = newBase + relLIM;
registers[CPU.PC] = newBase + relPC;
registers[CPU.SP] = newBase + relSP;
//Restore if need be
if(this == m_currProcess)
restore(m_CPU);
debugPrintln("Process " + getProcessId() + " has moved from " + oldBase + " to " + newBase + ".");
return true;
}//move
|
f22a8c77-c7b4-411e-b7c2-b7266e741527
| 1
|
private void parameter()
{
if (have(NonTerminal.PARAMETER))
{
tryDeclareSymbol(current);
nextToken();
expect(Token.Kind.COLON);
type();
}
}
|
e82d3d62-49ca-4840-adfd-dc7769e5efa5
| 6
|
private static String _v2DirStr(Vector2d v)
{
if (v.equals(NIL)) return "DNIL";
if (v.equals(NONE)) return "DNONE";
if (v.equals(UP)) return "DUP";
if (v.equals(DOWN)) return "DDOWN";
if (v.equals(LEFT)) return "DLEFT";
if (v.equals(RIGHT)) return "DRIGHT";
return null;
}
|
baee0af8-0425-4dc7-878f-060a234ec64d
| 3
|
public SecondaryPowerFailure(Grid grid, int lifetime, PrimaryPowerFailure parentPowerFailure, Rotation rotation, Position pos) {
super(grid, lifetime);
if (parentPowerFailure == null)
throw new IllegalArgumentException("The given PrimaryPowerFailure is invalid!");
if (rotation == null)
throw new IllegalArgumentException("The given Rotation is invalid!");
if (pos == null)
throw new IllegalArgumentException("The given Position is invalid!");
this.parentPowerFailure = parentPowerFailure;
this.rotation = rotation;
this.pos = pos;
getGrid().getEventManager().addListener(this, EventType.END_ACTION);
}
|
8d6336b2-7633-49c4-919b-22f99f230e45
| 2
|
public void addTrack(Song song) {
// System.out.println("Album called " + title + " inserting track named " + song.getTitle() + "...");
if(song.getTitle() == null) {
song.setTitle("No Title");
}
if(!albumContainsTrack(song)) {
tracks.put(song.getTitle(), song);
}
}
|
a074271b-b28d-48af-a751-1afacf40f91f
| 1
|
public void visitInstanceOfExpr(final InstanceOfExpr expr) {
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(" instanceof " + expr.checkType());
}
|
ed9cc09c-db62-4871-94cb-b3e0a931c18f
| 8
|
private void decode(byte[] bytes) throws InvalidUIntException
{
if (bits != 1 && bits != 2 && bits != 4 && bits != 8)
throw new InvalidUIntException();
byteBuffer = ByteBuffer.wrap(bytes);
switch (bits)
{
case 1:
value = byteBuffer.get();
break;
case 2:
value = byteBuffer.getShort();
break;
case 4:
value = byteBuffer.getInt();
break;
case 8:
value = byteBuffer.getLong();
break;
}
}
|
84924ce0-9ebf-4471-a0da-daef7927b7ca
| 4
|
public boolean equals(Object obj) {
if (obj == this)
return true;
/* is obj reference null */
if (obj == null)
return false;
/* Make sure references are of same type */
if (!(getClass() == obj.getClass()))
return false;
else {
Style tmp = (Style) obj;
if (tmp.name.equalsIgnoreCase(this.name)) {
return true;
} else
return false;
}
}
|
dd70360b-09ca-4b51-9fb0-9c20e905dbef
| 8
|
public Move(GameBoard b, Position start, Position dest)
{
this.startPiece=b.getPiece(start);
this.start = start;
this.dest = dest;
killedPiece=b.getPiece(dest);
if(startPiece.getType()==Piece.KING&&!b.hasKingMoved(startPiece.getColor())){
flags=(byte)BitField.setBit(flags, KING_MOVED_FLAG);
}
if(startPiece.getType()==Piece.ROOK){
if(start.getColumn()==0&&!b.hasLRookMoved(startPiece.getColor())){
//TODO Check whether it's the bottom line
//TODO We need to set L_ROOK_FLAG if l rook is killed
flags=(byte)BitField.setBit(flags, L_ROOK_FLAG);
}else if(start.getColumn()==7&&start.getRow()==0&&!b.hasRRookMoved(startPiece.getColor())){
flags=(byte)BitField.setBit(flags, R_ROOK_FLAG);
}
}
}
|
513c84b0-413d-4f16-b63c-92f815b43358
| 9
|
protected Direction moveRandomly(String logMe, Direction direction) {
final Unit unit = getUnit();
if (unit.getMovesLeft() <= 0 || unit.getTile() == null) return null;
if (logMe == null) logMe = "moveRandomly";
Random aiRandom = getAIRandom();
if (direction == null) {
direction = Direction.getRandomDirection(logMe, aiRandom);
}
Direction[] directions
= direction.getClosestDirections(logMe, aiRandom);
for (int j = 0; j < directions.length; j++) {
Direction d = directions[j];
Tile moveTo = unit.getTile().getNeighbourOrNull(d);
if (moveTo != null
&& unit.getMoveType(d) == MoveType.MOVE) {
return (AIMessage.askMove(aiUnit, d)
&& unit.getTile() == moveTo) ? d
: null; // Failed!
}
}
return null; // Stuck!
}
|
07be4fff-ec0f-49e6-bd46-a6a1f43125b8
| 5
|
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ControlScheme other = (ControlScheme) obj;
if (Jump != other.Jump)
return false;
if (Left != other.Left)
return false;
if (Right != other.Right)
return false;
return true;
}
|
3b0349e1-ef18-4856-8dd7-64f9625c5240
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ModificarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModificarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModificarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModificarProveedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final ModificarProveedor provv = new ModificarProveedor();
provv.setVisible(true);
provv.setLocationRelativeTo(null);
}
});
}
|
8e42f161-752c-4913-b7aa-4c99f9c0afba
| 9
|
public static RecordableTextAction getAction(int action) {
if (action<MIN_ACTION_CONSTANT || action>MAX_ACTION_CONSTANT)
return null;
switch (action) {
case COPY_ACTION:
return copyAction;
case CUT_ACTION:
return cutAction;
case DELETE_ACTION:
return deleteAction;
case PASTE_ACTION:
return pasteAction;
case REDO_ACTION:
return redoAction;
case SELECT_ALL_ACTION:
return selectAllAction;
case UNDO_ACTION:
return undoAction;
}
return null;
}
|
134f2e58-97bc-4b75-8060-d23eb8c57f5b
| 7
|
public static void main(String[] args) {
DataGIS gis = null;
TopRegionalRC rc = null;
DataGridUser user = null;
//FIRST STEP---------------------------------------------
//Initialize the GridSim package
int num_user = 1; // number of grid users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // means trace GridSim events
boolean gisFlag = false; // means using DataGIS instead
GridSim.init(num_user, calendar, trace_flag, gisFlag);
// set the GIS into DataGIS that handles specifically for data grid
// scenarios
try {
gis = new DataGIS();
GridSim.setGIS(gis);
} catch (Exception e) {
e.printStackTrace();
}
//SECOND STEP---------------------------------------------
//Create a top level Replica Catalogue
double baud_rate = 1000000; // bits/sec
double propDelay = 10; // propagation delay in millisecond
int mtu = 1500; // max. transmission unit in byte
try {
SimpleLink l = new SimpleLink("rc_link", baud_rate, propDelay, mtu);
rc = new TopRegionalRC(l);
} catch (Exception e1) {
e1.printStackTrace();
}
//THIRD STEP---------------------------------------------
//Create resources
int i = 0;
int totalResource = 3;
ArrayList resList = new ArrayList(totalResource);
for (i = 0; i < totalResource; i++) {
DataGridResource res = createGridResource("Res_" + i, baud_rate,
propDelay, mtu);
resList.add(res);
}
//FOURTH STEP---------------------------------------------
//Create user(s)
try {
user = new DummyUser("Dummy_User", baud_rate, propDelay, mtu);
// set a replica catalogue, if not set the TopReplica RC will be
// used
user.setReplicaCatalogue(TopRegionalRC.DEFAULT_NAME);
} catch (Exception e2) {
e2.printStackTrace();
}
// FIFTH STEP---------------------------------------------
//Create network
Router r1 = new RIPRouter("router1"); // router 1
Router r2 = new RIPRouter("router2"); // router 2
try {
//connect the routers
baud_rate = 10000000;
Link link = new SimpleLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler();
FIFOScheduler r2Sched = new FIFOScheduler();
// attach r2 to r1
r1.attachRouter(r2, link, r1Sched, r2Sched);
} catch (Exception e3) {
e3.printStackTrace();
}
//FIFTH STEP---------------------------------------------
//Connect resources, users and catalogues to the network
try {
//connect resources
GridResource resObj = null;
for (i = 0; i < resList.size(); i++) {
FIFOScheduler resSched = new FIFOScheduler();
resObj = (GridResource) resList.get(i);
r2.attachHost(resObj, resSched); //attach resource to router r2
}
//connect user
FIFOScheduler userSched = new FIFOScheduler();
r1.attachHost(user, userSched); //atach the user to router r1
//connect rc
FIFOScheduler rcSched = new FIFOScheduler();
r2.attachHost(rc, rcSched); // attach RC
} catch (ParameterException e4) {
e4.printStackTrace();
}
//SIXTH STEP---------------------------------------------
//Finally start the simulation
GridSim.startGridSimulation();
}
|
79a6650b-f711-4657-8dab-62e8a2ae1a88
| 8
|
final public void Assignment() throws ParseException {
/*@bgen(jjtree) Assignment */
BSHAssignment jjtn000 = new BSHAssignment(JJTASSIGNMENT);
boolean jjtc000 = true;
jjtree.openNodeScope(jjtn000);
jjtreeOpenNodeScope(jjtn000);int op ;
try {
PrimaryExpression();
op = AssignmentOperator();
jjtn000.operator = op;
Expression();
} catch (Throwable jjte000) {
if (jjtc000) {
jjtree.clearNodeScope(jjtn000);
jjtc000 = false;
} else {
jjtree.popNode();
}
if (jjte000 instanceof RuntimeException) {
{if (true) throw (RuntimeException)jjte000;}
}
if (jjte000 instanceof ParseException) {
{if (true) throw (ParseException)jjte000;}
}
{if (true) throw (Error)jjte000;}
} finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000, true);
jjtreeCloseNodeScope(jjtn000);
}
}
}
|
2e1565c3-cacf-4798-907a-7adb5831b33f
| 5
|
public int[] twoSum(int[] numbers, int target) {
int[] a = {0,0};
Hashtable<Integer, Integer> hash = new Hashtable<Integer, Integer>();
for (int i = 0; i <= numbers.length-1; i++) {
hash.put(numbers[i], i);
}
for (int i = 0; i <= numbers.length-1; i++) {
Integer n = hash.get(target - numbers[i]);
if (n != null && n!=i) {
if (n<i) {
a[0] = n + 1;
a[1] = i + 1;
return a;
} else {
a[0] = i + 1;
a[1] = n + 1;
return a;
}
}
}
return a;
}
|
1ffc3ee6-0963-4980-8332-f06a6aef124d
| 3
|
private void processEvent(MouseEvent e, TouchCommandMessageType down) {
Dimension componentDimension = e.getComponent().getSize();
float xRate = (float) e.getX() / (float) componentDimension.width;
float yRate = (float) e.getY() / (float) componentDimension.height;
switch (down) {
case TOUCH_DOWN:
client.sendMessage(new TouchCommandMessage(client
.getNextSequenceNumber(), device.getSerialNumber(),
TouchCommandMessageType.TOUCH_DOWN, xRate, yRate));
Script.registerActionTouch(TouchCommandMessageType.TOUCH_DOWN,
String.valueOf(xRate), String.valueOf(yRate));
break;
case TOUCH_MOVE:
client.sendMessage(new TouchCommandMessage(client
.getNextSequenceNumber(), device.getSerialNumber(),
TouchCommandMessageType.TOUCH_MOVE, xRate, yRate));
Script.registerActionTouch(TouchCommandMessageType.TOUCH_MOVE,
String.valueOf(xRate), String.valueOf(yRate));
break;
case TOUCH_UP:
client.sendMessage(new TouchCommandMessage(client
.getNextSequenceNumber(), device.getSerialNumber(),
TouchCommandMessageType.TOUCH_UP, xRate, yRate));
Script.registerActionTouch(TouchCommandMessageType.TOUCH_UP,
String.valueOf(xRate), String.valueOf(yRate));
break;
}
}
|
0a31b398-da4e-48e6-b947-2ec5bb4bb32e
| 7
|
public Object invoke(JMSRemoteRef jmsRemoteRef, Method method, Object[] params) throws Exception {
boolean oneway = JMSRemoteRef.isOneWay(method);
long timeout = 0;
if (!oneway) {
timeout = REQUEST_TIMEOUT;
if (method.isAnnotationPresent(Timeout.class)) {
timeout = method.getAnnotation(Timeout.class).value();
}
// Perhaps there is per inovocation timeout configured..
Long nto = JMSRemoteObject.removeNextInvocationTimeout();
if (nto != null) {
timeout = nto;
}
// Kicks off the receiver thread...
kickReceiveThread();
}
int deliveryMode = method.isAnnotationPresent(Persistent.class) ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT;
int priority = 4;
if (method.isAnnotationPresent(Priority.class)) {
priority = method.getAnnotation(Priority.class).value();
}
RequestExchange requestExchange = new RequestExchange(this, jmsRemoteRef, signature(method), params, oneway, timeout, deliveryMode, priority);
getSenderThread().execute(requestExchange);
try {
return requestExchange.getResult();
} catch (Exception e) {
throw e;
} catch (Throwable e) {
throw new RemoteException("Unexepected error", e);
}
}
|
5e764f8c-4a1a-43f2-b7e2-81f08b783a49
| 0
|
public void setTotalTicketsSold(long totalTicketsSold) {
this.totalTicketsSold = totalTicketsSold;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.