text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public String getScrambledWord(int idx) {
String c = WORD_LIST[idx];
Random rnd = new Random();
String[] a = new String[c.length()];
char f = 0;
String g = "";
String[] b = new String[100];
String e = "";
for(int i = 0; i<c.length();i++){
f=c.charAt(i);
a[i] = String.valueOf(f);
}
for(int i = 0; i<c.length();i++){
int ran = rnd.nextInt(c.length());
int r = ran;
if(a[r]==null)i--;
else {
g = a[r];
b[i]=g;
a[r]=null;
}
}
for(int i = 0; i<c.length(); i++){
e += b[i];
}
return e;
}
| 4 |
public int sizeOfWsFrameLength(byte type, int length) throws IOException {
// one bite for the type
int size = 1;
// Encode length.
int b1 = length >>> 28 & 0x7F;
int b2 = length >>> 14 & 0x7F;
int b3 = length >>> 7 & 0x7F;
if (b1 == 0) {
if (b2 == 0) {
if (b3 == 0) {
size += 1;
} else {
size += 2;
}
} else {
size += 3;
}
} else {
size += 4;
}
return size;
}
| 3 |
public void paint ()
{
int i, j;
dl_atom dla = null;
dl_bond dlb = null;
Vector dlist = new Vector ();
if (showForces)
computeForces ();
for (i = 0; i < atomList.size (); i++)
{
dla = new dl_atom ((atom) atomList.elementAt(i), v);
dlist.addElement (dla);
}
for (i = 0; i < atomList.size (); i++)
{
atom a1 = (atom) atomList.elementAt (i);
for (j = 0; j < a1.bonds.size (); j++)
{
bond b = (bond) a1.bonds.elementAt(j);
atom a2 = b.otherAtom(a1);
if (a1.x[0] < a2.x[0])
{
dlb = new dl_bond (b, v);
dlist.addElement (dlb);
}
}
if (showForces)
{
dlforce dlf = new dlforce (a1.x, a1.f, v);
dlf.setForceMultiplier (forceMultiplier);
dlist.addElement (dlf);
}
}
if (dla != null)
dla.paint (dlist, mypanel.getGraphics ());
else if (dlb != null)
dlb.paint (dlist, mypanel.getGraphics ());
}
| 8 |
public void CheckCommands(String channel, String sender, String login, String hostname, String message)
{
if(!message.startsWith("!"))
return;
String params[] = message.split(" ");
String commandName = params[0].substring(1).toLowerCase();
for(BotCommand com : m_Commands)
{
if(com.GetCommandName().equals(commandName))
{
com.Execute(this, channel, sender, login, hostname, message, params);
}
}
}
| 3 |
private static<T extends Comparable<? super T>> void merge(T[] data, T[] tmp, int leftPos, int rightPos, int rightEnd) {
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int leftPos2 = leftPos;
while (leftPos <= leftEnd && rightPos <= rightEnd) {
if (data[leftPos].compareTo(data[rightPos]) > 0) {
tmp[tmpPos++] = data[rightPos++];
} else {
tmp[tmpPos++] = data[leftPos++];
}
}
while (leftPos <= leftEnd) {
tmp[tmpPos++] = data[leftPos++];
}
while (rightPos <= rightEnd) {
tmp[tmpPos++] = data[rightPos++];
}
for (; rightEnd >= leftPos2; rightEnd--) {
data[rightEnd] = tmp[rightEnd];
}
}
| 7 |
public int minDepth(TreeNode root) {
if(root == null)
return 0;
deepTree(root,1);
return minDeep;
}
| 1 |
public BagOfTiles() {
_tileBag = new ArrayList<Tile>();
_pointValueMap = new HashMap<Tile, Integer>();
String[] s = null;
@SuppressWarnings("resource")
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("Txt/Characters"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String currentLine;
try {
while ((currentLine = br.readLine()) != null) {
s = currentLine.split(" ");
for (int i = 0; i < Integer.parseInt(s[1]); i++) {
for (int j = 0; j < s[0].length(); j++) {
_tileBag.add(new Tile(s[0].charAt(j)));
}
}_pointValueMap.put(new Tile(s[0].charAt(0)), Integer.parseInt(s[2]));
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| 6 |
public CtClass getCtClass() {
if (resolved != null)
return resolved.getCtClass();
return Type.OBJECT.getCtClass();
}
| 1 |
public FindReplaceResultsDialog() {
super(false, false, false, INITIAL_WIDTH, INITIAL_HEIGHT, MINIMUM_WIDTH, MINIMUM_HEIGHT);
}
| 0 |
public void collision(PhysicsCollisionEvent event) {
Spatial nodeA = event.getNodeA();
Spatial nodeB = event.getNodeB();
String nameA = nodeA.getName();
String nameB = nodeB.getName();
if(Meteor.NAME.equals(nameA) && "Me".equals(nameB)){
maybeDamage(1000);
}
else if(Meteor.NAME.equals(nameB) && "Me".equals(nameA)){
maybeDamage(1000);
}
}
| 4 |
public void addEvent(Event event) {
events.add(event);
switch (event.getType()) {
case Event.BIRTH:
if (birth == null)
birth = event;
break;
case Event.BAPTISM:
if (baptism == null)
baptism = event;
break;
case Event.DEATH:
if (death == null)
death = event;
break;
case Event.BURIAL:
if (burial == null)
burial = event;
break;
}
}
| 8 |
void printStdout(String text) {
if (text.lastIndexOf("%r") > 0) {
stdout.replaceRange(text.substring(text.lastIndexOf("%r") + 2),
stdout.getText().lastIndexOf('\n') + 1,
stdout.getText().length());
} else {
stdout.append(text);
stdout.setCaretPosition(stdout.getDocument().getLength() - (text.length() - 1));
}
}
| 1 |
public void update() {
speedX = bg.getSpeedX() * 5;
tileX += speedX;
r.setBounds(tileX, tileY, 40, 40);
if (r.intersects(Robot.yellowRed) && type != 0) {
checkVerticalCollision(Robot.rectBody, Robot.rectLegs);
checkSideCollision(Robot.rectLeft, Robot.rectRight, Robot.footleft,
Robot.footright);
}
}
| 2 |
public boolean Salvar(T obj) {
try{
//salva o objeto
manager.merge(obj);
return true;
}catch (Exception ex){
System.out.println(ex.getMessage());
return false;
}
}
| 1 |
void setExampleWidgetBackground () {
if (colorAndFontTable == null) return; // user cannot change color/font on this tab
Control [] controls = getExampleControls ();
if (!instance.startup) {
for (int i = 0; i < controls.length; i++) {
controls[i].setBackground (backgroundColor);
}
}
// Set the background color item's image to match the background color of the example widget(s).
Color color = backgroundColor;
if (controls.length == 0) return;
if (color == null) color = controls [0].getBackground ();
TableItem item = colorAndFontTable.getItem(BACKGROUND_COLOR);
Image oldImage = item.getImage();
if (oldImage != null) oldImage.dispose();
item.setImage (colorImage (color));
}
| 6 |
public void actionPerformed(ActionEvent e) {
MindMapNodeModel node = (MindMapNodeModel) mMindMapController
.getSelected();
// if something is wrong, abort.
if (mMindMapController.getMap() == null || node == null
|| node.isRoot()) {
mMindMapController.getFrame().err("Could not export branch.");
return;
}
// If the current map is not saved yet, save it first.
if (mMindMapController.getMap().getFile() == null) {
mMindMapController.getFrame().out(
"You must save the current map first!");
mMindMapController.save();
}
// Open FileChooser to choose in which file the exported
// branch should be stored
FreeMindFileDialog chooser = mMindMapController.getFileChooser();
chooser.setSelectedFile(new File(Tools.getFileNameProposal(node)
+ freemind.main.FreeMindCommon.FREEMIND_FILE_EXTENSION));
int returnVal = chooser.showSaveDialog(mMindMapController
.getSelectedView());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File chosenFile = chooser.getSelectedFile();
URL link;
// Force the extension to be .mm
String ext = Tools.getExtension(chosenFile.getName());
if (!ext.equals(freemind.main.FreeMindCommon.FREEMIND_FILE_EXTENSION_WITHOUT_DOT)) {
chosenFile = new File(
chosenFile.getParent(),
chosenFile.getName()
+ freemind.main.FreeMindCommon.FREEMIND_FILE_EXTENSION);
}
try {
link = Tools.fileToUrl(chosenFile);
} catch (MalformedURLException ex) {
JOptionPane.showMessageDialog(mMindMapController.getView(),
"couldn't create valid URL!");
return;
}
// Confirm overwrite if file exists.
if (chosenFile.exists()) { // If file exists, ask before
// overwriting.
int overwriteMap = JOptionPane.showConfirmDialog(
mMindMapController.getView(),
mMindMapController.getText("map_already_exists"),
"FreeMind", JOptionPane.YES_NO_OPTION);
if (overwriteMap != JOptionPane.YES_OPTION) {
return;
}
}
/*
* Now make a copy from the node, remove the node from the map and
* create a new Map with the node as root, store the new Map, add
* the copy of the node to the parent, and set a link from the copy
* to the new Map.
*/
MindMapNodeModel parent = (MindMapNodeModel) node.getParentNode();
// set a link from the new root to the old map
String linkToNewMapString = Tools.fileToRelativeUrlString(
mMindMapController.getModel().getFile(), chosenFile);
mMindMapController.setLink(node, linkToNewMapString);
int nodePosition = parent.getChildPosition(node);
mMindMapController.deleteNode(node);
// save node:
node.setParent(null);
// unfold node
node.setFolded(false);
// construct new controller:
ModeController newModeController = mMindMapController.getMode()
.createModeController();
MindMapMapModel map = new MindMapMapModel(node,
mMindMapController.getFrame(), newModeController);
map.save(chosenFile);
// new node instead:
MindMapNode newNode = mMindMapController.addNewNode(parent,
nodePosition, node.isLeft());
// TODO: Keep formatting of node.
mMindMapController.setNodeText(newNode, node.getText());
String linkString = Tools.fileToRelativeUrlString(chosenFile, mMindMapController.getModel().getFile());
mMindMapController.setLink(newNode, linkString);
mMindMapController.newMap(map);
// old map should not be save automatically!!
}
}
| 9 |
public void subSolve(ArrayList<String[]> resArr, int[] res, int n, int x) {
if (x > n - 1) { // DONE
String[] tmp = new String[n];
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
sb.append(j == res[i] ? 'Q' : '.');
}
tmp[i] = sb.toString();
}
resArr.add(tmp);
return;
}
for (int i = 0; i < n; i++) {
boolean flag = true;
int j = 0;
// CHECK
for (j = 0; j < x; j++) {
if (res[j] == i || Math.abs(res[j] - i) == Math.abs(j - x)) {
flag = false;
break;
}
}
if (flag) {
res[x] = i;
subSolve(resArr, res, n, x + 1);
res[x] = -1; // 可有可无,因为不会影响到后续子问题
}
}
}
| 9 |
public boolean updateOneSymbol(Investment oneInvestment) {
boolean flag = false;
int type = getInvestType(oneInvestment.getSymbol());
String typeTable;
if (type == 0) {
typeTable = "stock";
} else {
typeTable = "mutual_fund";
}
Timestamp stamp = getLatestTimestamp(oneInvestment.getSymbol(), typeTable);
if (stamp != null) {// if existed, update it
//update stock set time = TO_TIMESTAMP('2014-04-01 22:05:00.0', 'YYYY-MM-DD HH24:MI:SS.FF'), price = 32.33 where tiker_symbol = 'AAN'
if (stamp.before(oneInvestment.getTimestamp())) {
String query = "update " + typeTable + " set time = TO_TIMESTAMP('" + oneInvestment.getTimestamp().toString() + "', 'YYYY-MM-DD HH24:MI:SS.FF'), " +
"price = '" + oneInvestment.getPrice() + "' where symbol = '" + oneInvestment.getSymbol() + "'";
Statement s;
try {
s = con.createStatement();
ResultSet result;
result = s.executeQuery(query);
if (result.next()) {
flag = true;
}
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
flag = true; // the input is in fact older...
}
} else {
//insert into mutual_fund values('AABNX', TO_TIMESTAMP('2014-04-01 22:05:00.0', 'YYYY-MM-DD HH24:MI:SS.FF'), 12.50)
String query1 = "insert into investment values ('" + oneInvestment.getSymbol() + "', '" + type + "')";
String query2 = "insert into " + typeTable + " values('" + oneInvestment.getSymbol() + "', TO_TIMESTAMP('" + oneInvestment.getTimestamp().toString() +
"', 'YYYY-MM-DD HH24:MI:SS.FF'), '" + oneInvestment.getPrice() + "')";
Statement s;
try {
con.setAutoCommit(false);
s = con.createStatement();
int result1, result2;
result1 = s.executeUpdate(query1);
result2 = s.executeUpdate(query2);
if (result1 > 0 && result2 > 0) {
flag = true;
}
s.close();
con.commit();
con.setAutoCommit(true);
} catch (SQLException e) {
try {
con.rollback();
con.setAutoCommit(true);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
return flag;
}
| 9 |
public static String selectListParam(Map<String, Object> paramMap) throws SQLException{
@SuppressWarnings("unchecked")
java.util.Map<String,Object> sqlWhereMap = (Map<String, Object>) (paramMap.get("sqlWhereMap")==null ? "": paramMap.get("sqlWhereMap"));
BEGIN();
SELECT(User.COLUMNS);
FROM(User.TABLE_NAME);
if (sqlWhereMap != null && !"".equals(sqlWhereMap)) {
//拼接查询条件
WHERE(BaseModel.getSqlWhereWithValues(sqlWhereMap));
}
return SQL();
}
| 3 |
public TreeNode sortedListToBST(ListNode head) {
int count = 0;
ListNode p = head;
while (p != null) {
count++;
p = p.next;
}
int[] num = new int[count];
p = head;
count = 0;
while (p != null) {
num[count] = p.val;
count++;
p = p.next;
}
if (num.length == 0)
return null;
return BST(num, 0, num.length - 1);
}
| 3 |
public ArrayList<String> anagrams(String[] strs) {
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> result = new ArrayList<String>();
for (String str : strs) {
String min = toSmallest2(str);
ArrayList<String> tmp = map.get(min);
if (tmp == null) {
tmp = new ArrayList<String>();
map.put(min, tmp);
}
tmp.add(str);
}
for (ArrayList<String> tmp : map.values()) {
if (tmp.size() > 1)
result.addAll(tmp);
}
return result;
}
| 4 |
public void render(int x, int y, Renderable rend){
if(rend == null){
ErrorHandler.nullRenderableInterface(this, "@ render (line ~90");
return;
}
for(int yy = 0; yy <= rend.getHeight(); yy++){
int yp = yy + y;
for(int xx = 0; xx <= rend.getWidth(); x++){
int xp = xx + x;
if(xp < 0 || xp > this.width ||yp < 0 || yp > this.height) continue;
pixels[xp + yp * this.width] = rend.getPixels()[xx + yy * rend.getWidth()];
}
}
}
| 7 |
private void renderAttributes(PrintWriter out,
String labelName, Map<String, String> attributes) {
if ((labelName == null) && (attributes == null)) {
return;
}
out.print(" [ ");
if ((labelName == null) && (attributes != null)) {
labelName = attributes.get("label");
}
if (labelName != null) {
out.print("label=\"" + labelName + "\" ");
}
if (attributes != null) {
for (Map.Entry<String, String> entry : attributes.entrySet()) {
String name = entry.getKey();
if (name.equals("label")) {
// already handled by special case above
continue;
}
out.print(name + "=\"" + entry.getValue() + "\" ");
}
}
out.print("]");
}
| 8 |
@Override
public void detectAndHandleCollisions(EntityGrid grid, CollisionHandler physics, float dt) {
nearestEntity = grid.getNearest(this);
if (physics.boxCollisionTest(this, nearestEntity)) {
if (nearestEntity instanceof PlayerEntity) {
handlePlayerIntersection((PlayerEntity) nearestEntity);
} else if (nearestEntity instanceof BulletEntity) {
handleBulletIntersection((BulletEntity) nearestEntity, physics);
} else if (nearestEntity instanceof AsteroidEntity) {
handleAsteroidIntersection((AsteroidEntity) nearestEntity, physics);
}
}
if (isOutOfBounds(grid)) {
handleOutOfBounds(grid);
}
}
| 5 |
public static String getAppPath(String type) throws UnsupportedEncodingException{
String appRoot = "";
String path = "";
String slash = System.getProperty("file.separator");
String jpath = new File(SBStringUtils.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getPath();
//File nFile = new File(jpath).getParentFile().getPath();
appRoot = URLDecoder.decode(jpath, "UTF-8");
Debug.print("Path: "+ appRoot);
if (type.equals("data"))
path = appRoot + slash + "src" + slash + "ca"
+ slash + "strangebrew" + slash + "data";
else if (type.equals("icons"))
path = appRoot + slash + "src" + slash + "ca"
+ slash + "strangebrew" + slash + "icons";
else if (type.equals("recipes"))
path = appRoot + slash + "recipes";
else if (type.equals("help"))
path = "file://" + appRoot + slash + "help" + slash;
else if (type.equals("ini"))
path = appRoot + slash;
else
path = appRoot;
return path;
}
| 5 |
public void setSelect(boolean select) {
selected = select;
}
| 0 |
private void readInputAndUpdateCamera(Camera cam) {
int angle = mDemoKeyListener.getKeyDirectionAngle();
if (mDemoKeyListener.getMoveState()) {
switch(angle) {
case 0:
cam.x += 1;
break;
case 45:
cam.x += 1;
cam.y += 1;
break;
case 90:
cam.y += 1;
break;
case 135:
cam.y += 1;
cam.x -= 1;
break;
case -180:
cam.x -= 1;
break;
case -135:
cam.x -= 1;
cam.y -= 1;
break;
case -90:
cam.y -= 1;
break;
case -45:
cam.y -= 1;
cam.x += 1;
break;
}
}
}
| 9 |
public int maxSubArray(int[] A) {
int max = A[0];
int sum = 0;
for (int sell = 0; sell < A.length; sell++) {
sum = sum + A[sell];
max = Math.max(sum, max);
if (sum < 0)
sum = 0;
}
return max;
}
| 2 |
public void doTestParsers() {
final int repeat = ConsoleMenu.getInt("How many Rows?", 1000);
final int numberOfCols = ConsoleMenu.getInt("How many columns?", 100);
final boolean qualif = ConsoleMenu.getBoolean("With qualifier?", true);
final StringBuffer aRow = new StringBuffer();
for (int i = 0; i < numberOfCols; i++) {
if (qualif) {
aRow.append("\"");
}
aRow.append("Column ").append(i);
if (qualif) {
aRow.append("\"");
}
}
final String line = aRow.toString();
final long start = System.currentTimeMillis();
for (int i = 0; i < repeat; i++) {
ParserUtils.splitLine(line, ',', '\"', FPConstants.SPLITLINE_SIZE_INIT, false, false);
}
final long stop = System.currentTimeMillis();
System.out.println("ParserUtil " + (stop - start) + " ms.");
}
| 4 |
public void testit( String argstr )
{
WorkBookHandle book = new WorkBookHandle();
// IMPORTANT PERFORMANCE SETTINGS!!!
book.setDupeStringMode( WorkBookHandle.SHAREDUPES );
book.setStringEncodingMode( WorkBookHandle.STRING_ENCODING_COMPRESSED );
WorkSheetHandle sheet = null;
try
{
sheet = book.getWorkSheet( "Sheet1" );
}
catch( WorkSheetNotFoundException e )
{
System.out.println( "couldn't find worksheet" + e );
}
System.out.println( "Beginning Cell Adds" );
String addr = "";
// add a Double check that it was set
sheet.add( new Double( 22250.321 ), "A1" );
try
{
CellHandle cellA3 = sheet.getCell( "A1" );
System.out.println( cellA3.getStringVal() );
}
catch( CellNotFoundException e )
{
;
}
long ltimr = System.currentTimeMillis();
for( int i = 1; i < NUMADDS; i++ )
{
addr = "E" + String.valueOf( i );
sheet.add( new Double( 1297.2753 * i ), addr );
// try{sheet.getCell(addr).getRow().setHeight(2000);}catch(CellNotFoundException e){;}
}
System.out.print( "Adding " + NUMADDS );
System.out.println( " Double values took: " + ((System.currentTimeMillis() - ltimr)) + " milliseconds." );
String teststr = "ExtenXLS is used around the world by Global 1000 and Fortune 500 companies to provide dynamic Excel reporting in their Java web applications.";
teststr += "Written entirely in Java, ExtenXLS frees you from platform dependencies, allowing you to give your users the information they need, in the world's most popular Spreadsheet format.";
try
{
sheet = book.getWorkSheet( "Sheet2" );
}
catch( WorkSheetNotFoundException e )
{
System.out.println( "couldn't find worksheet" + e );
}
String t = "";
// IMPORTANT PERFORMANCE SETTING!!!
sheet.setFastCellAdds( true );
ltimr = System.currentTimeMillis();
for( int i = 1; i < NUMADDS; i++ )
{
addr = "B" + String.valueOf( i );
t = teststr + String.valueOf( i );
sheet.add( t, addr );
//try{sheet.getCell(addr).getRow().setHeight(ROWHEIGHT);}catch(CellNotFoundException e){;}
}
System.out.print( "Adding " + NUMADDS );
System.out.println( " Strings took: " + ((System.currentTimeMillis() - ltimr)) + " milliseconds." );
ltimr = System.currentTimeMillis();
testWrite( book );
System.out.println( "Done." );
System.out.print( "Writing " + book );
System.out.println( " took: " + ((System.currentTimeMillis() - ltimr)) + " milliseconds." );
}
| 5 |
private void createMenu() {
menuBar = new JMenuBar();
setJMenuBar(menuBar);
mnProject = new JMenu("Projekt");
menuBar.add(mnProject);
JMenuItem mntmNewProjectItem = new JMenuItem("Nowa gra");
mnProject.add(mntmNewProjectItem);
JMenuItem mntmSaveProjectItem = new JMenuItem("Zapisz grę");
mnProject.add(mntmSaveProjectItem);
JMenuItem mntmOpenProjectItem = new JMenuItem("Wczytaj grę");
mnProject.add(mntmOpenProjectItem);
mnProject.addSeparator();
JMenuItem mntmGenRaport = new JMenuItem("Raport");
mnProject.add(mntmGenRaport);
JMenuItem mntmCloseProgramItem = new JMenuItem("Zakończ");
mnProject.add(mntmCloseProgramItem);
JMenu mnUser = new JMenu("Użytkownicy");
menuBar.add(mnUser);
JMenuItem dodajUzytkownikaItem = new JMenuItem("Dodaj użytkownika");
mnUser.add(dodajUzytkownikaItem);
JMenuItem usunQuestyItem = new JMenuItem("Usuń zagadki");
mnUser.add(usunQuestyItem);
JMenuItem usunWszystkieDaneItem = new JMenuItem("Usuń wszystkie dane");
mnUser.add(usunWszystkieDaneItem);
JMenu mnPomoc = new JMenu("Pomoc");
menuBar.add(mnPomoc);
JMenuItem infoGameItem = new JMenuItem("Informacje o tworzeniu gier");
mnPomoc.add(infoGameItem);
JMenuItem infoUserItem = new JMenuItem("Informacje o zarządzaniu użytkownikami");
//mnPomoc.add(infoUserItem);
JMenuItem oProgramieItem = new JMenuItem("O programie");
mnPomoc.add(oProgramieItem);
JMenuItem infoAuthorsItem = new JMenuItem("Twórcy");
mnPomoc.add(infoAuthorsItem);
mntmGenRaport.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
createPDFRaport.generatePDF();
createHTMLRaport.generateHTML();
}
});
mntmOpenProjectItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
wczytajPaczke();
}
});
mntmSaveProjectItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tworzNowaGre();
}
});
mntmCloseProgramItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
mntmNewProjectItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int dialogResult = JOptionPane.showConfirmDialog (null, "Twój obecny projekt zostanie utracony. Czy chcesz kontynuować?");
if(dialogResult == JOptionPane.YES_OPTION){
nowaPaczka();
JOptionPane.showMessageDialog(null, "Utworzono nowy projekt gry.");
}
}
});
infoGameItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, instrukcja);
}
});
oProgramieItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane
.showMessageDialog(
null,
"Program utworzony na potrzeby Instytutu Pamięć i Przyszłość jako narzędzie wspomagające proces tworzenia gier edukacyjnych na platformę Android");
}
});
infoAuthorsItem.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane
.showMessageDialog(
null,
"O autorach\n\nKrzysztof Pozorski:\n\tProjektowanie:\n\t\tpomysł, \t\tmechanika gry\n"
+ "\tAndroid:\n\t\tdevelopment\n\tEdytor:\n\t\tnarzędzia, \t\tkonsulting, "
+ "\t\tintegracja z aplikacją mobilną, \ttestowanie\n\nMichał Kowalik:\n\tAndroid:\n"
+ "\t\tintegracja aplikacji z web serwisem\n\tWeb serwis:\n\t\tbaza danych, "
+ "\t\tdevelopment, \t\ttestowanie\n\tEdytor:\n\t\tintegracja z web serwisem, \ttestowanie\n\n"
+ "Arkadiusz Janz:\n\tEdytor:\n\t\tGUI, \t\tLogika\n\nMateusz Olczak:\n\tWeb serwis:\n\t\tintegracja z edytorem, "
+ "\t\tkonsulting\t\nAdministracja\n\nMichał Sypniewski:\n\tEdytor:\n\t\tmapa, \t\tgenerowanie plikow wynikowych, "
+ "\t\tpomoc przy GUI, \t\tobsługa I/O, \ttestowanie\n");
}
});
usunQuestyItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
questTableView.setVisible(true);
}
});
usunWszystkieDaneItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
confirmView.setVisible(true);
}
});
dodajUzytkownikaItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ev) {
userDataRegister.setVisible(true);
}
});
}
| 1 |
public void actionPerformed(ActionEvent ae) {
if (((MenuItem)ae.getSource()).equals(importMenuItem)) {
importAgents();
} else {
exportAgents();
}
}
| 1 |
@Override
public void changedStatus(boolean running, boolean connected){
String icon;
if(running){
if(connected){
this.status.setText("Status: " + STATUS_CONNECTED);
icon = GREEN_ICON;
}else{
this.status.setText("Status: " + STATUS_WAITING);
icon = YELLOW_ICON;
}
toggleBtn.setText("Disable");
}else{
this.status.setText("Status: " + STATUS_DISABLED);
icon = RED_ICON;
toggleBtn.setText("Enable");
}
// Change Frame Icon
ImageIcon im = new ImageIcon(getClass().getResource(icon));
setIconImage(im.getImage());
// Change the system tray icon if it is supported
if (trayIcon != null) {
if(running){
disableAction.setLabel("Disable");
}else{
disableAction.setLabel("Enable");
}
BufferedImage bufImage = null;
try {
bufImage = ImageIO.read(getClass().getResourceAsStream(icon));
} catch (IOException e) {
System.err.println("Could Not Change SysTray icon");
}
int trayIconWidth = new TrayIcon(bufImage).getSize().width;
trayIcon.setImage(bufImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH));
}
}
| 5 |
private IntegerAggregate setDistance(Node start, Node finish, IntegerAggregate distance)
{
IntegerAggregate oldValue = distances.get(NodePair.get(start, finish));
boolean addDistance = oldValue == null || (oldValue.isNonterminating() && !distance.isNonterminating());
if (addDistance)
distances.put(NodePair.get(start, finish), distance);
if (addDistance && start.getId() < getMaxStartNode() && finish.getId() < getMaxTargetNode() &&
start.getId() >= 0 && finish.getId() >= 0)
{
for (IntegerAggregationListener listener : listeners)
listener.aggregateChanged(start.getId(), finish.getId(), distance, this);
}
return oldValue;
}
| 9 |
public int nextopt() {
int argChar = -1;
for (int counter = this.argindex; counter < this.args.length; ++counter) {
if ((args[counter] != null) && (args[counter].length() > 1)
&& (args[counter].charAt(0) == '-')) {
int charIndex = 0;
argChar = args[counter].charAt(1);
charIndex = this.optstring.indexOf(argChar);
this.optarg = null;
if (charIndex != -1) {
this.argindex = counter + 1;
if ((this.optstring.length() > (charIndex + 1))
&& (this.optstring.charAt(charIndex + 1) == ':')) {
if (args[counter].length() > 2) {
this.optarg = args[counter].substring(2).trim();
} else if (args.length > (counter + 1)) {
this.optarg = args[counter + 1];
++this.argindex;
}
}
}
break;
}
}
return argChar;
}
| 9 |
public synchronized static boolean updatePollAnswer(String pollID, String recipientID, String answerID) {
boolean retValu = false;
XStream xstream = new XStream(new DomDriver());
Polls[] allPolls = new Polls[0];
try {
File file = new File((String) Server.prop.get("pollFilePath"));
allPolls = (Polls[]) xstream.fromXML(file);
for (Polls polls : allPolls) {
if (polls.getId().equals(pollID)) {
for (Recipient recipient : polls.getRecipientsArray()) {
if (recipient.getId().equals(recipientID) && !recipient.isDidReply()) {
for (Answer answer : polls.getAnswers()) {
if (answer.getId().equals(answerID)) {
recipient.setDidReply(true);
answer.addToCount();
FileOutputStream fos = new FileOutputStream(file);
xstream.toXML(allPolls, fos);
fos.close();
retValu = true;
}
}
}
}
}
}
} catch (Exception e) {
retValu = false;
}
return retValu;
}
| 8 |
private void determineNextToken() {
if (dfa.isInReturnState())
executeReturn();
else if (dfa.didJumpOccur())
executeJump();
else
moveToNextToken();
}
| 2 |
@Override
public void run() {
while(true){
if(Keyboard.isKeyPressed(KeyEvent.VK_SPACE)){if(energie > 0){energie -= 1;}}
if(energie < 100 && Keyboard.isKeyPressed(KeyEvent.VK_SPACE) == false){energie += 0.25;}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 6 |
public static Lexical scanLexicon(String lexFilePath){
String line= "";
iIdentifier out;
PScanner scan = new PScanner(lexFilePath);
HashMap<String, CharacterC> chars = new HashMap<String, CharacterC>();
ArrayList<TokenC> tokens = new ArrayList<TokenC>();
int state = 0; //state 0 = first comments, 1 = in characters, 2 = in identifiers.
while((line = scan.getLine()) != null)
{
if(line.startsWith("%") || line.isEmpty())
{
if(state == 0)
state = 1;
else if(state == 1)
state = 2;
}
else
if(state == 1 || state == 0) // characters
{
if(state == 0) state = 1;
//Create new char and parse line.
CharacterC character = new CharacterC(line, chars);
chars.put(character.getTitle(), character);
}
else if(state == 2) // identifiers
{
//create new token and parse line
TokenC token = new TokenC(line);
tokens.add(token);
}
}
//Create epsilon using @ symbol
String epsilonStr = "$Epsilon [@]";
chars.put("$Epsilon", new CharacterC(epsilonStr, chars));
return new Lexical(tokens, chars);
}
| 9 |
public void makeColorKeyPixelsTransparent(BufferedImage img, Color colorKey)
{
// NOW MAKE ALL PIXELS WITH COLOR (64, 224, 224) TRANSPARENT
WritableRaster raster = img.getRaster();
int[] dummy = null;
for (int i = 0; i < raster.getWidth(); i++)
{
for (int j = 0; j < raster.getHeight(); j++)
{
int[] pixel = raster.getPixel(i, j, dummy);
if ((pixel[0] == colorKey.getRed())
&& (pixel[1] == colorKey.getGreen())
&& (pixel[2] == colorKey.getBlue()))
{
pixel[3] = 0;
raster.setPixel(i, j, pixel);
}
}
}
}
| 5 |
private void posizionaComponenti()
{
// Prepara il GroupLayout
this.remove(pannello); // Rimuove il pannello
pannello = new JPanel(); // Ne crea uno nuovo
GroupLayout layout = new GroupLayout(pannello); // Crea un nuovo GroupLayout
pannello.setLayout(layout); // Applica un nuovo GroupLayout
this.add(pannello); // Reinserisce il pannello immacolato. Tutto questo perché altrimenti non si possono eliminare le righe in eccesso.
layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);
// Imposta i gruppi orizzontali
GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
layout.setHorizontalGroup(hGroup);
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(btnRimuovi.get(i));
}
}
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
pGroup.addComponent(cbbSpazio);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(txtSpazio.get(i));
}
}
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
pGroup.addComponent(cbbTempo);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(txtTempo.get(i));
}
}
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
pGroup.addComponent(cbbVelocita);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(txtVelocita.get(i));
}
}
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
pGroup.addComponent(cbbMassa);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(txtMassa.get(i));
}
}
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
pGroup.addComponent(cbbEnergia);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(txtEnergia.get(i));
}
}
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(LEADING);
hGroup.addGroup(pGroup);
for (int i=0; i<calcoli; i++)
{
pGroup.addComponent(btnAggiungi.get(i));
}
}
// Imposta la stessa dimensione per i pulsanti Aggiungi e Rimuovi
for (int i=0; i<calcoli; i++)
{
layout.linkSize(SwingConstants.HORIZONTAL, btnAggiungi.get(i), btnRimuovi.get(i));
}
// Imposta i gruppi verticali
GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
layout.setVerticalGroup(vGroup);
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(BASELINE, false);
vGroup.addGroup(pGroup);
pGroup.addComponent(cbbSpazio);
pGroup.addComponent(cbbTempo);
pGroup.addComponent(cbbVelocita);
pGroup.addComponent(cbbMassa);
pGroup.addComponent(cbbEnergia);
}
for (int i=0; i<calcoli; i++)
{
GroupLayout.ParallelGroup pGroup = layout.createParallelGroup(BASELINE, false);
vGroup.addGroup(pGroup);
pGroup.addComponent(btnRimuovi.get(i));
pGroup.addComponent(txtSpazio.get(i));
pGroup.addComponent(txtTempo.get(i));
pGroup.addComponent(txtVelocita.get(i));
pGroup.addComponent(txtMassa.get(i));
pGroup.addComponent(txtEnergia.get(i));
pGroup.addComponent(btnAggiungi.get(i));
}
setMinimumSize(getPreferredSize()); // Imposta la dimensione minima
pack(); // Setta la dimensione minima
}
| 9 |
public static void openFile(File file, Codec[] codecs) {
ParseException p = null;
for (int i = 0; i < codecs.length; i++) {
try {
Serializable object = codecs[i].decode(file, null);
if (openOrRead && !(object instanceof TuringMachine)) {
JOptionPane.showMessageDialog(null,
"Only Turing Machine files can be added as building blocks.", "Wrong File Type",
JOptionPane.ERROR_MESSAGE);
return;
}
lastObject = object;
lastFile = file;
// Set the file on the thing.
if (!openOrRead) {
EnvironmentFrame ef = FrameFactory.createFrame(object);
if (ef == null)
return;
ef.getEnvironment().setFile(file);
ef.getEnvironment().setEncoder(
codecs[i].correspondingEncoder());
}
return;
} catch (ParseException e) {
p = e;
}
}
if (codecs.length != 1)
p = new ParseException("No format could read the file!");
throw p;
}
| 7 |
public boolean satisfy(TagNode tagNode) {
if (tagNode != null ) {
for(Map.Entry<String, String>entry: tagNode.getAttributes().entrySet()) {
if ( (attNameRegex == null || attNameRegex.matcher(entry.getKey()).find()) && (attValueRegex == null || attValueRegex.matcher( entry.getValue() ).find())) {
return true;
}
}
}
return false;
}
| 6 |
public void actionPerformed(java.awt.event.ActionEvent e) {
// Selecting an item results in an actioncommand "comboBoxChanged".
// We should be reacting to these since the drop down doesn't update immediately.
// Hitting enter results in an actioncommand "comboBoxEdited"
// But checking for isValid() tells us if an item was selected
// SB ComboBoxes are meant to be JComboBoxes
if (e.getSource() instanceof JComboBox) {
JComboBox source = (JComboBox) e.getSource();
if (source.isValid()) {
stopCellEditing();
return;
}
}
// Fall back if needed
if (e.getActionCommand().equals("comboBoxEdited")) {
stopCellEditing();
}
}
| 3 |
public int strStr(String haystack, String needle) {
if (haystack == null || needle == null
|| needle.length() > haystack.length()) {
return -1;
}
if (haystack.isEmpty() && needle.isEmpty()) {
return 0;
} else if (needle.isEmpty()) {
return 0;
}
char[] sr = haystack.toCharArray();
char[] nd = needle.toCharArray();
for (int i = 0; i < sr.length; i++) {
if (sr[i] == nd[0]) {
if (isMatch(sr, nd, i)) {
return i;
}
}
}
return -1;
}
| 9 |
public static int jump(int[] A) {
int len = A.length;
if(len < 2) {
return 0;
}
int currentPosition = 0;
int scope = A[0];
int count = 0;
while(currentPosition+scope < len-1) {
if(scope == 0) {
break;
}
int max = 0;
int position = 0;;
for(int i=currentPosition+1;i<(currentPosition+scope+1);i++) {
if((A[i]+i-currentPosition-1) > max && A[i] != 0) {
max = (A[i]+i-currentPosition-1);
position = i;
}
}
currentPosition = position;
count++;
scope = A[position];
}
count++;
if(scope == 0) {
return 0;
} else {
return count;
}
}
| 7 |
public void mergeWithChunkOnEdge(Chunk chunk, Edge edge){
//get the reads
Read rightReadInThisChunk = this.reads.get(this.reads.size() - 1);
Read leftInOther = chunk.reads.get(0);
//establish a connection between them, reuse the edge
edge.setIdA(rightReadInThisChunk.getId());
edge.setIdB(leftInOther.getId());
rightReadInThisChunk.addEdge(edge);
leftInOther.addEdge(edge);
//remove the edge from chunks
this.edges.remove(edge);
chunk.edges.remove(edge);
if(this == chunk){
System.out.println("SAM SA SOBOM!");
System.out.println("EDGE "+edge);
}
//add the reads from other chunk to this one
for(Read readInOtherChunk : chunk.reads){
this.reads.add(readInOtherChunk);
}
//redirect the edges from other chunk to this one
for(Edge edgeInOtherChunk : chunk.edges){
if(edgeInOtherChunk.getIdA() == chunk.getId()){
edgeInOtherChunk.setIdA(this.id);
}else{
edgeInOtherChunk.setIdB(this.id);
}
this.edges.add(edgeInOtherChunk);
}
}
| 4 |
private int getOption()
{
while (true)
{
try
{
System.out.print("\nEnter option: ");
int option = new Scanner(System.in).nextInt();
if (option >= 1 && option <= menuItems.length
|| option == EXIT_OPTION)
{
return option;
}
else
{
System.out.println("\nERROR - Invalid option.");
}
}
catch (InputMismatchException e)
{
System.out.println("ERROR - Not a number.");
}
}
}
| 5 |
public static void main(String[] args) {
OptionParser optionParser = new OptionParser() {
{
accepts(USE_CONFIG)
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(Defaults.USE_CONFIG)
.describedAs("Whether or not the server should create/use a config file");
acceptsAll(asList(JLINE, "jlineEnabled"))
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(Defaults.JLINE_ENABLED)
.describedAs("Whether or not Jline should be enabled");
accepts(ENABLE_LEGACY_PING)
.withRequiredArg()
.ofType(boolean.class)
.defaultsTo(Defaults.LEGACY_PING_ENABLED)
.describedAs("Whether or not the server should also answer legacy ping requests.");
acceptsAll(asList(LOG_FILE, "log"))
.withRequiredArg()
.ofType(String.class)
.defaultsTo(Defaults.LOG_FILE)
.describedAs("The file which should be used to log");
acceptsAll(asList(PORT, "p"))
.withRequiredArg()
.ofType(int.class)
.defaultsTo(Defaults.PORT)
.describedAs("The port the server should bind to.");
accepts(IP)
.withRequiredArg()
.ofType(String.class)
.defaultsTo(Defaults.IP)
.describedAs("The IP the server should bind to");
accepts(PROTOCOL)
.withRequiredArg()
.ofType(int.class)
.defaultsTo(Defaults.PROTOCOL)
.describedAs("The Protocol version the server should use");
accepts(VERSION)
.withRequiredArg()
.ofType(String.class)
.defaultsTo("nope!")
.describedAs("The version displayed to the client when server and client are incompatible");
accepts(ONLINE_PLAYERS)
.withRequiredArg()
.ofType(int.class)
.defaultsTo(Defaults.ONLINE_PLAYERS)
.describedAs("The online players (will appear client side)");
accepts(MAX_ONLINE)
.withRequiredArg()
.ofType(int.class)
.defaultsTo(Defaults.MAX_ONLINE_PLAYERS)
.describedAs("The max online players (will appear client side)").defaultsTo(Defaults.MAX_ONLINE_PLAYERS);
accepts(MOTD)
.withRequiredArg()
.ofType(String.class)
.defaultsTo(Defaults.MOTD)
.describedAs("The motd");
accepts(KICK_MESSAGE)
.withRequiredArg()
.ofType(String.class)
.defaultsTo(Defaults.KICK_MESSAGE)
.describedAs("The default kick message that will be send to the player when he/she tries to login");
accepts(KICK_MESSAGE_BANNED)
.withRequiredArg()
.ofType(String.class)
.defaultsTo(Defaults.KICK_MESSAGE_BANNED)
.describedAs("The default kick message that will be used when a banned player tries to login");
accepts(KICK_MESSAGE_NOT_ON_WHITELIST)
.withRequiredArg()
.ofType(String.class)
.defaultsTo(Defaults.KICK_MESSAGE_NOT_ON_WHITELIST)
.describedAs("The default kick message that will be used when a non-whitelisted player tries to login");
acceptsAll(asList("h", "?", "help", "info"), "Displays some help/info");
}
};
OptionSet optionSet = optionParser.parse(args);
if (optionSet.has("help")) {
PrintWriter printWriter = null;
try {
optionParser.printHelpOn(printWriter = new PrintWriter(System.out));
} catch (IOException e) {
MaintenanceServer.LOGGER.warning("Failed to display the help!");
} finally {
if (printWriter != null) {
printWriter.close();
}
}
return;
}
MaintenanceServer server = new MaintenanceServer(optionSet);
try {
server.start();
server.bind();
} catch (Throwable throwable) {
MaintenanceServer.LOGGER.log(Level.WARNING, "An error occurred during server startup", throwable);
System.exit(-1);
}
}
| 4 |
public Builder addAllPerson(
java.lang.Iterable<? extends protocols.ChatProtocol.ChatPerson> values) {
if (personBuilder_ == null) {
ensurePersonIsMutable();
super.addAll(values, person_);
onChanged();
} else {
personBuilder_.addAllMessages(values);
}
return this;
}
| 2 |
public boolean isConstant() {
if ((Options.options & Options.OPTION_ANON) == 0)
return super.isConstant();
ClassInfo clazz = getClassInfo();
InnerClassInfo outer = getOuterClassInfo(clazz);
ClassAnalyzer clazzAna = methodAnalyzer.getClassAnalyzer(clazz);
if (clazzAna != null && outer != null && outer.outer == null
&& outer.name != null && clazzAna.getParent() == methodAnalyzer) {
/*
* This is a named method scope class, it needs declaration. And
* therefore can't be moved into a field initializer.
*/
return false;
}
return super.isConstant();
}
| 6 |
private void displayItem()
{
Statement st = null;
ResultSet rs = null;
try {
st = custConn.getConnection().createStatement();
System.out.println(customerID);
String qry = "select * from ShoppingCart sc where sc.customer_ID = '" + customerID + "'";
rs = st.executeQuery(qry);
while(rs.next())
{
System.out.println("stock number: " + rs.getString("stock_number"));
System.out.println(" qty: " + rs.getInt("quantity"));
}
while (rs.next())
{
System.out.println("Shopping Cart:");
}
} catch (Exception e) {
System.out.println("error with sql statement");
}
}
| 3 |
protected void stepBackward() {
CellElement currentCell;
switch (m_currentPhase) {
case PHASE_CALC_GRID:
m_currentStep--;
if (m_currentStep <= 0) {
stepZero();
return;
}
Point realD = getCoordsByStep(m_currentStep);
currentCell = m_dpTable.getCell(realD.x, realD.y);
// erasing pointers
currentCell.clearAll();
m_currentStep--;
stepForward(true);
break;
case PHASE_SELECT_LOCAL:
putFourDrawablePanel();
m_currentStep--;
m_currentPhase = PHASE_CALC_GRID;
m_dpTable.clearHighlightColors();
m_dpTable.clearInteractiveCells();
stepForward(true);
break;
case PHASE_BACKTRACK:
currentCell = (CellElement) m_backTrackList.getLast();
currentCell.clearColor();
if (m_backTrackList.size() <= 1) {
m_currentPhase = PHASE_SELECT_LOCAL;
m_backTrackList.clear();
m_dpTable.clearAllArrows();
m_dpTable.clearGridCircle();
m_dpTable.clearHighlightColors();
m_dpTable.clearInteractiveCells();
setInfoMessage("Select Starting local!");
m_lDEqual.setText("D(x, x) = Select");
m_l1Choiche.setText("No Pointer");
m_l2Choiche.setText("No Pointer");
m_l3Choiche.setText("No Pointer");
this.findMaxValues();
}
else {
m_backTrackList.removeLast();
currentCell = (CellElement) m_backTrackList.getLast();
currentCell.clearColor();
if (m_backTrackList.size() == 0) {
m_backtrackLastSel = m_dpTable.getLastCell();
}
else {
m_backtrackLastSel = (CellElement) m_backTrackList.getLast();
m_backTrackList.removeLast();
}
// cut result string
boolean toErase = false;
for (int i = 0; i < 3; i++) {
if (m_resLine[i].length() > 1) {
m_resLine[i] = m_resLine[i].substring(2,
m_resLine[i].length());
}
else {
m_resLine[i] = "";
toErase = true;
}
}
if (toErase) {
m_bottomResultArea.setText("");
}
stepFWDBackTrack(true);
}
break;
}
}
| 9 |
static public Object deserializeArray(InputStream in, Class elemType, int length)
throws IOException
{
if (elemType==null)
throw new NullPointerException("elemType");
if (length<-1)
throw new IllegalArgumentException("length");
Object obj = deserialize(in);
Class cls = obj.getClass();
if (!cls.isArray())
throw new InvalidObjectException("object is not an array");
Class arrayElemType = cls.getComponentType();
if (arrayElemType!=elemType)
throw new InvalidObjectException("unexpected array component type");
if (length != -1)
{
int arrayLength = Array.getLength(obj);
if (arrayLength!=length)
throw new InvalidObjectException("array length mismatch");
}
return obj;
}
| 6 |
public void render(int[] pixels, int offset, int row)
{
for (int yTile = yOffset >> 3; yTile <= (yOffset + height) >> 3; yTile++)
{
int yMin = yTile * 8 - yOffset;
int yMax = yMin + 8;
if (yMin < 0) yMin = 0;
if (yMax > height) yMax = height;
for (int xTile = xOffset >> 3; xTile <= (xOffset + width) >> 3; xTile++)
{
int xMin = xTile * 8 - xOffset;
int xMax = xMin + 8;
if (xMin < 0) xMin = 0;
if (xMax > width) xMax = width;
int tileIndex = (xTile & (MAP_SIZE_MASK)) + (yTile & (MAP_SIZE_MASK)) * MAP_SIZE;
for (int y = yMin; y < yMax; y++)
{
int sheetPixel = ((y + yOffset) & 7) * sheet.width + ((xMin + xOffset) & 7);
int tilePixel = offset + xMin + y * row;
for (int x = xMin; x <xMax; x++)
{
int colour = tileIndex * 4 + sheet.pixels[sheetPixel++];
pixels[tilePixel++] = colours[colour];
}
}
}
}
}
| 8 |
public void setTwitter_user_name(String twitter_user_name) {
this.twitter_user_name = twitter_user_name;
}
| 0 |
@Override
public void windowDeiconified(WindowEvent e)
{
}
| 0 |
public static void main(String[] args) throws IOException {
MelonSearch search = MelonSearch.getinstance();
search.setOrder(MelonSearch.POPULAR);
search.setMaxSize(100);
search.setMinSize(1);
search.setSongName("괜찮아");
search.Search();
search.getSIDList();
search.getAlbumartList();
System.out.println(search.getAllData().size());
// for (SearchData DATA : search.getAllData()) {
// System.out.println(DATA.getSID() + ":" + DATA.getSongName() + ":" + DATA.getAlbumart() + ":" + DATA.getSinger());
// }
// search.Top100(MelonSearch.TOP100WEEKLY);
// System.out.println(search.getAllData().size());
for (SearchData DATA : search.getAllData()) {
System.out.println(DATA.getSID() + ":" + DATA.getSongName() + ":" + DATA.getAlbumart() + ":" + DATA.getSinger());
}
/*
* Melon Class는
* Melon(아이디, 페스워드); 로 초기화.
* melon.Login(); Keycookie와 IdCookie생성.
* 아이디와 비밀번호를 따로 지정 할 수 있음.
* melon.setID(String ID);
* melon.setPW(String PW);
* melon.Login();
* 이과정을 걸치면 다시 Keycookie와 IdCookie를 다시 설정.
*/
try {
Melon melon = new Melon(id, pw);
melon.Login();
System.out.println(melon.getKeyCookie());
melon.setKeyCookie(String.valueOf(Integer.parseInt(melon.getKeyCookie()) + 100));
/*
* MelonSong Class에는 Melon Class Object를 파라미터로 한다.
* MelonSong Class에서는 음악 ID를 입력 getSongData(String SONGID); 와 같은 형식으로
* 음악 정보를 받아와서 getMusicURL(); getSongName(); getSingerName(); getBitrate(); getAlbumID(); getLyricsURL();
* 를 이용해 그 음악 ID의 음악 정보를 볼 수 있다.
*/
MelonSong melonsong = new MelonSong(melon);
melonsong.getSongData(search.getSIDList().get(1));
System.out.println("AlbumID : " + melonsong.getAlbumID());
System.out.println("Bitrate : " + melonsong.getBitrate());
System.out.println("AlbumName : " + melonsong.getAlbumName());
System.out.println("Lyrics : " + melonsong.getLyricsURL());
System.out.println("Year : " + melonsong.getYear().substring(0, 4));
System.out.println("Music : " + melonsong.getMusicURL());
System.out.println("Singer : " + melonsong.getSingerName());
System.out.println("Title : " + melonsong.getSongName());
System.out.println("AlbumArt : " + melonsong.getAlbumArtURL());
System.out.println("MusicVideo : " + melonsong.getMvURL());
System.out.println("StringLyrics : " + melonsong.getStringLyrics());
System.out.println("BanSong : " + melonsong.isBanSong());
} catch (LoginFailException e) {
e.printStackTrace();
} catch (GetSongDataException e) {
e.printStackTrace();
}
}
| 3 |
public static Rarity fromString(String s) throws IOException {
if (s.equalsIgnoreCase("basic")) {
return BASIC;
} else if (s.equalsIgnoreCase("fine")) {
return FINE;
} else if (s.equalsIgnoreCase("masterwork")) {
return MASTERWORK;
} else if (s.equalsIgnoreCase("rare")) {
return RARE;
} else if (s.equalsIgnoreCase("exotic")) {
return EXOTIC;
} else if (s.equalsIgnoreCase("ascended")) {
return ASCENDED;
} else if (s.equalsIgnoreCase("legendary")) {
return LEGENDARY;
} else {
throw new IOException();
}
}
| 7 |
private void fillStatement(PreparedStatement stmt, Object... params)
throws SQLException {
// check the parameter count, if we can
ParameterMetaData pmd = null;
if (!pmdKnownBroken) {
pmd = stmt.getParameterMetaData();
int stmtCount = pmd.getParameterCount();
int paramsCount = params == null ? 0 : params.length;
if (stmtCount != paramsCount) {
throw new SQLException("Wrong number of parameters: expected "
+ stmtCount + ", was given " + paramsCount);
}
}
if (params == null) {
return;
}
for (int i = 0; i < params.length; i++) {
if (params[i] != null) {
stmt.setObject(i + 1, params[i]);
} else {
int sqlType = Types.VARCHAR;
if (!pmdKnownBroken) {
try {
sqlType = pmd.getParameterType(i + 1);
} catch (SQLException e) {
pmdKnownBroken = true;
}
}
stmt.setNull(i + 1, sqlType);
}
}
}
| 8 |
protected HttpEntity toJsonEntity(final Object obj) {
String json = toJson(obj);
try {
return new JsonEntity(json);
} catch (Exception ex) {
Class clazz = null;
if (obj != null) {
clazz = obj.getClass();
}
throw new RuntimeException("failure, obj class=" + clazz, ex);
}
}
| 2 |
@Override
public void QuitNetGame() throws IOException {
int i, j;
if (eval(debugfile))
try {
debugfile.close();
} catch (IOException e) {
e.printStackTrace();
}
if (!netgame || !usergame || consoleplayer == -1 || demoplayback)
return;
// send a bunch of packets for security
netbuffer.player = (byte) consoleplayer;
netbuffer.numtics = 0;
for (i = 0; i < 4; i++) {
for (j = 1; j < doomcom.numnodes; j++)
if (nodeingame[j])
HSendPacket(j, NCMD_EXIT);
I.WaitVBL(1);
}
}
| 9 |
public boolean onCommand(Player player, String[] args) {
File fichier_language = new File(OneInTheChamber.instance.getDataFolder() + File.separator + "Language.yml");
FileConfiguration Language = YamlConfiguration.loadConfiguration(fichier_language);
if(player.hasPermission(getPermission())){
if(args.length > 1){
try{
Integer.parseInt(args[0]);
}catch(NumberFormatException e){
String badArg = Language.getString("Language.Error.Bad_args");
UtilSendMessage.sendMessage(player, badArg);
return true;
}
int minPlayers = Integer.parseInt(args[0]);
String arenaName = args[1];
if(ArenaManager.getArenaManager().getArenaByName(arenaName) != null){
if(ArenaManager.getArenaManager().getArenaByName(arenaName).getMaxPlayers() >= minPlayers){
ArenaManager.getArenaManager().getArenaByName(arenaName).setMinPlayers(minPlayers);
ArenaManager.getArenaManager().getArenaByName(arenaName).saveConfig();
String succes = Language.getString("Language.Setup.Min_players_succesfully_set").replaceAll("%arena", arenaName);
UtilSendMessage.sendMessage(player, succes);
return true;
}else{
String tooBig = Language.getString("Language.Setup.Min_players_too_big");
UtilSendMessage.sendMessage(player, tooBig);
return true;
}
}else{
String doesntExist = Language.getString("Language.Error.Arena_does_not_exist").replaceAll("%arena", arenaName);
UtilSendMessage.sendMessage(player, doesntExist);
}
}else{
String notEnoughArgs = Language.getString("Language.Error.Not_enough_args");
UtilSendMessage.sendMessage(player, notEnoughArgs);
return true;
}
}else{
String notPerm = Language.getString("Language.Error.Not_permission");
UtilSendMessage.sendMessage(player, notPerm);
}
return true;
}
| 5 |
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(JFrameMembresia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(JFrameMembresia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(JFrameMembresia.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(JFrameMembresia.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 JFrameMembresia(esNueva, cliente).setVisible(true);
}
});
}
| 6 |
public boolean SEEK()
{
if(order.length()>0)
{
idx O = ( Cdx==null ? Idx :
( Cdx.I>=0 ? Cdx.Idx[ Cdx.I ] : null ));
if(O!=null)
{
PREPARE_KEY_FROM_DATA( O );
if(Idx!=null) Idx.seek(false);
else Cdx.seek(false);
go_recno( O.found || (O.sRecno>0) ? O.sRecno : reccount+1 );
// otherwise sRecno contains nearest
return O.found;
}
}
return false;
}
| 7 |
private void construire(){
this.setLayout(new BorderLayout(0,0));
JPanel semaine = new JPanel(new GridLayout(1, 7));
JPanel mois = new JPanel(new GridLayout(6, 7));
String[] nomsJours = {"Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"};
// Affichage des noms des jours de la semaine dans le JPanel semaine.
for(int i = 0; i < nomsJours.length; i++){
JLabel jour = new JLabel(nomsJours[i], JLabel.CENTER);
if(i == 0)
jour.setBorder(new MatteBorder(1,1,0,1, new Color(0x888888)));
else
jour.setBorder(new MatteBorder(1,0,0,1, new Color(0x888888)));
semaine.add(jour);
}
jours = new Jour[6*7];
labelsJours = new JLabel[6*7];
// Affichage des numéros des jours du mois dans le JPanel mois.
for(int i = 0; i < 6*7; i++){
jours[i] = new Jour();
labelsJours[i] = jours[i].num_jour;
/* bordures */
/* il y a surement un moyen moins dégeulasse de faire ça */
if(i == 0)
jours[i].setBorder(new MatteBorder(1,1,1,1, new Color(0x888888)));
else if(i < 7)
jours[i].setBorder(new MatteBorder(1,0,1,1, new Color(0x888888)));
else if(i % 7 == 0)
jours[i].setBorder(new MatteBorder(0,1,1,1, new Color(0x888888)));
else
jours[i].setBorder(new MatteBorder(0,0,1,1, new Color(0x888888)));
mois.add(jours[i]);
}
this.add(semaine, BorderLayout.NORTH);
this.add(mois, BorderLayout.CENTER);
}
| 6 |
public static boolean wordBreak(String s, Set<String> dict) {
boolean[] isWord = new boolean[s.length()+1];
isWord[0] = true;
for( int i = 0; i< s.length(); i++) {
// start from the matching word
if(!isWord[i]) {
continue;
}
for( String word : dict) {
int end = i + word.length();
if(end > s.length()) {
continue;
}
if(isWord[end]) {
continue;
}
if(s.substring(i, end).equals(word)) {
isWord[end] = true;
}
}
}
return isWord[s.length()];
}
| 6 |
public void Start() {
if (Running)
return;
Running = true;
BanHandler.init();
es = new EventSystem(this);
startLogger();
Log("Starting..");
ch = new CommandHandler(this);
Group.Load(this);
p = Properties.init(this);
loadSystemProperties();
pm = new PacketManager(this);
pm.StartReading();
Log("Loading main level..");
lm = new LevelHandler(this);
if (!new File(getSystemProperties().getValue("MainLevel")).exists()) {
Level l = new Level((short)64, (short)64, (short)64);
l.name = "Main";
l.FlatGrass(this);
try {
l.Save();
} catch (IOException e) {
e.printStackTrace();
}
}
MainLevel = lm.loadLevel(getSystemProperties().getValue("MainLevel"));
lm.loadLevels();
tick.start();
Log("Done!");
Log("Generating salt");
SecureRandom sr = null;
try {
sr = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int i = 0; i < 100; i++) {
byte[] seedb = new byte[16];
sr.nextBytes(seedb);
Salt = new sun.misc.BASE64Encoder().encode(seedb).replace("=", "" + ((Salt != null) ? Salt.toCharArray()[0] : "A"));
if (new Random().nextDouble() < .3)
break;
}
Salt = LetterOrNumber(Salt);
Log("SALT: " + Salt);
Log("Setting up SQL");
sql.Connect(this);
final String[] commands = new String[] {
"CREATE TABLE if not exists " + sql.getPrefix() + "_extra (name VARCHAR(20), setting TEXT, value TEXT);",
};
sql.ExecuteQuery(commands);
Log("Done!");
Log("Create heartbeat..");
heartbeater = new Beat(this);
heartbeater.addHeart(new MBeat());
heartbeater.addHeart(new WBeat());
heartbeater.start();
Log("Done!");
ph = new PluginHandler();
ph.loadplugins(this);
try {
addCommands();
} catch (IOException e) {
e.printStackTrace();
}
}
| 8 |
public static void load() {
// Create the connection to
ExecutorService pool = Executors.newFixedThreadPool(1);
Thread th = new Thread() {
public void run() {
int i = 0;
while (i++ < 10) {
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
};
Future fut = pool.submit(th);
int i = 0;
while (true) {
if (fut.isDone())
break;
try {
Thread.sleep(300);
if (i++ > 20) {
i = 0;
System.out.println();
}
System.out.print(".");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
pool.shutdown();
}
| 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(ListaCartoesNAOUSADA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ListaCartoesNAOUSADA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ListaCartoesNAOUSADA.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ListaCartoesNAOUSADA.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() {
getInstace().setVisible(true);
}
});
}
| 6 |
void addIfTestMethod(Method m) {
if(m.getAnnotation(Test.class) == null)
return;
if(!(m.getReturnType().equals(boolean.class) ||
m.getReturnType().equals(void.class)))
throw new RuntimeException("@Test method" +
" must return boolean or void");
m.setAccessible(true); // In case it's private, etc.
add(m);
}
| 3 |
private String getDescription() {
String desc = "@MongoCount(" + this.getParsedShell().getOriginalExpression() + ")";
if (!StringUtils.isEmpty(globalCollectionName)) {
desc = ",@MongoCollection(" + globalCollectionName + ")";
}
return desc;
}
| 1 |
private int getMachineIndexBySelectedRow(JTable table){
InputTableModel model = (InputTableModel) table.getModel();
int row = table.getSelectedRow();
if(row < 0) return -1;
String machineFileName = (String)model.getValueAt(row, 0);
return getMachineIndexByName(machineFileName);
}
| 1 |
public boolean distributionStrategy(int[] bowl) {
predictDistribution();
double expectedScore = calculateExpectedScore();
// Take a bowl greater than your expected score based on the distribution
if (bowlScore(bowl) > expectedScore + .05 * expectedScore)
return true;
return false;
}
| 1 |
public static int[][] textToGrid(String text) {
int[] nums = stringToInts(text);
if (nums.length != SIZE*SIZE) {
throw new RuntimeException("Needed 81 numbers, but got:" + nums.length);
}
int[][] result = new int[SIZE][SIZE];
int count = 0;
for (int row = 0; row<SIZE; row++) {
for (int col=0; col<SIZE; col++) {
result[row][col] = nums[count];
count++;
}
}
return result;
}
| 3 |
public static Storeable deserialize(Table table, String value) {
if (value == null) {
return null;
}
Storeable result = new MyStoreable(table);
JsonArray array = (new JsonParser().parse(value)).getAsJsonArray();
for (Integer i = 0; i < array.size(); ++i) {
result.setColumnAt(i, array.get(i));
}
return result;
}
| 2 |
protected Environment getEnvironment() {
return environment;
}
| 0 |
@Override
public Line getNextFromTitle() {
Title title = (Title) this.getParent();
if (title.getParent().isVisible()) {
if (title.getParent().getTextIntro().getLineNb() > 0) {
return title.getParent().getTextIntro().getFirstLine();
}
else if(title.getParent().getNextSection() != null){
return title.getParent().getNextSection().getFirstLine();
}
else {
return this;
}
} else {
if (title.getParent().getNextSiblingOrAncestor() != null) {
return title.getParent().getNextSiblingOrAncestor().getFirstLine();
}
return this;
}
}
| 4 |
private static Connection getDBConnection() {
Connection dbConnection = null;
url = "jdbc:oracle:thin:@" + server + ":" + port + ":" + sid;
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
dbConnection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return dbConnection;
}
| 2 |
public void Tick()
{
//MOVEMENT
boolean[][]RoomUnitMap = new boolean[this.GrabModel().MapSizeX][this.GrabModel().MapSizeY];
for(Session mSession : this.GrabParty().values())
{
if(mSession.GrabActor().NeedsPathChange) //Give them .5 of a second to get ready for their new path
{
Collection<byte[]> Path = this.Pathfinder.Path(
(byte)mSession.GrabActor().CurrentPosition.X,
(byte)mSession.GrabActor().CurrentPosition.Y,
(byte)mSession.GrabActor().GoalPosition.X,
(byte)mSession.GrabActor().GoalPosition.Y,
Grizzly.GrabHabboHotel().GrabRoomHandler().MaxDrop,
Grizzly.GrabHabboHotel().GrabRoomHandler().MaxJump);
mSession.GrabActor().CurrentPath = Path;
mSession.GrabActor().Move(true);
//mSession.GrabActor().NewPathReady = true;
}
else if(mSession.GrabActor().GoalPosition != null && !mSession.GrabActor().IsMoving && !mSession.GrabActor().NeedsPathChange) //Start moving them
{
Collection<byte[]> Path = this.Pathfinder.Path(
(byte)mSession.GrabActor().CurrentPosition.X,
(byte)mSession.GrabActor().CurrentPosition.Y,
(byte)mSession.GrabActor().GoalPosition.X,
(byte)mSession.GrabActor().GoalPosition.Y,
Grizzly.GrabHabboHotel().GrabRoomHandler().MaxDrop,
Grizzly.GrabHabboHotel().GrabRoomHandler().MaxJump);
mSession.GrabActor().CurrentPath = Path;
mSession.GrabActor().Move(false);
}
RoomUnitMap[mSession.GrabActor().CurrentPosition.X][mSession.GrabActor().CurrentPosition.Y] = true;
this.Pathfinder.ApplyCollisionMap(GenerateCollisionMap(RoomUnitMap), GenerateFurniHeightMap());
//SIGNS
if (mSession.GrabActor().SignTimer > 0)
{
if (mSession.GrabActor().SignTimer == 1)
{
mSession.GrabActor().UpdateStatus("");
}
mSession.GrabActor().SignTimer--;
}
}
}
| 7 |
public String retrieveOrderInfo(String supName,int orderID) throws SQLException{
String orderInfo = null;
try{
databaseConnector=myConnector.getConnection();
stmnt=(Statement) databaseConnector.createStatement();
SQLQuery="SELECT orderInfo FROM familydoctor.order WHERE orderID="+"'"+orderID+"'";
dataSet=stmnt.executeQuery(SQLQuery);
while(dataSet.next()){
orderInfo=dataSet.getString("orderInfo");
}
}
catch(SQLException e){
System.out.println(e.getMessage());
}
finally{
if(stmnt!=null)
stmnt.close();
if(databaseConnector!=null)
databaseConnector.close();
}
return orderInfo;
}
| 4 |
public int[] getRange()
{
return myRange;
}
| 0 |
public void createMemento() {
c.saveMemento(new Memento(state));
}
| 0 |
public Coordinate move(String commands) {
move:
for(int i = 0; i < commands.length(); i++) {
Coordinate newPosition;
switch(commands.charAt(i)) {
case 'l':
turnLeft();
break;
case 'r':
turnRight();
break;
case 'f':
newPosition = grid.getNewPosition(currentPosition, moveForward());
if(grid.isAvailable(newPosition)) {
currentPosition = newPosition;
} else {
reportObstacle();
break move;
}
break;
case 'b':
newPosition = grid.getNewPosition(currentPosition, moveBackward());
if(grid.isAvailable(newPosition)) {
currentPosition = newPosition;
} else {
reportObstacle();
break move;
}
break;
}
}
return currentPosition;
}
| 7 |
public static void main (String[] args)
{
if (args.length != 1) {
System.err.println("Uso: java LectorMatrizXML <archivo>");
System.exit(1);
}
try {
LectorMatrizXML lector = new LectorMatrizXML(args[0]);
int i;
System.out.println("Default "+lector.getDefault());
System.out.println("Renglones "+lector.getRenglones());
System.out.println("Columnas "+lector.getColumnas());
System.out.println("Tipo "+lector.getTipo());
System.out.println("Entradas "+lector.getEntradas());
for (i=0; i<lector.getEntradas(); i++){
System.out.print("i= "+i+"\tRenglon: "+lector.getRenglon());
System.out.print("\tColumna: "+lector.getColumna());
System.out.println("\tContenido: "+lector.getEntrada());
if (lector.haySiguiente())
lector.siguienteEntrada();
}
}
catch (IndexOutOfBoundsException exio){
System.err.println("Se salio");
}
catch (Exception ex){
System.err.println("Oops!");
}
}
| 5 |
@Override
public void metaData(String[] args) {
MetaData.main(args);
}
| 0 |
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("money")) {
update();
}
}
| 1 |
public int getPartsSize(){
return parts.size();
}
| 0 |
private TimeSerieRange findBiggestTimeSerieRange() {
if (this.timeSeriesConfigs != null) {
TimeSerieRange result = new TimeSerieRange();
if (this.timeSeriesConfigs.size() >= 1) {
TimeSerieRange tscRange = this.timeSeriesConfigs.get(0).getTimeSerie().getRange();
result.setMinX(tscRange.getMinX());
result.setMaxX(tscRange.getMaxX());
result.setMinY(tscRange.getMinY());
result.setMaxY(tscRange.getMaxY());
}
for (TimeSerieConfig tsc : this.timeSeriesConfigs) {
TimeSerieRange tscRange = tsc.getTimeSerie().getRange();
if (tscRange.getMinX() < result.getMinX()) {
result.setMinX(tscRange.getMinX());
}
if (tscRange.getMinY() < result.getMinY()) {
result.setMinY(tscRange.getMinY());
}
if (tscRange.getMaxX() > result.getMaxX()) {
result.setMaxX(tscRange.getMaxX());
}
if (tscRange.getMaxY() > result.getMaxY()) {
result.setMaxY(tscRange.getMaxY());
}
}
return result;
}
return null;
}
| 7 |
private int getMMC(int valor1, int valor2) {
int n = 2;
int resultado = 1;
valor1 = valor1 < 0 ? valor1*-1: valor1;
valor2 = valor2 < 0 ? valor2*-1: valor2;
while(valor1 != 1 || valor2 != 1){
while(valor1 % n != 0 && valor2 % n != 0){
n++;
}
if(valor1 % n == 0){
valor1 = valor1 / n;
}
if(valor2 % n == 0){
valor2 = valor2 / n;
}
resultado *= n;
}
return resultado;
}
| 8 |
@Test
public void scale_test() {
try{
double [][]mat1= {{1.0,2.0}, {3.0,1.0}};
double factor= 2;
double[][]result = Matrix.scale(mat1, factor);
double exp[][]={{2.0,4.0},{6.0,2.0}};
Assert.assertArrayEquals(exp, result);
}
catch (Exception e) {
// TODO Auto-generated catch block
fail("Not yet implemented");
}
}
| 1 |
private boolean backtracking(ArrayList<Clausula> clau, Quadricula qu, int j) {
if (clau.size() == j) { // Tenim una solucio
return true;
} else {
Clausula c = clau.get(j);
for (ClausulaNom cn : c.getClausula()) {
Element e = new Element();
e.setAssignatura(c.getAssignatura());
e.setAula(cn.getAula());
e.setGrupo(c.getGrup());
int duracio = c.getDuracio();
int esVal = 0;
for (int i = 0; i < duracio; ++i) {
int hor = cn.getHora()+i;
String di = cn.getDia();
qu.afegirElement(di, hor, e);
if (! assignacioValida(qu, e, di, hor,cn,c,duracio,i)) ++esVal;
}
if (esVal == 0) {
boolean b = backtracking(clau, qu,j+1);
if (b) return true;
else {
for (int i = 0; i < duracio; ++i) {
int hor = cn.getHora() + i;
String di = cn.getDia();
qu.borrarElement(di, hor, e);
}
}
}
else {
for (int i = 0; i < duracio; ++i) {
int hor = cn.getHora() + i;
String di = cn.getDia();
qu.borrarElement(di, hor, e);
}
}
}
return false;
}
}
| 8 |
void parseFields()
{
int ndx = 0;
for (Field field : actualClass.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
int hash = (jsonProperty != null ? jsonProperty.name().hashCode() : field.getName().hashCode());
fieldHashes[ndx] = hash;
ndx++;
}
}
Arrays.sort(fieldHashes);
for (Field field : actualClass.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class);
int hash = (jsonProperty != null ? jsonProperty.name().hashCode() : field.getName().hashCode());
boolean excluded = (jsonProperty != null && jsonProperty.exclude());
Phield phield = new Phield(field, excluded);
// Hash slot
int slot = (hash & quickLookup.length - 1);
for (int i = 0; i < fieldHashes.length; i++) {
if (fieldHashes[i] == hash) {
fields[i] = phield;
quickLookup[slot] = i + 1;
break;
}
}
}
}
}
| 9 |
private void MovieTitleRemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_MovieTitleRemoveButtonActionPerformed
String delMovie = MovieTitleRTextField.getText();
out.println("4!" + delMovie);
try {
String delRecord = in.readLine();
if (delRecord.equals("0")) {
JOptionPane.showMessageDialog(null, "The movie has been successfully deleted!!!", "Videio Deleted", 1);
} else {
JOptionPane.showMessageDialog(null, "the movie does not exist!!", "Error", 0);
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e, "Error", 0);
}
}//GEN-LAST:event_MovieTitleRemoveButtonActionPerformed
| 2 |
public void setVisible(boolean isVisible) {
if (!isVisible && superGroup != null) {
superGroup.setNewGroupBounds();
}
this.isVisible = isVisible;
}
| 2 |
private String getStartButtonTooltips(){
StringBuffer sb = new StringBuffer();
if(isGameReady()){
sb.append( "Start the Scrabble Game with: ");
for(Player p : players){
sb.append(p.getName()+" ");
}
}
else{
sb.append("Invalid player number. Must have 2 - 4 players.");
if(players == null || players.size()==0){
sb.append("Currently there is no player in the game.");
}
else{
sb.append("Currently there are: ");
for(Player p : players){
sb.append(p.getName());
}
}
}
return sb.toString();
}
| 5 |
public ArrayList<Object> upperOutliersAnscombe_as_double(double constant) {
switch (type) {
case 1:
double[] dd = this.getArray_as_double();
upperOutlierDetails = upperOutliersAnscombeAsArrayList(dd, constant);
break;
case 12:
BigDecimal[] bd = this.getArray_as_BigDecimal();
ArrayList<Object> ret = new ArrayList<Object>();
ret = upperOutliersAnscombeAsArrayList(bd, new BigDecimal(constant));
upperOutlierDetails.add(ret.get(0));
BigDecimal[] bd1 = (BigDecimal[]) ret.get(1);
ArrayMaths am1 = new ArrayMaths(bd1);
upperOutlierDetails.add(am1.getArray_as_Double());
upperOutlierDetails.add(ret.get(2));
BigDecimal[] bd2 = (BigDecimal[]) ret.get(3);
ArrayMaths am2 = new ArrayMaths(bd2);
upperOutlierDetails.add(am2.getArray_as_Double());
break;
case 14:
throw new IllegalArgumentException("Outlier detection of Complex is not supported");
default:
throw new IllegalArgumentException("This type number, " + type + ", should not be possible here!!!!");
}
upperDone = true;
return upperOutlierDetails;
}
| 3 |
public short getShort(Object key) {
Number n = get(key);
if (n == null) {
return (short) 0;
}
return n.shortValue();
}
| 1 |
public final void setRootAction(Action a) {
if(a == null)
rootAction = defaultRootAction;
else
rootAction = a;
}
| 1 |
public List<IPEntry> getIPEntries(String s) {
List<IPEntry> ret = new ArrayList<IPEntry>();
try {
// 映射IP信息文件到内存中
if (mbb == null) {
FileChannel fc = ipFile.getChannel();
mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, ipFile.length());
mbb.order(ByteOrder.LITTLE_ENDIAN);
}
int endOffset = (int) ipEnd;
for (int offset = (int) ipBegin + 4; offset <= endOffset; offset += IP_RECORD_LENGTH) {
int temp = readInt3(offset);
if (temp != -1) {
IPLocation ipLoc = getIPLocation(temp);
// 判断是否这个地点里面包含了s子串,如果包含了,添加这个记录到List中,如果没有,继续
if (ipLoc.getCountry().indexOf(s) != -1
|| ipLoc.getArea().indexOf(s) != -1) {
IPEntry entry = new IPEntry();
entry.country = ipLoc.getCountry();
entry.area = ipLoc.getArea();
// 得到起始IP
readIP(offset - 4, b4);
entry.beginIp = Util.getIpStringFromBytes(b4);
// 得到结束IP
readIP(temp, b4);
entry.endIp = Util.getIpStringFromBytes(b4);
// 添加该记录
ret.add(entry);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
| 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.