text stringlengths 14 410k | label int32 0 9 |
|---|---|
public static void main(String[] args) throws IOException, ParseException {
EvidenceRecordFileIterator iterator = new EvidenceRecordFileIterator(new File(args[0]));
Read context = new Read();
SAMFileHeader header = new SAMFileHeader();
header.setSortOrder(SAMFileHeader.SortOrder.unsorted);
SAMSequenceRecord samSequenceRecord = new SAMSequenceRecord("chr10", 135534747);
samSequenceRecord.setAttribute(SAMSequenceRecord.ASSEMBLY_TAG, iterator.assembly_ID);
String readGroup = String.format("%s-%s", iterator.assembly_ID, iterator.chromosome);
SAMReadGroupRecord readGroupRecord = new SAMReadGroupRecord(readGroup);
readGroupRecord.setAttribute(SAMReadGroupRecord.READ_GROUP_SAMPLE_TAG, iterator.sample);
readGroupRecord.setAttribute(SAMReadGroupRecord.PLATFORM_UNIT_TAG, readGroup);
readGroupRecord.setAttribute(SAMReadGroupRecord.SEQUENCING_CENTER_TAG, "\"Complete Genomics\"");
Date date = new SimpleDateFormat("yyyy-MMM-dd hh:mm:ss.S").parse(iterator.generatedAt);
readGroupRecord.setAttribute(SAMReadGroupRecord.DATE_RUN_PRODUCED_TAG,
new SimpleDateFormat("yyyy-MM-dd").format(date));
readGroupRecord.setAttribute(SAMReadGroupRecord.PLATFORM_TAG, "\"Complete Genomics\"");
header.addReadGroup(readGroupRecord);
header.addSequence(samSequenceRecord);
SAMFileWriterFactory f = new SAMFileWriterFactory();
SAMFileWriter samWriter;
if (args.length > 1)
samWriter = f.makeBAMWriter(header, false, new File(args[1]));
else
samWriter = f.makeSAMWriter(header, false, System.out);
int i = 0;
long time = System.currentTimeMillis();
DedupIterator dedupIt = new DedupIterator(iterator);
while (dedupIt.hasNext()) {
EvidenceRecord evidenceRecord = dedupIt.next();
if (evidenceRecord == null)
throw new RuntimeException();
try {
context.reset(evidenceRecord);
context.parse();
} catch (Exception e) {
System.err.println("Failed on line:");
System.err.println(evidenceRecord.line);
throw new RuntimeException(e);
}
SAMRecord[] samRecords = context.toSAMRecord(header);
for (SAMRecord samRecord : samRecords) {
samRecord.setAttribute(SAMTag.RG.name(), readGroup);
samWriter.addAlignment(samRecord);
}
i++;
if (i % 1000 == 0) {
if (System.currentTimeMillis() - time > 10 * 1000) {
time = System.currentTimeMillis();
System.err.println(i);
}
}
if (i > 10000)
break;
}
samWriter.close();
} | 8 |
float getInterpolatedVoxelValue(Point3f pt) {
int iMax;
int xDown = indexDown(pt.x, iMax = voxelCounts[0] - 1);
int xUp = xDown + (pt.x < 0 || xDown == iMax ? 0 : 1);
int yDown = indexDown(pt.y, iMax = voxelCounts[1] - 1);
int yUp = yDown + (pt.y < 0 || yDown == iMax ? 0 : 1);
int zDown = indexDown(pt.z, iMax = voxelCounts[2] - 1);
int zUp = zDown + (pt.z < 0 || zDown == iMax || jvxlDataIs2dContour ? 0 : 1);
float v1 = getFractional2DValue(pt.x - xDown, pt.y - yDown, voxelData[xDown][yDown][zDown],
voxelData[xUp][yDown][zDown], voxelData[xDown][yUp][zDown], voxelData[xUp][yUp][zDown]);
float v2 = getFractional2DValue(pt.x - xDown, pt.y - yDown, voxelData[xDown][yDown][zUp],
voxelData[xUp][yDown][zUp], voxelData[xDown][yUp][zUp], voxelData[xUp][yUp][zUp]);
return v1 + (pt.z - zDown) * (v2 - v1);
} | 7 |
public static String readDomainName(DataInputStream dis, byte firstCount) throws Exception {
StringBuffer strBuf = new StringBuffer();
while (true) {
// read character count
byte count = 0;
if (firstCount != 0) {
count = firstCount;
firstCount = 0;
} else
count = dis.readByte();
if (count == 0)
break;
if (strBuf.length() > 0)
strBuf.append('.');
while (count-- > 0) {
byte c = dis.readByte();
strBuf.append((char)c);
}
}
return strBuf.toString();
} | 5 |
@Override
public T validate(String fieldName, T value) throws ValidationException {
if (value == null) {
return null;
}
if (min.compareTo(value) > 0) {
return min;
}
return value;
} | 2 |
@Override
public boolean execute(WorldChannels plugin, CommandSender sender,
Command command, String label, String[] args) {
final Map<Flag, String> info = new EnumMap<Flag, String>(Flag.class);
info.put(Flag.TAG, WorldChannels.TAG);
if(!(sender instanceof Player)) {
sender.sendMessage(Localizer.parseString(LocalString.NO_CONSOLE,
info));
} else {
try {
final Channel channel = parseChannel(sender, args[0],
plugin.getModuleForClass(ConfigHandler.class));
if(channel != null) {
if(sender.hasPermission(channel.getPermissionJoin())) {
channel.addListener(sender.getName());
plugin.getModuleForClass(ChannelManager.class).setCurrentChannel(sender.getName(), channel.getWorld() + channel.getName());
sender.sendMessage(ChatColor.GREEN + WorldChannels.TAG
+ " Joined channel '" + channel.getName() + "'");
} else {
info.put(Flag.EXTRA, channel.getPermissionJoin());
sender.sendMessage(Localizer.parseString(
LocalString.PERMISSION_DENY, info));
}
} else {
info.put(Flag.EXTRA, args[0]);
info.put(Flag.REASON, "channel");
sender.sendMessage(Localizer.parseString(
LocalString.UNKNOWN, info));
}
} catch(ArrayIndexOutOfBoundsException e) {
info.put(Flag.EXTRA, "channel");
sender.sendMessage(Localizer.parseString(
LocalString.MISSING_PARAM, info));
}
}
return true;
} | 4 |
@Override
public String getVersion() {
return "*";
} | 0 |
@Override
public void run()
{
for(int i=0 ; i<pCapacity;i++)
{
if(i<list.getSize()){
list.addItems(rand.nextInt(45));
try {
Thread.sleep(rand.nextInt(30));
} catch (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{Thread.yield();}
}
} | 3 |
public boolean endTurn() {
timer--;
return timer == 0;
} | 0 |
public void render()
{
Image buffer = createImage(500, 600);
Graphics b = buffer.getGraphics();
super.paint(b);
b.drawImage(null, 0, 0, 500, 550, this);
// any other drawing goes here
getGraphics().drawImage(buffer, 0, 0, 500, 600, this);
} | 0 |
private boolean isHexDigit(int value){
return (value>='0' && value<='9'
|| value>='a' && value<='f'
|| value>='A' && value<='F');
} | 5 |
public Queue<String> getUnsearchList(){
return this.staticList;
} | 0 |
public CheckResultMessage check26(int day) {
return checkReport.check26(day);
} | 0 |
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(btnNewButton)){
MetodiDiSupporto.nuovoThread(new Runnable() {
public void run() {
disposeFrame();
GiocoOffline gO = new GiocoOffline(LauncherFrame.this);
gO.inizia();
}
});
}
if(e.getSource().equals(btnNewButton_1)){
int numeroGiocatori = 0;
boolean done = false;
boolean launch = false;
do{
String risposta = JOptionPane.showInputDialog("Inserisci il numero di giocatori!");
if(risposta!=null){
try{
numeroGiocatori = Integer.parseInt(risposta);
if(numeroGiocatori>=2&&numeroGiocatori<=6){
done = true;
launch = true;
} else {
JOptionPane.showMessageDialog(null, "Inserisci un intero da 2 a 6!");
}
} catch (NumberFormatException ex){
JOptionPane.showMessageDialog(null, "Inserisci un intero da 2 a 6!");
}
} else {
done = true;
}
} while(!done );
if(launch){
MetodiDiSupporto.nuovoThread(new Runnable() {
private int numeroGiocatori;
public void run() {
disposeFrame();
server = new ServerMain();
server.addListener(LauncherFrame.this);
server.start(new String[]{Integer.toString(numeroGiocatori)});
}
public Runnable initialize(int numeroGiocatori) {
this.numeroGiocatori = numeroGiocatori;
return this;
}
}.initialize(numeroGiocatori));
}
}
if(e.getSource().equals(btnNewButton_2)){
MetodiDiSupporto.nuovoThread(new Runnable() {
public void run() {
disposeFrame();
ControlloreGrafica cG = new ControlloreGrafica();
cG.addListener(LauncherFrame.this);
cG.show();
}
});
}
} | 9 |
private void updateTable(){
// FileTable tablemodel = new FileTable();
// myfiletable = new JTable(tablemodel);
files = new ArrayList<File>();
dirs = new ArrayList<File>();
int rowCount=tablemodel.getRowCount();
for (int i = rowCount - 1;i >= 0;i--) {
tablemodel.removeRow(i);
}
File folder = new File(currentpath);
File[] filelist = folder.listFiles();
if (!filelist.equals(null)){
for (File currentfile : filelist){
if(currentfile.isFile())
files.add(currentfile);
else if(currentfile.isDirectory())
dirs.add(currentfile);
}
if(!currentpath.equals(rootpath))
tablemodel.addRow(new Object[]{"..","","","yes"});
for(int i = 0;i<dirs.size();i++){
tablemodel.addRow(new Object[]{dirs.get(i).getName(),"",new SimpleDateFormat().format(new Date(dirs.get(i).lastModified())),"yes"});
}
for(int i = 0;i<files.size();i++){
tablemodel.addRow(new Object[]{files.get(i).getName(),files.get(i).length() + " bytes",new SimpleDateFormat().format(new Date(files.get(i).lastModified())),"yes"});
}
pathlabel.setText("path:" + currentpath);
}
else{
if(!currentpath.equals(rootpath))
tablemodel.addRow(new Object[]{"..","","","yes"});
}
} | 9 |
public Properties getAttributesInNamespace(String namespace) {
Properties result = new Properties();
Iterator enm = this.attributes.iterator();
while (enm.hasNext()) {
XMLAttribute attr = (XMLAttribute) enm.next();
if (namespace == null) {
if (attr.getNamespace() == null) {
result.put(attr.getName(), attr.getValue());
}
} else {
if (namespace.equals(attr.getNamespace())) {
result.put(attr.getName(), attr.getValue());
}
}
}
return result;
} | 4 |
private Map<Date, Double> addCreditCardCommission(Map<Date, Double> fees, String options) {
if (options == null || options.length() == 0) {
return fees;
}
boolean found = false;
String[] optionArray = options.split(";");
for (int i = 0; i < optionArray.length; i++) {
if ("CCARD".equalsIgnoreCase(optionArray[i])) {
found = true;
}
}
if (found && fees.size() >= 1) {
for (Date date : fees.keySet()) {
Double amount = fees.get(date);
final Properties prop = loadProperties();
double creditCardCommission = Double.parseDouble(prop.getProperty("creditcardcommission"));
fees.put(date, amount + creditCardCommission);
}
} else {
return fees;
}
return fees;
} | 7 |
public ElementInfo getElementInfo(Element element){
ElementInfo elementInfo=(ElementInfo)Factory.getFactory().getDataObject(Factory.ObjectTypes.ElementInfo);
elementInfo.setElement(element);
String type=XmlUtil.stripNameSpaceIf(element.getTagName());
SchemaTypes types=null;
if("element".equalsIgnoreCase(type)){
types=SchemaTypes.Element;
}else if("complextype".equalsIgnoreCase(type)){
types=SchemaTypes.ComplexType;
}else if("simpletype".equalsIgnoreCase(type)){
types=SchemaTypes.SimpleType;
}else if("enumeration".equalsIgnoreCase(type)){
types=SchemaTypes.Enumeration;
}else if("attribute".equalsIgnoreCase(type)){
types=SchemaTypes.Attribute;
}else if("service".equalsIgnoreCase(type)){
types=SchemaTypes.Service;
}else if("operation".equalsIgnoreCase(type)){
types=SchemaTypes.Operation;
}
elementInfo.setType(types);
elementInfo.setCompletePath(getPathOfElement(elementInfo));
return elementInfo;
} | 7 |
protected Object[] initializeRow(int row) {
Object[] newRow = new Object[getColumnCount()];
Arrays.fill(newRow, null);
return newRow;
} | 0 |
public House(){
for (int y=0;y<100;y++)
{
for (int x=0;x<100;x++)
tileLayout[x][y] = new Tile('.',1,1,x,y); // create each actual tile
}
} | 2 |
public JCalkPanel()
{
setLayout(null);
final JTextField txt = new JTextField("0");
add(txt);
txt.setBounds(20, 20, 400, 22);
String [] str = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0"};
JPanel butPan1 = new JPanel();
butPan1.setLayout(new GridLayout(4, 3));
for (int i = 1; i <= 10; i++)
{
JButton btn = new JButton (str [i-1]);
butPan1.add(btn);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (txt.getText().equals("0") || newNumber) {
txt.setText(((JButton) e.getSource()).getText());
} else {
txt.setText(txt.getText() + ((JButton) e.getSource()).getText());
}
fValue += Integer.parseInt(txt.getText());
newNumber = false;
}
});
}
butPan1.setBounds(10, 80, 200, 300);
add(butPan1);
butPan1.setBackground(Color.lightGray);
String [] str1 = {"-", "+", "*", "/", "="};
JPanel butPan2 = new JPanel();
butPan2.setLayout(new GridLayout(5, 1));
for (int j = 1; j <= 5; j++)
{
JButton btn = new JButton (str1 [j-1]);
butPan2.add(btn);
btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//проверить был ли задан какой либо operation ранее
//и если он был вычилить результат и записать на экран
switch (operation) {
case "+":
result += Integer.parseInt(txt.getText());
break;
case "-":
result -= Integer.parseInt(txt.getText());
break;
case "*":
result *= Integer.parseInt(txt.getText());
break;
case "/":
result /= Integer.parseInt(txt.getText());
break;
default:
result = Integer.parseInt(txt.getText());
}
//выводим результат
txt.setText(result + "");
newNumber = true;
//если было нажато равно очистить
if ("=".equals(operation)) {
result = 0;
operation = "";
} else {
operation = ((JButton) e.getSource()).getText();
}
/**
int sValue = 0;
String operation2 = null;
operation = (String) e.getSource();
if (operation.equals("-") || operation.equals("*") || operation.equals("+") || operation.equals("/"))
{
sValue += Integer.parseInt(txt.getText());
operation2 = operation;
}
else if (operation.equals("="))
{
if (operation2.equals("-") || newNumber)
{
result = fValue - sValue;
txt.setText("" + result);
}
else if (operation2.equals("+") || newNumber)
{
result = fValue + sValue;
txt.setText("" + result);
}
else if (operation2.equals("*") || newNumber)
{
result = fValue * sValue;
txt.setText("" + result);
}
else if (operation2.equals("/") || newNumber)
{
result = fValue / sValue;
txt.setText("" + result);
}
}
//в случае если операция есть считать если равно считать и вывести на экран
//так задаем данные и преобразуем в инт
//проверить был ли задан какой либо operation ранее
//и если он был вычилить результат и записать на экран
//выводим результат
newNumber = true;
//если было нажато равно очистить
operation = ((JButton) e.getSource()).getText();
**/
}
});
}
butPan2.setBounds(250, 80, 200, 300);
add(butPan2);
butPan2.setBackground(Color.CYAN);
setVisible(true);
} | 9 |
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(Stimulated_timetable_database_simulate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Stimulated_timetable_database_simulate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Stimulated_timetable_database_simulate.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Stimulated_timetable_database_simulate.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() {
try {
new Stimulated_timetable_database_simulate().setVisible(true);
} catch (InterruptedException ex) {
Logger.getLogger(Stimulated_timetable_database_simulate.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
} | 7 |
public int getEntityType(String ename)
{
Object entity[] = (Object[]) entityInfo.get(ename);
if (entity == null) {
return ENTITY_UNDECLARED;
} else {
return ((Integer) entity[0]).intValue();
}
} | 1 |
private static int getNthValue(Integer[] a, int startIndex, int endIndex, int n) {
int pivotValueIndex = startIndex + (endIndex - startIndex) / 2;
int resultPivotValueIndex = setInOrderPosition(a, pivotValueIndex, startIndex, endIndex);
if (resultPivotValueIndex + 1 == n) {
return a[resultPivotValueIndex];
}
if (resultPivotValueIndex + 1 > n) {
return getNthValue(a, startIndex, resultPivotValueIndex - 1, n);
} else {
return getNthValue(a, resultPivotValueIndex + 1, endIndex, n);
}
} | 2 |
public String toSentence() {
List<Long> aStartTime = new ArrayList<Long>();
List<Long> aEndTime = new ArrayList<Long>();
boolean currAvailability = false;
for (int i = 0; i < nSlot; i++)
{
if (this.aIsAvailable[i] == currAvailability)
continue;
currAvailability = this.aIsAvailable[i];
if (currAvailability)
{
aStartTime.add(this.getSlot(i));
} else
{
aEndTime.add(this.getSlot(i));
}
}
if (currAvailability)
{
aEndTime.add(this.getSlot(nSlot));
}
StringBuilder sb = new StringBuilder("");
for (int i = 0; i < aStartTime.size(); i++)
{
Date startD = new Date(aStartTime.get(i));
Date endD = new Date(aEndTime.get(i));
sb.append("[").append(dateFormat.format(startD)).append(" - ").append(
dateFormat.format(endD)).append("] \n");
}
return sb.toString();
} | 5 |
public void applyMutation(Individual offspring)
{
int rand = 8;
if(offspring.problemInstance.periodCount==1)rand--;
int selectedMutationOperator = Utility.randomIntInclusive(rand);
if(selectedMutationOperator==0)
{
//greedy //intra
IntraRouteGreedyInsertion.mutate(offspring);
}
else if (selectedMutationOperator == 1)
{
//random //intra
IntraRouteRandomInsertion.mutate(offspring);
}
else if (selectedMutationOperator == 2)
{
//random+greedy //inter
OneZeroExchange.mutate(offspring);
// offspring.mutateRouteWithInsertion();
}
else if (selectedMutationOperator == 3)
{
//greedy //inter
GreedyVehicleReAssignment.mutate(offspring);
}
else if (selectedMutationOperator == 4)
{
//intra
Two_Opt.mutateRandomRoute(offspring);
}
else if (selectedMutationOperator == 5)
{
//random+greedy //inter
OneOneExchange.mutate(offspring);
}
else if (selectedMutationOperator == 6)
{
//greedy //inra
Or_Opt.mutateRandomRoute(offspring);
}
else if (selectedMutationOperator == 7)
{
//greedy //inra
Three_Opt.mutateRandomRoute(offspring);
}
else
{
//random //inter
MutatePeriodAssignment.mutatePeriodAssignment(offspring);
}
offspring.calculateCostAndPenalty();
} | 9 |
@Override
public void actionPerformed(ActionEvent event) {
Openable openable = getTarget(Openable.class);
if (openable != null) {
openable.openSelection();
}
} | 1 |
private String prependTimestamp(String str) {
if ( str.isEmpty() ) {
return str;
} else {
Calendar c = Calendar.getInstance();
String timestamp = timestampFormat;
timestamp = timestamp.replaceFirst("h", getTwoDigits( c.get(Calendar.HOUR_OF_DAY) ) );
timestamp = timestamp.replaceFirst("m", getTwoDigits( c.get(Calendar.MINUTE) ) );
timestamp = timestamp.replaceFirst("s", getTwoDigits( c.get(Calendar.SECOND) ) );
return HTML.small(timestamp) + " " + str;
}
} | 1 |
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
RequestDispatcher rd = null;
try {
producten.haalBestellingOp(Integer.parseInt(req.getParameter("pId")), Integer.parseInt(req.getParameter("inBestelling")), Integer.parseInt(req.getParameter("voorraad")));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(Integer.parseInt(req.getParameter("type")) == 2){
rd = req.getRequestDispatcher("onderdelen_bestellen.jsp");
}else{
rd = req.getRequestDispatcher("brandstof_bestellen.jsp");
}
rd.forward(req, resp);
} | 2 |
public JSONObject main(Map<String,String> params, Session session) throws Exception {
return CommonResponses.showNotImplemented();
}; | 0 |
public String basename() {
int p = name.lastIndexOf('/');
if (p < 0)
return (name);
return (name.substring(p + 1));
} | 1 |
public void searchLinkAndAddToSet(String str) {
String tmp;
str = str.replace(" ", "");
int start = str.indexOf("<a");
if(start >= 0){
start = str.indexOf("href=\"");
if(start >= 0){
str = str.substring(start+6, str.length());
start = str.indexOf("\"");
tmp = str;
if(start >= 0){
str = str.substring(0, start);
start = str.indexOf("http");
if(start < 0){
str = protocol + "://" + host + str;
}
links.add(str);
}
searchLinkAndAddToSet(tmp);
}
}
} | 4 |
public DroneController(final VisualRenderer visual) {
try {
drone = new ARDrone();
drone.connect();
drone.addImageListener(new BufferedImageVideoListener() {
@Override
public void imageReceived(BufferedImage image) {
RescaleOp rescaleOp = new RescaleOp(1.4f, 50, null);
rescaleOp.filter(image, image);
quadImage = image;
}
});
drone.addNavDataListener(new NavDataListener() {
@Override
public void navDataReceived(NavData fdata) {
data = fdata;
}
});
Thread t = new Thread() {
@Override
public void run() {
while (true) {
long millis = System.currentTimeMillis();
LocationData speed = null;
LocationData angle = null;
if (visual.global_main.flightMode != null)
if (visual.global_main.flightMode.getMode() == FlightMode.eMode.MUHA_MODE)
speed = calc.getFlowData(quadImage);
else if (visual.global_main.flightMode.getMode() == FlightMode.eMode.TAG_MODE) {
angle = MarkerTracker.getMarkerData(quadImage);
MarkerCalculator.calculateAndControl(angle,
visual.global_main);
}
visual.reloadDatas(quadImage, speed, data, angle);
millis = System.currentTimeMillis() - millis;
try {
if (millis < 70)
Thread.sleep(70 - millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | 8 |
public void init() {
this.setTitle("Config Model");
this.setResizable(true);
this.setVisible(true);
this.setSize(ecran.getWidth() / 2, ecran.getHeight() / 2);
this.setLayout(new GridLayout());
this.setLocation(ecran.getFrame().getX() + ecran.getWidth() / 2 - this.getWidth() / 2, ecran.getFrame().getY() + ecran.getHeight() / 2 - this.getHeight() / 2);
this.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == e.VK_DELETE) {
for (int i = 0; i < jList_hashtag.getSelectedValues().length; i++) {
GestionBDD.deleteTag((String) jList_hashtag.getSelectedValues()[i]);
}
refreshJlistHashtag();
}
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
jList_hashtag.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
requestFocus();
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
jList_model.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
requestFocus();
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
jList_modelavechashtag.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
requestFocus();
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
ajouthashtag = new JTextField();
scrollBarreW = new JScrollPane(jList_hashtag);
scrollBarreEN = new JScrollPane(jList_model);
scrollBarreES = new JScrollPane(jList_modelavechashtag);
scrollBarreW.setBorder(BorderFactory.createTitledBorder("hashtag"));
scrollBarreEN.setBorder(BorderFactory.createTitledBorder("modele"));
scrollBarreES.setBorder(BorderFactory.createTitledBorder("modele avec hashtag "));
JPanel jp1 = new JPanel();
JPanel jp3 = new JPanel();
jp1.setLayout(new BorderLayout());
jp3.setLayout(new GridLayout(2, 1, 20, 20));
jp1.add(ajouthashtag, BorderLayout.NORTH);
jp1.add(scrollBarreW, BorderLayout.CENTER);
this.add(jp1);
this.add(scrollBarreEN);
this.add(jp3);
this.add(scrollBarreES);
ajout = new JButton(new ImageIcon(Parametre.workspace + "/flecheD.png"));
retire = new JButton(new ImageIcon(Parametre.workspace + "/flecheG.png"));
ajout.setFocusable(false);
ajout.setBorderPainted(false);
ajout.setContentAreaFilled(false);
ajout.setFocusPainted(false);
ajout.setOpaque(false);
retire.setFocusable(false);
retire.setBorderPainted(false);
retire.setContentAreaFilled(false);
retire.setFocusPainted(false);
retire.setOpaque(false);
jp3.add(ajout);
jp3.add(retire);
retire.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < jList_hashtag.getSelectedValues().length; i++) {
for (int j = 0; j < jList_modelavechashtag.getSelectedValues().length; j++) {
GestionBDD.removeConnection((String) jList_modelavechashtag.getSelectedValues()[j], (String) jList_hashtag.getSelectedValues()[i]);
}
}
refreshJListModel();
}
});
ajout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < jList_hashtag.getSelectedValues().length; i++) {
for (int j = 0; j < jList_model.getSelectedValues().length; j++) {
System.out.println("" + (String) jList_hashtag.getSelectedValues()[i] + "," + (String) jList_model.getSelectedValues()[j]);
GestionBDD.addConnection((String) jList_model.getSelectedValues()[j], (String) jList_hashtag.getSelectedValues()[i]);
}
}
refreshJListModel();
}
});
ajouthashtag.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == e.VK_ENTER) {
if (!ajouthashtag.getText().equals("")) {
GestionBDD.insertTag(ajouthashtag.getText());
}
refreshJlistHashtag();
}
}
@Override
public void keyPressed(KeyEvent e) {
}
});
jList_hashtag.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent ex) {
refreshJListModel();
}
});
this.refreshJlistHashtag();
this.refreshJListModel();
} | 8 |
public String toSql()
{
return sql
+ (whereClause != null ? " WHERE " + whereClause.toSql() : "")
+ (orderClause != null ? " ORDER BY " + orderClause.toSql() : "")
+ (limit != null ? limit.toSql() : "");
} | 3 |
private void newQuestion() {
if(ques == Const.QUES_PER_ROUND || lvs == 0) {
if(rnd == Const.NUM_ROUNDS || lvs == 0) {
final_points.setText(Integer.toString(points));
if(total_ques == Const.NUM_ROUNDS * Const.QUES_PER_ROUND && lvs > 0)
complete.setVisible(true);
CardLayout cl = (CardLayout)windows.getLayout();
cl.show(windows, Const.QUIT);
} else {
if(perfect_round) {
lives.setText(Integer.toString(++lvs));
new_life.setVisible(true);
} else {
new_life.setVisible(false);
}
mode = Const.Mode.ROUND;
ques = 0; perfect_round = true;
round_num.setText(Integer.toString(++rnd));
round_play.setText(Integer.toString(rnd));
CardLayout cl = (CardLayout)windows.getLayout();
cl.show(windows, Const.ROUND);
}
} else {
mode = Const.Mode.QUES;
if(ques == 0) {
CardLayout cl = (CardLayout)windows.getLayout();
cl.show(windows, Const.GAME);
}
q = p.randomQuestion(rnd);
if(q.isDom())
ques2.setText(Const.QUES2_DOM);
else
ques2.setText(Const.QUES2_PDOM);
node.setText(q.getNode().getLabel());
p.redraw();
next.setEnabled(false);
submit.setEnabled(true);
console.append("\n");
}
} | 9 |
public void activate(Robot paramRobot, int paramInt) {
Vector[][] arrayOfVector = getEnvironment().getObjectMap();
boolean bool = true;
int i = this.location.x; for (int j = 0; j < this.shape.length; j++)
{
int k = this.location.y; for (int m = 0; m < this.shape[0].length; m++)
{
if (this.shape[j][m] == this)
{
if (arrayOfVector[i][k] != null)
{
Enumeration localEnumeration = arrayOfVector[i][k].elements();
while (localEnumeration.hasMoreElements())
{
if (!(localEnumeration.nextElement() instanceof Robot))
continue;
bool = false;
}
}
}
k++;
}
i++;
}
setVisible(bool);
} | 6 |
public String getUrl() {
return this.getReferRequestWrapper().getUrl();
} | 0 |
private boolean verifierDeplacementSinge(final int tmpX, final int tmpY)
{
boolean dplInterdit = false;
if (this.monkeyIsland.valeurCarte(tmpX, tmpY) == Integer.valueOf(0)) {
dplInterdit = true;
} else {
// Verifier pas de singe
int n = 0;
final List<SingeErratique> erratiques = this.monkeyIsland.getSingesErratiques().getSingesErratiques();
while (n < erratiques.size() && !dplInterdit) {
dplInterdit = erratiques.get(n).coordonneesEgales(tmpX, tmpY);
n++;
}
// Verifier pirate present => si oui a tuer
if (tmpX == this.monkeyIsland.getPirate().getX() && tmpY == this.monkeyIsland.getPirate().getY()) {
this.monkeyIsland.getPirate().setMort(true);
if (this.monkeyIsland.getPirate().getPirateEcouteurs() != null) {
for (final PirateEcouteur pirateEcouteur : this.monkeyIsland.getPirate().getPirateEcouteurs()
.getListeners(PirateEcouteur.class)) {
pirateEcouteur.mortPirate(0);
}
}
}
}
return dplInterdit;
} | 7 |
public Iterator<Ticket> getAvaliableTickets() {
List<Ticket> avaliableTickets = new ArrayList<Ticket>();
for (Ticket ticket : tickets) {
if (ticket.getStatus() == TicketStatus.ENABLE) {
avaliableTickets.add(ticket);
}
}
return avaliableTickets.iterator();
} | 2 |
public static void main(String[] args) {
URLMonitor mon = new URLMonitor();
mon.addRemaining("http://cs.lth.se/eda095");
ArrayList<Processor> processors = new ArrayList<Processor>();
for (int i = 0; i < 10; i++) {
Processor p = new Processor(mon, "http://cs.lth.se/eda095");
processors.add(p);
p.start();
}
for (Processor p : processors) {
try {
p.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Queue<String> links = mon.getTraversed();
for (String s : links) {
System.out.println(s);
}
} | 4 |
public List<FoodDataBean> getBoardCommentaryList(int idx) throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<FoodDataBean> commList = null;
String sql = "";
FoodDataBean comm = null;
try{
conn = getConnection();
sql = "select * from foodcommentary where idx=? order by num desc";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, idx);
rs = pstmt.executeQuery();
if(rs.next()){
commList = new ArrayList<FoodDataBean>();
do{
comm = new FoodDataBean();
comm.setComm_content(rs.getString("content"));
comm.setComm_nickname(rs.getString("nickname"));
comm.setComm_wdate(rs.getTimestamp("wdate"));
commList.add(comm);
}
while(rs.next());
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs!=null)try{rs.close();}catch(SQLException ex){}
if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){}
if(conn!=null)try{conn.close();}catch(SQLException ex){}
}
return commList;
} | 9 |
private void addAnswersTable() {
tablePanel = new JPanel();
tableModel = new DefaultTableModel(new String[] { "Treść odpowiedzi", "Poprawna" }, 0){
Class[] types = {
String.class, Boolean.class
};
// making sure that it returns boolean.class.
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
};;
tablePanel.setLayout(new BorderLayout());
table = new JTable(tableModel);
header = table.getTableHeader();
table.getColumn("Poprawna").setMinWidth(80);
table.getColumn("Poprawna").setMaxWidth(80);
// Moze bedzie kolumna JButtonow
table.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
JTable target = (JTable) e.getSource();
rowNum = target.getSelectedRow();
colNum = target.getSelectedColumn();
}
}
});
tableScrollPane = new JScrollPane(tablePanel);
tableScrollPane.setBounds(23, 286, 518, 203);
add(tableScrollPane);
tablePanel.add(header, BorderLayout.NORTH);
tablePanel.add(table, BorderLayout.CENTER);
splitPane = new JPanel();
tablePanel.add(splitPane, BorderLayout.SOUTH);
btnUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveUp();
}
});
add(btnUp);
btnUp.setBounds(200, 500, 89, 23);
btnDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveDown();
}
});
btnDown.setBounds(100, 500, 89, 23);
add(btnDown);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String tempAnswer = "";
createDialog(tempAnswer);
}
});
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (tableModel.getRowCount() != 0 && rowNum >= 0) {
tableModel.removeRow(rowNum);
}
}
});
btnAdd.setBounds(551, 309, 89, 23);
btnDelete.setBounds(551, 350, 89, 23);
add(btnAdd);
add(btnDelete);
} | 3 |
public static void main(String[] args) {
StopWatch stopWatch1 = new StopWatch();
final int LENGTH_OF_LIST = 100000;
int[] list = new int[LENGTH_OF_LIST];
stopWatch1.start();
for (int i = 0; i < LENGTH_OF_LIST; i++) {
list[i] = (int) (Math.random() * list.length);
}
for (int i = 0; i < LENGTH_OF_LIST; i++) {
int currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < LENGTH_OF_LIST; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
stopWatch1.stop();
System.out
.println("The execution time of sorting 10000 numbers using selection sort is "
+ stopWatch1.getElapsedTime());
} | 5 |
public String getCurrentPuzzle() {
String currentPuzzle = "";
for(int i = 0; i < 16; i++) {
for(int j = 0; j < 16; j++) {
if(entries[i][j].isEditable()) {
currentPuzzle = currentPuzzle + "E ";
} else {
currentPuzzle = currentPuzzle + "N ";
}
if(entries[i][j].getText().equals("")) {
currentPuzzle = currentPuzzle + "0 ";
} else {
currentPuzzle = currentPuzzle + entries[i][j].getText() + " ";
}
}
}
System.out.println("Current Puzzle is" + currentPuzzle);
return currentPuzzle;
} | 4 |
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
Result otherResult = (Result) obj;
boolean statsEqual;
if (status == null) {
if (otherResult.getStatus() == null) {
statsEqual = true;
} else {
statsEqual = false;
}
} else {
statsEqual = status.equals(otherResult.getStatus());
}
return decision == otherResult.getDecision() && Strings.safeEquals(resourceId, otherResult.getResourceId())
&& obligations.equals(otherResult.getObligations()) && statsEqual;
} | 8 |
public boolean move() {
game_area.updateDirection();
Point next_field = getHead().add(direction);
/* Wenn sich neuer Punkt im Spielfeld befindet,
* fuege den Punkt der Schlange hinzu und ueberpruefe
* anschliessend, ob Schlange zu lang ist. Wenn ja, loesche
* letzten Punkt */
if (isPossible(next_field)) {
if (bytes.containsByte(next_field)) {
int byte_type = bytes.getType(next_field);
if (byte_type == Config.BYTE_BLUE) {
count_sm += Config.DURATION_SPECIAL_MODE;
special_mode = true;
} else if (byte_type == Config.BYTE_RED) {
if (isSpecialMode()) {
changeLength(5);
} else {
changeLength(-5);
accelerate();
}
} else {
changeLength(1);
}
if (length < 1)
return false;
bytes.removeByte(next_field);
body.add(next_field);
bytes.addByte();
} else {
body.add(next_field);
}
if (count_sm > 0)
count_sm--;
else
special_mode = false;
while (body.size() > length)
body.remove(0);
return true;
} else {
/* Game Over */
return false;
}
} | 8 |
public static void loadVideoInfo() {
checkUSB();
System.out.println("start to load videos' info from usb");
String rootPath = USBConfig.drivePath;
String videonewFolder = rootPath + USBConfig.VIDEO_NEW_FOLDER + "\\";
System.out.println(videonewFolder);
File videoFilesPath = new File(videonewFolder);
if (!videoFilesPath.exists()) {
videoFilesPath.mkdirs();
}
File[] videos = videoFilesPath.listFiles();
Video v = null;
for (File f : videos) {
System.out.println(f.getName());
if (USBConfig.EXTS.contains(StringUtils.getSuffixWithoutDot(f
.getName()))) {
String name = f.getName();
String ext = name.substring(name.lastIndexOf("."),
name.length());
String path = f.getAbsolutePath();
String size = String.valueOf((f.length() / 1024 / 1024));
String updateDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date(f.lastModified()));
v = new Video(name, ext, path, size, updateDate);
VideoDao.instance().addVideo(v);
}
}
} | 3 |
private void drawCenter(int[] circle, int r){ //TODO: change
int d = getD();
for (int i = -3; i < 4; i++ ){
circle[((r+i)*d) + r] = GUIStandarts.drawColor;
circle[(r*d) + r + i] = GUIStandarts.drawColor;
}
} | 1 |
void setActive(String name){
Sheet a=null;
for(Sheet s:sheets){
if(s.getName().equals(name)){
a=s;
break;
}
}
if(a==null) return ;
switch(viewType){
case VIEWTYPE_TABS:{
JTabbedPane tabs=(JTabbedPane)container;
tabs.setSelectedComponent(a);
}break;
case VIEWTYPE_MDI:{
JDesktopPane mdi=(JDesktopPane)container;
((JInternalFrame)a.getParent()).restoreSubcomponentFocus();
}break;
}
} | 5 |
private void dropTable(String tableName) throws SQLException {
if (conn != null)
{
PreparedStatement stmt = conn.prepareStatement(String.format("DROP TABLE IF EXISTS %s", tableName));
stmt.execute();
}
} | 1 |
@Override
public File getFile() {
return super.getFile();
} | 0 |
public SmallCardsViewer(DeckCreator parent) {
super(JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.parent = parent;
swingWorker = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
JScrollBar b = SmallCardsViewer.this.getHorizontalScrollBar();
while (!isCancelled()) {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {}
Point p;
if ((p = SmallCardsViewer.this.getMousePosition()) != null) {
int x = p.x;
int w = SmallCardsViewer.this.getSize().width;
int i = 0;
if (x < w / 12) {
i = -5;
} else if (x < w / 6 ) {
i = -4;
} else if (x < w / 3) {
i = -3;
} else if (x > 11 * w / 6) {
i = 5;
} else if (x > 5 * w / 6) {
i = 4;
} else if (x > 2 * w / 3) {
i = 3;
}
b.setValue(b.getValue() + Card.W * i / 15);
}
}
return null;
}
};
cards = new ArrayList<>();
panel = new JPanel(new GridLayout(1, 0));
panel.setPreferredSize(new Dimension(0, Card.H));
this.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
this.setViewportView(panel);
swingWorker.execute();
} | 9 |
public static StandardObject extractParameterType(StandardObject self, Symbol parameter, Object [] MV_returnarray) {
{ Surrogate testValue000 = Stella_Object.safePrimaryType(self);
if (Surrogate.subtypeOfSurrogateP(testValue000)) {
{ Surrogate self000 = ((Surrogate)(self));
{ Slot slot = Stella_Class.lookupSlot(((Stella_Class)(self000.surrogateValue)), parameter);
if (slot != null) {
{ StandardObject _return_temp = slot.type();
MV_returnarray[0] = BooleanWrapper.wrapBoolean(true);
return (_return_temp);
}
}
else {
{ StandardObject _return_temp = Stella.SGT_STELLA_OBJECT;
MV_returnarray[0] = BooleanWrapper.wrapBoolean(false);
return (_return_temp);
}
}
}
}
}
else if (Surrogate.subtypeOfParametricTypeSpecifierP(testValue000)) {
{ ParametricTypeSpecifier self000 = ((ParametricTypeSpecifier)(self));
{ Symbol pname = null;
Cons iter000 = ((Stella_Class)(self000.specifierBaseType.surrogateValue)).parameters().theConsList;
StandardObject ptype = null;
Cons iter001 = self000.specifierParameterTypes.theConsList;
for (;(!(iter000 == Stella.NIL)) &&
(!(iter001 == Stella.NIL)); iter000 = iter000.rest, iter001 = iter001.rest) {
pname = ((Symbol)(iter000.value));
ptype = ((StandardObject)(iter001.value));
if (pname == parameter) {
{ StandardObject _return_temp = ptype;
MV_returnarray[0] = BooleanWrapper.wrapBoolean(true);
return (_return_temp);
}
}
}
}
{ StandardObject _return_temp = Stella.SGT_STELLA_OBJECT;
MV_returnarray[0] = BooleanWrapper.wrapBoolean(false);
return (_return_temp);
}
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("extract-parameter-type: Not defined on `" + self + "'");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
}
} | 6 |
public CtField lookupField(String className, Symbol fieldName)
throws CompileError
{
CtClass cc = lookupClass(className, false);
try {
return cc.getField(fieldName.get());
}
catch (NotFoundException e) {}
throw new CompileError("no such field: " + fieldName.get());
} | 1 |
@Override
public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) {
if(!(sender instanceof Player)) {
return true;
}
Player player = (Player) sender;
if(!(args.length == 1)) {
return true;
}
if(!(Util.hasLocations(player))) {
return true;
}
for(Region r : Regions.getRegionManager().getRegions())
{
if(r.getName().equalsIgnoreCase(args[0]))
{
player.sendMessage("Region with this name already exists.");
return true;
}
}
Region region = new Region(args[0], Util.loc1.get(player), Util.loc2.get(player), player);
Regions.getRegionManager().createRegion(region);
player.sendMessage("You have created a new region called '" + args[0] + "'");
return true;
} | 5 |
private void mergeTwoRegions(DenseRegion r1, DenseRegion r2){
Cluster c = null;
int clusterID =0;
if(!r1.getIsInCluster() && !r2.getIsInCluster()){
c = new Cluster(this.clustersCount);
c.addDenseRegion(r1);
c.addDenseRegion(r2);
r1.setClusterID(c.getID());
r2.setClusterID(c.getID());
this.clusters.add(c);
this.clustersCount++;
}
else if(r1.getIsInCluster() && r2.getIsInCluster()){
mergeCluster(this.clusters.get(r1.getClusterID()), this.clusters.get(r2.getClusterID()));
}
else if(r1.getIsInCluster()){
clusterID= r1.getClusterID();
c = this.clusters.get(clusterID);
r2.setClusterID(clusterID);
c.addDenseRegion(r2);
}
else if (r2.getIsInCluster()){
clusterID = r2.getClusterID();
c = this.clusters.get(clusterID);
r1.setClusterID(clusterID);
c.addDenseRegion(r1);
}
} | 6 |
@Override
public void show() {
System.out.println(name + ", here are your search results:");
Auction[] auctionResults = as.search(input);
for(Auction auc : auctionResults){
try{
System.out.println(auc.toString());
}
catch(Exception e){
System.out.println("No results match");
}
}
System.out.println("Enter the item id to increase the bid by $1. Otherwise, enter another search: (hit enter to go back to home page)");
} | 2 |
public int uniquePaths(int m, int n) {
if (m==0||n==0){
return 0;
}
int posible[][] = new int[m][n];
posible[0][0] = 1;
for (int i = 1;i<m;i++){
posible[i][0] = 1;
}
for (int i = 1;i<n;i++){
posible[0][i] = 1;
}
for (int i = 1;i<m;i++){
for (int j=1;j<n;j++){
posible[i][j] = posible[i-1][j] + posible[i][j-1];
}
}
return posible[m-1][n-1];
} | 6 |
private static void sortBlock(File[] files, int start, int end, File[] mergeTemp) {
final int length = end - start + 1;
if (length < 8) {
for (int i = end; i > start; --i) {
for (int j = end; j > start; --j) {
if (compareFiles(files[j - 1], files[j]) > 0) {
final File temp = files[j];
files[j] = files[j-1];
files[j-1] = temp;
}
}
}
return;
}
final int mid = (start + end) / 2;
sortBlock(files, start, mid, mergeTemp);
sortBlock(files, mid + 1, end, mergeTemp);
int x = start;
int y = mid + 1;
for (int i = 0; i < length; ++i) {
if ((x > mid) || ((y <= end) && compareFiles(files[x], files[y]) > 0)) {
mergeTemp[i] = files[y++];
} else {
mergeTemp[i] = files[x++];
}
}
for (int i = 0; i < length; ++i) files[i + start] = mergeTemp[i];
} | 9 |
public JPanel getUserlistLayoutMenu() {
if (!this.init_1) {
IllegalStateException e = new IllegalStateException("Call init first!");
throw e;
}
return this.userlistLayoutMenu;
} | 1 |
public MatchTuple match(Tree<String> a, Tree<String> b) {
if (!a.getRoot().getLabel().equalsIgnoreCase(b.getRoot().getLabel())) {
return new MatchTuple(0, a.size(), b.size());
} else {
int m = a.getRoot().getChildrenSize();
int n = b.getRoot().getChildrenSize();
// start initialize match matrix
Matrix<Integer> matchMatrix = new Matrix<Integer>(m + 1, n + 1);
for (int i = 0; i <= m; i++) {
matchMatrix.setElement(i, 0, 0);
}
for (int j = 0; j <= n; j++) {
matchMatrix.setElement(0, j, 0);
}
// end initialization match matrix
// start W matrix
Matrix<MatchTuple> wMatrix = new Matrix<MatchTuple>(m, n);
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
wMatrix.setElement(
i,
j,
match(new Tree<String>(a.getRoot()
.getChildAt(i - 1)), new Tree<String>(b
.getRoot().getChildAt(j - 1))));
}
}
DetectListTuple detectListTuple = detectLists(wMatrix, a, b);
wMatrix = detectListTuple.matchTuple();
//compute scores
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
matchMatrix.setElement(i, j, Math.max(Math.max(
matchMatrix.getElement(i, j - 1),
matchMatrix.getElement(i - 1, j)),
matchMatrix.getElement(i - 1, j - 1) + wMatrix.getElement(i, j).score()));
}
}
return new MatchTuple(matchMatrix.getElement(m, n)+1, detectListTuple.nodesA(), detectListTuple.nodesB());
}
} | 7 |
public int countRightDiagonal(Example e, int currentToken, int numTokensCountingFor){
int height = e.getBoard().height; // 6
int width = e.getBoard().width; // 7
int countOfTokensEncounteredDiagonallyRight = 0; // counter
int countOfCurrentPlayersNInARow = 0;
// bottom index is (5, 0)
for (int i = height - 1; i > -1; i--) {
for (int j = 0; j < width; j++) {
if (e.getBoard().boardArray[i][j] == currentToken) { // current
// player's
// tokens
for (int k = i, l = j; k > -1; k--, l++) {
if(l == width){ // check to make sure not out of bounds
break;
}
else if (e.getBoard().boardArray[i][j] == e.getBoard().boardArray[k][l]) {
countOfTokensEncounteredDiagonallyRight++;
} else { // since the continuity between tokens is
// broken, stop
break;
}
}
}
if(countOfTokensEncounteredDiagonallyRight >= numTokensCountingFor){
countOfCurrentPlayersNInARow++;
countOfTokensEncounteredDiagonallyRight = 0;
}
}
}
return countOfCurrentPlayersNInARow;
} | 7 |
private Set<String> keywordsFromUrlString(String urlChunk) {
Set<String> keywords = new HashSet<>();
if (urlChunk.length() < MIN_KEYWORD_LENGTH) {
return keywords; // enforce a minimum keyword length.
}
if (dictionary.isStringInDictionary(urlChunk)) {
keywords.add(urlChunk); // recursive base case of sorts.
return keywords;
}
for (int i = 1; i < urlChunk.length(); i++) {
String substringA = urlChunk.substring(0, i);
String substringB = urlChunk.substring(i, urlChunk.length());
if (dictionary.isStringInDictionary(substringA)) {
if (substringA.length() >= MIN_KEYWORD_LENGTH) {
keywords.add(substringA);
}
keywords.addAll(keywordsFromUrlString(substringB));
} else if (dictionary.isStringInDictionary(substringB)) {
if (substringB.length() >= MIN_KEYWORD_LENGTH) {
keywords.add(substringB);
}
keywords.addAll(keywordsFromUrlString(substringA));
}
}
return keywords;
} | 7 |
public Company getCompany() {
return Cmp;
} | 0 |
@SuppressWarnings("unchecked")
private List<IResource> fetchResources(HtmlPage page) throws MalformedURLException {
List<IResource> resources = new ArrayList<>();
for (HtmlScript script : (List<HtmlScript>) page.getByXPath("/html/head/script")) {
String src = script.getSrcAttribute();
addResource(src, resources);
}
for (HtmlLink link : (List<HtmlLink>) page.getByXPath("/html/head/link")) {
addResource(link.getHrefAttribute(), resources);
}
for (HtmlImage image : (List<HtmlImage>) page.getByXPath("//img")) {
addResource(image.getSrcAttribute(), resources);
}
return resources;
} | 3 |
@Override
public boolean partieTerminee()
{
//On teste chaque ligne possible pour les deux joueurs
for(int i = 1; i <= getPlateau().getLongueur() - getValeurVictoire() + 1; i++)
{
for(int j = 1; j <= getPlateau().getLongueur(); j++)
{
if(getPlateau().CheckColonneId(new Position(i, j), getValeurVictoire(), 1))
return true;
if(getPlateau().CheckColonneId(new Position(i, j), getValeurVictoire(), 2))
return true;
}
}
//On teste chaque colonne possible pour les deux joueurs
for(int i = 1; i <= getPlateau().getLargeur(); i++)
{
for(int j = 1; j <= getPlateau().getLargeur() - getValeurVictoire() + 1; j++)
{
if(getPlateau().CheckLigneId(new Position(i, j), getValeurVictoire(), 1))
return true;
if(getPlateau().CheckLigneId(new Position(i, j), getValeurVictoire(), 2))
return true;
}
}
//On retourne faux si personne ne gagne
return false;
} | 8 |
public static Map<String,String> getDataGroupSubjectMap(String url,String minDateStr,String maxDateStr) throws ParseException{
Map<String,String> map = new IdentityHashMap<String,String>();
List<String> DataGroupList = new ArrayList<String>();
List<String> SubjectList = new ArrayList<String>();
List<String> removeList = new ArrayList<String>();
try {
System.out.println("[INFO]Calling URL ["+url+"] to build up the 'DataGroup'<=>'Subject' map");
BaseReader reader = ReaderFactory.create(SourceSwitcher.NotificationSystem);
Document docObj = reader.getXMLDocument(url);
DataGroupList = ReaderFactory.responseHandle(docObj,"DataGroup");
SubjectList = ReaderFactory.responseHandle(docObj, "Subject");
for(String subjectStr:SubjectList){
Date minDate = dateFormatter1.parse(minDateStr);
Date maxDate = dateFormatter1.parse(maxDateStr);
String[] ele = subjectStr.split("=");
Date actrualDate = dateFormatter2.parse(ele[1]);
if(actrualDate.before(minDate) || actrualDate.after(maxDate)){
removeList.add(subjectStr);
}
}
//Remove all datas which beyond of date range
if(!removeList.isEmpty()){
SubjectList.removeAll(removeList);
}
if(!SubjectList.isEmpty() && !DataGroupList.isEmpty()){
int count=0;
for(String refferenceIdDateStr:SubjectList){
map.put(DataGroupList.get(count), refferenceIdDateStr);
count++;
}
}
} catch (ReaderConfigException | LoginException | XMLReadException e) {
e.printStackTrace();
}
return map;
} | 8 |
private void scrollSelectionIntoViewInternal() {
Selection selection = mModel.getSelection();
int first = selection.nextSelectedIndex(getFirstRowToDisplay());
int max = getLastRowToDisplay();
if (first != -1 && first <= max) {
Rectangle bounds = getRowIndexBounds(first);
int tmp = first;
int last;
do {
last = tmp;
tmp = selection.nextSelectedIndex(last + 1);
} while (tmp != -1 && tmp <= max);
if (first != last) {
bounds = Geometry.union(bounds, getRowIndexBounds(last));
}
scrollRectToVisible(bounds);
}
} | 5 |
public String consultarTurnos(boolean sentenciaCompleta) {
conexion.conectar();
String respuesta = "exito";
String modificadorConsulta = "";
String modificadorConsulta2 = "";
if (sentenciaCompleta) {
modificadorConsulta = "and descripcion='' and t.estado = false ";
} else {
modificadorConsulta2 = " and t.fecha_inicio > 'yesterday'::timestamp with time zone";
}
turnos = new LinkedList<Turno>();
String sql = "select u.first_name, u.last_name, t.fecha_inicio,t.duracion,"
+ "t.descripcion, t.id, t.tipo, u.id from users as u inner join turno as t "
+ "on u.id = t.estudiante "
+ modificadorConsulta + " and t.tipo=1 " + modificadorConsulta2 + " order by t.fecha_inicio";
try {
conexion.consultar(sql);
while (conexion.getRes().next()) {
String realizadoPor = conexion.getRes().getString(1) + " " + conexion.getRes().getString(2);
String fechaI = conexion.getRes().getString(3);
int duracion = 0;
try {
duracion = Integer.parseInt(conexion.getRes().getString(4));
} catch (SQLException | NumberFormatException e) {
}
String descripcion = conexion.getRes().getString(5);
int id = Integer.parseInt(conexion.getRes().getString(6));
int idTurno = Integer.parseInt(conexion.getRes().getString(7));
int idEstudiante = Integer.parseInt(conexion.getRes().getString(8));
Turno turno = new Turno(id, idEstudiante, idTurno, fechaI);
turno.setRealizadoPor(realizadoPor);
turno.setDuración(duracion);
turno.setDescripcion(descripcion);
if (duracion != 0) {
Timestamp fe = Timestamp.valueOf(fechaI);
Calendar ca = Calendar.getInstance();
ca.setTime(fe);
ca.add(Calendar.MINUTE, duracion);
fe = new Timestamp(ca.getTimeInMillis());
String fechaFinal = fe.toString();
turno.setFechaFinal(fechaFinal);
}
turnos.add(turno);
}
} catch (SQLException e) {
respuesta = e.getMessage();
}
conexion.cerrarConexion();
return respuesta;
} | 5 |
public boolean checkChunksExist(int var1, int var2, int var3, int var4, int var5, int var6) {
if (var5 >= 0 && var2 < 128) {
var1 >>= 4;
var2 >>= 4;
var3 >>= 4;
var4 >>= 4;
var5 >>= 4;
var6 >>= 4;
for (int var7 = var1; var7 <= var4; ++var7) {
for (int var8 = var3; var8 <= var6; ++var8) {
if (!this.chunkExists(var7, var8)) {
return false;
}
}
}
return true;
} else {
return false;
}
} | 5 |
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
String cmd = command.getName().toLowerCase();
if (cmd.equalsIgnoreCase("roomy"))
return RoomyCommands.roomyCmd(sender, args);
else if (cmd.equalsIgnoreCase("setroom"))
return RoomyCommands.setroomCmd(sender, args);
else if(cmd.equalsIgnoreCase("loadrooms"))
return RoomyCommands.loadroomsCmd(sender, args);
else if(cmd.equalsIgnoreCase("saverooms"))
return RoomyCommands.saveroomsCmd(sender, args);
else if(cmd.equalsIgnoreCase("track"))
return RoomyCommands.trackCmd(sender, args);
else if(cmd.equalsIgnoreCase("inside"))
return RoomyCommands.insideCmd(sender, args);
else if(cmd.equalsIgnoreCase("removeroom"))
return RoomyCommands.removeroomCmd(sender, args);
else if(cmd.equalsIgnoreCase("listrooms"))
return RoomyCommands.listroomsCmd(sender, args);
return false;
} | 8 |
public static void main(String a)
{
SpringApplication.run(BookAFlightApplication.class, a);
} | 0 |
public static EnterMineAndDigForNugget getSingleton(){
// needed because once there is singleton available no need to acquire
// monitor again & again as it is costly
if(singleton==null) {
synchronized(EnterMineAndDigForNugget.class){
// this is needed if two threads are waiting at the monitor at the
// time when singleton was getting instantiated
if(singleton==null)
singleton = new EnterMineAndDigForNugget();
}
}
return singleton;
} | 2 |
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MSN)) return false;
MSN msn = (MSN) o;
if (!MTSO.equals(msn.MTSO)) return false;
if (!location.equals(msn.location)) return false;
if (!mateMSN.equals(msn.mateMSN)) return false;
if (tdmMSN != null ? !tdmMSN.equals(msn.tdmMSN) : msn.tdmMSN != null) return false;
return true;
} | 7 |
@Override
public boolean supportsMoveability() {return true;} | 0 |
@Override
public void run() {
for(long i = 0; i < 2000000000; i++);
System.out.println("Slowly thread completed");
} | 1 |
public static String toString(Line line) {
if (line == null) return null;
Line.Info info = line.getLineInfo();
return info.toString();// + " (" + line.getClass().getSimpleName() + ")";
} | 1 |
public boolean pensar(ArrayList<Carta> cartasAbiertas) {
int cuenta = contar(cartasAbiertas);
int acum = sumarCartas();
if (acum == 21) {
return false;
} else if ((cuenta > 0 && cuenta <= 5 && acum <= 17)||(cuenta<= -5 && acum>=17 )||(cuenta==0 && acum<17)) {
return true;
}
return false;
} | 8 |
private boolean isPunctuation(char next) {
return next == '{' || next == '}' || next == '|' || next == ':'
|| next == '.' || next == '!' || next == '='
|| next == '&' || next == ';';
} | 8 |
public Vector3D[][] exportVectors() {
for(int i = 0; i < numPlane; i++) {
Equation e = equations[i];
String s = "";
if (Equation.needUpdate[i]) {
// s = s + ":" + i;
needDraw[i] = updateVecs(e, i);
e.update(false);
alpha[i] = e.alpha;
}
if (i == 4 && s != "") {
// System.out.println(s);
}
}
return vecs;
} | 4 |
public static void print(int intArr[], int len){
System.out.println("After sorting array using RADIX SORT...\nThe following is the sorted array:");
for (int i=0; i<len; i++){
System.out.println(intArr[i]);
}
} | 1 |
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int iDelay = 0;
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
if(req.getParameter("delay") != null)
{
try
{
iDelay = Integer.valueOf(req.getParameter("delay"));
}
catch(Exception e)
{
//Do nothing and let delay = zero
}
}
writer.println(PAGE_HEADER);
writer.println("This build can take an input parm and pass it to helloService for delay...");
writer.println("<h1>" + helloService.createHelloMessage(req.getHeader("x-forwarded-for"), iDelay) + "</h1>");
writer.println("<p>Date / Time = "+new Date().toString()+"</p>");
writer.println(PAGE_FOOTER);
writer.close();
} | 2 |
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {// parcour par colonne
case 0://colonne id_Stock
return Pharmacies.get(rowIndex).getId_ph();
case 1://colonne id_Stock
return Pharmacies.get(rowIndex).getNom_ph();
case 2://colonne type_vetement
return Pharmacies.get(rowIndex).getTel();
case 3://colonne g
return Pharmacies.get(rowIndex).getFax();
case 4://colonne adresse depot
return Pharmacies.get(rowIndex).getAdresse();
case 5://colonne adresse depot
return Pharmacies.get(rowIndex).getType();
case 6:
return Pharmacies.get(rowIndex).getGouvernorat();
case 7:
return Pharmacies.get(rowIndex).getGarde();
default:
return null;
}
} | 8 |
public void addFileDownloadItem(FileDownloadItem item){
items.add(item);
} | 0 |
public static List<String> depthFirstSearch(Graph graph, String startName, String goalName)
{
HashMap<String,Vertex> vertices = graph.getVertices(); // get all the vertices
if(!vertices.containsKey(startName) || !vertices.containsKey(goalName))
throw new UnsupportedOperationException("The graph does not contain either the starting vertex or the goal vertex");
List<String> list = new LinkedList<String>(); // temp to store cameFroms
//Recurive Step
dfsRecursive(graph, vertices, startName, goalName);
//Final Step:
if(vertices.get(goalName).getCameFrom() == null)
return list;
list.add(vertices.get(goalName).getName());//add the goal to cameFrom
Vertex temp = vertices.get(goalName);//set a temp Vertex as the goal
while(!temp.equals(vertices.get(startName))){//While the temp is not equal to the start
list.add(0, temp.getCameFrom().getName());//add them in reverse order to get the travel path
temp = temp.getCameFrom();//switch the temp pointer
}
return list;
} | 4 |
private void setSkin(String lookAndFeel) throws FileNotFoundException, IOException{
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.updateComponentTreeUI(frmGroovejaar);
frmGroovejaar.pack();
} | 4 |
public void visitEnum(final String name, final String desc,
final String value) {
if (name != null) {
cp.newUTF8(name);
}
cp.newUTF8(desc);
cp.newUTF8(value);
av.visitEnum(name, desc, value);
} | 1 |
public int binaryToDecimal(String binary) {
int decimal = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
decimal += (binary.charAt(i) - '0')
* Math.pow(2, binary.length() - i - 1);
}
return decimal;
} | 1 |
public Game(List<Player> players) throws FileNotFoundException, IOException{
if(players == null){
throw new NullPointerException("Players can't be null");
}
if(players.size()<2){
throw new IllegalArgumentException("The game needs at least 2 players.");
}
allLetterTiles = new ArrayList<Tile>();
allPlayers = new ArrayList<Player>(players);
gameBoard = new StandardGameBoard();
currTurn = 0;
passedTurn = 0;
d= new Dictionary();
//init letter tiles
for(String letter : d.getLetterPool()){
allLetterTiles.add(new LetterTile(letter.toUpperCase(), d.getPoints(letter)));
}
Collections.shuffle(allLetterTiles);
for(Player p : allPlayers){
fillUpLetterTile(p);
}
} | 4 |
public Instances getDataSet() throws IOException {
Instances result;
double[] sparse;
double[] data;
int i;
if (m_sourceReader == null)
throw new IOException("No source has been specified");
if (getRetrieval() == INCREMENTAL)
throw new IOException("Cannot mix getting Instances in both incremental and batch modes");
setRetrieval(BATCH);
if (m_structure == null)
getStructure();
result = new Instances(m_structure, 0);
// create instances from buffered arrays
for (i = 0; i < m_Buffer.size(); i++) {
sparse = (double[]) m_Buffer.get(i);
if (sparse.length != m_structure.numAttributes()) {
data = new double[m_structure.numAttributes()];
// attributes
System.arraycopy(sparse, 0, data, 0, sparse.length - 1);
// class
data[data.length - 1] = sparse[sparse.length - 1];
}
else {
data = sparse;
}
// fix class
if (result.classAttribute().isNominal()) {
if (data[data.length - 1] == 1.0)
data[data.length - 1] = result.classAttribute().indexOfValue("+1");
else if (data[data.length - 1] == -1)
data[data.length - 1] = result.classAttribute().indexOfValue("-1");
else
throw new IllegalStateException("Class is not binary!");
}
result.add(new SparseInstance(1, data));
}
try {
// close the stream
m_sourceReader.close();
} catch (Exception ex) {
}
return result;
} | 9 |
private Dimension layoutSize(Container target, boolean preferred)
{
synchronized (target.getTreeLock())
{
// Each row must fit with the width allocated to the containter.
// When the container width = 0, the preferred width of the container
// has not yet been calculated so lets ask for the maximum.
int targetWidth = target.getSize().width;
if (targetWidth == 0)
targetWidth = Integer.MAX_VALUE;
int hgap = getHgap();
int vgap = getVgap();
Insets insets = target.getInsets();
int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
int maxWidth = targetWidth - horizontalInsetsAndGap;
// Fit components into the allowed width
Dimension dim = new Dimension(0, 0);
int rowWidth = 0;
int rowHeight = 0;
int nmembers = target.getComponentCount();
for (int i = 0; i < nmembers; i++)
{
Component m = target.getComponent(i);
if (m.isVisible())
{
Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
// Can't add the component to current row. Start a new row.
if (rowWidth + d.width > maxWidth)
{
addRow(dim, rowWidth, rowHeight);
rowWidth = 0;
rowHeight = 0;
}
// Add a horizontal gap for all components after the first
if (rowWidth != 0)
{
rowWidth += hgap;
}
rowWidth += d.width;
rowHeight = Math.max(rowHeight, d.height);
}
}
addRow(dim, rowWidth, rowHeight);
dim.width += horizontalInsetsAndGap;
dim.height += insets.top + insets.bottom + vgap * 2;
// When using a scroll pane or the DecoratedLookAndFeel we need to
// make sure the preferred size is less than the size of the
// target containter so shrinking the container size works
// correctly. Removing the horizontal gap is an easy way to do this.
Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);
if (scrollPane != null && target.isValid())
{
dim.width -= (hgap + 1);
}
return dim;
}
} | 8 |
public int getAverage(final String callName) {
float avg = -1;
final List<CallData> callDataList = getCallData(callName);
for (final CallData callDataEntry : callDataList) {
if (avg == -1) {
avg = callDataEntry.getDuration();
} else {
avg = (avg + (float)callDataEntry.getDuration()) / (float)2;
}
}
return (int) avg;
} | 2 |
private void processMessage() throws InterruptedException {
try {
MessageUnit mu = messageQueue.take();
Message m = mu.msg;
Object result = null;
if (m instanceof SubmitWorkerMessage) {
SubmitWorkerMessage swm = ((SubmitWorkerMessage) m);
submitWorker(swm.getUid(), swm.getWorker());
} else if (m instanceof CancelWorkerMessage) {
CancelWorkerMessage cm = ((CancelWorkerMessage) m);
result = cancelWorker(cm.getUid());
} else if (m instanceof GetStateMessage) {
GetStateMessage gsm = ((GetStateMessage) m);
result = getWorker(gsm.getUid());
} else if(m instanceof ShutdownMessage) {
shutdownController();
}
mu.cb.process(result);
} catch (RuntimeException e) {
Logger.getGlobal().log(Level.SEVERE, e.getMessage(), e);
}
} | 5 |
public static SwtorParserEvent newEvent(SwtorParser.StateChange sc){
SwtorParserEvent ev = null;
switch(sc.getType()){
case HEALS: ev = new HealEvent(sc);
break;
case DAMAGE: ev = new DamageEvent(sc);
break;
case THREAT: ev = new ThreatEvent(sc);
break;
case COMBAT:
ev = new CombatEvent(sc);
break;
case DEATH:
ev= new DeathEvent(sc);
case UPDATE:
break;
case CLEAR:
break;
default:
ev=new UnknownEvent();
}
return ev ;
} | 7 |
public static void main(String[] args) {
int valor1=0;
int valor2=0;
double resultado=0;
char continuar;
boolean validar=true;
int opcion=0;
Scanner teclado=new Scanner(System.in);
operacion ooperacion=new operacion();
do
{
System.out.println("digite la opercion a evaluar");
System.out.println("1. suma");
System.out.println("2. resta");
System.out.println("3. division");
System.out.println("4. multiplicacion");
System.out.println("5. raiz");
System.out.println("6. potencia");
System.out.println("digite la opcion" +"\n");
opcion=Integer.parseInt(teclado.nextLine());
switch(opcion)
{
case 1:
System.out.println("digite el valor del primer digito");
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("digite el valor del segundo digito");
valor2=Integer.parseInt(teclado.nextLine());
resultado= ooperacion.sumar(valor1,valor2);
System.out.println(resultado);
break;
case 2:
System.out.println("digite el valor del primer digito");
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("digite el valor del segundo digito");
valor2=Integer.parseInt(teclado.nextLine());
resultado= ooperacion.resta(valor1,valor2);
System.out.println(resultado);
break;
case 3:
System.out.println("digite el valor del primer digito");
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("digite el valor del segundo digito");
valor2=Integer.parseInt(teclado.nextLine());
resultado= ooperacion.division(valor1,valor2);
System.out.println(resultado);
break;
case 4:
System.out.println("digite el valor del primer digito");
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("digite el valor del segundo digito");
valor2=Integer.parseInt(teclado.nextLine());
resultado= ooperacion.multiplicacion(valor1,valor2);
System.out.println(resultado);
break;
case 5:
System.out.println("digite el valor del primer digito");
valor1=Integer.parseInt(teclado.nextLine());
resultado= ooperacion.raiz(valor1);
System.out.println(resultado);
break;
case 6:
System.out.println("digite el valor del primer digito");
valor1=Integer.parseInt(teclado.nextLine());
System.out.println("digite el valor del segundo digito");
valor2=Integer.parseInt(teclado.nextLine());
resultado= ooperacion.potencia(valor1,valor2);
System.out.println(resultado);
break;
default:
break;
}
System.out.println("Desea continuar con otra operacion S/N");
continuar=teclado.nextLine() .charAt(0);
if((continuar=='S')||(continuar=='s'))
{
validar=true;
}
else
{
validar=false;
}
}while (validar);
} | 9 |
public void loadPlayerConfigFile(String file) throws FileNotFoundException, BadConfigFormatException {
FileReader playerReader = new FileReader(file);
Scanner playerScanner = new Scanner(playerReader);
HumanPlayer human;
ComputerPlayer currentComputer;
final int numColumns = 4;
int row = 0, column = 0;
int numRows = 0;
Point location;
String name;
java.awt.Color color;
while(playerScanner.hasNextLine()) {
String inputLine = playerScanner.nextLine();
String[] parts = inputLine.split(",");
//if first line, create human player
if(numRows == 0) {
//check for all data
if(parts.length != numColumns)
throw new BadConfigFormatException("Too few columns in player legend file");
else {
name = parts[0];
row = Integer.parseInt(parts[1]);
column = Integer.parseInt(parts[2]);
location = new Point(row,column);
color = convertColor(parts[3]);
human = new HumanPlayer(name, location, color);
this.human = human;
}
}
//otherwise make computer player
else {
//check for all data
if(parts.length != numColumns)
throw new BadConfigFormatException("Too few columns in player legend file");
else {
name = parts[0];
row = Integer.parseInt(parts[1]);
column = Integer.parseInt(parts[2]);
location = new Point(row,column);
color = convertColor(parts[3]);
currentComputer = new ComputerPlayer(name, location, color);
this.computer.add(currentComputer);
}
}
numRows++;
}
playerScanner.close();
} | 4 |
public TankDrive() {
requires(Robot.driveTrain);
} | 0 |
public SaveFileFormat getSaveFormat(String formatName) {
int index = indexOfName(formatName, saverNames);
if (index >= 0) {
return (SaveFileFormat) savers.get(index);
}
return null;
} | 1 |
public void abort() throws java.io.IOException {
//String command = createInferenceAbortionCommand();
//DefaultSubLWorkerSynch newWorker = new DefaultSubLWorkerSynch(command, getCycServer(), false, getTimeoutMsecs());
//newWorker.getWork();
if (this.suspendReason == InferenceWorkerSuspendReason.INTERRUPT) {
this.suspendReason = InferenceWorkerSuspendReason.ABORTED;
}
super.abort();
} | 1 |
public boolean checkHasLost() {
if(this.life < 1){
return true;
}
return this.hasLost;
} | 1 |
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.