method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
ebbc607b-b5b2-4e3e-8eae-881a71add78f | 5 | public MenuLevelSelect(Game game) {
setVisible(false);
int gridx = 0;
int gridy = 0;
int lvlCount = 0;
if (path.exists()) {
for (File lvl : path.listFiles()) {
if (lvl.getName().contains("terrain")) {
if (lvlCount > 12)
BlueMaggot.e = new Exception("Too many levels added! Max is 12.");
MenuLevelButton btnLvl = new MenuLevelButton(lvl, this);
if (gridx <= 3) {
gridx++;
} else {
gridx = 1;
++gridy;
}
add(btnLvl, new GBC(gridx, gridy, Align.MID));
lvlBtns.add(btnLvl);
lvlCount++;
}
}
} else
BlueMaggot.e = new FileNotFoundException("\nPath: " + path.getAbsolutePath());
add(new MenuButton(Labels.APPLY, this, game), new GBC(1, ++gridy, Align.MID).setSpan(2, 1));
add(new MenuButton(Labels.RETURN, this, game), new GBC(3, gridy, Align.MID).setSpan(2, 1));
} |
14818f38-c9d1-4c1b-957c-cc1f219e20d8 | 9 | public int grow(int growdirection) {
int dx =0;
int dy = 0;
switch (growdirection) {
case 0:
dx = 0;
dy = -1;
break;
case 1:
dx = 1;
dy = 0;
break;
case 2:
dx = 0;
dy = 1;
break;
case 3:
dx = -1;
dy = 0;
break;
default:
//System.out.println("invalid growdirection");
break;
}
try{
if(length<14 && ready ==1 &&(bitMap.Map[body[length].x+dx][ body[length].y+dy].Resident==null))
{
length += 1;
body[length] = bitMap.Map[body[length-1].x+dx][ body[length-1].y+dy];
if(length == 1)
{body[length].color =11916201;}
else
body[length].color = (body[length-1].color + 255*2 + 4);
body[length].Resident = body[0].Resident;
//(int)(body[length-1].color*1.1);
ready =0;
return 1;
}
else{
// System.out.println("grow failed!");
ready =0;
return 0;
}
}catch(ArrayIndexOutOfBoundsException e ){
ready =0;
return 0;
}
} |
7cea19d3-4720-4a65-8444-24edc13bb079 | 1 | public char evaluate_char(Object[] dl) throws Throwable {
if (Debug.enabled)
Debug.println("Wrong evaluateXXXX() method called,"+
" check value of getType().");
return '?';
}; |
7514a746-db3b-4d48-bbf1-f2f35e546094 | 0 | public void setItem(Items item) {
this.item = item;
} |
63bf7b9c-3d01-49ed-990e-5306f0c99cad | 7 | public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.jtattoo.plaf.texture.TextureLookAndFeel");
}
catch (UnsupportedLookAndFeelException e)
{
try
{
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
System.exit(1);
}
catch (InstantiationException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
System.exit(1);
}
colorMap = new LinkedHashMap<String, Color>();
colorMap.put("Pastel Green", pastelGreen);
colorMap.put("Pastel Blue", pastelBlue);
colorMap.put("Pastel Yellow", pastelYellow);
colorMap.put("Pastel Cyan", pastelCyan);
colorMap.put("Pastel Purple", pastelPurple);
colorMap.put("Pastel Red", pastelRed);
colorMap.put("Melon", melon);
colorMap.put("Salmon", salmon);
colorMap.put("Orange", orange);
colorMap.put("Red", red);
colorMap.put("Light Green", lightGreen);
colorMap.put("Banana", banana);
colorMap.put("Lemon", lemon);
colorMap.put("Spindrift", spindrift);
colorMap.put("Flora", flora);
colorMap.put("Sea Foam", seaFoam);
colorMap.put("Lime", lime);
colorMap.put("Green", green);
colorMap.put("Sky", sky);
colorMap.put("Ice", ice);
colorMap.put("Turquoise", turquoise);
colorMap.put("Lavender", lavender);
colorMap.put("Orchid", orchid);
colorMap.put("Aqua", aqua);
//colorMap.put("Grape", grape);
colorMap.put("Light Pink", lightPink);
colorMap.put("Bubble Gum", bubbleGum);
colorMap.put("Magenta", magenta);
colorMap.put("Hot Pink", hotPink);
colorMap.put("Black", black);
colorMap.put("Snow", snow);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
} |
ceea162d-9aaa-4d01-87d2-85bdede8d5ab | 1 | public MainFrame_View() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {}
frame = new JFrame("World Map - Interactive Map");
frame.setSize(INIT_WIDTH, INIT_HEIGHT);
frame.setResizable(RESIZABLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane = frame.getContentPane();
pane.setLayout(null);
insets = pane.getInsets();
} |
4191e0df-df3e-4234-a98b-2a5ebe845013 | 0 | public void addNode(Node node) {
nodes.add(node);
} |
0d4e9db0-fb57-488c-8c65-ddfb48f5484c | 7 | private void filterPixels(DirectGif89Frame dgf) throws IOException
{
if (ciLookup == null)
throw new IOException("RGB frames require palette autodetection");
int[] argb_pixels = (int[]) dgf.getPixelSource();
byte[] ci_pixels = dgf.getPixelSink();
int npixels = argb_pixels.length;
for (int i = 0; i < npixels; ++i)
{
int argb = argb_pixels[i];
// handle transparency
if ((argb >>> 24) < 0x80) // transparent pixel?
if (transparentIndex == -1) // first transparent color encountered?
transparentIndex = ciCount; // record its index
else if (argb != theColors[transparentIndex]) // different pixel value?
{
// collapse all transparent pixels into one color index
ci_pixels[i] = (byte) transparentIndex;
continue; // CONTINUE - index already in table
}
// try to look up the index in our "reverse" color table
int color_index = ciLookup.getPaletteIndex(argb & 0xffffff);
if (color_index == -1) // if it isn't in there yet
{
if (ciCount == 256)
throw new IOException("can't encode as GIF (> 256 colors)");
// store color in our accumulating palette
theColors[ciCount] = argb;
// store index in reverse color table
ciLookup.put(argb & 0xffffff, ciCount);
// send color index to our output array
ci_pixels[i] = (byte) ciCount;
// increment count of distinct color indices
++ciCount;
}
else // we've already snagged color into our palette
ci_pixels[i] = (byte) color_index; // just send filtered pixel
}
} |
ebc650a8-25ae-4010-9128-b716baed1591 | 8 | public void generateMapImage() {
BufferedImage dungeonImage = new BufferedImage(sizeX * TILE_SIZE, sizeY * TILE_SIZE, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = dungeonImage.createGraphics();
for (int y = 0; y < sizeY; y++) {
for (int x = 0; x < sizeX; x++) {
int tile = getTileNumber(x, y);
int tileSetXTiles = TILE_SET.getWidth(null) / TILE_SIZE;
int tileSetYTiles = TILE_SET.getHeight(null) / TILE_SIZE;
int srcXTile = tile % tileSetXTiles;
int srcYTile = (int) Math.floor(tile / tileSetYTiles);
int srcX = srcXTile * TILE_SIZE;
int srcY = srcYTile * TILE_SIZE;
g2.drawImage(TILE_SET, x * TILE_SIZE, y * TILE_SIZE, x * TILE_SIZE + TILE_SIZE, y * TILE_SIZE + TILE_SIZE, srcX, srcY, srcX + TILE_SIZE, srcY + TILE_SIZE, null);
// Opacity
if (getParam(OPACITY_SWITCH) == 1) {
Room theRoom = getRoom(x, y);
if (theRoom != null) {
double opacity = Math.floor(((double) theRoom.getDepth() / (getMaxDepth() + 1)) * 255);
g2.setColor(new Color(0, 0, 0, (int) opacity));
g2.fillRect(x * TILE_SIZE, y * TILE_SIZE, 16, 16);
}
}
// Room ids
if (getParam(ROOM_ID_SWITCH) == 1 && getTile(x, y) != TILE_EMPTY) {
for (Room r : mapRooms) {
int index = r.hasTile(x, y);
if (index != -1) {
g2.drawString("" + r.getId(), x * TILE_SIZE, y * TILE_SIZE + 10);
break;
}
}
}
}
}
this.mapImage = dungeonImage;
} |
41db74e7-7071-4499-9a8f-cb7ffdadff15 | 3 | private final void resetModDate() {
final Path repo = ((SongData) this.songdata).getRoot()
.resolve(
this.main.getConfigValue(Main.VC_SECTION,
Main.REPO_KEY, "band"));
try {
final Git session = Git.open(repo.toFile());
try {
final ObjectId head = session.getRepository().getRef("HEAD")
.getObjectId();
final RevWalk walk = new RevWalk(session.getRepository());
final RevCommit commit = walk.parseCommit(head);
final ObjectReader reader = session.getRepository()
.newObjectReader();
diff(session, walk, commit, reader);
reader.release();
for (final Map.Entry<String, Integer> mod : this.changed
.entrySet()) {
final File f = repo.resolve(mod.getKey()).toFile();
if (f.exists()) {
f.setLastModified(TimeUnit.SECONDS.toMillis(mod
.getValue()));
}
}
this.io.printMessage(null,
"update of modification time completed", true);
} finally {
session.close();
}
} catch (final IOException e) {
this.io.handleException(ExceptionHandle.CONTINUE, e);
}
} |
89997d41-b9f1-4c39-a690-fe2e490f5835 | 5 | public void keyReleased(KeyEvent key){
switch (key.getKeyCode()){
case KeyEvent.VK_UP:
player.moveY(1);
break;
case KeyEvent.VK_LEFT:
player.moveX(1);
break;
case KeyEvent.VK_RIGHT:
player.moveX(-1);
break;
case KeyEvent.VK_DOWN:
player.moveY(-1);
break;
case KeyEvent.VK_SPACE:
System.out.println(player.getX() + ", " + player.getY());
break;
}
} |
6b585d80-8987-41e9-abf5-e02922808f10 | 4 | public String getText(Key key) {
String text = texts.getProperty(key.getProperty());
if (text == null && "month".equals(key.getKind())) {
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, key.getIndex());
ComponentFormatDefaults defaults = ComponentFormatDefaults.getInstance();
DateFormat monthFormat = defaults.getFormat(ComponentFormatDefaults.Key.MONTH_SELECTOR);
text = monthFormat.format(c.getTime());
}
if (text == null && "dow".equals(key.getKind())) {
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, key.getIndex());
ComponentFormatDefaults defaults = ComponentFormatDefaults.getInstance();
DateFormat dowFormat = defaults.getFormat(ComponentFormatDefaults.Key.DOW_HEADER);
text = dowFormat.format(c.getTime());
}
return text;
} |
83ca3d85-c398-4e62-8629-be8fc8e0d9de | 6 | public boolean isValidSudoku(char[][] board) {
int[] cols = new int[9];
int[] rows = new int[9];
int[] squs = new int[9];
Arrays.fill(cols,0);
Arrays.fill(rows,0);
Arrays.fill(squs,0);
for (int i=0; i < 9 ;i++ ) {
for (int j =0 ; j < 9 ;j++ ) {
if(board[i][j] != '0' ){
int val = board[i][j] - '0';
if((rows[i] & 1 << val) > 0)
return false; // 一行出现 重复数。
else
rows[i] |= 1<< val;
if((cols[j] & 1 << val) > val)
return false;// 一列出现重复数;
else
cols[j] |= 1<< val;
int index = i/3*3 + j/3;
if((squs[index] & 1<<val) > 0)
return false;
else
squs[index] |= 1<<val;
}
}
}
return true;
} |
9c859d5f-6db7-49ea-bc86-6f83a1d89de8 | 8 | @Override
public void init(int l, int h) {
this.grille = new BlocService[l][h];
this.l=l;
this.h=h;
for(int i=0; i<l; i++)
for(int j=0; j<h; j++)
if(i==0 || i==l-1 || j==0 || j==h-1 || (i%2==1 && j%2==1)) {
BlocService t = new BlocImpl();
t.init(BlocType.MURMETAL);
grille[i][j] = t;
} else {
BlocService t = new BlocImpl();
t.init(BlocType.VIDE);
grille[i][j] = t;
}
} |
a9c237f0-9283-4d19-954d-2828a5e45886 | 2 | public Map<String, EventDetail> sendRequest(String params) {
Map<String, EventDetail> result = new HashMap<String, EventDetail>();
RestTemplate rest = new RestTemplate();
String json = rest.getForObject("https://api.guildwars2.com/v1/event_details.json"+params, String.class);
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode node = mapper.readTree(json);
node = node.get("events");
result = mapper.readValue(node.traverse(), new TypeReference<Map<String, EventDetail>>() {
});
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
} |
f322c154-68f3-479a-a322-2b1b3bab8ad1 | 4 | public boolean actionSupervise(Actor actor, Venue venue) {
//
// If you have any items demanded by the venue, put them away-
for (Item i : actor.gear.allItems()) {
if (i.refers != null || i.type.form != FORM_COMMODITY) continue ;
if (venue.stocks.demandFor(i.type) > 0) actor.gear.transfer(i, venue) ;
}
return true ;
} |
9dcbcbb3-fbf0-4db4-8383-1d2780bed0a0 | 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(info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(info.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(info.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 info().setVisible(true);
}
});
} |
a08c775e-931b-415e-ac6e-104dc8d9173a | 1 | public void SetRangByScore(){
// Ordre meilleur joueur selon le score
Collections.sort(listeScores, ScoreJoueur.InscritNomComparator);
int i=0;
// ajout le rang au joueur
for(ScoreJoueur joueur : listeScores){
i++;
joueur.setRang(i);
}
} |
3aec8b60-e502-4af5-bd7a-df0c4bb3dc9d | 4 | public static Field getField(Class<?> clazz, String name) {
while (clazz != null) {
for (Field field : clazz.getDeclaredFields()) {
if (field.getName().equals(name)) {
field.setAccessible(true);
return field;
}
}
clazz = clazz.getSuperclass();
}
return null;
} |
8d6798f9-8009-447c-89bf-63c3c33b90b6 | 8 | @Override
public void render(Graphics g, Visibility visibility, float x, float y, float scale) {
if(visibility == Visibility.VISIBLE) {
boolean hasSomeEntities = occupying.size() > 0;
boolean hasSomeEntering = entering.size() > 0;
boolean hasSomeLeaving = leaving.size() > 0;
if(hasSomeEntities) {
if(hasSomeEntering && hasSomeLeaving)
g.setColor(new Color(255, 150, 255));
else if(hasSomeEntering)
g.setColor(new Color(100, 255, 255));
else if(hasSomeLeaving)
g.setColor(new Color(255, 100, 100));
else
g.setColor(new Color(255, 255, 255));
}
else if(hasSomeEntering) {
g.setColor(new Color(0, 85, 85));
}
else if(hasSomeLeaving) {
g.setColor(new Color(85, 0, 0));
}
else {
g.setColor(new Color(0, 0, 0));
}
g.fillRect(x - level.getTileWidth() /2 * scale, y - level.getTileHeight() / 2 * scale, level.getTileWidth() * scale, level.getTileHeight() * scale);
g.setColor(Color.gray);
g.setLineWidth(1);
g.drawRect(x - level.getTileWidth() /2 * scale, y - level.getTileHeight() / 2 * scale, level.getTileWidth() * scale, level.getTileHeight() * scale);
}
} |
b09ab63a-60fe-4638-8ce4-5d455388b4e0 | 9 | public static String normalizePath(String path)
{
String[] comps = path.split("/");
String[] ap = new String[comps.length];
int j = 0;
boolean absolute = comps[0].length() == 0;
for (int i = 0; i < comps.length; ++i)
{
String s = comps[i];
if (s.equals(".") || s.length() == 0)
continue;
if (s.equals(".."))
{
if (j > 0)
--j;
}
else
ap[j++] = s;
}
if (j == 0)
return absolute ? "/" : ".";
if (absolute)
path = "/" + ap[0];
else
path = ap[0];
for (int i = 1; i < j; ++i)
path += "/" + ap[i];
return path;
} |
bd43ebae-a595-4c15-a8eb-59a7727cb48e | 3 | @Override
public byte[] save(JoeTree tree, DocumentInfo docInfo) {
String lineEnding = PlatformCompatibility.platformToLineEnding(PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_LINE_ENDING));
// Show dialog where use can pick a CSS or cancel. Do lazy instantiation since text assets won't be ready yet.
if (dialog == null) {
dialog = new SelectHTMLExportStyleDialog(Outliner.outliner,"Select a Style");
}
dialog.show();
if (!dialog.shouldProceed()) {
return null;
}
// Get the CSS
String template = dialog.getStyle(lineEnding);
// Prepare the file
String merged = prepareFile(tree, docInfo, lineEnding, template);
try {
return merged.getBytes(PropertyContainerUtil.getPropertyAsString(docInfo, DocumentInfo.KEY_ENCODING_TYPE));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return merged.getBytes();
}
} |
65cb5bd4-00cd-4664-811b-821b77e8e5d0 | 3 | @Override
public void deserialize(Buffer buf) {
objectUID = buf.readInt();
if (objectUID < 0)
throw new RuntimeException("Forbidden value on objectUID = " + objectUID + ", it doesn't respect the following condition : objectUID < 0");
foodUID = buf.readInt();
if (foodUID < 0)
throw new RuntimeException("Forbidden value on foodUID = " + foodUID + ", it doesn't respect the following condition : foodUID < 0");
foodQuantity = buf.readShort();
if (foodQuantity < 0)
throw new RuntimeException("Forbidden value on foodQuantity = " + foodQuantity + ", it doesn't respect the following condition : foodQuantity < 0");
} |
ba575916-c2a7-4e01-a285-7bf99174ac41 | 7 | private void checkLaserCollisionsWithSprites(Laser laser){
// update other sprites
//Iterator i = map.getSprites();
LinkedList <Sprite> oldSprites = map.getSprites();
LinkedList <Sprite> sprites = (LinkedList<Sprite>) oldSprites.clone();
//sprites.add(map.getPlayer()); Not doing this right now
for(int i = 0; i < map.getAIShips().size(); i++){
sprites.add(map.getAIShips().get(i));
}
for (int i = 0; i < sprites.size(); i++) {
Sprite sprite = (Sprite)sprites.get(i);
if (sprite instanceof Planet) {
Planet planet = (Planet)sprite;
if(isCollision(laser, planet)) collideLaserWithSprite(laser, planet);
}else if(sprite instanceof Ship){
Ship ship = (Ship)sprite;
if(isCollision(laser, ship)) collideLaserWithSprite(laser, ship);
}else if(sprite instanceof Turret){
Turret t = (Turret)sprite;
//if(isCollision(laser, t)) collideLaserWithSprite(laser, t);
//lasers shoujldn't collide with turrets should they? maybe later
}
}
} |
e9bc90a8-74c9-46f2-87ae-2e4b3df5d4b6 | 4 | public Collection<DependencyNode<V>> toNodes()
{
Map<K, DependencyNode<V>> nodeMap = new HashMap<K, DependencyNode<V>>();
for (Entry<K, V> e : values.entrySet())
{
nodeMap.put( e.getKey(), new DependencyNode<V>( e.getValue() ) );
}
for (Entry<K, DependencyNode<V>> e : nodeMap.entrySet())
{
DependencyNode<V> dn = e.getValue();
Set<K> deps = dependencies.get( e.getKey() );
if (deps != null)
{
for (K d : deps)
{
dn.addDependency( nodeMap.get( d ) );
}
}
}
return nodeMap.values();
} |
77ec394f-4021-4158-848f-94c945c7324e | 7 | public static void check(HttpURLConnection c) throws IOException {
int code = c.getResponseCode();
switch (code) {
case HttpURLConnection.HTTP_OK:
case HttpURLConnection.HTTP_PARTIAL:
return;
case HttpURLConnection.HTTP_MOVED_TEMP:
case HttpURLConnection.HTTP_MOVED_PERM:
// rfc2616: the user agent MUST NOT automatically redirect the
// request unless it can be confirmed by the user
throw new DownloadMoved(c);
case HttpURLConnection.HTTP_PROXY_AUTH:
throw new ProxyAuth(c);
case HttpURLConnection.HTTP_FORBIDDEN:
throw new DownloadIOCodeError(code);
case 416:
// HTTP Error 416 - Requested Range Not Satisfiable
throw new DownloadIOCodeError(416);
}
} |
7f89333a-59a9-4d48-ac3b-a364aef2ccf6 | 7 | public static int minCut(String s) {
if(s.length() == 0)return 0;
int length =s.length();
int[] dp = new int[s.length()+1];
boolean[][] palin = new boolean[s.length()][s.length()];
for(int i =s.length(); i>=0;i--){
dp[i] = length-i;
}
for(int i = length-1; i>=0;i--){
for(int j = i; j < length ;j++){
if(s.charAt(i) == s.charAt(j) && (j -i<2 || palin[i+1][j-1])){
palin[i][j] = true;
dp[i] = Math.min(dp[j], dp[i]);
}
}
}
return dp[0]-1;
} |
63bef0c7-2dd5-472b-bd19-289519e36c5d | 2 | public TableCellEditor getCellEditor(int row, int column) {
if (!finalEdit)
return super.getCellEditor(row, column);
int mc = convertColumnIndexToModel(column);
return cellEditors[row][mc] == null ? super.getCellEditor(row, column)
: cellEditors[row][mc];
} |
ab7882b8-a648-4adf-9138-9cda032e00ed | 1 | public void resetInteractiveObject() {
for (int i = 0; i < interactiveObjectCachePos; i++) {
InteractiveObject interactiveObject = interactiveObjectCache[i];
method289(interactiveObject);
interactiveObjectCache[i] = null;
}
interactiveObjectCachePos = 0;
} |
44a8c1a3-3de0-41e5-9179-657593b9784d | 1 | private JButton getJButton0() {
if (jButton0 == null) {
jButton0 = new JButton();
jButton0.setText("SELECT");
jButton0.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent event) {
jButton0MouseMouseClicked(event);
}
});
}
return jButton0;
} |
833168bb-9b6a-4a2c-92ec-f43593283f26 | 2 | public List<String> getTableDescription(String tableName) throws DataBaseTableException {
TableDescription td = null;
for (DataBase db : databases.values()) {
td = db.getTableDescription(tableName);
if (td != null) {
return td.getColumnNames();
}
}
return null;
} |
50733595-3654-4893-9516-4cc789a86578 | 7 | public void preUpdate()
{
LinkedList<Element> elementTouch = collisionElementList((int)x, (int)y, Type.ALL, false);
Element elem;
while(!elementTouch.isEmpty())
{
elem = elementTouch.removeFirst();
if(elem.type == Type.BOMBERMAN)
pushEvent(elem,"explosion", power);
if(elem.type == Type.ROBOT)
pushEvent(elem,"explosion", power);
if(elem.type == Type.MONSTER)
pushEvent(elem,"explosion", power);
else if(elem.type == Type.WEAPONS)
pushEvent(elem,"explode");
}
if(anim.getLap() == 1 || animBorder.getLap() == 1)
destroy();
} |
47bd22c2-81cb-4986-a25f-548f2050c8d6 | 3 | public void setUpComboBoxes(Set<Card> cards) {
JComboBox peoplePossibilities = new JComboBox();
JComboBox roomsPossibilities = new JComboBox();
JComboBox weaponsPossibilities = new JComboBox();
for (Card card : cards) {
String name = card.getName();
if (card.getType().equals(CardType.PERSON)) {
peoplePossibilities.addItem(name);
} else if (card.getType().equals(CardType.WEAPON)) {
weaponsPossibilities.addItem(name);
} else {
roomsPossibilities.addItem(name);
}
}
peoplePossibilities.addItem("unsure");
roomsPossibilities.addItem("unsure");
weaponsPossibilities.addItem("unsure");
personGuess.add(peoplePossibilities);
roomGuess.add(roomsPossibilities);
weaponGuess.add(weaponsPossibilities);
} |
c757ebe0-48e8-4b23-aca7-3ce038479514 | 6 | @AfterGroups("MaxHeapIntegers")
@Test(groups = { "MinHeapIntegers" })
public void testMinHeapIntPushPop() {
Reporter.log("[ ** MinHeap Integer Push ** ]\n");
testQueueInt = new MinPriorityQueue<>(new Integer[seed], true);
try {
Reporter.log("Insertion : \n");
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
testQueueInt.push(shuffledArrayWithDuplicatesInt[i]);
}
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
} catch (CollectionOverflowException e) {
throw new TestException("MinHeap Insertion Failed!!!");
}
try {
testQueueInt.push(1);
} catch (CollectionOverflowException e) {
Reporter.log("**Overflow Exception caught -- Passed.\n");
}
Reporter.log("[ ** MinHeap Integer Pop ** ]\n");
try {
Reporter.log("Deletion : \n");
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
testQueueInt.pop();
}
Reporter.log((System.currentTimeMillis() - timeKeeper) + " ms\n");
} catch (EmptyCollectionException e) {
throw new TestException("MinHeap Removal Failed!!!");
}
try {
testQueueInt.pop();
} catch (EmptyCollectionException e) {
Reporter.log("**Empty Exception caught -- Passed.\n");
}
} |
2e15517a-5418-4aea-9d49-a21fed74d416 | 0 | public void setAge(String age) {
this.age = age;
} |
91a27500-847e-47e2-8f25-c37d94ca91de | 2 | public void read(String filename) throws MySecondException {
String content;
if (filename == null)
throw new MySecondException("The file name provided is null");
File file = new File(filename);
try {
FileReader reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
System.out
.println("There was an error in the read() method of class Human :"
+ e.getMessage() + " " + e.getCause());
}
} |
fdfce4b3-b796-4955-993d-070620496e37 | 1 | @EventHandler
public void onChat(PlayerBlockChangeEvent event) {
if (event.getPlayer() == getPlayer()) {
found = true;
X = event.getX();
Y = event.getY();
Z = event.getZ();
holding = event.getBlock();
mode = event.getPlaceType();
super.wakeUp();
event.Cancel(true);
}
} |
bf9c8ac2-b37b-422d-92a8-101d88499941 | 2 | private boolean jj_3_58() {
if (jj_3R_74()) return true;
if (jj_scan_token(POINT)) return true;
return false;
} |
924734d8-d0ab-48de-9293-b8936604b793 | 1 | @Override
public boolean addGroup(String group) {
if (!groups.contains(group)) {
groups.add(group);
return true;
}
return false;
} |
ddb5df8b-c086-4cba-a3cd-c529ae3320a7 | 3 | private char[] convertToString(CharSequence s) {
if (s == null && s.length() % 2 != 0) {
throw new IllegalArgumentException();
}
int len = s.length();
char[] dest = new char[len / 2];
for (int i = 0, j = 0; i < len; i += 2, j++)
dest[j] = (char) ((s.charAt(i) << 8) | s.charAt(i + 1));
return dest;
} |
2218f618-8356-489f-b4dd-4d6b48c19e02 | 2 | public static void write(HighScore hs, int n, String file){
try{
RandomAccessFile f = new RandomAccessFile(file, "rw");
char[] ch = hs.getName();
f.seek(FILE_SIZE * n);
for(int i = 0; i < STRING_SIZE; i++){
f.writeChar(ch[i]);
}
f.writeInt(hs.getScore());
f.close();
}
catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
} |
7e82c898-5309-489a-b818-13ed5b3a8b8c | 3 | public List<ArrayList<String>> parceEntry(String toCheck) {
List<ArrayList<String>> toReturn = new ArrayList<>();
List<String> books = readBooks();
List<ArrayList<String>> topics = readTopics();
toReturn.add(new ArrayList<>());
toReturn.add(new ArrayList<>());
for (String book : books) {
//for each book in the scrpitures check the text to see if it has a scripture refference
String regx = book + "( chapter [0-9]{1,}) |" + book + " ([0-9]{1,}+:[0-9]{1,}+(-[0-9]{1,})*)";
toReturn.get(0).addAll(regexChecker(regx, toCheck));
}
for (ArrayList<String> topic : topics) {
for (String t : topic) {
String regx = t;
toReturn.get(1).addAll(regexChecker(regx, toCheck));
}
}
return toReturn;
} |
0faad46f-5ea5-40d9-b970-7753f5b3ddf2 | 2 | @Override
public void caretUpdate(CaretEvent e) {
if(isLiveDecode()) {
try {
int methodID = Integer.parseInt(((JTextField) e.getSource()).getName());
parent.executeCipher(methodID);
} catch(Exception ex) {
ex.printStackTrace();
}
}
} |
89f482dc-fc98-4935-a400-8011505c8d65 | 1 | public void run(QuitKeyListener user) {
window.activate();
sleep(500);
while(!user.hasQuit()){
world.update();
window.repaint();
sleep(25);
}
window.deactivate();
} |
2d9e314d-08c7-4192-91ae-282f57aae534 | 8 | public static void main (String args[]) {
int iii,i,ic,k,m,n,nread,ntries,nwrite;
int info[] = new int[2];
// int nprob;
// int nfev[] = new int[2];
// int njev[] = new int[2];
int nprobfile[] = new int[29];
int nfile[] = new int[29];
int mfile[] = new int[29];
int ntryfile[] = new int[29];
int ma[] = new int[61];
int na[] = new int[61];
int nf[] = new int[61];
int nj[] = new int[61];
int np[] = new int[61];
int nx[] = new int[61];
double factor,fnorm1,fnorm2,tol;
double fjac[][] = new double[66][41];
double fnm[] = new double[61];
double fvec[] = new double[66];
double x[] = new double[41];
int ipvt[] = new int[41];
int num5, ilow, numleft;
// The npa, na, ma, and nta values are the
// nprob, n, m, and ntries values from the testdata file.
nprobfile[1] = 1;
nprobfile[2] = 1;
nprobfile[3] = 2;
nprobfile[4] = 2;
nprobfile[5] = 3;
nprobfile[6] = 3;
nprobfile[7] = 4;
nprobfile[8] = 5;
nprobfile[9] = 6;
nprobfile[10] = 7;
nprobfile[11] = 8;
nprobfile[12] = 9;
nprobfile[13] = 10;
nprobfile[14] = 11;
nprobfile[15] = 11;
nprobfile[16] = 11;
nprobfile[17] = 12;
nprobfile[18] = 13;
nprobfile[19] = 14;
nprobfile[20] = 15;
nprobfile[21] = 15;
nprobfile[22] = 15;
nprobfile[23] = 15;
nprobfile[24] = 16;
nprobfile[25] = 16;
nprobfile[26] = 16;
nprobfile[27] = 17;
nprobfile[28] = 18;
nfile[1] = 5;
nfile[2] = 5;
nfile[3] = 5;
nfile[4] = 5;
nfile[5] = 5;
nfile[6] = 5;
nfile[7] = 2;
nfile[8] = 3;
nfile[9] = 4;
nfile[10] = 2;
nfile[11] = 3;
nfile[12] = 4;
nfile[13] = 3;
nfile[14] = 6;
nfile[15] = 9;
nfile[16] = 12;
nfile[17] = 3;
nfile[18] = 2;
nfile[19] = 4;
nfile[20] = 1;
nfile[21] = 8;
nfile[22] = 9;
nfile[23] = 10;
nfile[24] = 10;
nfile[25] = 30;
nfile[26] = 40;
nfile[27] = 5;
nfile[28] = 11;
mfile[1] = 10;
mfile[2] = 50;
mfile[3] = 10;
mfile[4] = 50;
mfile[5] = 10;
mfile[6] = 50;
mfile[7] = 2;
mfile[8] = 3;
mfile[9] = 4;
mfile[10] = 2;
mfile[11] = 15;
mfile[12] = 11;
mfile[13] = 16;
mfile[14] = 31;
mfile[15] = 31;
mfile[16] = 31;
mfile[17] = 10;
mfile[18] = 10;
mfile[19] = 20;
mfile[20] = 8;
mfile[21] = 8;
mfile[22] = 9;
mfile[23] = 10;
mfile[24] = 10;
mfile[25] = 30;
mfile[26] = 40;
mfile[27] = 33;
mfile[28] = 65;
ntryfile[1] = 1;
ntryfile[2] = 1;
ntryfile[3] = 1;
ntryfile[4] = 1;
ntryfile[5] = 1;
ntryfile[6] = 1;
ntryfile[7] = 3;
ntryfile[8] = 3;
ntryfile[9] = 3;
ntryfile[10] = 3;
ntryfile[11] = 3;
ntryfile[12] = 3;
ntryfile[13] = 2;
ntryfile[14] = 3;
ntryfile[15] = 3;
ntryfile[16] = 3;
ntryfile[17] = 1;
ntryfile[18] = 1;
ntryfile[19] = 3;
ntryfile[20] = 3;
ntryfile[21] = 1;
ntryfile[22] = 1;
ntryfile[23] = 1;
ntryfile[24] = 3;
ntryfile[25] = 1;
ntryfile[26] = 1;
ntryfile[27] = 1;
ntryfile[28] = 1;
tol = Math.sqrt(epsmch);
ic = 0;
for (iii = 1; iii <= 28; iii++) {
// nprob = nprobfile[iii];
n = nfile[iii];
m = mfile[iii];
ntries = ntryfile[iii];
LmderTest_f77 lmdertest = new LmderTest_f77();
lmdertest.nprob = nprobfile[iii];
factor = one;
for (k = 1; k <= ntries; k++) {
ic++;
LmderTest_f77.initpt_f77(n,x,lmdertest.nprob,factor);
LmderTest_f77.ssqfcn_f77(m,n,x,fvec,lmdertest.nprob);
fnorm1 = Minpack_f77.enorm_f77(m,fvec);
System.out.print("\n\n\n\n\n problem " + lmdertest.nprob +
", dimensions: " + n + " " + m + "\n");
// write (nwrite,60) nprob,n,m
// 60 format ( //// 5x, 8h problem, i5, 5x, 11h dimensions, 2i5, 5x //
// * )
lmdertest.nfev = 0;
lmdertest.njev = 0;
Minpack_f77.lmder1_f77(lmdertest,m,n,x,fvec,fjac,tol,info,ipvt);
LmderTest_f77.ssqfcn_f77(m,n,x,fvec,lmdertest.nprob);
fnorm2 = Minpack_f77.enorm_f77(m,fvec);
np[ic] = lmdertest.nprob;
na[ic] = n;
ma[ic] = m;
nf[ic] = lmdertest.nfev;
nj[ic] = lmdertest.njev;
nx[ic] = info[1];
fnm[ic] = fnorm2;
System.out.print("\n Initial L2 norm of the residuals: " + fnorm1 +
"\n Final L2 norm of the residuals: " + fnorm2 +
"\n Number of function evaluations: " + lmdertest.nfev +
"\n Number of Jacobian evaluations: " + lmdertest.njev +
"\n Info value: " + info[1] +
"\n Final approximate solution: \n\n");
num5 = n/5;
for (i = 1; i <= num5; i++) {
ilow = (i-1)*5;
System.out.print(x[ilow+1] + " " + x[ilow+2] + " " +
x[ilow+3] + " " + x[ilow+4] + " " +
x[ilow+5] + "\n");
}
numleft = n%5;
ilow = n - numleft;
switch (numleft) {
case 1:
System.out.print(x[ilow+1] + "\n\n");
break;
case 2:
System.out.print(x[ilow+1] + " " + x[ilow+2] + "\n\n");
break;
case 3:
System.out.print(x[ilow+1] + " " + x[ilow+2] + " " +
x[ilow+3] + "\n\n");
break;
case 4:
System.out.print(x[ilow+1] + " " + x[ilow+2] + " " +
x[ilow+3] + " " + x[ilow+4] + "\n\n");
break;
}
// write (nwrite,70)
// * fnorm1,fnorm2,nfev,njev,info,(x(i), i = 1, n)
// 70 format (5x, 33h initial l2 norm of the residuals, d15.7 // 5x,
// * 33h final l2 norm of the residuals , d15.7 // 5x,
// * 33h number of function evaluations , i10 // 5x,
// * 33h number of jacobian evaluations , i10 // 5x,
// * 15h exit parameter, 18x, i10 // 5x,
// * 27h final approximate solution // (5x, 5d15.7))
factor *= ten;
}
}
System.out.print("\n\n\n Summary of " + ic +
" calls to lmder1: \n\n");
// write (nwrite,80) ic
// 80 format (12h1summary of , i3, 16h calls to lmder1 /)
System.out.print("\n\n nprob n m nfev njev info final L2 norm \n\n");
// write (nwrite,90)
// 90 format (49h nprob n m nfev njev info final l2 norm /)
for (i = 1; i <= ic; i++) {
System.out.print(np[i] + " " + na[i] + " " + ma[i] + " " +
nf[i] + " " + nj[i] + " " + nx[i] + " " + fnm[i] +
"\n");
// write (nwrite,100) np[i],na[i],ma[i],nf[i],nj[i],nx[i],fnm[i]
// 100 format (3i5, 3i6, 1x, d15.7)
}
} |
dad2249f-674a-4535-8807-08814941cb9a | 4 | private static void getInput(){
/* Single action input */
if (Keyboard.next()){
if (Keyboard.getEventKey() == Keyboard.KEY_ESCAPE){
quitGame();
}
}
/* Game input */
if (Keyboard.isKeyDown(Keyboard.KEY_W)){
Court.player.moveUp();
}
if (Keyboard.isKeyDown(Keyboard.KEY_S)){
Court.player.moveDown();
}
} |
9786d79f-f567-4297-a4dd-89b303c115c9 | 4 | public TabuStageParams(int maxSteps,
int minTheta,
int maxTheta) {
if (maxSteps <= 0) {
throw new IllegalArgumentException("'max steps' <= 0");
}
MAX_STEPS = maxSteps;
if ( minTheta < 0
|| maxTheta < 0) {
throw new IllegalArgumentException("'theta' < 0");
}
if (minTheta > maxTheta) {
throw new IllegalArgumentException("'min theta' > 'max theta'");
}
MIN_THETA = minTheta;
MAX_THETA = maxTheta;
} |
bd822499-4204-4afd-a935-45d9faad4dcf | 6 | @Override
public List<String> onTabComplete(CommandSender sender, Command command,
String alias, String[] args) {
if (args.length == 1) {
List<String> matches = new ArrayList<String>();
for (String subcommand : subcommands) {
if (StringUtil.startsWithIgnoreCase(subcommand, args[0])) {
matches.add(subcommand);
}
}
for (Sound sound : Sound.values()) {
if (StringUtil.startsWithIgnoreCase(sound.name(), args[0])) {
matches.add(sound.name());
}
}
if (!matches.isEmpty()) {
return matches;
}
}
return null;
} |
9d5c0843-f058-40df-a3a4-f8cce79b2550 | 7 | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try{
MySQLcon db = new MySQLcon("jdbc:mysql://localhost:3306/project","a","a");
ResultSet r = db.Quer("SELECT * FROM project_assignements");
ResultSetMetaData rsmd = (ResultSetMetaData) r.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
String columnValue;
out.print("<h1>Project Assignments Overview</h1>");
out.print("<table border=\"1\">");
out.print("<tr><td>Assignment Id</td><td>Assignment name</td><td>Author</td><td>Prefix</td><td>Description</td><td>Sugested reading</td><td>Project ID</td><td>Version</td></tr>");
while (r.next()) {
out.print("<tr>");
for (int i = 1; i <= numberOfColumns; i++)
{
columnValue = r.getString(i);
if (i == 4) {
if (columnValue.equalsIgnoreCase("Pending")) {
out.print("<td style=\"background:yellow\">");
} else if (columnValue.equalsIgnoreCase("Approved")) {
out.print("<td style=\"background:green\">");
} else if (columnValue.equalsIgnoreCase("Discard")) {
out.print("<td style=\"background:red\">");
}
} else {
out.print("<td>");
}
out.print(columnValue);
out.print("</td>");
}
out.print("</tr>");
}
out.print("</table>");
} catch (Exception e) {
e.printStackTrace();
}
} |
a1d16ab2-8f94-4faa-b173-851002f3d312 | 0 | public static String getPrivateKey(Map<String, Object> keyMap)
throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return SecurityCoder.base64Encoder(key.getEncoded());
} |
ed884120-b8fe-4c25-a36a-d60ca30677a7 | 9 | private static String get_pattern(BufferedReader input, String pattern)
{
PDPM_DEBUG.PDPM_REPORTER_LOG("->get_pattern() pattern: " +
pattern);
String line = null;
String value = null;
while(true)
{
try
{
line = input.readLine();
PDPM_DEBUG.PDPM_REPORTER_LOG("Read line: " + line);
if(line == null)
{
break;
}
line = line.trim();
if(line.length() == 0)
{
continue;
}
if(line.charAt(0) == '#')
{
continue;
}
if(!line.startsWith(pattern))
{
continue;
}
PDPM_DEBUG.PDPM_REPORTER_LOG("Found pattern");
int index = line.indexOf('=');
value = line.substring(index + 1);
value = value.trim();
// Strip newline
if(value.endsWith("\n"))
{
value = value.substring(0, value.length() - 2);
}
// Strip double qoutes
if(value.startsWith("\""))
{
value = value.substring(1, value.length() - 1);
}
if(value.endsWith("\""))
{
value = value.substring(0, value.length() - 2);
}
break;
}
catch(Exception e)
{
PDPM_DEBUG.PDPM_REPORTER_ERR(
"Exception while processing. Trying next line");
PDPM_DEBUG.PDPM_REPORTER_ERR(e);
}
}
PDPM_DEBUG.PDPM_REPORTER_LOG("Value: " + value);
PDPM_DEBUG.PDPM_REPORTER_LOG("<- get_pattern()");
return value;
} |
8eacd9da-722a-45f0-a067-bc6d058ee67e | 5 | public static void main(String[] args) {
int rc = 0;
for (String fname : args) {
File file = new File(fname);
if (!file.canRead()) {
System.err.println("Cannot read " + fname);
rc++;
continue;
}
try {
DocumentBuilder db = XMLUtils.newDocumentBuilder(false);
Document doc = db.parse(file);
ValidateMetadata.validate(doc);
System.out.println("Valid: " + fname);
} catch (MetadataException e) {
rc++;
System.err.println("Invalid: " + fname + "\n" + e.getMessage());
} catch (SAXException e) {
rc++;
System.err.println("Invalid: " + fname + "\n" + e.getMessage());
} catch (IOException e) {
rc++;
System.err.println("IO exception during read: " + fname + "\n"
+ e.getMessage());
}
}
System.exit(rc);
} |
9dea6a23-a75a-423b-aa49-42d254d1253b | 9 | Color AdvColorPix(int count, String[] ColorIndex) {
int c1;
int c2;
int r;
int g;
int b;
int or; //old red
int og;
int ob;
double dr;
double dg;
double db;
String fg; //foreground colour
String bg; //background colour
ArrayList<Integer> ClrVal = new ArrayList<>();
for (int i = 0; i <= (count / 255) - 1; i++) ClrVal.add(255);
if (ClrVal.size() < ColorIndex.length) ClrVal.add(count % 255);
if (ClrVal.size() >= 2) {
fg = String.valueOf(ColorIndex[ClrVal.size() - 2]);
or = Integer.valueOf(fg.substring(0, 3));
og = Integer.valueOf(fg.substring(3, 6));
ob = Integer.valueOf(fg.substring(6, 9));
c2 = Integer.valueOf(String.valueOf(ClrVal.get(ClrVal.size() - 1)));
bg = String.valueOf(ColorIndex[ClrVal.size() - 1]);
dr = ((Integer.valueOf(bg.substring(0, 3)) - Integer.valueOf(fg.substring(0, 3))) / 256.0);
dg = ((Integer.valueOf(bg.substring(3, 6)) - Integer.valueOf(fg.substring(3, 6))) / 256.0);
db = ((Integer.valueOf(bg.substring(6, 9)) - Integer.valueOf(fg.substring(6, 9))) / 256.0);
r = (int) ((or) + (c2 * dr));
g = (int) ((og) + (c2 * dg));
b = (int) ((ob) + (c2 * db));
} else {
c1 = Integer.valueOf(String.valueOf(ClrVal.get(ClrVal.size() - 1)));
fg = String.valueOf(ColorIndex[ClrVal.size() - 1]);
dr = (Integer.valueOf(fg.substring(0, 3)) / 256.0);
dg = (Integer.valueOf(fg.substring(3, 6)) / 256.0);
db = (Integer.valueOf(fg.substring(6, 9)) / 256.0);
r = (int) (c1 * dr);
g = (int) (c1 * dg);
b = (int) (c1 * db);
}
if (r > 255 || g > 255 || b > 255 || r < 0 || g < 0 || b < 0) {
System.out.println(r + "," + g + "," + b);
return Color.black;
} else {
return new Color(r, g, b);
}
} |
1e909ad7-eca6-480f-944a-f6272ec3f04f | 0 | public void print(){
int y = 10; // local variable declaration
System.out.println(y);
} |
5a4ac3ed-2e0c-46df-80dd-0e1ea488a479 | 8 | @Override
public void channelRead(ChannelHandlerContext channelHandlerContext, Object object) {
ByteBuf byteBuf = ((ByteBuf) object);
boolean isLegacyPing = false;
byteBuf.markReaderIndex();
try {
if (byteBuf.readUnsignedByte() == 254) {
int id = byteBuf.readableBytes();
switch (id) {
case 0x0:
// Client is <1.3.x
send(channelHandlerContext, createPacket(String.format("%s\u00A7%d\u00A7%d", this.server.motd, this.server.onlinePlayers, this.server.maxOnlinePlayers)));
break;
case 0x1:
// Client is 1.4.x - 1.5.x
if (byteBuf.readUnsignedByte() != 1)
return;
String packetContent = String.format("\u00A71\0%d\0%s\0%s\0%d\0%d", 127, this.server.serverVersion, this.server.motd, this.server.onlinePlayers, this.server.maxOnlinePlayers);
send(channelHandlerContext, createPacket(packetContent));
break;
default:
// 1.6
boolean isPingPacket = byteBuf.readUnsignedByte() == 1;
isPingPacket &= byteBuf.readUnsignedByte() == 250;
isPingPacket &= "MC|PingHost".equals(new String(byteBuf.readBytes(byteBuf.readShort() * 2).array(), StandardCharsets.UTF_16BE));
int length = byteBuf.readUnsignedShort();
isPingPacket &= byteBuf.readUnsignedByte() >= 73;
isPingPacket &= 3 + byteBuf.readBytes(byteBuf.readShort() * 2).array().length + 4 == length;
isPingPacket &= byteBuf.readInt() <= '\uffff';
isPingPacket &= byteBuf.readableBytes() == 0; // did we read all the bytes?
if (!isPingPacket)
return;
String packetContents = String.format("\u00A71\0%d\0%s\0%s\0%d\0%d", 127, this.server.serverVersion, this.server.motd, this.server.onlinePlayers, this.server.maxOnlinePlayers);
ByteBuf packet = createPacket(packetContents);
try {
send(channelHandlerContext, packet);
} finally {
if (packet.refCnt() > 0) // TODO: Improve?
packet.release(); // -> causes error, bytebuf needs to be released, else mem-leaks allover the place
}
}
isLegacyPing = true;
byteBuf.release();
}
} catch (RuntimeException e) {
// Swallow, There's a chance something goes wrong (eg: when a user is spamming the refresh button)
// We we'll just swallow this exception and go on with our life
} finally {
if (!isLegacyPing) {
byteBuf.resetReaderIndex();
channelHandlerContext.channel().pipeline().remove("legacy_ping_handler");
channelHandlerContext.pipeline().fireChannelRead(object);
}
}
} |
5b37633d-f72d-4a83-a7e9-a9e27ea266b7 | 2 | private void skip(long amount) throws IOException {
while(amount > 0) {
long skipped = input.skip(amount);
if(skipped < 0) {
throw new EOFException();
}
amount -= skipped;
}
} |
beeb4fbb-0f63-4083-83e7-bd8b82924bc1 | 5 | @Override
public void onCloseFile(String arg0, DokanFileInfo arg1)
throws DokanOperationException {
synchronized (handles)
{
if (DEBUG)
System.out.println("CloseFile: " + arg0);
if (arg1.handle == 0)
return;
FileHandle handle = handles.remove(arg1.handle);
if (handle != null)
{
try {
fileSystem.close(handle);
} catch (DriveFullException e) {
throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_DISK_FULL);
} catch (Exception e)
{
e.printStackTrace();
}
}
else
throw new DokanOperationException(net.decasdev.dokan.WinError.ERROR_INVALID_HANDLE);
}
} |
18869319-7da4-4317-81e1-2d4d3907c8d5 | 1 | public ResultSet getList(String whereString) {
StringBuffer sql = new StringBuffer("");
sql.append("SELECT Exam_ID,Instructions,isPublic");
sql.append(" FROM `Exam`");
if (whereString.trim() != "") {
sql.append(" where " + whereString);
}
SQLHelper sQLHelper = new SQLHelper();
sQLHelper.sqlConnect();
ResultSet rs = sQLHelper.runQuery(sql.toString());
//sQLHelper.sqlClose();
return rs;
} |
c6547596-1b37-4563-ab7c-357158a3b515 | 0 | @Override
public void start() throws Exception {
super.start();
} |
8d3f58fd-c00b-4a7b-bff5-9cedbda25abf | 1 | public void updateTime() {
if (this.isActive) {
this.playersTurn.time++;
// if (this.isWhitesTurn) {
// this.playerWhite.time++;
// } else {
// this.playerBlack.time++;
// }
} else {
this.stopTime();
}
this.setWindowTitle();
} |
c9c232ed-f2aa-4574-ba45-5e765cdff530 | 0 | public int getPageFirstItem() {
return page * pageSize;
} |
72f2d7a4-e686-4341-91c2-d8c1f79cda57 | 7 | private List<Distance> getAMatchingDistance(List<Distance> referenceDistances, List<Distance> probeDistances) {
List<Distance> list = new ArrayList<Distance>();
do {
list.clear();
int random = new Random().nextInt(referenceDistances.size());
list.add(referenceDistances.get(random));
for(Distance d : probeDistances){
if( ((list.get(0).getMinutia1().getType() == d.getMinutia1().getType() && list.get(0).getMinutia2().getType() == d.getMinutia2().getType()) ||
(list.get(0).getMinutia1().getType() == d.getMinutia2().getType() && list.get(0).getMinutia2().getType() == d.getMinutia1().getType())) &&
Math.abs(d.getDistance() - list.get(0).getDistance()) <= thresholdDistance){
list.add(d);
}
}
} while (list.size() != 2);
return list;
} |
ffa71c60-68a0-47de-812e-79eda9faa5a3 | 4 | private void checkMaxRotationForMoments()
{
// If the maxrotation is negative, no maxrotation is checked
if (getMaxRotation() < 0)
return;
// limits the moment(s) if needed
for (Point momentorigin: this.moments.keySet())
{
double moment = this.moments.get(momentorigin);
if (Math.abs(moment) > getMaxRotation())
{
if (moment < 0)
moment = -getMaxRotation();
else
moment = getMaxRotation();
this.moments.put(momentorigin, moment);
}
}
} |
67fa914a-6f1a-42b7-b699-58501b7a0258 | 4 | private void kimmota(Pelihahmo h){
asetaKimmotusehto(h);
if (getEhtoX(h) == 1){
h.setVaakaNopeus((-1)*h.getVaakaNopeus()*h.getNopeudenHidastusKerroin());
if (!h.getSuojakilpi()){
h.setElinvoima(h.getElinvoima() - Math.abs(h.getVaakaNopeus())*VAHENTAMIS_VAKIO);
}
}
if (getEhtoY(h) == 1){
h.setPystyNopeus((-1)*h.getPystyNopeus()*h.getNopeudenHidastusKerroin());
if (!h.getSuojakilpi()){
h.setElinvoima(h.getElinvoima() - Math.abs(h.getPystyNopeus())*VAHENTAMIS_VAKIO);
}
}
alaPaastaLaitojenYli(h);
} |
bc3d9869-4696-469c-8a2c-f3868cde8933 | 1 | private void combo_expertizesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_combo_expertizesItemStateChanged
//заносим в глобальную переменную текущую ID экспертизы
try
{
Globals.idCurrentExpertize = Integer.parseInt(String.valueOf(combo_expertizes.getSelectedItem()));
}
catch(NumberFormatException nfe)
{
Globals.idCurrentTask = 0;
}
label_date.setText( Globals.global_connection.t_экспертизы_дата_from_t_экспертизы_id(Globals.idCurrentExpertize) );
// TODO add your handling code here:
}//GEN-LAST:event_combo_expertizesItemStateChanged |
926dc597-acdf-4c33-8246-f0c5936a1c44 | 9 | public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int length = to.length();
char[] circle = new char[length];
/*
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
for (i = 0; i < length; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (;;) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < length; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= length) {
j -= length;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= length) {
offset -= length;
}
}
} |
3b0f0b39-7cea-4dc7-a4fb-e93ca8a5abcb | 7 | @Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost, msg))
return false;
if((myHost instanceof MOB)&&(myHost == this.affected)&&(((MOB)myHost).location()!=null))
{
if((msg.sourceMinor()==CMMsg.TYP_SHUTDOWN)
||((msg.sourceMinor()==CMMsg.TYP_QUIT)&&(msg.amISource((MOB)myHost))))
{
aborted=true;
unInvoke();
}
}
return true;
} |
f8432c0b-80d7-40cd-9064-3f7221892fd6 | 4 | public static List<Card> process(String xmlFileName){
List<Card> cards = new ArrayList<Card>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(XMLDomProcess.class.getResourceAsStream(xmlFileName));
NodeList nl = doc.getElementsByTagName("card");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
int value = new Integer(e.getElementsByTagName("value").item(0).getTextContent());
String path = e.getElementsByTagName("path").item(0).getTextContent();
Card c = new Card(value, new ImageIcon(XMLDomProcess.class.getResource(path)));
cards.add(c);
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return cards;
} |
292aa4c9-4e32-433a-8580-cec58e997ed5 | 8 | private Instances assignClassValue(Instances dataSet) {
if (dataSet.classIndex() < 0) {
if (m_logger != null) {
m_logger.
logMessage("[ClassValuePicker] "
+ statusMessagePrefix()
+ " No class attribute defined in data set.");
m_logger.statusMessage(statusMessagePrefix()
+ "WARNING: No class attribute defined in data set.");
}
return dataSet;
}
if (dataSet.classAttribute().isNumeric()) {
if (m_logger != null) {
m_logger.
logMessage("[ClassValuePicker] "
+ statusMessagePrefix()
+ " Class attribute must be nominal (ClassValuePicker)");
m_logger.statusMessage(statusMessagePrefix()
+ "WARNING: Class attribute must be nominal.");
}
return dataSet;
} else {
if (m_logger != null) {
m_logger.statusMessage(statusMessagePrefix() + "remove");
}
}
if (m_classValueIndex != 0) { // nothing to do if == 0
// swap selected index with index 0
try {
SwapValues sv = new SwapValues();
sv.setAttributeIndex(""+(dataSet.classIndex()+1));
sv.setFirstValueIndex("first");
sv.setSecondValueIndex(""+(m_classValueIndex+1));
sv.setInputFormat(dataSet);
Instances newDataSet = Filter.useFilter(dataSet, sv);
newDataSet.setRelationName(dataSet.relationName());
return newDataSet;
} catch (Exception ex) {
if (m_logger != null) {
m_logger.
logMessage("[ClassValuePicker] "
+statusMessagePrefix()
+ " Unable to swap class attibute values.");
m_logger.statusMessage(statusMessagePrefix()
+ "ERROR (See log for details)");
}
}
}
return dataSet;
} |
f2507699-7fa9-4965-8463-b71aa633b8ae | 9 | private String getConcatenated() {
StringBuilder concatenated = new StringBuilder();
concatenated.append("receiver_id=").append(getReceiverId());
concatenated.append("&subject=").append(_subject);
concatenated.append("&body=").append(_body != null ? _body : "");
concatenated.append("&amount=").append(_amount);
concatenated.append("&payer_email=").append(_email);
concatenated.append("&bank_id=").append(_bankId != null ? _bankId : "");
concatenated.append("&expires_date=").append(_expiresDate != null ? _expiresDate.getTime() / 1000 : "");
concatenated.append("&transaction_id=").append(_transactionId != null ? _transactionId : "");
concatenated.append("&custom=").append(_custom != null ? _custom : "");
concatenated.append("¬ify_url=").append(_notifyUrl != null ? _notifyUrl : "");
concatenated.append("&return_url=").append(_returnUrl != null ? _returnUrl : "");
concatenated.append("&cancel_url=").append(_cancelUrl != null ? _cancelUrl : "");
concatenated.append("&picture_url=").append(_pictureUrl != null ? _pictureUrl : "");
return concatenated.toString();
} |
626db883-71ad-4c07-a881-50f5003c988a | 4 | public void paintComponent(Graphics g)
{
super.paintComponent(g);
//draw the background
for(int h = 0; h <= 400; h+=cellH)
{
g.drawLine(0, h, 400, h);
}
for(int w = 0; w <= 400; w+=cellW)
{
g.drawLine(w, 0, w, 400);
}
for(int i = 0; i<numEnemy; i++)
enemy[i].draw(g);
p1.draw(g);
if(gameOver)
{
Font f = new Font("Sans Serif", Font.BOLD, 120);
g.setFont(f);
g.setColor(new Color(255, 0, 0, 128));
g.drawString("Game",50, 150);
g.drawString("Over",50, 270);
}
} |
60c2bef4-3ef4-4648-b5c4-4be6efab2ad9 | 3 | public void startGame(long noPlayers) {
if (noPlayers != 1 && noPlayers != 2) {
new MemoryGameError().displayError("startGame - invalid number of players specified.");
return;
}
Game game;
if (noPlayers == 1) {
new OptionsMenuView().getInput();
//game = this.createGame(Game.ONE_PLAYER_GAME);
}
else {
game = this.createGame(Game.TWO_PLAYER_GAME);
}
/* GameMenuView gameMenu = new GameMenuView(game);
gameMenu.getInput();*/
} |
5d7847c7-c95a-4a9b-ad35-eea4acf75c2e | 4 | public boolean isFirstColumn(Column column) {
if (column != null) {
for (Column col : mColumns) {
if (col == column) {
return true;
}
if (col.isVisible()) {
return false;
}
}
}
return false;
} |
2145a16e-95bc-4ee1-84b9-4c7bf8edb68c | 0 | public void sacrifice()
{
} |
05d320ff-df05-42fa-b02b-ae3b76551925 | 8 | public static double[][] get_line_points_stegers(ImageProcessor ip, double sigma, boolean mode)
{
int image_width = ip.getWidth();
int image_height = ip.getHeight();
int l;
double a;
double b;
//final line points
double[][] line_points = new double[7][image_width*image_height];
// store results of eigendecomposition
// [0] = lambda1_magnitude n(t)
// [1] = lambda1_direction_x n_x(t)
// [2] = lambda1_direction_y n_y(t)
// [3] = derivative of image in y
// [4] = derivative of image in x
// [5] = super-resolved_x t_y, or dlpy
// [6] = super-resolved_y t_x, or dlpx
// calculate derivatives of gaussian from image
ImageProcessor dx = derivativeX(ip, sigma);
ImageProcessor dy = derivativeY(ip, sigma);
ImageProcessor dxdx = derivativeXX(ip, sigma);
ImageProcessor dxdy = derivativeXY(ip, sigma);
ImageProcessor dydy = derivativeYY(ip, sigma);
//calculate Eigen decomposition of Hessian matrix
for(int py = 0; py < image_height; ++py)
{
for(int px = 0; px < image_width; ++px)
{
l = LINCOOR(py,px,image_width);
// determine first and second eigenvalue and eigenvector
double first_eigenvalue = 0.0; // |n(t)|
double first_eigenvector_x = 0.0; // n(t) -> perpendicular to s(t)
double first_eigenvector_y = 0.0; // n(t) -> perpendicular to s(t)
double t;
//*
double dfdrc = dxdy.getf(px, py);
double dfdrr = dxdx.getf(px, py);
double dfdcc = dydy.getf(px, py);
double theta, e1,e2,n1,n2,c,s;
if (dfdrc != 0.0)
{
theta = 0.5*(dfdcc-dfdrr)/dfdrc;
t = 1.0/(Math.abs(theta)+Math.sqrt(theta*theta+1.0));
if (theta < 0.0) t = -t;
c = 1.0/Math.sqrt(t*t+1.0);
s = t*c;
e1 = dfdrr-t*dfdrc;
e2 = dfdcc+t*dfdrc;
} else
{
c = 1.0;
s = 0.0;
e1 = dfdrr;
e2 = dfdcc;
}
n1 = c;
n2 = -s;
//actually since hessian is a symmetric matrix
//eigen vectors are perpendicular, so no need to store another vector
if (Math.abs(e1) > Math.abs(e2))
{
first_eigenvalue = e1;
//eigval[1] = e2;
first_eigenvector_x = n1;
first_eigenvector_y = n2;
//eigvec[1][0] = -n2;
//eigvec[1][1] = n1;
}
else if (Math.abs(e1) < Math.abs(e2))
{
first_eigenvalue = e2;
//eigval[1] = e1;
first_eigenvector_x = -n2;
first_eigenvector_y = n1;
//eigvec[1][0] = n1;
//eigvec[1][1] = n2;
}
else
{
if (e1 < e2)
{
first_eigenvalue = e1;
//eigval[1] = e2;
first_eigenvector_x = n1;
first_eigenvector_y = n2;
//eigvec[1][0] = -n2;
//eigvec[1][1] = n1;
} else
{
first_eigenvalue = e2;
//eigval[1] = e1;
first_eigenvector_x = -n2;
first_eigenvector_y = n1;
//eigvec[1][0] = n1;
//eigvec[1][1] = n2;
}
}
//*/
// store eigenvalues and eigenvector for new optimum
if (mode)
line_points[0][l] = first_eigenvalue*(-1);
else
line_points[0][l] = first_eigenvalue;
line_points[1][l] = first_eigenvector_y;
line_points[2][l] = first_eigenvector_x;
line_points[3][l] = dy.getf(px,py);
line_points[4][l] = dx.getf(px,py);
// calculate position of peak in second order Taylor polynomial from Steger's algorithm
b = (dx.getf(px,py)*first_eigenvector_x + dy.getf(px,py)*first_eigenvector_y);
a = (dxdx.getf(px,py)*first_eigenvector_x*first_eigenvector_x + 2.0*dxdy.getf(px,py)*first_eigenvector_x*first_eigenvector_y + dydy.getf(px,py)*first_eigenvector_y*first_eigenvector_y);
//a = (dxdx.getf(px,py)*first_eigenvector_x*first_eigenvector_x + dxdy.getf(px,py)*dxdy.getf(px,py)*first_eigenvector_x*first_eigenvector_y + dydy.getf(px,py)*first_eigenvector_y*first_eigenvector_y);
t = (+1)*b/a;
double dlpx = t*first_eigenvector_x;
double dlpy = t*first_eigenvector_y;
// store line point
line_points[5][l] = dlpy+py;
line_points[6][l] = dlpx+px;
}
}
return line_points;
} |
81a9f42d-0a5b-4544-9b45-5909dfd842dc | 8 | public void sendToServer(final File fileToSend, final boolean isDirectory) {
//TODO opportunity to append the file
new Thread() {
@Override
public void run() {
try {
boolean haveToShowDialog = false;
boolean appendFile = false;
for (FTPFile f : ftpFiles) {
if (fileToSend.getName().equals(f.getFilename())) haveToShowDialog = true;
}
if (haveToShowDialog) {
Object[] options = {"Overwrite",
"Append",
"Cancel"};
int n = JOptionPane.showOptionDialog(frmFtpClient,
"File already exists",
"A Silly Question",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
if (n==2) return ;
if (n==1) appendFile=true;
}
if (isDirectory) serverConnect.sendDirectory(fileToSend);
else {
if (appendFile) serverConnect.sendFile(fileToSend, false);
else serverConnect.sendFile(fileToSend, true);
}
refreshFTPDirectory();
} catch (IOException | ConnectionException e) {
throwException(e);
}
}
}.start();
} |
88188484-175a-41da-a6c6-27e8d87bef5a | 5 | @Override
public void sendMessage(String sender, String receiver, String message, int sentBy) throws RemoteException {
System.out.println("sending ...");
if(_userStore.get(receiver) != null) {
System.out.println("user is online");
ClientInterface client = _userStore.get(receiver);
if(client != null)
client.notifyMessage(sender, message);
} else {
System.out.println("user not online!!");
db.storeMessage(sender, receiver, message);
if((sentBy == ServerInterface.CLIENT) && (backupServer != null)) {
try {
backupServer.ping();
backupServer.sendMessage(sender, receiver, message, ServerInterface.SERVER);
} catch(Exception ex) {
System.out.println("backup Server not responding");
resetBackupServer();
}
}
}
} |
4673be06-579e-4639-a3df-a78e683a5ae5 | 2 | protected void writeColumnTitles() throws IOException {
final Iterator<String> titleIter = columnTitles.iterator();
while (titleIter.hasNext()) {
final String title = titleIter.next();
if (titleIter.hasNext()) {
this.writeWithDelimiter(title);
} else {
this.write(title);
}
}
} |
82a0ba22-c8c9-414f-ae53-25c327d61f10 | 1 | public void registerAll(String fallbackPrefix, List<Subcommand> commands) {
for (Subcommand cmd : commands) {
register(fallbackPrefix, cmd);
}
} |
dfc18db1-2968-40a3-9747-bfd87b739675 | 1 | @Override
public String toString() {
if (tile == null) {
return "p" + number + " is dead (" + cooldown
+ " turns remaining) with " + points + " points";
}
return "p" + number + " at " + tile.x + "," + tile.y + " with "
+ points + " points";
} |
7195eda8-0ff6-4503-98aa-cdc5b2034ccb | 6 | public static void main(String[] args) {
final String menu[] = {"Quitter", "Solde", "Paiement", "Retrait", "Dépot"};
int choix;
boolean quit;
Banque compte = new Banque(0);
NumberFormat argent = NumberFormat.getCurrencyInstance();
//boucler tant et aussi longtemps que l'utilisateur n'a pas quitté
quit = false;
while(!quit) {
choix = JOptionPane.showOptionDialog(
null, "Quelle action voulez-vous faire?", "Banque",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
menu, menu[0]);
switch(choix) {
case 0: quit = true; break;
case 1: JOptionPane.showMessageDialog(null, "Votre compte à "+argent.format(compte.getSolde())+"."); break;
case 2: compte.paiement(); break;
case 3: compte.retrait(); break;
case 4: compte.depot(); break;
}
}
System.exit(0);
} |
e54773f8-6da9-4a5d-97a6-d30d4b36b47f | 5 | private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
boolean isValueNumeric = false;
try {
if (value.equals("0") || !value.endsWith("0")) {
Double.parseDouble(value);
isValueNumeric = true;
}
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
} |
a918af67-d08a-411c-bc90-b04b082a9bc5 | 5 | private Message collectMessageFromR(int c, int r) {
int messageRound = 0;
Message m;
do {
m = outcome.get(c);
if (m != null) {
messageRound = getRoundFromPayload(m.getPayload());
}
if (isSuspect(c)) {
// r is been suspected, no need to block any further
break;
}
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} while (m == null || messageRound < r);
return m;
} |
fc6bd6f8-75d1-4b48-8de3-4e2403cf2bd0 | 8 | public void loadSchema(String catalogFile) {
String line = "";
String baseFolder=new File(catalogFile).getParent();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(catalogFile)));
while ((line = br.readLine()) != null) {
//assume line is of the format name (field type, field type, ...)
String name = line.substring(0, line.indexOf("(")).trim();
//System.out.println("TABLE NAME: " + name);
String fields = line.substring(line.indexOf("(") + 1, line.indexOf(")")).trim();
String[] els = fields.split(",");
ArrayList<String> names = new ArrayList<String>();
ArrayList<Type> types = new ArrayList<Type>();
String primaryKey = "";
for (String e : els) {
String[] els2 = e.trim().split(" ");
names.add(els2[0].trim());
if (els2[1].trim().toLowerCase().equals("int"))
types.add(Type.INT_TYPE);
else if (els2[1].trim().toLowerCase().equals("string"))
types.add(Type.STRING_TYPE);
else {
System.out.println("Unknown type " + els2[1]);
System.exit(0);
}
if (els2.length == 3) {
if (els2[2].trim().equals("pk"))
primaryKey = els2[0].trim();
else {
System.out.println("Unknown annotation " + els2[2]);
System.exit(0);
}
}
}
Type[] typeAr = types.toArray(new Type[0]);
String[] namesAr = names.toArray(new String[0]);
TupleDesc t = new TupleDesc(typeAr, namesAr);
HeapFile tabHf = new HeapFile(new File(baseFolder+"/"+name + ".dat"), t);
addTable(tabHf,name,primaryKey);
System.out.println("Added table : " + name + " with schema " + t);
}
} catch (IOException e) {
e.printStackTrace();
System.exit(0);
} catch (IndexOutOfBoundsException e) {
System.out.println ("Invalid catalog entry : " + line);
System.exit(0);
}
} |
6dc6b90c-255c-4aeb-adde-3528e8df9d7c | 4 | @Override
public boolean set(T object)
{
if (this.locked())
{
return false;
}
if (this.lis != null && !this.lis.canChange(this))
{
return false;
}
if (super.set(object))
{
this.count++;
return true;
}
return false;
} |
914d6959-4493-4f5d-b5ed-5e87e1636341 | 1 | public void dropAllTables(){
try{
Connection connection = DriverManager.getConnection(connectionString);
Statement s = connection.createStatement();
s.executeUpdate("drop table if exists parent");
s.executeUpdate("drop table if exists recipeingredients");
s.executeUpdate("drop table if exists ingredient");
s.executeUpdate("drop table if exists recipe");
connection.close();
}
catch(SQLException ex){
ex.printStackTrace();
System.exit(-1);
}
} |
8dd54e6b-f9fd-4eb4-baaa-43471406ba63 | 8 | public void output_characterised_trace(String file_path, ArrayList<TraceEntry> trace, boolean debug, boolean output_enabled){
BufferedWriter bw = null;
if(output_enabled){
try {
bw = new BufferedWriter(new FileWriter(new File(file_path),false));
} catch (IOException e) {
System.out.println("Couldn't open the output file");
e.printStackTrace();
return;
}
}
for(TraceEntry entry : trace){
String line = "";
line+=entry.getFunctionName();
line+=":";
ArrayList<TraceEntry> follower_list = entry.getFollowingEntries();
for(TraceEntry follower_entry : follower_list){
line+=follower_entry.getFunctionName()+",";
}
line+="\n";
System.out.println(line);
if(output_enabled){
try{
bw.write(line);
}catch(IOException e){
System.out.println("Couldn't write to the output file");
e.printStackTrace();
}
}
}
if(bw!=null){
try {
bw.flush();
bw.close();
} catch (IOException e) {
System.out.println("Couldn't close the output file");
e.printStackTrace();
}
}
} |
b884ee30-13ad-4352-8487-e4db1ef09f82 | 2 | static final ArchitectureToolkit getFactory(ARCH architecture)
{
switch (architecture)
{
case ENGINOLA:
return enginolaToolkit;
case EMBER:
return emberToolkit;
} // switch
String errMsg = Integer.toString(architecture.ordinal());
throw new IllegalArgumentException(errMsg);
} // getFactory() |
97855b5f-8660-4b01-b590-bd0727a730c4 | 6 | public static void main(String args[]) {
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(InitWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(InitWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(InitWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(InitWindowUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new InitWindowUI().setVisible(true);
}
});
} |
1b172c10-0b9a-41d9-b3d5-adee562b906c | 5 | public void calculateAdjacentAnts(World world) {
// Iterate through World cells in radius 1 around this cell and update adjacent ants count as necessary
adjacentAntsBlack = 0;
adjacentAntsRed = 0;
for (int i = 0; i < 6; i++) {
int[] adjCell = adjacentCell(i);
Cell cell = world.getCell(adjCell);
if (cell != null && cell.getAnt() != null) {
Ant adjAnt = cell.getAnt();
if (adjAnt.getColour()) { //BLACK
adjacentAntsBlack++;
} else if (!adjAnt.getColour()) {
adjacentAntsRed++;
}
}
}
} |
1a4203e7-4856-444d-8440-51b98162c000 | 7 | void count(int i, int pos){
for(int digit=0; digit<=digits[pos]; digit++){
if(pos==digits.length-1 && digit==0) continue;
if(isAsserted(i, digit) && !used[digit]){
if(digit<digits[pos]){
dp[1][i]+= factorial(pos);
} else{
if(pos>0){
used[digit] = true;
count(i, pos-1);
used[digit] = false;
} else dp[1][i]++;
}
}
}
} |
86ad7c8f-7dc5-48d5-8ed4-3bd8ad958668 | 5 | public String saveAssignment(){
preCreateAssignment();
boolean check = true;
if(asmo.getDeadline().isEmpty()){
check = false;
addFieldError("asmo.deadline", "You must to enter a value to deadline");
}else {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date = df.parse(asmo.getDeadline());
if(date.after(new Date())){
} else {
check = false;
addFieldError("asmo.deadline", "You must to enter a value to deadline which greater than now");
}
} catch (Exception e) {
check = false;
addFieldError("asmo.deadline", "You must to enter a value to deadline which format is dd/MM/yyyy");
}
}
if(check){
boolean blnSave = asmModel.insert(asmo);
if(blnSave){
addActionMessage("Create assignment successfull");
}
}
return SUCCESS;
} |
e889a728-96ec-4754-9a4d-9e459133f061 | 5 | public Map<Integer, Integer> getGeneSpans(String text) {
Map<Integer, Integer> begin2end = new HashMap<Integer, Integer>();
Annotation document = new Annotation(text);
pipeline.annotate(document);
List<CoreMap> sentences = document.get(SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
List<CoreLabel> candidate = new ArrayList<CoreLabel>();
for (CoreLabel token : sentence.get(TokensAnnotation.class)) {
String pos = token.get(PartOfSpeechAnnotation.class);
if (pos.startsWith("NN")) {
candidate.add(token);
} else if (candidate.size() > 0) {
int begin = candidate.get(0).beginPosition();
int end = candidate.get(candidate.size() - 1).endPosition();
begin2end.put(begin, end);
candidate.clear();
}
}
if (candidate.size() > 0) {
int begin = candidate.get(0).beginPosition();
int end = candidate.get(candidate.size() - 1).endPosition();
begin2end.put(begin, end);
candidate.clear();
}
}
return begin2end;
} |
965438dc-4033-4309-a739-af8ed7dd9b26 | 6 | public List<String> getAllSongs(String artistName){
if(artistName.equals(null) || artistName.equals("")) return null;
List<String> allSongs = null;
String url = buildUrl(artistName,null);
try {
Document document = reader.read(url);
// XMLUtil.writeToFile(document, artistName + " - songs.xml");
Element root = document.getRootElement(); //getArtistResponse element
Element albumElement = root.element("albums"); // albums element
List<Element> songsElement = albumElement.elements("songs");
allSongs = new ArrayList<String>();
for (Element songs : songsElement) {
List<Element> items = songs.elements();
for (Element item : items)
if(!allSongs.contains(item.getText())) allSongs.add(item.getText());
}
} catch (Exception e) {
e.printStackTrace();
}
return allSongs;
} |
6e0a0467-0e9e-4f63-b66b-d1cceb6f21bd | 0 | private static AnswerCombination generateAnswerCombination() {
List<Token<AnswerColors>> tokens = new ArrayList<Token<AnswerColors>>();
tokens.add(new Token<AnswerColors> (AnswerColors.BLACK));
tokens.add(new Token<AnswerColors> (AnswerColors.BLACK));
tokens.add(new Token<AnswerColors> (AnswerColors.WHITE));
tokens.add(new Token<AnswerColors> (AnswerColors.WHITE));
tokens.add(new Token<AnswerColors> (AnswerColors.EMPTY));
return new AnswerCombination(tokens);
} |
696fa9d8-0773-431a-a865-084f91e3fdcd | 8 | private Double pricingPlan(String plan) {
final Properties prop = loadProperties();
if (plan != null) {
if (PLAN_BASIC.equals(plan)) {
return Double.parseDouble(prop.getProperty("plan.basic.fee"));
}
if (PLAN_PREMIER.equals(plan)) {
Double.parseDouble(prop.getProperty("plan.premier.fee"));
}
if (PLAN_HOULAHOUP.equals(plan)) {
Double.parseDouble(prop.getProperty("plan.houlahoup.fee"));
}
if (PLAN_VIP.equals(plan)) {
Double.parseDouble(prop.getProperty("plan.vip.fee"));
}
// BIZ
if (BIZ1.equals(plan)) {
return Double.parseDouble(prop.getProperty("plan.biz1.fee"));
}
if (BIZ2.equals(plan)) {
Double.parseDouble(prop.getProperty("plan.biz2.fee"));
}
if (BIZ3.equals(plan)) {
Double.parseDouble(prop.getProperty("plan.biz3.fee"));
}
}
return null;
} |
1bb56da2-de06-4b17-8e05-fdf03df06070 | 1 | public OutlineHeader(Outline owner) {
super();
mOwner = owner;
setOpaque(true);
addMouseListener(this);
addMouseMotionListener(this);
setAutoscrolls(true);
ToolTipManager.sharedInstance().registerComponent(this);
if (!GraphicsUtilities.inHeadlessPrintMode()) {
DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
setDropTarget(new DropTarget(this, this));
}
} |
af6f825f-6273-4e6a-ae70-82606b996283 | 7 | private void initCloseCode() throws InvalidFrameException {
code = CloseFrame.NOCODE;
ByteBuffer payload = super.getPayloadData();
payload.mark();
if( payload.remaining() >= 2 ) {
ByteBuffer bb = ByteBuffer.allocate( 4 );
bb.position( 2 );
bb.putShort( payload.getShort() );
bb.position( 0 );
code = bb.getInt();
if( code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR || code == CloseFrame.NOCODE || code > 4999 || code < 1000 || code == 1004 ) {
throw new InvalidFrameException( "closecode must not be sent over the wire: " + code );
}
}
payload.reset();
} |
50aa1e5a-4b83-4285-b8ab-b92a0b2f0a84 | 5 | private void doRequest() {
try {
// jumping to START_OBJECT
if(jp.nextToken() != JsonToken.START_OBJECT) {
System.out.println("Root should be object: quitting");
return;
}
// jumping to fieldName "cell"
jp.nextToken();
// jumping to START_OBJECT
jp.nextToken();
JsonNode n = jp.readValueAsTree();
// System.out.println(n.size());
cell = createCell(n);
// jumping to fieldName "measurements"
jp.nextToken();
// jumping to START_ARRAY
jp.nextToken();
// OpenCellIdCell openCellIdCell = (OpenCellIdCell) cell;
List<Measurement> measurements = new ArrayList<Measurement>(cell.getSamples());
// int measurementsCounter = 0;
// jumping to either the next START_OBJECT or END_ARRAY
while(jp.nextToken() != JsonToken.END_ARRAY) {
n = jp.readValueAsTree();
measurements.add(createMeasurement(n));
// measurementsCounter++;
}
cell.setMeasurements(measurements);
if(cell.getMeasurements().size() != cell.getSamples()) {
System.out.println("The number of measurements in file is not equal to the number of samples");
}
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
} |
dfc1c6f3-18ba-47e7-9556-01a04775ae30 | 3 | private int popupExit () {
int choix ;
choix = GUIUtilities.question_YES_NO ( Utilities.getLangueMessage( Constantes.MESSAGE_FERMER_LOGICIEL )) ;
if ( choix == JOptionPane.YES_OPTION ) {
if ( this.fileName != null ) {
choix = GUIUtilities.question_YES_NO_CANCEL ( Utilities.getLangueMessage( Constantes.MESSAGE_SAUVEGARDER_FICHIER_ENCOURS) ) ;
if (choix == JOptionPane.YES_OPTION)
save();
}
}
else {
/*
* exprès pour la fonction appelante NO dans ce cas est équivalent à CANCEL
*/
choix = JOptionPane.CANCEL_OPTION ;
}
return choix ;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.