text stringlengths 14 410k | label int32 0 9 |
|---|---|
public boolean startTurn(int day)
{
Iterator<Castle> i = castles.iterator();
while (i.hasNext()) {
Castle c = i.next();
if (c.getColor() != color) {
i.remove();
}
}
return false;
} | 2 |
public EasyDate endOf(int field) {
switch (field) {
case Calendar.YEAR:
calendar.set(Calendar.MONTH, 11);
case Calendar.MONTH:
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
case Calendar.DAY_OF_MONTH:
calendar.set(Calendar.HOUR_OF_DAY, 23);
case Calendar.HOUR_OF_DAY:
calendar.set(Calendar.MINUTE, 59);
case Calendar.MINUTE:
calendar.set(Calendar.SECOND, 59);
case Calendar.SECOND:
calendar.set(Calendar.MILLISECOND, 999);
break;
default:
throw new IllegalArgumentException("无法识别的日期字段:" + field);
}
return this;
} | 6 |
public static void main(String[] args){
String kod = null;
int[][] tabla = new int[8][3];
sc = new Scanner( System.in );
while( true )
{
System.out.println("Játék indítasa : 1");
System.out.println("Játék szabály : 2");
System.out.println("Kilépés : 3");
logger.info( "Játék indul, választás játék szabály vagy játék indítás vagy kilépés között." );
kod = sc.nextLine();
if( kod.equals("1") )
{
logger.info("1 választva, tehát kezdődik a játék. kod = 1");
System.out.println("Üdvözöllek, kezdödjön a jatek!");
System.out.println();
Kezdes.nullaz(tabla);
Jatek.lerak(tabla);
Jatek.leptet(tabla);
}
else if( kod.equals("2") )
{
logger.info("2 választva, tehát játékszabály kiíratás. kod = 2");
Szabalyok.Kiir();
}
else if( kod.equals("3") )
{
logger.info("3 választva, tehát kilépés kod = 3");
System.out.println( "Köszi hogy játszottál velem, vagy ha nem akkor is várlak legközelebb!\n" );
break;
}
else
{
logger.error("Hibásan beírt szám, újbóli bekérés.");
System.out.println("Hibásan beírt szám, választható lehetőségek: 1 vagy 2 vagy 3\n"
+ "Próbáld újra");
}
}
} | 4 |
@Override
public boolean accept(File dir, String name) {
try{
if (name.substring(name.lastIndexOf(".")).equalsIgnoreCase(".dat"))
return true;
}
catch (Exception e){
System.err.println("Exception caught: " + e);
}
return false;
} | 2 |
public void close(){
try{
if(in!=null)in.close();
if(out!=null)out.close();
if(socket!=null)socket.close();
}
catch(Exception e){
}
in=null;
out=null;
socket=null;
} | 4 |
private static void updateTexturePacks () {
for (int i = 0; i < texturePackPanels.size(); i++) {
if (selectedTexturePack == i) {
String packs = "";
if (TexturePack.getTexturePack(getIndex()).getCompatible() != null) {
packs += "<p>This texture pack works with the following packs:</p><ul>";
for (String name : TexturePack.getTexturePack(getIndex()).getCompatible()) {
packs += "<li>" + (ModPack.getPack(name) != null ? ModPack.getPack(name).getName() : name) + "</li>";
}
packs += "</ul>";
}
texturePackPanels.get(i).setBackground(UIManager.getColor("control").darker().darker());
texturePackPanels.get(i).setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
LaunchFrame.updateTpInstallLocs(TexturePack.getTexturePack(getIndex()).getCompatible());
File tempDir = new File(OSUtils.getCacheStorageLocation(), "TexturePacks" + File.separator + TexturePack.getTexturePack(getIndex()).getName());
textureInfo.setText("<html><img src='file:///" + tempDir.getPath() + File.separator + TexturePack.getTexturePack(getIndex()).getImageName() + "' width=400 height=200></img> <br>"
+ TexturePack.getTexturePack(getIndex()).getInfo() + packs);
textureInfo.setCaretPosition(0);
} else {
texturePackPanels.get(i).setBackground(UIManager.getColor("control"));
texturePackPanels.get(i).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
}
} | 5 |
private boolean suitMoveIsValid(Card.Suit from, Card.Suit to) {
switch (to) {
case HEARTS:
return from != Card.Suit.DIAMONDS;
case DIAMONDS:
return from != Card.Suit.HEARTS;
case CLUBS:
return from != Card.Suit.SPADES;
case SPADES:
return from != Card.Suit.CLUBS;
default:
return false;
}
} | 4 |
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("killall")){
if(sender instanceof Player){
Player p = (Player) sender;
if(p.isOp() || p.hasPermission("scmds.killall")){
for(Entity entity : p.getNearbyEntities(2000, 2000, 2000)){
if((!(entity instanceof Player)) && entity instanceof LivingEntity || (!(entity instanceof Player)) && entity instanceof Entity){
entity.remove();
}
}
sender.sendMessage(ChatColor.YELLOW + "[" + ChatColor.GREEN + "SCmds" + ChatColor.YELLOW + "] " + ChatColor.YELLOW + "All Mobs killed!");
}else{
sender.sendMessage(ChatColor.YELLOW + "[" + ChatColor.GREEN + "SCmds" + ChatColor.YELLOW + "] " + ChatColor.YELLOW + "You may not use this command!");
}
}else{
sender.sendMessage("Only players may use this command!");
}
}
return true;
} | 9 |
private void check (int [ ] array1, int [ ] array2) {
assertTrue (array1.length == array2.length);
for (int k=0; k<array1.length; k++) {
assertTrue (array1[k] == array2[k]);
}
} | 1 |
public void deleteActor(long id) {
if(actors.get(id) != null) {
actors.get(id).destroy();
actors.remove(id);
}
} | 1 |
protected JComponent makeTextPanel(String text) {
JPanel panel;
if(text.equals("Open tickets")){
panel = new TicketOverview();
}
else if(text.equals("Solutions")){
//panel = new QAThesaurusView();
panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
}
else{
panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
}
return panel;
} | 2 |
public static void main( String[] args ) throws IOException {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setBounds( 20, 20, 800, 600 );
final UmlDiagramRepository repository = UmlDiagramRepository.createDefaultRepository();
repository.getConfiguration().getComment().setPathShape( PathShape.CURVED );
repository.getConfiguration().getComment().source().setDirection( Direction.ORTHOGONAL );
UmlDiagramView view = repository.createView();
JMenu menu = new JMenu( "Actions" );
menu.add( saveImage( view ) );
JMenuBar menuBar = new JMenuBar();
menuBar.add( menu );
frame.setJMenuBar( menuBar );
frame.setLayout( new GridBagLayout() );
Insets insets = new Insets( 0, 0, 0, 0 );
frame.add( view.getComponent(), new GridBagConstraints( 0, 1, 100, 100, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, insets, 0, 0 ) );
frame.add( createTools( view.getTools() ), new GridBagConstraints( 0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, insets, 0, 0 ) );
UmlDiagram diagram = tryRead( repository );
if( diagram == null ) {
diagram = repository.createEmptyDiagram();
TypeBox a = diagram.createType();
a.setText( "alpha" );
a.setLocation( 50, 50 );
TypeBox b = diagram.createType();
b.setText( "beta" );
b.setLocation( 350, 350 );
TypeBox c = diagram.createType();
c.setText( "gamma" );
c.setLocation( 50, 450 );
TypeBox d = diagram.createType();
d.setText( "delta" );
d.setLocation( 350, 70 );
a.addInheritsFrom( b );
a.addImplementsFrom( c );
Connection con = b.addAggregation( d );
c.addComposition( d );
CommentBox co = a.addComment( "some comment text" );
co.setLocation( 250, 170 );
con.addLabel( ConnectionLabelConfiguration.SOURCE ).setText( "source" );
con.addLabel( ConnectionLabelConfiguration.MIDDLE ).setText( "middle" );
con.addLabel( ConnectionLabelConfiguration.TARGET ).setText( "target" );
}
diagram.addItemContextListener( disposingListener( diagram ) );
diagram.addItemSelectionListener( selectionListener() );
view.setDiagram( diagram );
frame.addWindowListener( writeOnClose( diagram, repository ) );
frame.setVisible( true );
} | 1 |
public Dimension getPreferredSize() {
if (image != null) {
return new Dimension(image.getWidth(), image.getHeight());
}
return super.getPreferredSize();
} | 1 |
public void getStarGraph(mxAnalysisGraph aGraph, int numVertices)
{
if (numVertices < 4)
{
throw new IllegalArgumentException();
}
mxGraph graph = aGraph.getGraph();
Object parent = graph.getDefaultParent();
Object[] vertices = new Object[numVertices];
for (int i = 0; i < numVertices; i++)
{
vertices[i] = graph.insertVertex(parent, null, new Integer(i).toString(), 0, 0, 25, 25);
}
int numVertexesInPerimeter = numVertices - 1;
for (int i = 0; i < numVertexesInPerimeter; i++)
{
graph.insertEdge(parent, null, getNewEdgeValue(aGraph), vertices[numVertexesInPerimeter], vertices[i]);
}
}; | 3 |
public double magnitudeSquared()
{
double doubleA = a.doubleValue();
double doubleB = b.doubleValue();
return doubleA * doubleA + doubleB * doubleB;
} | 0 |
public List<Token> tokenize(final InputStream stream) throws IOException {
LineColumnReader reader = new LineColumnReader(new InputStreamReader(stream));
List<Token> tokens = new LinkedList<Token>();
try {
while (reader.ready()) {
int c = reader.read();
if (Character.isWhitespace(c)) {
whitespaceReader.readValue(reader, c);
} else if (Character.isLetter(c)) {
tokens.add(identifierReader.getToken(reader, c));
} else if (Character.isDigit(c)) {
tokens.add(numberReader.getToken(reader, c));
} else if (c == '"') {
tokens.add(stringReader.getToken(reader, c));
} else {
Token symbol = symbolReader.getToken(reader, c);
if (symbol != null) {
tokens.add(symbol);
}
}
}
return tokens;
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
reader.close();
}
} | 7 |
public void testConstructorEx5_TypeArray_intArray() throws Throwable {
try {
new Partial(new DateTimeFieldType[] {DateTimeFieldType.dayOfYear()}, new int[2]);
fail();
} catch (IllegalArgumentException ex) {
assertMessageContains(ex, "same length");
}
} | 1 |
private void readPinNames(HDLTokenizer input, int partNumber, String partName)
throws HDLException {
boolean endOfPins = false;
// read pin names
while (!endOfPins) {
// read left pin name
input.advance();
if (!(input.getTokenType() == HDLTokenizer.TYPE_IDENTIFIER))
input.HDLError("A pin name is expected");
String leftName = input.getIdentifier();
// check '='
input.advance();
if (!(input.getTokenType() == HDLTokenizer.TYPE_SYMBOL && input.getSymbol() == '='))
input.HDLError("Missing '='");
// read right pin name
input.advance();
if (!(input.getTokenType() == HDLTokenizer.TYPE_IDENTIFIER))
input.HDLError("A pin name is expected");
String rightName = input.getIdentifier();
addConnection(input, partNumber, partName, leftName, rightName);
// check ',' or ')'
input.advance();
if (input.getTokenType() == HDLTokenizer.TYPE_SYMBOL && input.getSymbol() == ')')
endOfPins = true;
else if (!(input.getTokenType() == HDLTokenizer.TYPE_SYMBOL
&& input.getSymbol() == ','))
input.HDLError("',' or ')' are expected");
}
} | 9 |
protected static void exportOutlinerDocument(OutlinerDocument document, FileProtocol protocol) {
// We need to swap in a new documentSettings object so that the changes don't carry over
// to the open document, but are conveyed to the export. We'll put the real object back
// when we're done.
DocumentSettings oldSettings = document.settings;
DocumentInfo oldDocInfo = document.getDocumentInfo();
DocumentSettings newSettings = new DocumentSettings(document);
DocumentInfo newDocInfo = null;
try {
newDocInfo = (DocumentInfo) oldDocInfo.clone();
} catch (CloneNotSupportedException cnse) {
cnse.printStackTrace();
}
document.settings = newSettings;
document.setDocumentInfo(newDocInfo);
// We also need to swap out the tree with a new tree that just contains the current selection
JoeTree newTree = Outliner.newTree(null);
JoeTree oldTree = document.tree;
if (document.tree.getComponentFocus() == OutlineLayoutManager.TEXT) {
Node node = document.tree.getEditingNode();
int cursor = document.tree.getCursorPosition();
int mark = document.tree.getCursorMarkPosition();
int startIndex = Math.min(cursor,mark);
int endIndex = Math.max(cursor,mark);
String text = node.getValue().substring(startIndex, endIndex);
newTree.getRootNode().getFirstChild().setValue(text);
} else {
Node root = newTree.getRootNode();
root.removeChild(root.getFirstChild());
for (int i = 0; i < document.tree.getSelectedNodes().size(); i++) {
Node node = document.tree.getSelectedNodes().get(i).cloneClean();
node.setDepthRecursively(0);
newTree.getRootNode().appendChild(node);
}
}
document.tree = newTree;
if (protocol.selectFileToSave(document, FileProtocol.EXPORT)) {
FileMenu.exportFile(PropertyContainerUtil.getPropertyAsString(document.getDocumentInfo(), DocumentInfo.KEY_PATH), document, protocol);
}
// Swap it back the settings
document.settings = oldSettings;
document.setDocumentInfo(oldDocInfo);
document.tree = oldTree;
} | 4 |
public LinkedList<FaultsStore> getFaults(){
LinkedList<FaultsStore> psl = new LinkedList<FaultsStore>();
Connection Conn;
FaultsStore ps = null;
ResultSet rs = null;
try {
Conn = _ds.getConnection();
} catch (Exception et) {
System.out.println("No Connection in Faults Model");
return null;
}
PreparedStatement pmst = null;
Statement stmt = null;
String sqlQuery = "select summary,idfault from fault";
//System.out.println("Faults Query " + sqlQuery);
try {
try {
// pmst = Conn.prepareStatement(sqlQuery);
stmt = Conn.createStatement();
} catch (Exception et) {
System.out.println("Can't create prepare statement");
return null;
}
System.out.println("Created prepare");
try {
// rs=pmst.executeQuery();
rs = stmt.executeQuery(sqlQuery);
} catch (Exception et) {
System.out.println("Can not execute query " + et);
return null;
}
System.out.println("Statement executed");
if (rs.wasNull()) {
System.out.println("result set was null");
} else {
System.out.println("result set wasn't null");
}
while (rs.next()) {
//System.out.println("Getting RS");
ps = new FaultsStore();
ps.setFaultid(rs.getString("idfault"));
ps.setFaultSummary(rs.getString("summary"));
psl.add(ps);
}
} catch (Exception ex) {
System.out.println("Opps, error in query " + ex);
return null;
}
try {
Conn.close();
} catch (Exception ex) {
return null;
}
return psl;
} | 7 |
public void update(){
if(active){
curTime++;
if(curTime>duration){
active = false;
curTime = 0;
curCooldown = cooldown;
}
}
if(curCooldown>0){
curCooldown--;
}
} | 3 |
public Object parseValue(String value) throws NumberFormatException, ParseException {
switch(type){
case("int"): return Integer.valueOf(value);
case("string"): return value;
case("float"): return Float.valueOf(value);
case("date"): return dateFormatter.parse(value);
default: return null;
}
} | 4 |
public void connect() {
if (connection != null) {
throw new IllegalStateException("Already connected!");
}
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database
+ "?useUnicode=true&characterEncoding=utf-8", user, password);
Statement stmt = connection.createStatement();
stmt.execute("CREATE TABLE IF NOT EXISTS PartTable (id INT PRIMARY KEY AUTO_INCREMENT, modName TEXT, partName TEXT, INDEX (partName(16)))");
insertPartStatement = connection.prepareStatement("INSERT INTO PartTable (modName, partName) VALUES (?, ?)");
// Read database, create index.
ResultSet result = stmt.executeQuery("SELECT modName, partName FROM PartTable");
while (result.next()) {
inMemory.put(result.getString(2), result.getString(1));
}
result.close();
} catch (SQLException | ClassNotFoundException e) {
LOG.log(Level.FATAL, "Could not connect to database!", e);
throw new RuntimeException(e);
}
} | 3 |
@Override
public void run() {
while (true) {
Packet packet = null;
try {
packet = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
if ( packet.isFormat() ) {
while (queue.size() < 100 )
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
format = packet;
//for (int i=0; i<this.receivers.size(); i++)
// receivers.get(i).hasFormat = false;
}
for (int i=0; i<receivers.size(); i++) {
if (!receivers.get(i).hasFormat)
format.send(receivers.get(i), tsocket);
if (!packet.isFormat())
packet.send(receivers.get(i), tsocket);
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//tsocket.close();
} | 9 |
@Override
public double evaluate(int[][] board) {
int r = 0;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] != 0) {
if (blocked(i, j, board)) {
r++;
}
}
}
}
return r;
} | 4 |
public YamlPermissionBase(String n, ConfigurationSection config) {
name = n;
yamlConfiguration = config;
} | 0 |
private void send() {
int maxAttemps = 5, cnt = 0;
while (cnt < maxAttemps) {
Node nextNode = null;
boolean initiator = false;
try {
nextNode = RoutingManager.nextNode(packet);
if (isNodeInitiator(nextNode)) {
initiator = true;
}
sentToNextNode(nextNode);
} catch (IOException e) {
stdOut.printError(TAG + " can not connect to: " + nextNode);
organizeNodesToVisit(nextNode);
if (initiator) cnt++;
continue; // Posli znovu
}
break; // Uspech, konec
}
if (cnt == maxAttemps) {
stdOut.writeln(TAG + " packet undeliverable to initiator ");
}
} | 5 |
public static ContactLocation convertLocationToType(String loc)
{
if (loc.equalsIgnoreCase("DC")) return ContactLocation.DIALLED_CALLS;
else if (loc.equalsIgnoreCase("MC")) return ContactLocation.MISSED_CALLS;
else if (loc.equalsIgnoreCase("ME")) return ContactLocation.PHONE_ENTRIES;
else if (loc.equalsIgnoreCase("SM")) return ContactLocation.SIM_ENTRIES;
else if (loc.equalsIgnoreCase("MT")) return ContactLocation.ALL_ENTRIES;
else return ContactLocation.UNKNOWN_ENTRY;
} | 5 |
public static String toCamel(final String... string) {
StringBuilder builder = new StringBuilder(100);
if ((string != null) && (string.length > 0)) {
for (int i = 0; i < string.length; i++) {
String part = string[i];
if (!isEmpty(part)) {
part = part.trim().toLowerCase();
builder.append(part.substring(0, 1).toUpperCase());
if (part.length() > 1) {
builder.append(part.substring(1, part.length()));
}
}
}
}
return builder.toString();
} | 5 |
final NPCComposite method1149() {
int j = -1;
if (anInt2099 == -1) {
if (anInt2077 != -1) {
j = Class21.settings[anInt2077];
}
} else {
j = Class142_Sub27_Sub14.method1892(anInt2099);
}
if (~j > -1 || j >= -1 + anIntArray2085.length || anIntArray2085[j] == -1) {
int k = anIntArray2085[-1 + anIntArray2085.length];
if (k == -1) {
return null;
} else {
return Class21.npcCompositeForID(k);
}
}
return Class21.npcCompositeForID(anIntArray2085[j]);
} | 6 |
private String startSetToString() {
StringBuffer FString = new StringBuffer();
boolean didPrint;
if (m_starting == null) {
return getStartSet();
}
for (int i = 0; i < m_starting.length; i++) {
didPrint = false;
if ((m_hasClass == false) ||
(m_hasClass == true && i != m_classIndex)) {
FString.append((m_starting[i] + 1));
didPrint = true;
}
if (i == (m_starting.length - 1)) {
FString.append("");
}
else {
if (didPrint) {
FString.append(",");
}
}
}
return FString.toString();
} | 7 |
public void testConstructor_ObjectStringEx4() throws Throwable {
try {
new TimeOfDay("1970-04-06T10:20:30.040+14:00");
fail();
} catch (IllegalArgumentException ex) {}
} | 1 |
public void fusionWithDarkenFullAlpha(CPLayer fusion, CPRect rc) {
CPRect rect = new CPRect(0, 0, width, height);
rect.clip(rc);
for (int j = rect.top; j < rect.bottom; j++) {
int off = rect.left + j * width;
for (int i = rect.left; i < rect.right; i++, off++) {
int color1 = data[off];
int alpha1 = (color1 >>> 24) * alpha / 100;
int color2 = fusion.data[off];
int alpha2 = (color2 >>> 24) * fusion.alpha / 100;
int newAlpha = alpha1 + alpha2 - alpha1 * alpha2 / 255;
if (newAlpha > 0) {
// This alpha is used when color1 > color2
int alpha12 = alpha1 * (alpha2 ^ 0xff) / newAlpha;
int invAlpha12 = alpha12 ^ 0xff;
// This alpha is used when color2 > color1
int alpha21 = alpha2 * (alpha1 ^ 0xff) / newAlpha;
int invAlpha21 = alpha21 ^ 0xff;
int color = newAlpha << 24;
int c1, c2;
c1 = (color1 >>> 16 & 0xff);
c2 = (color2 >>> 16 & 0xff);
color |= ((c2 >= c1) ? (c2 * alpha21 + c1 * invAlpha21) : (c1 * alpha12 + c2 * invAlpha12)) / 255 << 16;
c1 = (color1 >>> 8 & 0xff);
c2 = (color2 >>> 8 & 0xff);
color |= ((c2 >= c1) ? (c2 * alpha21 + c1 * invAlpha21) : (c1 * alpha12 + c2 * invAlpha12)) / 255 << 8;
c1 = color1 & 0xff;
c2 = color2 & 0xff;
color |= ((c2 >= c1) ? (c2 * alpha21 + c1 * invAlpha21) : (c1 * alpha12 + c2 * invAlpha12)) / 255;
fusion.data[off] = color;
}
}
}
fusion.alpha = 100;
} | 6 |
private void btnImprimirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnImprimirActionPerformed
// Codigo de imprimir
int a = panelGeneral.getSelectedIndex();
Imprimir imp;
try {
if (a == 0) {
imp = new Imprimir(this);
} else if (a == 1) {
tabla.print();
}
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, "Error al imprimir, " + ex.getMessage(),
"ERROR", JOptionPane.ERROR_MESSAGE);
} finally {
imp = null;
}
}//GEN-LAST:event_btnImprimirActionPerformed | 3 |
@Override
public int getBrewButtonStatus() {
return brewButtonStatus;
} | 0 |
public void setPrice(String price) {
this.price = price;
} | 0 |
public static void main(String[] args) {
// Methods in Comparator
List<Person> people = new ArrayList<>();
people.sort(
Comparator.comparing(Person::getLastName)
.thenComparing(Person::getFirstName)
.thenComparing(
Person::getEmailAddress,
Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)
)
);
// Old way of initializing ThreadLocal:
ThreadLocal<List<String>> oldThreadLocalString = new ThreadLocal<List<String>>() {
@Override
public List<String> initialValue() {
return new ArrayList<>();
}
};
System.out.println(oldThreadLocalString.get());
// New way:
ThreadLocal<List<String>> newThreadLocalString = ThreadLocal.withInitial(ArrayList::new);
System.out.println(newThreadLocalString.get());
// Java Optional
Optional<Integer> optional = new ArrayList<Integer>().stream().min(Integer::compareTo);
System.out.println(optional);
// Files can now return streams
try {
Stream stream = Files.list(Paths.get("c:\\temp\\"));
stream = Files.lines(Paths.get("c:\\temp\\"), Charset.forName("UTF_32"));
stream = Files.find(Paths.get("c:\\"),
5,
(T, U) -> (T == U)
);
} catch (IOException e) {
UncheckedIOException ex = new UncheckedIOException("cause", e);
System.out.println(ex.getMessage());
}
// Rejoice, for we finally have string joins!
String joinExample = String.join(",", "a", "b", "c", "4", "E", "6");
System.out.println(joinExample);
StringJoiner joiner = new StringJoiner("-");
joiner.add("abbie");
joiner.add("doobie");
System.out.println(joiner.toString());
} | 1 |
public void insert_aswrange(final Swizzler indswz) {
final Iterator iter = CFG.preds(indswz.phi_block()).iterator();
while (iter.hasNext()) {
final Block blk = (Block) iter.next();
if (!indswz.phi_block().dominates(blk)) {
final SRStmt aswrange = new SRStmt((Expr) indswz.array()
.clone(), (Expr) indswz.init_val().clone(),
(Expr) indswz.end_val().clone());
blk.tree().addStmtBeforeJump(aswrange);
changed = true;
if (InductionVarAnalyzer.DEBUG) {
System.out.println("Inserted ASWR: " + aswrange
+ "\nin block: " + blk);
System.out.println("$$$ can insert aswrange now\n"
+ "array: " + indswz.array() + "\nIV: "
+ indswz.ind_var() + "\ninit: " + indswz.init_val()
+ "\nend: " + indswz.end_val());
}
}
}
} | 3 |
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if (bs == null) {
this.createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
if (state == STATE.MENU) {
menu.render(g);
}
if (state == STATE.LEVELS) {
levels.render(g);
}
if (state == STATE.GAME || state == STATE.PAUSE || state == STATE.GAMEOVER) {
g2d.drawImage(tex.getGameBackground(), 0, 0, 800 + 10, 600 + 10, null);
if (cam.getZoomOn()) {
g2d.scale(2.0, 2.0);
g2d.translate(cam.getX(), cam.getY()); // Cam start
handler.render(g);
g2d.translate(-cam.getX(), -cam.getY()); // Cam end
g2d.scale(0.5, 0.5);
} else {
g2d.translate(cam.getX(), cam.getY()); // Cam start
handler.render(g);
g2d.translate(-cam.getX(), -cam.getY()); // Cam end
}
ui.render(g);
}
if (state == STATE.PAUSE) {
pause.render(g);
}
g.dispose();
bs.show();
} | 8 |
void setLayoutData () {
Control [] children = layoutComposite.getChildren ();
TableItem [] items = table.getItems ();
GridData data;
int hSpan, vSpan, hIndent, vIndent;
String vAlign, hAlign, vGrab, hGrab, exclude;
for (int i = 0; i < children.length; i++) {
data = new GridData ();
/* Set widthHint and heightHint */
data.widthHint = new Integer (items [i].getText (WIDTH_COL)).intValue ();
data.heightHint = new Integer (items [i].getText (HEIGHT_COL)).intValue ();
/* Set vertical alignment and horizontal alignment */
hAlign = items [i].getText (HALIGN_COL);
if (hAlign.equals ("CENTER")) {
data.horizontalAlignment = SWT.CENTER;
} else if (hAlign.equals ("END")) {
data.horizontalAlignment = SWT.END;
} else if (hAlign.equals ("FILL")) {
data.horizontalAlignment = SWT.FILL;
} else {
data.horizontalAlignment = SWT.BEGINNING;
}
vAlign = items [i].getText (VALIGN_COL);
if (vAlign.equals ("BEGINNING")) {
data.verticalAlignment = SWT.BEGINNING;
} else if (vAlign.equals ("END")) {
data.verticalAlignment = SWT.END;
} else if (vAlign.equals ("FILL")) {
data.verticalAlignment = SWT.FILL;
} else {
data.verticalAlignment = SWT.CENTER;
}
/* Set spans and indents */
hSpan = new Integer (items [i].getText (HSPAN_COL)).intValue ();
data.horizontalSpan = hSpan;
vSpan = new Integer (items [i].getText (VSPAN_COL)).intValue ();
data.verticalSpan = vSpan;
hIndent = new Integer (items [i].getText (HINDENT_COL)).intValue ();
data.horizontalIndent = hIndent;
vIndent = new Integer (items [i].getText (VINDENT_COL)).intValue ();
data.verticalIndent = vIndent;
/* Set grabs */
hGrab = items [i].getText (HGRAB_COL);
data.grabExcessHorizontalSpace = hGrab.equals ("true");
vGrab = items [i].getText (VGRAB_COL);
data.grabExcessVerticalSpace = vGrab.equals ("true");
/* Set minimum width and height */
data.minimumWidth = new Integer (items [i].getText (MINWIDTH_COL)).intValue ();
data.minimumHeight = new Integer (items [i].getText (MINHEIGHT_COL)).intValue ();
/* Set exclude boolean */
exclude = items [i].getText (EXCLUDE_COL);
data.exclude = exclude.equals ("true");
children [i].setLayoutData (data);
}
} | 7 |
@Override
public List<Edge<N>> edgesFrom(N... fromList) {
LinkedList<Edge<N>> list = new LinkedList<Edge<N>>();
if(fromList.length == 1) {
N from = fromList[0];
if(containsNode(from)) {
list.addAll(nodes.get(from));
}
} else if(fromList.length > 1) {
for(int i = 0; i < fromList.length; i++) {
list.addAll(edgesFrom(fromList[i]));
}
}
return list;
} | 4 |
public char read() throws IOException {
if (isPriorEndLine) {
lineno++;
position = -1;
nextLine = source.readLine();
if(nextLine!= null) sourceText.add(nextLine);
// debug statement
/*
if (nextLine != null) {
System.out.println("READLINE: "+nextLine);
} */
isPriorEndLine = false;
}
if (nextLine == null) { // hit eof or some I/O problem
throw new IOException();
}
if ( nextLine.length() == 0) {
isPriorEndLine = true;
return ' ';
}
position++;
if (position >= nextLine.length()) {
isPriorEndLine = true;
return ' ';
}
return nextLine.charAt(position);
} | 5 |
public String getNewick(boolean bl) {
StringBuffer ret = new StringBuffer("");
for (int i = 0; i < this.getChildCount(); i++) {
if (i == 0) {
ret.append("(");
}
ret.append(this.getChild(i).getNewick(bl));
if (bl) {
double branchLength = this.getChild(i).getBL();
if (branchLength == 0)
branchLength = MIN_BRANCH_LENGTH;
ret.append(":".concat(String.valueOf(branchLength)));
}
if (i == this.getChildCount()-1) {
ret.append(")");
} else {
ret.append(",");
}
}
if (this.name != null) {
ret.append(this.name);
}
return ret.toString();
} | 6 |
public Builder mergeImage(protocols.ChatProtocol.Image value) {
if (imageBuilder_ == null) {
if (((bitField0_ & 0x00000010) == 0x00000010) &&
image_ != protocols.ChatProtocol.Image.getDefaultInstance()) {
image_ =
protocols.ChatProtocol.Image.newBuilder(image_).mergeFrom(value).buildPartial();
} else {
image_ = value;
}
onChanged();
} else {
imageBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000010;
return this;
} | 3 |
public final synchronized byte readByte(){
this.inputType = true;
String word="";
byte bb=0;
if(!this.testFullLineT) this.enterLine();
word = nextWord();
if(!eof)bb = Byte.parseByte(word.trim());
return bb;
} | 2 |
@Override
public void sort(T[] a, int lo, int hi)
{ // Sort a[] into increasing order.
boolean sorted = false;
for (int i = lo ; i <= hi && !sorted; i++)
{// Bubble the i'th smallest element up if the array is still unsorted
sorted = true;
for (int j = hi ; j > i; j--)
if (less(a[j], a[j - 1]))
{
exch(a, j, j-1);
sorted = false;
}
}
} | 4 |
@Override
public void adjust() {
CloseHandler handler = getTarget(CloseHandler.class);
setEnabled(handler != null ? handler.mayAttemptClose() : false);
} | 1 |
private List<List<String>> splice(String text) {
List<List<String>> lines = new ArrayList<List<String>>();
List<String> line = new ArrayList<String>();
int len = 0;
StringTokenizer st = new StringTokenizer(text, " ");
while (st.hasMoreTokens()) {
String word = st.nextToken();
if ((len + word.length()) > ColWidth) {
if (len == 0) {
line.add(word.substring(0, ColWidth-1) + "-");
word = word.substring(ColWidth-1, word.length());
}
lines.add(line);
line = null;
len = 0;
}
if (line == null) line = new ArrayList<String>();
line.add(word);
len += word.length() + (len == 0 ? 0 : 1);
}
if (line != null && line.size() > 0) {
lines.add(line);
}
return lines;
} | 7 |
private void addGuestToBookingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addGuestToBookingButtonActionPerformed
boolean addGuestSuccess;
Booking currentBooking = ctr.getCurrentBooking();
if (currentBooking != null && guestJList2.getSelectedValue() != null) {
Guest guest = (Guest) guestJList2.getSelectedValue();
if (!addedGuestsModel.contains(guest)) {
if (ctr.checkRoomAvailability(currentBooking, addedGuestsModel.getSize()) > 0) {
addGuestSuccess = ctr.createBookingDetail(guest, currentBooking);
if (addGuestSuccess) {
addedGuestsModel.addElement(guest);
addedGuestsJList.setModel(addedGuestsModel);
jOptionPane.showMessageDialog(this, guest.getFirstName() + " " + guest.getLastName() + " added to roomNo " + currentBooking.getRoomNo());
}
else {
jOptionPane.showMessageDialog(this, "Could not add guest to room.\nGuest might already be booked to a room in that period.", "Error.", jOptionPane.INFORMATION_MESSAGE);
}
}
else {
jOptionPane.showMessageDialog(this, "Cannot add guest because room is full!", "Room is full.", jOptionPane.INFORMATION_MESSAGE);
}
}
else {
jOptionPane.showMessageDialog(this, "Guest already added!", "Error.", jOptionPane.INFORMATION_MESSAGE);
}
}
}//GEN-LAST:event_addGuestToBookingButtonActionPerformed | 5 |
public int getBid(Letter bidLetter, ArrayList<PlayerBids> playerBidList, ArrayList<String> playerList, SecretState secretState) {
// Keep track of how many players have exactly 6 letters
int sixLetterCount = 0;
// Defense factor is to prevent other players from bidding high
// but getting letters cheaply
int defenseFactor = 0;
// Current idea -- if any opponent is bidding, on average, 10 greater
// than the letter value -- increase Defense Factor to 7
List<Opponent> opponents = new ArrayList<Opponent>(playerList.size());
int id = 0;
// Initialize opponents
for ( String playerName : playerList ) {
opponents.add( new Opponent() );
opponents.get(id).setId(id);
id++;
}
// Iterate over bidding rounds
for ( PlayerBids round : playerBidList ) {
Letter targetLetter = round.getTargetLetter();
int highBid = 0;
int highBidder = -1;
id = 0;
for ( int bid : round.getBidvalues() ) {
opponents.get(id).addBid(new Bid(bid,targetLetter.getValue(),targetLetter.getCharacter()));
if ( bid > highBid ) {
highBid = bid;
highBidder = id;
}
id++;
}
opponents.get(highBidder).addLetter(targetLetter);
}
// Iterate over opponents
for ( Opponent opponent : opponents ) {
if ( opponent.getLetterCount() == 6 ) {
sixLetterCount++;
}
}
// We're trying to stop users from getting 7 letters!
// How much are we willing to risk? In a 2-player game,
// it makes sense to spend 20 to keep the opponent from
// getting 50+. But with numerous players--Zero Player could win
if ( sixLetterCount > 0 )
{
return 20;
}
double st = stats.getStatistics(bidLetter.getCharacter());
return (int)Math.round(3d * (1- st)) + bidLetter.getValue() + defenseFactor;
} | 7 |
public void init() {
// remplir une première fois la grille
while (game.fillGrid());
// enlever les alignements existants
while (removeAlignments()) {
while (game.fillGrid());
}
} | 3 |
private boolean isPlayerKingInCheckFromPieceHorizontallyLeft() {
for (int j=playerKingPiece.pieceColumn - 1; j>=1; j--){
BoardSquare boardSquare = chessBoard.getBoardSquare(playerKingPiece.pieceLine, j);
if (boardSquare.containsBoardPiece()){
if (j==playerKingPiece.pieceColumn-1){
if (boardSquare.containsOpponentKing(playerColor)){
return true;
}
}
if (boardSquare.containsOpponentRookOrQueen(playerColor)){
return true;
}else{
return false;
}
}
}
return false;
} | 5 |
private void deleteRequest(HttpExchange he) throws IOException {
try {
InputStreamReader isr = new InputStreamReader(he.getRequestBody(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
String jsonInput = br.readLine();
String path = he.getRequestURI().getPath();
int lastIndex = path.lastIndexOf("/");
if (lastIndex > 0) {
int id = Integer.parseInt(path.substring(lastIndex + 1));
Person p = facade.delete(id);
response = trans.toJson(p);
status = 200;
} else {
status = 400;
response = "no id";
}
} catch (NumberFormatException nfe) {
response = "id is not a number";
status = 404;
}
} | 2 |
private void initKeys() {
inputManager.addMapping("down", new KeyTrigger(KeyInput.KEY_W));
inputManager.addMapping("up", new KeyTrigger(KeyInput.KEY_S));
inputManager.addMapping("left", new KeyTrigger(KeyInput.KEY_A));
inputManager.addMapping("right", new KeyTrigger(KeyInput.KEY_D));
inputManager.addMapping("one", new KeyTrigger(KeyInput.KEY_1));
inputManager.addMapping("two", new KeyTrigger(KeyInput.KEY_2));
inputManager.addMapping("three", new KeyTrigger(KeyInput.KEY_3));
inputManager.addMapping("four", new KeyTrigger(KeyInput.KEY_4));
inputManager.addMapping("shootB", new MouseButtonTrigger(
MouseInput.BUTTON_LEFT));
inputManager.addListener(analogListener, "left", "right", "down", "up",
"one", "two", "three", "four", "pulse");
ActionListener acl = new ActionListener() {
public void onAction(String name, boolean keyPressed, float tpf) {
if (name.equals("shootB") && keyPressed) {
Vector2f click2d = inputManager.getCursorPosition();
Vector3f click3d = cam.getWorldCoordinates(
new Vector2f(click2d.x, click2d.y), 0f).clone();
Vector3f dir = cam
.getWorldCoordinates(
new Vector2f(click2d.x, click2d.y), 1f)
.subtractLocal(click3d).normalizeLocal();
sharedstate.BeamD beamdata = new sharedstate.BeamD(
playerData, dir);
state.getMyObjects().add(beamdata);
state.getObjects().add(beamdata);
audio_beam.playInstance();
}
}
};
inputManager.addListener(acl, "shootB");
} | 2 |
public double getFMeasure(int idx) {
if (idx == 0){
return statistic[idxIDrefsFMeasure];
}else if (idx == 1){
return statistic[idxFEsFMeasure];
}else if (idx == 2){
return statistic[idxIDrefsNIFMeasure];
}else{
return -1.0;
}
} | 3 |
private void evalArrayLoad(Type expectedComponent, Frame frame) throws BadBytecode {
Type index = frame.pop();
Type array = frame.pop();
// Special case, an array defined by aconst_null
// TODO - we might need to be more inteligent about this
if (array == Type.UNINIT) {
verifyAssignable(Type.INTEGER, index);
if (expectedComponent == Type.OBJECT) {
simplePush(Type.UNINIT, frame);
} else {
simplePush(expectedComponent, frame);
}
return;
}
Type component = array.getComponent();
if (component == null)
throw new BadBytecode("Not an array! [pos = " + lastPos + "]: " + component);
component = zeroExtend(component);
verifyAssignable(expectedComponent, component);
verifyAssignable(Type.INTEGER, index);
simplePush(component, frame);
} | 3 |
public static void start()
{
/* 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(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new Frame().setVisible(true);
}
});
} | 6 |
public void init(generated.Cards XMLcards)
{
if (XMLcards == null)
throw new NullPointerException("XMLcards is null");
// init "go to" cards
generated.Gotos XMLgotos;
if (_type == SURPRISE)
{
XMLgotos = XMLcards.getSurprises().getGotos();
}
else // WARRANT
{
XMLgotos = XMLcards.getWarrants().getGotos();
}
int gotoSize = XMLgotos.getSize();
for (int i = 0; i < gotoSize; i++)
{
generated.Goto XMLgotoCard = XMLgotos.getGoto().get(i);
GotoCard myGotoCard = new GotoCard(_type, _game);
myGotoCard.init(XMLgotoCard);
this.addCard(myGotoCard);
}
// init "finance" cards
generated.Finances XMLfinances;
if (_type == SURPRISE)
{
XMLfinances = XMLcards.getSurprises().getFinances();
}
else // WARRANT
{
XMLfinances = XMLcards.getWarrants().getFinances();
}
int financesSize = XMLfinances.getSize();
for (int i = 0; i < financesSize; i++)
{
generated.Finance XMLfinanceCard = XMLfinances.getFinance().get(i);
FinancialCard myFinanceCard = new FinancialCard(_type, _game);
myFinanceCard.init(XMLfinanceCard);
this.addCard(myFinanceCard);
}
// init "pardon" cards
if (_type == SURPRISE)
{
generated.Pardons XMLpardons = XMLcards.getSurprises().getPardons();
int pardonSize = XMLpardons.getSize();
for (int i = 0; i < pardonSize; i++)
{
generated.Pardon XMLpardonCard = XMLpardons.getPardon().get(i);
PardonCard myPardonCard = new PardonCard(this);
myPardonCard.init(XMLpardonCard);
this.addCard(myPardonCard);
}
}
this.mixCards();
} | 7 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ThumbsUpPK that = (ThumbsUpPK) o;
if (accountId != that.accountId) return false;
if (replyId != that.replyId) return false;
return true;
} | 5 |
public Object get(String key) {
return symbols.get(key).getValue();
} | 0 |
@Override
public boolean isInCombat()
{
if (victim == null)
return false;
try
{
final Room vicR = victim.location();
if ((vicR == null) || (location() == null) || (vicR != location()) || (victim.amDead()))
{
if ((victim instanceof StdMOB) && (((StdMOB) victim).victim == this))
victim.setVictim(null);
setVictim(null);
return false;
}
return true;
}
catch (final NullPointerException n)
{
}
return false;
} | 8 |
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
s = new String[n];
for(int i=0; i<n; i++){
s[i] = br.readLine();
}
best = new int[n][m];
visited = new boolean[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++) best[i][j] = -1;
}
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(best[i][j]<0 && s[i].charAt(j)=='D'){
calc(i,j);
}
}
}
if(result == 0) System.out.println("Poor Dima!"); else
if(result == INF) System.out.println("Poor Inna!"); else System.out.println(result);
} | 9 |
public void update() {
for (int x = 0; x < Standards.CHUNK_SIZE; x++){
for (int y = 0; y < Standards.CHUNK_SIZE; y++){
contents[x][y].update();
}
}
} | 2 |
@Override
public Complex product(final Complex factor) {
if (factor == null)
throw new NullPointerException("The factor is not properly specified.");
if (Complex.isNaN(factor) || Complex.isNaN(this))
return Complex.NaN;
if ((Complex.isInfinite(factor) && Complex.isOrigin(this)) ||
(Complex.isInfinite(this) && Complex.isOrigin(factor)))
return Complex.NaN;
if (Complex.isInfinite(factor) || Complex.isInfinite(this))
return Complex.Infinity;
return Complex.Cartesian(this._real * factor._real -
this._imaginary * factor._imaginary,
this._real * factor._imaginary +
this._imaginary * factor._real);
} | 9 |
public ExponentialDialog(final Panel panel) {
setTitle("Exponential");
setBounds(1, 1, 400, 150);
Dimension size = getToolkit().getScreenSize();
setLocation(size.width/3 - getWidth()/3, size.height/3 - getHeight()/3);
this.setResizable(false);
setLayout(null);
JPanel paramPanel = new JPanel();
paramPanel.setBorder(BorderFactory.createTitledBorder("Parameters"));
paramPanel.setBounds(0, 0, 400, 75);
JLabel lambdaLabel = new JLabel("Lambda = ");
final JTextField lambdaTextField = new JTextField("1");
lambdaTextField.setColumns(3);
JLabel pLabel = new JLabel("Probability = ");
final JTextField pTextField = new JTextField("50");
pTextField.setColumns(3);
JButton okButton = new JButton("OK");
okButton.setSize(250, 40);
okButton.setBounds(50, 75, 250, 40);
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double lambda = 0;
double p = 0;
try {
lambda = Double.valueOf(lambdaTextField.getText());
p = Double.valueOf(pTextField.getText());
} catch (NumberFormatException ex) {
new MessageFrame("Invalid values");
return;
}
if (p < 0 || p > 100) {
new MessageFrame("Invalid values");
return;
}
Image image = panel.getImage();
panel.setImage(NoiseUtils.exponentialNoise(image, lambda, p*0.01));
panel.repaint();
dispose();
}
});
paramPanel.add(lambdaLabel);
paramPanel.add(lambdaTextField);
paramPanel.add(pLabel);
paramPanel.add(pTextField);
this.add(paramPanel);
this.add(okButton);
} | 3 |
public static int lenghtUnitStringToIndex(String unit) {
switch (unit) {
case "m":
return 0;
case "ft":
return 1;
case "mm":
return 2;
case "cm":
return 3;
case "km":
return 4;
case "mi":
return 5;
case "in":
return 6;
default:
return 0;
}
} | 7 |
public void click(Point point, Object source) {
if (ca.getMode() == EditorMode.NODE) {
Point p = new Point(point);
p.x += getX();
p.y += getY();
if (pathContainer_.contains(p) || path_.contains(p)) {
father_.deselectAll();
requestFocus();
selected_ = true;
repaint();
return;
} else {
if (source == this || source == null) {
father_.clickEvent(p, this);
}
if (isSelected()) {
setSelected(false);
repaint();
}
}
}
} | 6 |
@Override
public String toString() {
//return "TDS{" + "listeBloc=" + listeBloc + ", num_bloc=" + num_bloc + ", num_imbrication=" + num_imbrication + ", actuelle=" + region_actuelle + '}';
String str="";
Region r;
Entree e;
Symbole s;
for(Entry ent : listeBloc.entrySet()){
r=(Region) ent.getKey();
str+="Region "+r.getBloc()+" "+r.getProfondeur()+"\n";
for(Entry entry : listeBloc.get(r).entrySet()){
e = (Entree) entry.getKey();
s = (Symbole) entry.getValue();
str+="\t"+e.getNom()+"->"+s.toString()+"\n";
}
str+="\n";
}
return str;
} | 2 |
@Override
public void unInvoke()
{
// undo the affects of this spell
if(!(affected instanceof MOB))
return;
final MOB mob=(MOB)affected;
super.unInvoke();
if(canBeUninvoked())
if((mob.location()!=null)&&(!mob.amDead()))
{
final Room R=mob.location();
if((R.domainType()==Room.DOMAIN_INDOORS_CAVE)||(R.domainType()==Room.DOMAIN_INDOORS_STONE))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> <S-IS-ARE> drawn out of the walls."));
else
if((R.domainType()==Room.DOMAIN_OUTDOORS_MOUNTAINS)||(R.domainType()==Room.DOMAIN_OUTDOORS_ROCKS))
mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> <S-IS-ARE> drawn out of the rocks."));
else
mob.tell(L("Your stone walk has ended."));
}
} | 8 |
private boolean isWithinAccLimit(String ipaddress) {
int limit = plugin.getConfig().getInt("registration.account-limit");
if (limit < 1 || xPermissions.has(player.getPlayer(), "xauth.bypass.acclimit"))
return true;
int count = 0;
Connection conn = plugin.getDbCtrl().getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
String sql = String.format("SELECT COUNT(`id`) FROM `%s` WHERE `registerip` = ?",
plugin.getDbCtrl().getTable(Table.ACCOUNT));
ps = conn.prepareStatement(sql);
ps.setString(1, ipaddress);
rs = ps.executeQuery();
if (rs.next())
count = rs.getInt(1);
} catch (SQLException e) {
xAuthLog.severe("Could not check account count for ip: " + ipaddress, e);
} finally {
plugin.getDbCtrl().close(conn, ps, rs);
}
return limit > count;
} | 4 |
public boolean equals(Object x) {
if(!(x instanceof Entry))
return(false);
T[] a = arr.get();
if(a == null)
return(false);
Entry<?> e = (Entry<?>)x;
Object[] ea = e.arr.get();
if(ea == null)
return(false);
if(ea.length != a.length)
return(false);
for(int i = 0; i < a.length; i++) {
if(a[i] != ea[i])
return(false);
}
return(true);
} | 8 |
public Gui()
{
setBackground(new Color(0,50,100));
addMouseMotionListener(this);
addMouseListener(this);
addKeyListener(this);
for(int eks=0; eks<list.length; eks++)
if(eks%2==0) //if it's 0 or 2
x[eks] = (w/3)+(w/18);
else if(eks==1)
x[eks] = 2*(w/3)+(w/18);
else //if (eks==3)
x[eks] = (w/18);
for(int why=0; why<list.length; why++)
if(why%2!=0) //if it's 1 or 3
y[why] = (w/3)+(w/18);
else if(why==0)
y[why] = (w/18);
else //if (why==2)
y[why] = 2*(w/3)+(w/18);
list[0] = new Ball(x[0], y[0], ((2*w)/9)/2, new Color(0, 100, 150), "My Games", null, 0);
list[1] = new Ball(x[1], y[1], ((2*w)/9)/2, new Color(0, 100, 150), "My Applications", null, 1);
list[2] = new Ball(x[2], y[2], ((2*w)/9)/2, new Color(0, 100, 150), "My Computer", null, 2);
list[3] = new Ball(x[3], y[3], ((2*w)/9)/2, new Color(0, 100, 150), "My Documents", null, 3);
back = new Ball(w/3+w/9, w/3+w/9, w/9/2, "Back");
list[0].setSmallNum(4);
list[1].setSmallNum(3);
list[2].setSmallNum(4);
list[3].setSmallNum(4);
for(int big=0; big<4; big++) //add small balls, set small small num to 0
{
list[0].addBall(games[big]);
list[0].getSmallBall(big).setSmallNum(0);
list[2].addBall(comp[big]);
list[2].getSmallBall(big).setSmallNum(0);
list[3].addBall(docs[big]);
list[3].getSmallBall(big).setSmallNum(0);
}
list[1].addPainter("Paint");
list[1].getSmallBall(0).setSmallNum(0);
list[1].addCal("Calculator");
list[1].getSmallBall(1).setSmallNum(0);
list[1].addSpread("Spreadsheet");
list[1].getSmallBall(2).setSmallNum(0);
for(int big=0; big<4; big++) //set small small num of comp to 4
list[2].getSmallBall(big).setSmallNum(4);
for(int small2=0; small2<4; small2++) //add small small balls, set small small small num to 0
{
list[2].getSmallBall(0).addBall(hd[small2]);
list[2].getSmallBall(0).getSmallBall(small2).setSmallNum(0);
list[2].getSmallBall(1).addBall(floppy[small2]);
list[2].getSmallBall(1).getSmallBall(small2).setSmallNum(0);
list[2].getSmallBall(2).addBall(cd[small2]);
list[2].getSmallBall(2).getSmallBall(small2).setSmallNum(0);
list[2].getSmallBall(3).addBall(network[small2]);
list[2].getSmallBall(3).getSmallBall(small2).setSmallNum(0);
}
stack.push(list);
t = new Timer(0, this);
t.start();
} | 9 |
public void output() {
ListElement current = head;
while (current != tail.next()) {
System.out.print(current.getValue() + " ");
current = current.next();
}
System.out.println();
} | 1 |
public List<vassalInfo> getPlayerVassals(String playerName) {
List<vassalInfo> vassals = new ArrayList<vassalInfo>();
String SQL = "SELECT *" + " FROM " + tblAllegiance + " WHERE `patron` LIKE ?" + " ORDER BY XP DESC;";
try {
Connection con = getSQLConnection();
PreparedStatement statement = con.prepareStatement(SQL);
statement.setString(1, playerName);
ResultSet result = statement.executeQuery();
while (result.next()) {
// patron = result.getString(1);
vassals.add(new vassalInfo(result.getString(2), result.getInt(4)));
}
result.close();
statement.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vassals;
} | 2 |
public SpriteSheet(String relativePath) {
URL u = this.getClass().getResource(relativePath);
try {
spriteSheet = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
} | 1 |
@Override
public Component getListCellRendererComponent(JList<? extends TripComponent> list,
TripComponent value, int index, boolean isSelected, boolean cellHasFocus) {
riverNameLabel.setText("Gr " + (index+1) + ": " + value.getRiverName());
wwTopLevelLabel.setText ("\u02AC" + value.getWwTopLevel());
tripFromToLabel.setText (" " + value.getFromToString());
if (isSelected)
setTextColor (Color.BLUE);
else {
setTextColor (Color.BLACK);
}
rosterNamesLabel.setForeground(value.getRosterColor());
rosterNamesLabel.setText(value.getRosterNames());
if (isSelected) {
setBackground(list.getSelectionBackground());
centerPanel.setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
centerPanel.setBackground(list.getBackground());
setForeground(list.getForeground());
}
topPanel.setBackground(River.getRiverColor(Integer.decode(value.getWwTopLevel())));
return this;
} | 3 |
public boolean isCeilingTouched(BlockMap bmap)
{
for(int i = 0; i < bmap.entities.size(); i++)
{
Block tile = (Block)bmap.entities.get(i);
if(ceilingPoly.intersects(tile.poly))
{
return true;
}
}
return false;
} | 2 |
private void calcRotation(double timeMod) {
if (turningRight && turningLeft) {
//Do nothing
} else if (turningRight) {
faceAngle += turnSpeed*timeMod;
} else if (turningLeft) {
faceAngle -= turnSpeed*timeMod;
}
//Make sure faceAngle stays between 0 and 360 degrees
if(faceAngle>360) faceAngle -= 360;
if(faceAngle<0) faceAngle += 360;
} | 6 |
public static void main(String[] args) throws Exception {
int swValue = 0;
System.out.println("============================================================================");
System.out.println("| MENU SELECTION DEMO |");
System.out.println("============================================================================");
System.out.println("| Options: |");
System.out.println("| 1. Create JarClassLoader only once and load new functionality |");
System.out.println("| 2. Create new JarClassLoader every time and load new functionality|");
System.out.println("| 3. Exit |");
System.out.println("============================================================================");
ClassLoader loader = new JarClassLoader();
while (swValue != 3) {
swValue = Keyin.inInt(" Select option: ");
switch (swValue) {
case 1:
Class clazz = Class.forName("com.epam.sample.JarSampleImpl", true, loader);
JarSample object = (JarSample) clazz.newInstance();
LOG.info(object);
JarSampleWrapper jarSampleWrapper = new JarSampleWrapper(object);
jarSampleWrapper.plus();
//output classpath
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
for (int i = 0; i < classpathEntries.length; i++) {
LOG.info("CLASSPATH include: " + classpathEntries[i]);
}
LOG.info("New functionality was loaded by" + object.getClass().getClassLoader());
break;
case 2:
ClassLoader loader1 = new JarClassLoader();
Class clazz1 = Class.forName("com.epam.sample.JarSampleImpl", true, loader1);
JarSample object1 = (JarSample) clazz1.newInstance();
LOG.info(object1);
JarSampleWrapper jarSampleWrapper1 = new JarSampleWrapper(object1);
jarSampleWrapper1.plus();
//output classpath
String classpath1 = System.getProperty("java.class.path");
String[] classpathEntries1 = classpath1.split(File.pathSeparator);
for (int i = 0; i < classpathEntries1.length; i++) {
LOG.info("CLASSPATH include: " + classpathEntries1[i]);
}
LOG.info("New functionality was loaded by" + object1.getClass().getClassLoader());
break;
case 3:
System.out.println("Exit selected");
break;
default:
System.out.println("Invalid selection");
break;
}
}
} | 6 |
private synchronized void dequeue(PacketScheduler sched)
{
Packet np = sched.deque();
// process ping() packet
if (np instanceof InfoPacket) {
((InfoPacket) np).addExitTime( GridSim.clock() );
}
if (super.reportWriter_ != null) {
super.write("dequeuing, " + np);
}
// must distinguish between normal and junk packet
int tag = GridSimTags.PKT_FORWARD;
if (np.getTag() == GridSimTags.JUNK_PKT) {
tag = GridSimTags.JUNK_PKT;
}
// sends the packet via the link
String linkName = getLinkName( np.getDestID() );
super.sim_schedule(GridSim.getEntityId(linkName),
GridSimTags.SCHEDULE_NOW, tag, np);
// process the next packet in the scheduler
if ( !sched.isEmpty() )
{
double nextTime = (np.getSize() * NetIO.BITS) / sched.getBaudRate();
sendInternalEvent(nextTime, sched);
}
} | 4 |
public RandomBitFilter(final ConnectionProcessor proc, final Properties props) {
super(proc, props);
requireConfigKey(probability_key);
probability = Float.parseFloat(props.getProperty(probability_key));
for (int i = 0 ; i < table.length ; ++i) {
for (int j = 24 ; j < 32 ; ++j) {
table[i][j-24] = flip_bit_at(i, j);
}
}
} | 2 |
public CmdRemoveExecutor(SimpleQueues plugin) {
this.plugin = plugin;
} | 0 |
public static boolean canMove(Tile[][] board, Tile tile) {
boolean canMove = false;
switch (tile.getSpecialPosition()) {
case TOP_LEFT:
canMove = checkNeighborsFromTopLeft(board, tile);
break;
case TOP_RIGHT:
canMove = checkNeighborsFromTopRight(board, tile);
break;
case BOTTOM_LEFT:
canMove = checkNeighborsFromBottomLeft(board, tile);
break;
case BOTTOM_RIGHT:
canMove = checkNeighborsFromBottomRight(board, tile);
break;
case TOP:
canMove = checkNeighborsFromTop(board, tile);
break;
case BOTTOM:
canMove = checkNeighborsFromBottom(board, tile);
break;
case LEFT:
canMove = checkNeighborsFromLeft(board, tile);
break;
case RIGHT:
canMove = checkNeighborsFromRight(board, tile);
break;
case NONE:
canMove = checkNeighborsFromNone(board, tile);
break;
}
return canMove;
} | 9 |
@Test
public void getNumberOfDaysBillIsOlderThanPaul() throws Exception {
Assert.assertEquals(addressBook.getDaysOlder("Bill McKnight", "Paul Robinson"), 2862);
} | 0 |
@Override
public void dragExit(DropTargetEvent event) {
TreePanel panel = getPanel();
if (panel.getColumns().equals(mOriginal)) {
panel.repaintColumn(mColumn);
} else {
panel.restoreColumns(mOriginal);
}
} | 1 |
@Override
public void mouseDragged(MouseEvent event) {
JFrame frame = Game.get().display.getFrame();
float zoomX = (frame.getWidth()-frame.getInsets().left-frame.getInsets().right)/800f;
float zoomY = (frame.getHeight()-frame.getInsets().top-frame.getInsets().bottom)/800f;
int mouseX = (int) (event.getX()/zoomX);
int mouseY = (int) (event.getY()/zoomY);
if(mouseX == Game.get().mouseX && mouseY == Game.get().mouseY){
return;
}
if(mouseX <800 && mouseX>=0 && mouseY <800 && mouseY>=0){
Game.get().latestMouseX = Game.get().mouseX;
Game.get().latestMouseY = Game.get().mouseY;
Game.get().mouseX = mouseX;
Game.get().mouseY = mouseY;
}else{
Game.get().latestMouseX = -1;
Game.get().mouseX = -1;
Game.get().mouseY = -1;
}
} | 6 |
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource() == exit)
{
controller.mainWindowClosing();
System.exit(0);
}
if(arg0.getSource() == static_Open || arg0.getSource() == addSong)
{
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3 Audio Files", "mp3");
chooser.setFileFilter(filter);
chooser.grabFocus();
int returnVal = chooser.showOpenDialog(menu);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
String chosenFile = chooser.getSelectedFile().getAbsolutePath();
if(arg0.getSource() == static_Open)player.play(chosenFile);
else
table.addToList(chosenFile);
}
}
else if(arg0.getSource() == static_Delete)
{
//table.deleteRows(table.getTableObj().getSelectedRows());
//table.deleteRows(new int[] {-1});
table.deleteRows();
}
else if (arg0.getSource() == addPlayList)
{
plPanel.addPlayList(null); /* arg is null, addPlayList will ask user for name */
}
else if(arg0.getSource() == controls)
{
shuffle.setSelected(player.shuffle.isSelected());
repeat.setSelected(player.repeat.isSelected());
recent.removeAll();
ArrayList<String> songs = controller.getSongHistory();
for(int i = 0; i < songs.size(); i++)
{
final JMenuItem jm = new JMenuItem(songs.get(i));
jm.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0)
{
//System.out.println(jm.getText());
player.play(jm.getText());
}
});
recent.add(jm);
}
}
} | 9 |
public int getCharge()
{
if(isIon())
{
int pos = 0;
for(int i = 0; i < ions.length; i++)
{
if(this.equals(new MiniCompound(ions[i])))
{
pos = i;
break;
}
}
return ionCharges[pos];
// System.err.println("getCharge - this is an ion, but there isn't a corresponding charge");
}
int overAllCharge = 0;
for(int i = 0; i < elements.length; i++)
overAllCharge += elements[i].getCharge();
return overAllCharge;
} | 4 |
int readCorner3(int numRows, int numColumns) {
int currentByte = 0;
if (readModule(numRows - 1, 0, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(numRows - 1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 3, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(0, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 3, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 2, numRows, numColumns)) {
currentByte |= 1;
}
currentByte <<= 1;
if (readModule(1, numColumns - 1, numRows, numColumns)) {
currentByte |= 1;
}
return currentByte;
} | 8 |
protected void Fetch(String DBloc) throws IOException, JSONException
{
String found = "";
JSONObject obj;
if(Key == null && Qualifier == null)
{
File file = new File(DBloc+"/"+Table+"/"+ColumnFamily+"/");
read(file);
}
else if(Key == null)
{
FileInputStream fistream = new FileInputStream(DBloc+"/"+Table+"/"+ColumnFamily+"/"+Qualifier+"/");
DataInputStream in = new DataInputStream(fistream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
found = found + strLine+"\n";
}
Result = found;
in.close();
}
else{
FileInputStream fistream = new FileInputStream(DBloc+"/"+Table+"/"+ColumnFamily+"/"+Qualifier+"/");
DataInputStream in = new DataInputStream(fistream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
obj = new JSONObject(strLine);
if(obj.get(Key) != null)
{
found = found+obj.get(Key)+"\n";
}
}
Result = found;
in.close();
}
} | 6 |
public Grid createGrid(){
Grid grid = null;
if(fileCanCreateGrid()){
grid = new Grid(this.vehicleMap, this.gridSize, new ArrayList<Grid>());
grid.previousGrids.add(grid);
}
return grid;
} | 1 |
private boolean isWhitespace(int c) {
return Character.isWhitespace((char) c) && (c != strategy.getDelimiter());
} | 1 |
private void readConfigFile(String filename) {
// Chargement du fichier
Properties prop = new Properties();
try {
prop.load(new FileReader(filename));
} catch (Exception e) {
e.printStackTrace();
}
// Traitement des données chargées
String[] pluginsToLoad = prop.getProperty("loadAtStart").split("\\s*,\\s*");
String[] pathsToUse = prop.getProperty("binPaths").split("\\s*,\\s*");
String[] pathsToHome = prop.getProperty("homePath").split("\\s*,\\s*");
URL[] urls = new URL[pathsToUse.length];
int i = 0;
for(String s: pathsToHome) {
if(!s.startsWith("/")) {
if(new File(System.getProperty("user.home")+"/"+s).exists()) {
rightPathToHome = System.getProperty("user.home")+"/"+s;
}
} else {
if(new File(s).exists()) {
rightPathToHome = s;
}
}
}
for(String s: pathsToUse) {
try {
urls[i] = (new File(rightPathToHome+s)).toURI().toURL();
System.out.println(urls[i].toExternalForm());
i++;
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
pluginClassLoader = new URLClassLoader(urls);
System.out.println("================Scan================");
scanPlugins(urls);
System.out.println("====================================");
System.out.println(availablePlugins);
System.out.println("====================================");
if(pluginsToLoad.length > 0) {
for(String s : pluginsToLoad) {
//List<String> argsArray = Arrays.asList(prop.getProperty(s).split("\\s*,\\s*"));
loadPlugin(s,prop.getProperty(s));
}
}
} | 9 |
public static void main(String[] args) throws Exception {
TesterMainGUIMode testerMainGUI = new TesterMainGUIMode();
testerMainGUI.showChartFrame();
} | 0 |
public static void main(String[] args) {
printWelcome();
// Attempting authentication with server
try {
sock = new ServerConnection().getNewConnection();
new LoginHandler().handleIt(sock, currentUser);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Type \'h\' for a list of commands");
// This loop is infinite, until the user enters a valid command,
// which is then dispatched to the controller.
while (true) {
if(sock.isClosed()) {
sock = new ServerConnection().getNewConnection();
}
if(!currentUser.isLoggedIn()) {
new LoginHandler().handleIt(sock, currentUser);
}
Scanner inputReader = new Scanner(System.in);
showPrompt();
String userInput = inputReader.next();
if (isValidCommand(userInput)) {
try {
controller.execute(userInput, sock, currentUser);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Illogical Command. Please try again.");
}
}
} | 6 |
public int getInt() throws InvalidBEncodingException {
return this.getNumber().intValue();
} | 0 |
public CheckResultMessage checkF(int day) {
BigDecimal f = new BigDecimal(0);
int row = get(10, 2);
int clums = get(11, 2);
int total = get(13, 2);
if (version.equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
for (int i = row; i < total; i++) {
f = f.add(getValue(row, clums + day, 2));
}
if (0 != (f.compareTo(getValue(total, clums + day, 2)))) {
return error("支付机构单个账户报表<" + fileName + ">增加银行余额的特殊业务合计 F:"
+ day + "日错误");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
for (int i = row; i < total; i++) {
f = f.add(getValue(row, clums, 2));
}
if (0 != (f.compareTo(getValue(total, clums + day, 2)))) {
return error("支付机构单个账户报表<" + fileName + ">增加银行余额的特殊业务合计 F:"
+ day + "日错误");
}
in.close();
} catch (Exception e) {
}
}
return pass("支付机构单个账户报表<" + fileName + ">增加银行余额的特殊业务合计 F:" + day
+ "日正确");
} | 7 |
private String keyTranslate(String pkgType){
String key = null;
if(pkgType.equals("download")){
key = "Hash";
}else if(pkgType.equals("upload")){
key = "URL";
}else if(pkgType.equals("uploadType")){
key = "Upload Type";
}else if(pkgType.equals("downloadType")){
key = "Download Type";
}else{
key = "error";
}
return key;
} | 4 |
private void match1PlusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_match1PlusActionPerformed
if (!heureChoice.getSelectedItem().equals("Tous") && !courtChoice.getSelectedItem().equals("Tous")) {
try {
int terrain = courtChoice.getSelectedIndex();
int heure = Integer.valueOf(heureChoice.getSelectedItem().substring(0,
heureChoice.getSelectedItem().indexOf("h")));
MatchDao mdao = DaoFactory.getMatchDao();
Match m = mdao.selectMatchByTerrainByDateByHour(jour, terrain, heure);
fenMoreInfo.setVisible(true);
afficherFenMoreInfo(m);
} catch (IOException | SQLException ex) {
Logger.getLogger(MenuPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if (heureChoice.getSelectedItem().equals("Tous")) {
try {
int terrain = courtChoice.getSelectedIndex();
int heure = 8;
MatchDao mdao = DaoFactory.getMatchDao();
Match m = mdao.selectMatchByTerrainByDateByHour(jour, terrain, heure);
fenMoreInfo.setVisible(true);
afficherFenMoreInfo(m);
} catch (IOException | SQLException ex) {
Logger.getLogger(MenuPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}
else {
try {
int terrain = 1;
int heure = Integer.valueOf(heureChoice.getSelectedItem().substring(0,
heureChoice.getSelectedItem().indexOf("h")));
MatchDao mdao = DaoFactory.getMatchDao();
Match m = mdao.selectMatchByTerrainByDateByHour(jour, terrain, heure);
fenMoreInfo.setVisible(true);
afficherFenMoreInfo(m);
} catch (IOException | SQLException ex) {
Logger.getLogger(MenuPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//GEN-LAST:event_match1PlusActionPerformed | 6 |
public IHeuristic getHeuristic() {
IHeuristic ret = null;
switch (HeuristicType) {
case '1':
ret = new Heuristic1();
break;
case '2':
ret = new Heuristic2();
break;
case '3':
ret = new Heuristic3();
break;
case 'c':
ret = new Classifier();
break;
case 'n':
ret = new NeuralNet();
break;
}
return ret;
} | 5 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.