method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
8133843a-2c30-49bd-bee2-88c60d0924f4 | 1 | private static int promptUser(String msg) {
Object[] options = {GUITreeLoader.reg.getText("yes"), GUITreeLoader.reg.getText("no")};
int result = JOptionPane.showOptionDialog(
Outliner.outliner,
msg,
GUITreeLoader.reg.getText("confirm_save"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);
if (result == JOptionPane.NO_OPTION) {
return USER_ABORTED;
} else {
return SUCCESS;
}
} |
76fca4ad-fa72-4eca-a060-0e8a9ed466a5 | 1 | public double getAverageLoss(ArrayList<DataPoint> dataPoints) {
double result = 0;
for(DataPoint dp:dataPoints) {
result += dp.sqError;
}
return result/dataPoints.size();
} |
ced1cc6c-ef21-44b2-b702-9b53e61cd117 | 7 | public static LanguageIdentifier generateFromCounts(File countModelsDir, String[] languages) throws IOException {
Map<String, File> modelFileMap = Maps.newHashMap();
Map<String, CharNgramLanguageModel> modelMap = Maps.newHashMap();
File[] allFiles = countModelsDir.listFiles();
int order = 3;
if (allFiles == null || allFiles.length == 0)
throw new IllegalArgumentException("There is no file in:" + countModelsDir);
for (File file : allFiles) {
final String langStr = file.getName().substring(0, file.getName().indexOf("."));
modelFileMap.put(langStr, file);
}
// generate models for required models on the fly.
Log.info("Generating models for:" + Arrays.toString(languages));
for (String language : languages) {
String l = language.toLowerCase();
if (modelFileMap.containsKey(l)) {
CharNgramCountModel countModel = CharNgramCountModel.load(modelFileMap.get(l));
order = countModel.order;
MapBasedCharNgramLanguageModel lm = MapBasedCharNgramLanguageModel.train(countModel);
modelMap.put(l, lm);
modelFileMap.remove(l);
} else {
Log.warn("Cannot find count model file for language " + language);
}
}
// generate garbage model from the remaining files if any left.
if (!modelFileMap.isEmpty()) {
Log.info("Generating garbage model from remaining count models.");
CharNgramCountModel garbageModel = new CharNgramCountModel("unk", order);
for (File file : modelFileMap.values()) {
garbageModel.merge(CharNgramCountModel.load(file));
}
MapBasedCharNgramLanguageModel lm = MapBasedCharNgramLanguageModel.train(garbageModel);
modelMap.put(lm.getId(), lm);
}
return new LanguageIdentifier(modelMap);
} |
f5ed1250-eed3-4859-a977-4fdf8e0ccc47 | 7 | private ReadPreference createReadPreference(final Map<String, List<String>> optionsMap) {
Boolean slaveOk = null;
String readPreferenceType = null;
DBObject firstTagSet = null;
List<DBObject> remainingTagSets = new ArrayList<DBObject>();
for (String key : readPreferenceKeys) {
String value = getLastValue(optionsMap, key);
if (value == null) {
continue;
}
if (key.equals("slaveok")) {
slaveOk = _parseBoolean(value);
} else if (key.equals("readpreference")) {
readPreferenceType = value;
} else if (key.equals("readpreferencetags")) {
for (String cur : optionsMap.get(key)) {
DBObject tagSet = getTagSet(cur.trim());
if (firstTagSet == null) {
firstTagSet = tagSet;
} else {
remainingTagSets.add(tagSet);
}
}
}
}
return buildReadPreference(readPreferenceType, firstTagSet, remainingTagSets, slaveOk);
} |
26c99e4d-ec01-4185-a4c4-d3b5fbf17292 | 6 | @Override
public void drawSolutionk(Graphics drawingArea, int... arg) {
int diameter = arg[2];
int x = arg[0];
int y = arg[1];
int depth = arg[3];
int toDraw = DRAW_ALL;
if(arg.length == 5){
toDraw = arg[4];
}
if(depth == 0){return;}
drawingArea.drawRect(x, y, diameter, diameter);
if((toDraw & DRAW_UP) != 0){
drawSolutionk(drawingArea, x, y - diameter/2, diameter/2, depth-1, DRAW_ULR);
}
if((toDraw & DRAW_DOWN) != 0){
drawSolutionk(drawingArea, x + diameter/2, y + diameter, diameter/2, depth-1, DRAW_DLR);
}
if((toDraw & DRAW_LEFT) != 0){
drawSolutionk(drawingArea, x - diameter/2, y + diameter/2, diameter/2, depth-1, DRAW_LUD);
}
if((toDraw & DRAW_RIGHT) != 0){
drawSolutionk(drawingArea, x + diameter, y, diameter/2, depth-1, DRAW_RUD);
}
} |
a756694e-1737-47f2-b8b9-7224caafba66 | 6 | public static String escape(String string) {
char c;
String s = string.trim();
StringBuffer sb = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i += 1) {
c = s.charAt(i);
if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
sb.append('%');
sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
sb.append(Character.forDigit((char)(c & 0x0f), 16));
} else {
sb.append(c);
}
}
return sb.toString();
} |
2357d44e-cce5-47de-8233-59cee4bb658d | 3 | public int getHighestY()
{
int y = a[1];
if(b[1] > y)
{
y = b[1];
}
if(c[1] > y)
{
y = c[1];
}
if(d[1] > y)
{
y = d[1];
}
return(y);
} |
f76379b5-283c-4e06-9d67-9ebead85a978 | 1 | public String[] getSignal() {
String[] array = new String[signal.size()];
int n = 0;
for(Long key : signal.keySet()) {
array[n] = key.longValue() + "=" + signal.get(key);
n++;
}
return array;
} |
b576a126-ea15-44f6-9bb2-62c7d00b2583 | 3 | private void updateMealFound(List<Keyword> keywords, List<String> terms,
List<String> approval) {
//Since the user is asked for an approval, if he says yes, his history will be saved.
if (!approval.isEmpty()) {
if (approval.get(0).equals("yes")) {
//Save user history
//DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
MealDatePair mealAndDate = new MealDatePair(date, wishMeal.getMealData());
this.getCurrentSession().getCurrentUser().getUserData().addAcceptedSuggestion(mealAndDate);
getCurrentSession().getCurrentUser().getUserData().writeFile();
}
} else {
if (keywords.isEmpty()) {
//Didn't get any keyword
DialogManager.giveDialogManager().setInErrorState(true);
}
}
DialogState nextState = new DialogState();
nextState.setCurrentState(CanteenRecom.CR_EXIT);
getCurrentDialogState().setCurrentState(nextState.getCurrentState());
} |
3d4cc715-2ae0-413c-9294-0172b2933262 | 1 | public Siirto suurin(){
if (koko == 0){
return null;
}
return keko[0];
} |
841c72b0-03e9-4709-b04d-717ff5576629 | 1 | public static int[] leftHalf(int[] array) {
int size1 = array.length / 2;
int[] left = new int[size1];
for (int i = 0; i < size1; i++) {
left[i] = array[i];
}
return left;
} |
ba713e06-157e-49b7-a08d-d870afd16b7d | 4 | private File determineOutfile() {
File file;
final String fn = System.getProperty(PROPERTY_FILE_LOCATION);
if (fn != null) {
file = new File(fn);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
return file;
} catch (IOException ex) {
throw new RuntimeException("Unable to create snitch file", ex);
}
}
file = new File(System.getProperty("java.io.tmpdir")
+ File.separator + DEFAULT_FILE_NAME);
try {
file.createNewFile();
} catch (IOException ex) {
final String error = "Problem creating snitch out file in tmp "
+ "directory";
throw new RuntimeException(error, ex);
}
return file;
} |
718734a6-9176-4f36-af9c-b2ee4697909c | 6 | public boolean getBoolean(String key) throws JSONException {
Object object = get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONObject[" + quote(key) +
"] is not a Boolean.");
} |
a2ad937d-8708-4de0-8a72-6c917b6411c3 | 8 | public boolean comment(String comment, int imgId, String username) {
PreparedStatement stmt = null;
Connection conn = null;
ResultSet rs = null;
int user_id = 0;
Calendar currenttime = Calendar.getInstance();
Date date = new Date((currenttime.getTime()).getTime());
try {
conn = DbConnection.getConnection();
stmt = conn.prepareStatement(GET_USERID_STMT);
stmt.setString(1, username);
rs = stmt.executeQuery();
if (rs.next()) {
user_id = rs.getInt(1);
} else {
return false;
}
stmt = conn.prepareStatement(ADD_COMMENT_STMT);
stmt.setString(1, comment);
stmt.setInt(2, user_id);
stmt.setDate(3, date);
stmt.setInt(4, imgId);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (rs != null) {
try { rs.close(); }
catch (SQLException e) { ; }
rs = null;
}
if (stmt != null) {
try { stmt.close(); }
catch (SQLException e) { ; }
stmt = null;
}
if (conn != null) {
try { conn.close(); }
catch (SQLException e) { ; }
conn = null;
}
}
} |
2f172fbe-fad0-4c34-919c-f0cfe410dde3 | 1 | @Override
public void render() {
super.render();
Player player = Application.get().getLogic().getGame().getPlayer();
InventoryComponent ic = player.getInventory();
Renderer.get().drawText("Money:" + ic.getMoney(), x + 5, y + 5);
/*
Renderer.get().drawText("Crap:", x + 200, y + 5);
Renderer.get().drawText(ic.getCrap() + "", x + 200 + 5*16, y + 5);
Renderer.get().drawText("Cum:", x + 400, y + 5);
Renderer.get().drawText(ic.getCum() + "", x + 400 + 4*16, y + 5);
*/
Renderer.get().drawText("Score:" + player.getExp(), x + 250, y + 5);
long bID = Application.get().getLogic().getGame().getBaseID();
GameActor b = Application.get().getLogic().getActor(bID);
if(b != null) {
PhysicsComponent bPC = (PhysicsComponent)b.getComponent("PhysicsComponent");
Renderer.get().drawText("Vaginal health:" + bPC.getHealth(), x+450, y+5);
}
//if(Application.get().getLogic().getGame().getCurrentSector() != null) {
// Renderer.get().drawText(Application.get().getLogic().getGame().getCurrentSector().getName(), x + 5, y + 40);
//}
Renderer.get().drawText("Time:" + Application.get().getLogic().getGame().getTime() / 1000, x + 5, y + 40);
} |
b6c89784-4b2c-4932-bf8b-8227ad88fbb6 | 9 | public static boolean deleteDirectory(String dir) {
// 如果dir不以文件分隔符结尾,自动添加文件分隔符
if (!dir.endsWith(File.separator)) {
dir = dir + File.separator;
}
File dirFile = new File(dir);
// 如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
System.out.println("删除目录失败" + dir + "目录不存在!");
return false;
}
boolean flag = true;
// 删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
// 删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
}
if (!flag) {
System.out.println("delete failt 删除目录失败");
return false;
}
// 删除当前目录
if (dirFile.delete()) {
System.out.println("删除目录" + dir + "成功!");
return true;
} else {
System.out.println("删除目录" + dir + "失败!");
return false;
}
} |
643df288-69eb-47d5-917a-fa961394ad39 | 9 | private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
try {
if (validarDatos()){
//cargo Parametros del Reporte
Map parametros = new HashMap();
parametros.put("name_empresa", r_con.getRazon_social());
parametros.put("ultimo_asto",ult_asto+1);
if (ult_renglon!=0){
parametros.put("min_fec",campoFecha1.getText());
}
else{
parametros.put("min_fec",fecha.addDaysToDate(campoFecha1.getText(), -1));
}
parametros.put("max_fec",campoFecha2.getText());
parametros.put("cierre_fec",this.cierre_FEC);
parametros.put("nro_folio",this.nro_folio);
parametros.put("ultimo_renglon",ult_renglon);
parametros.put("SUBREPORT_DIR","src/Reportes/");
//localizo el reporte para usarlo
JasperReport report = JasperCompileManager.compileReport("src/Reportes/"+nombre_reporte);
r_con.Connection();
JasperPrint print = JasperFillManager.fillReport(report, parametros, r_con.getConn());
//paginas que ocupó
nro_folio = nro_folio+print.getPages().size();
//vector con las impresoras del modulo de la base de datos
Vector<Vector<String>>v = r_con.getContenidoTabla("SELECT * FROM impresoras WHERE imp_id_modulo = "+id_modulo_imp);
//total impresoras disponibles
PrintService [] impresoras = PrintServiceLookup.lookupPrintServices(null, null);
//vector con las impresoras del modulo como objeto impresora (PrintService)
Vector<PrintService>impresoras_modulo = new Vector();
//objeto impresora en el que se imprime
PrintService impresora = null;
if (v.size()>0){
String nombre_imp;
//caso en que haya mas de una impresora por modulo
if (v.size()>=1){
//localizo con el simple nombre de la base de dato, el objeto impresora y los cargo
for (int i = 0; i < v.size(); i++) {
nombre_imp=v.elementAt(i).firstElement();
AttributeSet aset = new HashAttributeSet();
aset.add(new PrinterName(nombre_imp, null));
impresoras = PrintServiceLookup.lookupPrintServices(null, aset);
impresora = impresoras[0];
impresoras_modulo.add(impresora);
}
//paso las impresoras del modulo a un arreglo para poder mostrarlo en el Dialog
PrintService [] listado_impresoras = new PrintService[impresoras_modulo.size()];
for (int i = 0; i < impresoras_modulo.size(); i++) {
listado_impresoras[i]=impresoras_modulo.elementAt(i);
}
//muestro el listado de impresoras como objeto y se la asigno a la impresora a imprimir
impresora = (PrintService) JOptionPane.showInputDialog(null, "Seleccione una impresora asignada a este módulo:",
"Imprimir Reporte", JOptionPane.QUESTION_MESSAGE, null, listado_impresoras, listado_impresoras[0]);
}
//mando a imprimir el reporte en la impresora
if (impresora != null){
JRPrintServiceExporter jrprintServiceExporter = new JRPrintServiceExporter();
jrprintServiceExporter.setParameter(JRExporterParameter.JASPER_PRINT, print );
jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.PRINT_SERVICE, impresora );
jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PAGE_DIALOG, Boolean.TRUE);
jrprintServiceExporter.setParameter(JRPrintServiceExporterParameter.DISPLAY_PRINT_DIALOG, Boolean.FALSE);
jrprintServiceExporter.exportReport();
String message="Se solicito la impresión del libro Diario, ¿Confirma la CORRECTA impresión?.";
int rta=JOptionPane.showConfirmDialog(null, message, "Confirmar", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);
if (rta==JOptionPane.YES_OPTION){
this.modificarDatosDiario ();
}
else{
JOptionPane.showMessageDialog(null,"Los parametros no se actualizaron. Puede volver a imprimir el Libro Diario.","Error",JOptionPane.WARNING_MESSAGE);
}
}
else{
System.out.println("IMPRESORA NULA VER QUE PASO.");
}
}
else{
JOptionPane.showMessageDialog(null, "No hay Impresoras asignadas a este Modulo, "
+ "\npóngase en contacto con el Administrador de Impresoras.","Atención",JOptionPane.WARNING_MESSAGE);
}
r_con.cierraConexion();
}
} catch (JRException ex) {
JOptionPane.showMessageDialog(null,"Ocurrió un Error.","Error",JOptionPane.WARNING_MESSAGE);
Logger.getLogger(GUI_Imprimir_Diario.class.getName()).log(Level.SEVERE, null, ex);
r_con.cierraConexion();
}
this.dispose();
}//GEN-LAST:event_jButton3ActionPerformed |
964f4609-fd60-4e9b-a9b5-24dab9fa5db5 | 6 | @SuppressWarnings("unchecked")
private void addEntityRestrictions(Restriction query, ExtendedField field,
Object patternObject) {
Restriction subPart = null;
if (field.isMappedAsList()) {
List<Object> liste = (List<Object>) field.getValue(patternObject);
if (liste != null) {
subPart = new Restriction();
for (Object object : liste) {
Restriction restriction = this.buildRestriction(object, field.getMappedType());
if (!restriction.isEmpty()) {
subPart.addOr();
subPart.add(restriction);
}
}
}
} else {
subPart = this.buildRestriction(field.getValue(patternObject), field.getMappedType());
}
if (subPart != null && !subPart.isEmpty()) {
query.addAnd();
query.add(subPart);
}
} |
0b775a56-54f4-4389-91eb-9ae1ad2987fd | 6 | @Override
public void crearFichero(String ruta)
{
FileInputStream from = null;
FileOutputStream to = null;
File toFile = new File(ruta + this.getMetadato("nombre") + this.getMetadato("extension"));
try
{
from = new FileInputStream(this.video);
to = new FileOutputStream(toFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
}
catch (IOException e) {}
finally
{
if (from != null)
try {from.close();}
catch (IOException e) {}
if (to != null)
try {to.close();}
catch (IOException e) {}
}
} |
961e3b39-fd8b-4f33-9045-7815571be24a | 6 | public static <VT> int[] generateRandomHopsOut(Random r, ChiVertex<VT, Float> vertex, int n) {
int l = vertex.numOutEdges();
float[] cumDist = new float[l];
float prefix = 0.0f;
for(int i=0; i < l; i++) {
float x = vertex.getOutEdgeValue(i);
cumDist[i] = prefix + x;
prefix += x;
}
int[] hops = new int[n];
for(int i=0; i < n; i++) {
float x = prefix * r.nextFloat();
if (l > 32) {
int h = Arrays.binarySearch(cumDist, x);
if (h < 0) h = -(h + 1);
hops[i] = h;
} else {
// linear scan
for(int j=0; j < l; j++) {
if (cumDist[j] > x) {
hops[i] = j;
break;
}
}
}
}
return hops;
} |
8d0ec87b-7ec4-40fa-8158-03d9e5b3d968 | 1 | public String showList(){
size = 5;
if(page == 0) page = 1;
List<Record> list = recordDAO.findPage(page, size);
recordList = new RecordList();
recordList.setList(list);
return SUCCESS;
} |
2a2bbd3a-98dd-4466-a62a-5cd5454953fe | 8 | private void mouseDraw(MouseEvent e) {
int states = Goldfish.getMaxStates(rule);
if (e.getX() < 0 || e.getY() < 0 || e.getX() / scale >= width || e.getY() / scale >= height)
return;
Patch p = _grid.getPatch(e.getX() / scale, e.getY() / scale);
if (_drawState == -1) {
if (p.getState() == 0) {
if (SwingUtilities.isLeftMouseButton(e))
_drawState = states - 1;
else if (SwingUtilities.isRightMouseButton(e))
_drawState = 1;
} else {
_drawState = 0;
}
}
p.setState(_drawState);
e.consume();
} |
2a6a6081-4489-433e-98f2-98ed7a95e3a3 | 9 | public SortedMap<Long, Boolean> berecheneZustandsWechselVonBis(Long von, Long bis)
{
// TODO Auto-generated method stub
Calendar cal1 = new GregorianCalendar();
cal1.setTimeInMillis(von);
Calendar cal2 = new GregorianCalendar();
cal2.setTimeInMillis(bis);
SimpleDateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss,SSS");
SortedMap<Long, Boolean> tmp = new TreeMap<Long, Boolean>();
SortedMap<Long, Boolean> map = new TreeMap<Long, Boolean>();
for (int i = cal1.get(Calendar.YEAR); i < cal2.get(Calendar.YEAR) + 1; i++)
{
if (cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR) > 0)
{
try
{
Date anf = df.parse("01.01." + i + " 00:00:00,000");
Date end = df.parse("31.12." + i + " 23:59:59,999");
if (i == cal1.get(Calendar.YEAR))
{
map = berechneZustandsWechsel(von, end.getTime(), i);
Date d = new Date();
d.setTime(von);
}
else if (i == cal2.get(Calendar.YEAR))
{
map = berechneZustandsWechsel(anf.getTime(), bis, i);
Date d = new Date();
d.setTime(bis);
}
else
{
map = berechneZustandsWechsel(anf.getTime(), end.getTime(), i);
}
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
map = berechneZustandsWechsel(von, bis, i);
}
if (map != null)
{
// tmp.putAll(map);
for (Map.Entry<Long, Boolean> me : map.entrySet())
{
if (me.getKey() >= von && me.getKey() <= bis)
tmp.put(me.getKey(), me.getValue());
}
}
}
// tmp = korrigiereErgebnis(von, bis, tmp);
return tmp;
} |
d44f9ff0-34f4-4e4e-a2c2-e5ec1652b7a2 | 9 | private static boolean updateHashEquiJoinCardinality(HashEquiJoin j,
Map<String, Integer> tableAliasToId,
Map<String, TableStats> tableStats) {
DbIterator[] children = j.getChildren();
DbIterator child1 = children[0];
DbIterator child2 = children[1];
int child1Card = 1;
int child2Card = 1;
String[] tmp1 = j.getJoinField1Name().split("[.]");
String tableAlias1 = tmp1[0];
String pureFieldName1 = tmp1[1];
String[] tmp2 = j.getJoinField2Name().split("[.]");
String tableAlias2 = tmp2[0];
String pureFieldName2 = tmp2[1];
boolean child1HasJoinPK = Database.getCatalog()
.getPrimaryKey(tableAliasToId.get(tableAlias1))
.equals(pureFieldName1);
;
boolean child2HasJoinPK = Database.getCatalog()
.getPrimaryKey(tableAliasToId.get(tableAlias2))
.equals(pureFieldName2);
;
if (child1 instanceof Operator) {
Operator child1O = (Operator) child1;
boolean pk = updateOperatorCardinality(child1O, tableAliasToId,
tableStats);
child1HasJoinPK = pk || child1HasJoinPK;
child1Card = child1O.getEstimatedCardinality();
child1Card = child1Card > 0 ? child1Card : 1;
} else if (child1 instanceof SeqScan) {
child1Card = (int) (tableStats.get(((SeqScan) child1)
.getTableName()).estimateTableCardinality(1.0));
}
if (child2 instanceof Operator) {
Operator child2O = (Operator) child2;
boolean pk = updateOperatorCardinality(child2O, tableAliasToId,
tableStats);
child2HasJoinPK = pk || child2HasJoinPK;
child2Card = child2O.getEstimatedCardinality();
child2Card = child2Card > 0 ? child2Card : 1;
} else if (child2 instanceof SeqScan) {
child2Card = (int) (tableStats.get(((SeqScan) child2)
.getTableName()).estimateTableCardinality(1.0));
}
j.setEstimatedCardinality(JoinOptimizer.estimateTableJoinCardinality(j
.getJoinPredicate().getOperator(), tableAlias1, tableAlias2,
pureFieldName1, pureFieldName2, child1Card, child2Card,
child1HasJoinPK, child2HasJoinPK, tableStats, tableAliasToId));
return child1HasJoinPK || child2HasJoinPK;
} |
83c30ea0-eb20-4c0d-9f97-be06f34a2c7e | 0 | public ClusteredMarker(Location location, float size) {
this.location = location;
this.size = size;
} |
e41415b7-7f1d-40b1-902b-f6a1a62e8528 | 9 | public void compose(Raster src, Raster dstIn, WritableRaster dstOut)
{
if (_Entity == null) { throw new IllegalArgumentException("You must set an entity before drawing anything with this composite."); }
try
{
// Get the max bounds of the writable raster.
int maxX = dstOut.getMinX() + dstOut.getWidth();
int maxY = dstOut.getMinY() + dstOut.getHeight();
// Translate coordinates from the raster's space to the SampleModel's space.
int dstInX = -dstIn.getSampleModelTranslateX();
int dstInY = -dstIn.getSampleModelTranslateY();
// Whether the source raster supports a 4th color band, ie. alpha.
boolean supportsAlpha = src.getNumBands() >= 4;
// For each pixel in the writable raster.
for (int y = dstOut.getMinY(); y < maxY; y++)
{
for (int x = dstOut.getMinX(); x < maxX; x++)
{
// Get the depth (z) for both the destination and source rasters.
double dstZ = getZ(dstInX + x, dstInY + y);
double srcZ = _Entity.getDepthSort(x, y);
// Get the pixel's alpha value.
int alpha = supportsAlpha ? src.getSample(x, y, A_BAND) : 1;
// If to overwrite or keep the source raster's data.
if (srcZ > dstZ && alpha > 0)
{
setZ(dstInX + x, dstInY + y, srcZ);
dstOut.setSample(x, y, R_BAND, src.getSample(x, y, R_BAND)); // R
dstOut.setSample(x, y, G_BAND, src.getSample(x, y, G_BAND)); // G
dstOut.setSample(x, y, B_BAND, src.getSample(x, y, B_BAND)); // B
}
else if (srcZ == dstZ && alpha > 0)
{
dstOut.setSample(x, y, R_BAND, src.getSample(x, y, R_BAND)); // R
dstOut.setSample(x, y, G_BAND, src.getSample(x, y, G_BAND)); // G
dstOut.setSample(x, y, B_BAND, src.getSample(x, y, B_BAND)); // B
}
else
{
dstOut.setSample(x, y, R_BAND, dstIn.getSample(x, y, R_BAND)); // R
dstOut.setSample(x, y, G_BAND, dstIn.getSample(x, y, G_BAND)); // G
dstOut.setSample(x, y, B_BAND, dstIn.getSample(x, y, B_BAND)); // B
}
}
}
}
catch (Exception e)
{
System.out.println(this + ": Depth Composite Error. (" + e + ", Entity: " + _Entity.getName() + ")");
}
} |
260be1f2-9094-4f3e-b867-ffd5d2b8127a | 6 | public boolean checkIfBinarySearchTree(Node root) {
if(root!=null) {
if(root.left != null && maxValue(root.left) > root.data)
return false;
else if(root.right != null && minValue(root.right) < root.data)
return false;
else
return (checkIfBinarySearchTree(root.left) && checkIfBinarySearchTree(root.right));
} else
return true;
} |
99dd3010-f64f-4a10-9cca-f68ade8d3649 | 1 | public static boolean password(String pass){
if(pass.matches("(\\w){8,30}"))
return true;
return false;
} |
6b7c8002-41ad-4320-b21b-4f1f98802301 | 5 | public void doGame() {
humanPlayer player1 = new humanPlayer();
System.out.println("\nWe need to know who Player 1 is!");
player1.getName();
player1.marker = "X";
System.out.println("\nNow for Player 2");
humanPlayer player2 = new humanPlayer();
player2.getName();
player2.marker = "O";
Board gameBoard = new Board();
boolean win = false;
int turn = 0;
while(!win){
turn++;
Player currentPlayer;
if((turn % 2)==1) {
currentPlayer = player1;
}
else {
currentPlayer = player2;
}
gameBoard.displayBoard();
System.out.println("\n" + currentPlayer.name + ", Please enter which column you'd like to place"
+ " an " + currentPlayer.marker + ":");
int markerPlace = getColumn();
placeMarker(markerPlace, Board.allMarkers, currentPlayer);
win = testHorizontal(Board.allMarkers);
if(!win){
win = testVertical(Board.allMarkers);
}
if(!win){
win = testDiagonal(Board.allMarkers);
}
if(win) {
currentPlayer.score++;
currentPlayer.wins++;
}
}
gameBoard.displayBoard();
gameBoard.clearBoard();
Player.displayScore(player1, player2);
//This should run the displayScore method that is not in the Player class.
} |
066ad77a-2715-4740-adfa-4b9557c7b3aa | 2 | public boolean hasNext() throws IOException {
while (!tokenizer.hasMoreTokens()) {
String line = reader.readLine();
if (line == null) {
return false;
}
tokenizer = new StringTokenizer(line);
}
return true;
} |
00f47d05-6ea3-4321-8d4d-3d6c4015c49c | 2 | public void saveSettings() {
try {
properties.store(new FileOutputStream(new File(Constants.PROPERTIES_FILE)), "");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} |
95c6163c-cbbb-42c8-b78b-43051799765e | 0 | public RequestFileTransferHandler(int port, File file, String ip){
fileData = file;
ipOfPeer = ip;
portFile = port;
} |
d8b6a087-7c6b-4144-b3fb-47b2f825dead | 9 | public static void openJMX(File file) {
FileInputStream reader = null;
try {
BmLog.debug("Loading file: " + file);
reader = new FileInputStream(file);
HashTree tree = SaveService.loadTree(reader);
GuiPackage guiPackage = GuiPackage.getInstance();
guiPackage.setTestPlanFile(file.getAbsolutePath());
Load.insertLoadedTree(1, tree);
JMeterTreeModel model = guiPackage.getTreeModel();
JMeterTreeNode testPlanNode = model.getNodesOfType(TestPlan.class).get(0);
List<JMeterTreeNode> nodes = Collections.list(testPlanNode.children());
boolean containsRemoteTestRunner = false;
for (JMeterTreeNode node : nodes) {
if (node.getStaticLabel().equals("BlazeMeter")) {
containsRemoteTestRunner = true;
}
if (node.getStaticLabel().contains("Thread Group")) {
List<JMeterTreeNode> subNodes = Collections.list(node.children());
for (JMeterTreeNode subNode : subNodes) {
if (subNode.getStaticLabel().equals("BlazeMeter")) {
containsRemoteTestRunner = true;
}
}
}
}
if (!containsRemoteTestRunner) {
TestElement remoteTestRunner = guiPackage.createTestElement(RemoteTestRunnerGui.class, RemoteTestRunner.class);
model.addComponent(remoteTestRunner, testPlanNode);
}
} catch (FileNotFoundException fnfe) {
BmLog.error("JMX file " + file.getName() + "was not found ", fnfe);
} catch (IllegalUserActionException iuae) {
BmLog.error(iuae);
} catch (Exception exc) {
BmLog.error(exc);
}
} |
7fafcb72-a1f3-4b25-8add-7c68a5456e84 | 5 | public Model getModelAt(int i, int j, int k, int l, int i1, int j1, int k1) {
Model model = getAnimatedModel(i, k1, j);
if (model == null)
return null;
if (adjustToTerrain || delayShading)
model = new Model(adjustToTerrain, delayShading, model);
if (adjustToTerrain) {
int l1 = (k + l + i1 + j1) / 4;
for (int v = 0; v < model.vertexCount; v++) {
int x = model.verticesX[v];
int z = model.verticesZ[v];
int l2 = k + ((l - k) * (x + 64)) / 128;
int i3 = j1 + ((i1 - j1) * (x + 64)) / 128;
int j3 = l2 + ((i3 - l2) * (z + 64)) / 128;
model.verticesY[v] += j3 - l1;
}
model.normalise();
}
return model;
} |
f841934e-cf91-4350-8a03-fcd2805568c7 | 5 | public boolean intersectsInner(AABB var1) {
return var1.x1 >= this.x0 && var1.x0 <= this.x1?(var1.y1 >= this.y0 && var1.y0 <= this.y1?var1.z1 >= this.z0 && var1.z0 <= this.z1:false):false;
} |
68fc1b72-9aba-42d8-a5dd-508b680f82dc | 6 | public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame2().setVisible(true);
}
});
} |
8cfff5ce-84bd-47ee-a6a5-dd3445385fff | 3 | private static void buildBasicMultiColor(Release set, List<SeperatorDefinition> seps) throws MalformedURLException {
SeperatorDefinition def = new SeperatorDefinition();
for(MagicColor c: MagicColor.values())
if (c.isBaseColor())
def.addLeftSymbol(new ImageIconDrawer(SymbolFactory.getIcon(c)));
for(Rarity r: Rarity.values())
def.addRightSymbol(new ImageIconDrawer(SymbolFactory.getIcon(set, r)));
seps.add(def);
} |
badcd908-d2bc-4c1d-9fa6-e3dae164c03b | 1 | @Test
public void arithmeticInstrOpcodeTest() {
try {
instr = new ArithmeticInstr(Opcode.BR, 10, 20);
}
catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
assertNull(instr); //Checks instruction isn't created with invalid opcode for its format.
} |
6e1fb5b2-c3d3-4c4b-80b5-73a214022669 | 6 | @Override
public boolean equals(Object o) {
if (!(o instanceof ParserSettings))
return false;
ParserSettings other = (ParserSettings) o;
return (allowLists == other.allowLists) &&
(allowSingleTokens == other.allowSingleTokens) &&
(ignoreComments == other.ignoreComments) &&
(printTimingInfo == other.printTimingInfo) &&
(tryToRecover == other.tryToRecover) &&
(warningsAreErrors == other.warningsAreErrors);
} |
661b4eb4-2077-453b-847e-8449d2692987 | 0 | public String toString() {
return a + "\n" + b;
} |
34948718-baff-4885-85fd-f0782aeffcd0 | 1 | public WatchKey addWatcher(String folderPath, int mask, boolean watchSubtree) throws IOException {
Watcher watcher = notifier.addWatcher(folderPath, mask, watchSubtree);
Watcher previousWatcher = registeredWatchers.put(watcher.getWatchKey(), watcher);
if (previousWatcher != null) {
LOG.warn(StringUtil.concatenateStrings(
"Failed to register a watcher. A watcher is already watching folder path: ", folderPath));
}
return watcher.getWatchKey();
} |
0014f339-c6cc-41ca-b4bc-1f6f9ed12710 | 7 | public static void main(String[] args){
int nodecounter=0;
Scanner sc=new Scanner(System.in);
Scanner str=new Scanner(System.in);
System.out.println("how many lines?");
int n=sc.nextInt();
Bst t=new Bst();
for(int i=0; i<n; i++)
{
String op=str.nextLine();
String temp=op.substring(0,2);
if(temp.equals("I ")){
int d=Integer.parseInt(temp.substring(2));
nodecounter++;
t.bstTree(root,d,nodecounter);
System.out.println("ok");
}
if(temp.equals("F ")){
String t2=temp.substring(2);
int d=Integer.parseInt(t2);
search(root,d);
}
if(temp.equals("F ")){
int d=Integer.parseInt(temp.substring(2));
successor(root,d,nodecounter);
}
if(temp.equals("P ")){
int d=Integer.parseInt(temp.substring(2));
predece(root,d,nodecounter);
}
if(temp.equals("M")){
maximum(root);
}
if(temp.equals("m")){
minimum(root);
}
}
} |
27a8b676-a25c-40ad-90c1-b369ffa1612f | 2 | public String getSimpleCode(){
String str = "";
String itemCode = item.getCode();
if(itemCode != ""){
String nextTemp = Tree.getNextTemp();
str = item.getCode() +
this.printLineNumber(true) +
nextTemp + " := " + item.place + "\n";
ArgumentListExpression.argList += nextTemp + ", ";
}
else{
ArgumentListExpression.argList += item.place + ", ";
}
ArgumentListExpression itemsList = this.items;
if(itemsList != null){
str = str + itemsList.getSimpleCode();
}
return str;
} |
4868829d-d080-4fd8-a1d3-b002ecd660a4 | 2 | void showPageContent(PageInfo page) {
try {
Desktop.getDesktop().browse(page.getURL().toURI());
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
} |
cc0c4023-2b4f-4d92-a1d0-9913d18e977b | 6 | private GameState mutineerNightAction(GameState state, Card card, boolean output)
{
GameState end = new GameState(state);
Color faction = card.getFaction();
Player player = end.getPlayer(faction);
//If only the mutineer remains, the pirate can't be offered up for
//2 gold and nothing happens
if(player.getDen().size() <= 1)
{
if(output)
{
end.log("The Mutineer (" + card.abbreviate() +
") was the only card in the den, so nothing happens");
}
return end;
}
Card least = null;
int leastVal = Integer.MAX_VALUE;
//Otherwise, the mutineer kills the least ranked pirate for 2 gold
for(Card c : player.getDen())
{
if(c.getValue() < leastVal && !c.equals(card))
{
least = c;
leastVal = c.getValue();
}
}
player.removeFromDen(least);
player.addToDiscard(least);
player.addGold(2);
if(output)
{
end.log("The Mutineer (" + card.abbreviate() +
") killed " + least.abbreviate() + " and gave " + Faction.getPirateName(faction)
+ " 2 gold");
}
return end;
} |
cef2921a-db7c-432d-b934-6f1419aade26 | 1 | public void award_bonus(BigInteger threshold, BigInteger bonus) {
if (getBalance().compareTo(threshold) >= 0)
deposit(bonus);
} |
b1ab381c-3d2d-4bd4-954a-d196c6183d05 | 4 | private void findRuleAndAddWords( String word, String wikiText ) {
int idxStart = wikiText.indexOf( "{{" );
int idxEnd = wikiText.indexOf( "}}", idxStart );
while( idxStart >= 0 && idxEnd >= 0 ) {
Properties props = parseRule( wikiText, idxStart + 2, idxEnd );
String ruleName = props.getProperty( "0" );
if( ruleName != null ) {
Template template = templates.get( ruleName );
if( template != null ) {
template.addWords( word, props );
}
}
idxStart = wikiText.indexOf( "{{", idxEnd );
idxEnd = wikiText.indexOf( "}}", idxStart );
}
} |
24b3dba4-a3b9-48af-8b20-24704c9c140b | 3 | @Override
public void actionPerformed(ActionEvent e) {
OutlinerDocument doc = (OutlinerDocument) Outliner.documents.getMostRecentDocumentTouched();
OutlinerCellRendererImpl textArea = doc.panel.layout.getUIComponent(doc.tree.getEditingNode());
if (textArea == null) {
return;
}
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
if (doc.tree.getComponentFocus() == OutlineLayoutManager.TEXT) {
ToggleEditableAction.toggleEditableText(node, tree, layout);
} else if (doc.tree.getComponentFocus() == OutlineLayoutManager.ICON) {
ToggleEditableAction.toggleEditable(node, tree, layout);
}
} |
77005776-1f64-42fd-b7c3-88feed0196e1 | 2 | private ArrayList<Journal> getSelectedJournals(){
int[] rows = tabel.getSelectedRows();
if (rows.length == 0) {
ActionUtils.showErrorMessage(ActionUtils.SELECT_JOURNAL_FIRST);
}
ArrayList<Journal> journalList = new ArrayList<Journal>();
for(int row : rows) {
Journal journal = (Journal) tabel.getModel().getValueAt(row, 0);
journalList.add(journal);
}
return journalList;
} |
31e497d6-d2fd-4922-9e6e-99a1b1e2d63b | 3 | public void update(GameContainer gc, StateBasedGame sb, float delta) {
if (cooldown <= 0) {
cooldown = 0;
onCooldown = false;
} else if (onCooldown) {
if(beamTimer >=5000){
beamOn=false;
}
beamTimer+=delta;
cooldown -= delta;
}
} |
fe209f89-a119-4710-8653-909ca0ac9d6e | 1 | private static void supplyBeverage() {
beverage = BeverageFactory.getInstance().makeBeverage(beverageChoice);
if (beverage == null) {
System.out.println("Invalid beverage name suppplied.");
} else {
System.out.println(beverage.getName() + " will cost you Rs. " + beverage.getPrice());
}
} |
0fcdb2d2-abe8-4394-90e1-e386581810fc | 2 | private void method95() {
for (int i = 0; i < localNpcCount; i++) {
int k = localNpcIndices[i];
Npc npc = localNpcs[k];
if (npc != null) {
method96(npc);
}
}
} |
5b296f2f-52d2-4506-b4d3-26dc7542d18e | 4 | private byte[] getDiagramBuffs(){
byte []diagramBuff = new byte[Optiums.DIAGRAM_BUFF];
if(lengthBuff != 0 && buff != null){
int needCoffe = Optiums.DIAGRAM_BUFF / lengthBuff;
needCoffe = Optiums.BUFF_SIZE / needCoffe;
for(int i = 0 , l = 0; i < lengthBuff; ++i)
for(int j = 0; j < Optiums.BUFF_SIZE - needCoffe; j += needCoffe, l++)
diagramBuff[l] = buff[i][j];
lengthBuff = 0;
return diagramBuff;
}
lengthBuff = 0;
return null;
} |
f8c002f0-57d9-4677-8906-fb2b6f81aaea | 3 | @Override
public Key next() {
if (!hasNext())
throw new NoSuchElementException();
Node node = stack.pop();
if (node.right != null)
stack.push(node.right);
if (node.left != null)
stack.push(node.left);
return node.key;
} |
3fbd6776-af44-4bd5-87df-a1626502dbe9 | 1 | private void renumberList(List<BaseElement> list){
int index = 1;
for (BaseElement element : list) {
element.setId(index);
index++;
}
} |
1d1f3b05-d078-4436-9fa3-c02d046971fc | 3 | private void initUI() {
setTitle("JProgressBar");
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(40, 40, 40, 40));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
progressBar = new JProgressBar();
progressBar.setMaximumSize(new Dimension(150, 20));
progressBar.setMinimumSize(new Dimension(150, 20));
progressBar.setPreferredSize(new Dimension(150, 20));
progressBar.setAlignmentX(0f);
panel.add(progressBar);
panel.add(Box.createRigidArea(new Dimension(0, 20)));
button = new JButton("Start");
button.setFocusable(false);
button.setMaximumSize(button.getPreferredSize());
updateProBar = new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
int val = progressBar.getValue();
if (val >= 100) {
timer.stop();
button.setText("End");
return;
}
progressBar.setValue(++val);
}
};
timer = new Timer(50, updateProBar);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
timer.stop();
button.setText("Start");
} else if (!"End".equals(button.getText())) {
timer.start();
button.setText("Stop");
}
}
});
panel.add(button);
add(panel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
setVisible(true);
} |
9977c455-ddc9-4aba-b201-ed52a69e5af8 | 1 | public int getPointsPerSubcomplex() {
return pointsPerSubcomplex > -1 ? pointsPerComplex : (NumOfParams + 1);
} |
e51da564-2c66-4439-ba22-da23cecf0614 | 9 | public byte[] next() throws IOException {
byte[] key1 = result1.next();
byte[] key2 = result2.next();
if (key1 == null || key2 == null)
return null;
int cmp = Bytes.compareTo(key1, key2);
while (cmp != 0) {
if (cmp < 0) {
while (cmp < 0) {
key1 = result1.next();
if (key1 == null)
return null;
cmp = Bytes.compareTo(key1, key2);
}
} else if (cmp > 0) {
while (cmp > 0) {
key2 = result2.next();
if (key2 == null)
return null;
cmp = Bytes.compareTo(key1, key2);
}
}
}
currentQResult = result1;
return key1;
} |
d1823e88-985f-466f-9fe4-2f15c70ee71e | 4 | @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(ok)){
valitseOikeaTapahtumaKunOkNappiaPainetaan();
}else if (e.getSource().equals(osasin)){
kertauspaneeli.paivitaOsaaminen(OsaamisenTila.OSATTU);
} else if (e.getSource().equals(melkein)){
kertauspaneeli.paivitaOsaaminen(OsaamisenTila.MELKEIN);
} else if (e.getSource().equals(enOsannut)){
kertauspaneeli.paivitaOsaaminen(OsaamisenTila.EI);
}
} |
90606ec6-f1d1-4441-9f97-18756aa5a5bb | 1 | public void mousePressed(MouseEvent event) {
Transition t = getDrawer().transitionAtPoint(event.getPoint());
if (t != null)
controller.transitionCheck((FSATransition) t);
} |
e05d2ece-16a7-4d62-9329-39916a31d856 | 3 | public Shape get_shape() {
Shape rval = null;
if (type == TYPE_RECT) {
rval = new Shape( (int)(rect.x),
(int)(rect.y),
(int)(rect.x+rect.width),
(int)(rect.y+rect.height));
}
else if (type == TYPE_CIRCLE) {
rval = new Shape( new Point(circle_center.x,
circle_center.y),
circle_r);
}
else if (type == TYPE_POLY) {
rval = new Shape(new Polygon(poly.xpoints,
poly.ypoints,
poly.npoints));
}
return rval;
} |
c519b807-3213-4595-a91e-8001a053dfc4 | 2 | @Test
public void testGetTile() {
System.out.println("getTile");
int x = 1;
int y = 1;
Tile newtile=new Tile();
Tile[][] store=new Tile[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
store[i][j]=newtile;
}
}
map.MapArray=store;
Tile expResult = newtile;
Tile result = map.getTile(x, y);
assertEquals(expResult, result);
} |
42b62aa5-89a1-4c69-9012-4b3f7c65bf86 | 4 | private static void waitForConnection() {
// waiting will be set true through notifyfreeconnection
waiting = true;
double delay = 0;
while (waiting) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// Nothing
}
delay += 0.1;
if (delay == WARN_TIME) {
System.err
.println("client is pending for databseconnection for more than "
+ WARN_TIME
+ " seconds now. - check if all connections are closed correctly");
}
if (delay == ERROR_TIME) {
throw new DBException(
"client is pending for databseconnection for more than "
+ ERROR_TIME
+ " seconds now. - check if all connections are closed correctly");
}
}
} |
e75939de-eb00-4b79-b25e-3946f10ee7b5 | 0 | public void paintConfiguration(Component c, Graphics2D g, int width, int height)
{
super.paintConfiguration(c, g, width, height);
MealyConfiguration config = (MealyConfiguration) getConfiguration();
// Draw the torn tape with the rest of the input.
Torn.paintString((Graphics2D)g, config.getInput(),
RIGHT_STATE.x+5.0f,
((float)super.getIconHeight())*0.5f,
Torn.MIDDLE, width-RIGHT_STATE.x-5.0f,
false, true, config.getInput().length()-
config.getUnprocessedInput().length());
// Draw the stack.
Torn.paintString((Graphics2D)g, config.getOutput(),
BELOW_STATE.x, BELOW_STATE.y + 5.0f,
Torn.TOP, getIconWidth(), false, true, -1);
} |
7a33242e-ed46-43f6-bc35-0906711625a8 | 9 | public TaskRow(final ControllerInterface controller,
final EDITED_TaskScrollPanel taskScrollPanel, Task ta) {
super();
t = ta;
// this.controller = controller;
this.taskScrollPanel = taskScrollPanel;
// TODO setlenient su sdf, rimosso
// TODO layout has to be fixed a lot! I didnt mind about it now
// this.setLayout(new FlowLayout(FlowLayout.LEFT,
// GlobalValues.TASKROW_ELEMENT_SPACING_X,
// GlobalValues.TASKROW_ELEMENT_SPACING_Y));
this.setLayout(new GridBagLayout());
// preferences
// this.setBorder(BorderFactory.createLineBorder(Color.BLACK, ));
// Now add my components: done Button
lang = controller.getLanguageBundle();
doneBut = new JButton();
// doneBut.setText(lang.getString("mainFrame.middlePanel.taskScrollPanel.taskRow.button.done.name"));
doneBut.setText("");
doneBut.setIcon(new ImageIcon(controller
.getResource("assets/Icons/donetask.png")));
doneBut.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
t.setCompleted(!t.getCompleted());
// TODO
// This button will notify the parent (scrollpanel component)
// that this TaskRow has to be moved to completed or pending
// section.
JOptionPane
.showMessageDialog(
null,
"This button will edit task status: completed/pending\nMaybe it should inform scrollpanel.. TODO");
}
});
GridBagConstraints con = new GridBagConstraints();
con.gridx = 0;
con.gridy = 0;
con.weightx = 1.0;
// con.insets = new Insets(0, 100, 0, 0);
con.anchor = GridBagConstraints.LINE_START;
// con.anchor = GridBagConstraints.LINE_END;
add(doneBut, con);
nameField = new JTextField(t.getName());
// nameField.setHorizontalAlignment(JTextField.TRAILING);
nameField.setEnabled(false);
// nameField.setBackground(Color.LIGHT_GRAY);
nameField.setFont(new Font(null, Font.BOLD, 30));
// nameArea.setDisabledTextColor(Color.BLACK);
// nameField.setBorder(null);
con = new GridBagConstraints();
con.gridx = 1;
con.gridy = 0;
con.weightx = 1.0;
// con.fill = GridBagConstraints.WEST;
// con.insets = new Insets(0, 0, 0, 100);
// con.insets = Insets.WEST_INSETS : EAST_INSETS;
con.anchor = GridBagConstraints.LINE_START;
add(nameField, con);
// date format
// TODO anche controlli su data qui
// dateField = new JTextField(sdf.format(t.getDate()));
dateField = new JTextField(controller.getDateFormat().format(
t.getDate()));
dateField.setEnabled(false);
// dateField.setBackground(Color.GREEN);
// dateField.setDisabledTextColor(Color.BLACK);
// dateField.setBorder(null);
con = new GridBagConstraints();
con.gridx = 2;
con.gridy = 0;
// con.insets = new Insets(0, 0, 0, 300);
// con.anchor = GridBagConstraints.LINE_START;
add(dateField, con);
// now build category ComboBox
// TODO: Kadir suggests special combobox, our component wich extends
// combobox
// TODO: Kadir suggests special combobox, our component wich extends
// combobox
// TODO: Kadir suggests special combobox, our component wich extends
// combobox
// TODO: Kadir suggests special combobox, our component wich extends
// combobox
// TODO: Kadir suggests special combobox, our component wich extends
// combobox
// TODO: Kadir suggests special combobox, our component wich extends
// combobox
// maybe is better a button? Then simple dialog with colorpicker???
categoryBox = new JComboBox<String>();
for (Category c : controller.getCategories().values()) {
categoryBox.addItem(c.getName());
}
// Add this special value for adding a task, will register listener
categoryBox.addItem(lang
.getString("shared_actions.newcategoryaction.text"));
categoryBox.addActionListener(new ActionListener() {
// If last "special item" is selected, open add category dialog
// will be an action, because also NewTaskDialog will use this
public void actionPerformed(ActionEvent e) {
JComboBox<String> source = ((JComboBox<String>) e.getSource());
// Note: this method fails is another category is called
// "New Category..."
// because it returns an index wich is not the last one
// TODO how do i prevent this problem? Check on values?
if (source.getSelectedIndex() == (source.getItemCount() - 1)) {
// TODO open add category dialog
// modify through controller
// view will be updated by observer call
// System.out.println("ultimo!");
// TODO
controller.getAction(ControllerInterface.ActionName.NEWCAT)
.actionPerformed(null);
// new AddCategoryDialog(controller);
}
}
});
// Select actual category
categoryBox.setSelectedItem(t.getCategory().getName());
categoryBox.setEnabled(false);
// categoryBox.setEditable(true);
// patternList.addActionListener(this);
con = new GridBagConstraints();
con.gridx = 3;
con.gridy = 0;
// con.insets = new Insets(0, 0, 0, 300);
// con.anchor = GridBagConstraints.LINE_START;
add(categoryBox, con);
// And set my background color!
setBackground(t.getCategory().getColor());
// ------------------------------------------------------
// TODO change this
// priorityField = new JTextField(t.getPrio().toString());
// priorityArea.addMouseListener(my);
// priorityField.setEnabled(false);
// priorityField.setBackground(Color.GREEN);
// priorityField.setDisabledTextColor(Color.BLACK);
// priorityField.setBorder(null);
// con.insets = new Insets(0, 0, 0, 300);
// con.anchor = GridBagConstraints.LINE_START;
// add(priorityField, con);
// PriorityBar pb = new PriorityBar(name, name, name, name, name, name,
// name, name, name, name);
bar = new PriorityBar("assets/def.png", "assets/hover1.png",
"assets/pressed1.png", "assets/pressed1.png",
"assets/hover2.png", "assets/pressed2.png",
"assets/pressed2.png", "assets/hover3.png",
"assets/pressed3.png", "assets/pressed3.png", t.getPrio());
bar.setEnabled(false);
con = new GridBagConstraints();
con.gridx = 4;
con.gridy = 0;
add(bar, con);
// ------------------------------------------------------
descriptionArea = new JTextArea(t.getDescription(),
GlobalValues.TASKROW_DESC_ROWS, GlobalValues.TASKROW_DESC_COLS);
// descriptionArea = new JTextArea(t.getDescription());
// descriptionArea.setBounds( 0, 0, 200, 200 );
// descriptionArea.addMouseListener(my);
descriptionArea.setEnabled(false);
// descriptionArea.setBackground(Color.GREEN);
// descriptionArea.setDisabledTextColor(Color.BLACK);
descriptionArea.setLineWrap(true);
descriptionArea.setWrapStyleWord(true);
descriptionArea.setAlignmentX(CENTER_ALIGNMENT); // TODO not sure it
// works.. once
// again check
// layout
descriptionPane = new JScrollPane(descriptionArea);
descriptionPane.setVisible(false);
con = new GridBagConstraints();
con.gridx = 5;
con.gridy = 0;
if (!descriptionArea.getText().isEmpty())
descriptionPane.setVisible(true);
add(descriptionPane, con);
// Now the edit button
editBut = new JButton();
// editBut = new
// JButton(lang.getString("mainFrame.middlePanel.taskScrollPanel.taskRow.button.edit.name"));
editBut.setIcon(new ImageIcon(controller
.getResource("assets/Icons/edittask.png")));
editBut.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// if (editBut.getActionCommand().equals(
// lang.getString("mainFrame.middlePanel.taskScrollPanel.taskRow.button.edit.name")))
// {
if (!editBut.getIcon().toString().contains("stop")) {
// nameField.setBackground(Color.GREEN);
// dateField.setBackground(Color.GREEN);
// categoryField.setBackground(Color.GREEN);
// priorityField.setBackground(Color.GREEN);
// descriptionArea.setBackground(Color.GREEN);
// editBut.setText("Stop editing");
// editBut.setIcon(defaultIcon)
editBut.setIcon(new ImageIcon(controller
.getResource("assets/Icons/stopedittask.png")));
} else { // call edit task method
// TODO
// priority will be a radiobutton, for the moment it's just
// some text
// did this for quick prototype
String name = nameField.getText();
String date = dateField.getText();
// TODO change priorty to drop down list
// String priority = priorityField.getText();
Task.Priority priority = bar.getPriority();
// TODO: non meglio che categoryBox contenga direttamente
// Category???
// non stringhe!
String categoryName = (String) categoryBox
.getSelectedItem();
String description = descriptionArea.getText();
try {
controller.editTask(t, name,
controller.getDateFormat(), date, priority,
t.getCompleted(), categoryName, description);
} catch (InvalidCategoryException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),
"Category Problem", JOptionPane.WARNING_MESSAGE);
} catch (InvalidDateException e) {
JOptionPane.showMessageDialog(null, e.getMessage(),
"Date problem", JOptionPane.WARNING_MESSAGE);
dateField.setText(controller.getDateFormat().format(
t.getDate()));
}
nameField.setBackground(Color.WHITE);
dateField.setBackground(Color.WHITE);
categoryBox.setBackground(Color.WHITE);
// bar.setBackground(Color.WHITE);
descriptionArea.setBackground(Color.WHITE);
setBackground(t.getCategory().getColor());
editBut.setIcon(new ImageIcon(controller
.getResource("assets/Icons/edittask.png")));
//
// editBut.setText(
// lang.getString("mainFrame.middlePanel.taskScrollPanel.taskRow.button.edit.name"));
}
nameField.setEnabled(!nameField.isEnabled());
dateField.setEnabled(!dateField.isEnabled());
categoryBox.setEnabled(!categoryBox.isEnabled());
// priorityField.setEnabled(!priorityField.isEnabled());
bar.setEnabled(!bar.isEnabled());
descriptionArea.setEnabled(!descriptionArea.isEnabled());
}
});
editBut.setVisible(false);
con = new GridBagConstraints();
con.gridx = 6;
con.gridy = 0;
con.weightx = 1.0;
con.anchor = GridBagConstraints.LINE_END;
add(editBut, con);
// Delete button apre un popup di conferma
deleteBut = new JButton();
// deleteBut = new JButton(
// lang.getString("mainFrame.middlePanel.taskScrollPanel.taskRow.button.delete.name"));
deleteBut.setIcon(new ImageIcon(controller
.getResource("assets/Icons/deletetask.png")));
deleteBut.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
// Display a dialog for confirmation and read answer
// if yes, delete (call to parent, he knows already we r
// focused)
if (JOptionPane.showOptionDialog(null,
"Are you sure you want to delete \"" + t.getName()
+ "\"", "Confirm task deletion",
JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE,
null, null, null) == JOptionPane.YES_OPTION) {
taskScrollPanel.deleteTask(); // TODO changed
// controller.deleteTask(t);
}
}
});
deleteBut.setVisible(false);
con = new GridBagConstraints();
// con.gridx = 7;
// con.gridy = 0;
add(deleteBut, con);
// Finally add panel listeners
addMouseListener(new MouseAdapter() {
// public void mousePressed(MouseEvent me) {
// XXX: to be discussed with team, do we really need a
// fixed focus when someone clicks? I feel that the onfocus
// event is enough!
// }
public void mouseEntered(MouseEvent e) {
if (!isSelected) {
setBorder(BorderFactory
.createBevelBorder(BevelBorder.LOWERED));
setSelected(true);
}
}
public void mouseExited(MouseEvent e) {
if (!isSelected) {
setBorder(BorderFactory
.createBevelBorder(BevelBorder.RAISED));
setSelected(false);
}
}
});
// setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
// setBorder(BorderFactory.createLineBorder(Color.black, 50));
setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
} |
4bcc39e5-22e7-48d4-b8f3-3aa0a918b7e8 | 4 | private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed
UsuarioSistema tmp = null;
try{
tmp = dao.Abrir(this.idUsuarioRemover);
}catch(Exception ex){
JOptionPane.showMessageDialog(rootPane, ex.getMessage());
}
PessoaDAO tmpPessoa = new PessoaDAO();
if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que deseja "
+ "apagar o Usuário selecionado ?","",JOptionPane.OK_CANCEL_OPTION)== 0){
if(dao.Apagar(this.idUsuarioRemover) && tmpPessoa.Apagar(tmp.getId())){
JOptionPane.showMessageDialog(rootPane, "Usuário apagado com sucesso !");
//listaDeUsuarios.clear();
preencheTabela(carregaDadosDoBanco());
}else{
JOptionPane.showMessageDialog(rootPane, "Erro ao apagar !");
}
}
}//GEN-LAST:event_btnRemoverActionPerformed |
a1366208-0677-417f-8372-8fdf90db211e | 5 | private boolean zzRefill() throws java.io.IOException {
/* first: make room (if you can) */
if (zzStartRead > 0) {
System.arraycopy(zzBuffer, zzStartRead,
zzBuffer, 0,
zzEndRead-zzStartRead);
/* translate stored positions */
zzEndRead-= zzStartRead;
zzCurrentPos-= zzStartRead;
zzMarkedPos-= zzStartRead;
zzStartRead = 0;
}
/* is the buffer big enough? */
if (zzCurrentPos >= zzBuffer.length) {
/* if not: blow it up */
char newBuffer[] = new char[zzCurrentPos*2];
System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
zzBuffer = newBuffer;
}
/* finally: fill the buffer with new input */
int numRead = zzReader.read(zzBuffer, zzEndRead,
zzBuffer.length-zzEndRead);
if (numRead > 0) {
zzEndRead+= numRead;
return false;
}
// unlikely but not impossible: read 0 characters, but not at end of stream
if (numRead == 0) {
int c = zzReader.read();
if (c == -1) {
return true;
} else {
zzBuffer[zzEndRead++] = (char) c;
return false;
}
}
// numRead < 0
return true;
} |
9e91d653-bd6e-4569-9abc-fd5da861ed0f | 4 | @Override
public Mortgage createNewChild(TreeMap<String, String> properties) {
Mortgage mortgage = new Mortgage();
mortgage.setName(properties.get(NAME));
String startCapitalString = properties.get(Mortgages.TOTAL);
String nrPayedString = properties.get(Mortgages.NRPAYED);
if(startCapitalString!=null){
mortgage.setStartCapital(new BigDecimal(startCapitalString));
}
if(nrPayedString!=null){
mortgage.setAlreadyPayed(Integer.parseInt(nrPayedString));
}
String capitalAccount = properties.get(Mortgages.CAPITAL_ACCOUNT);
if(capitalAccount!=null){
mortgage.setCapitalAccount(accounts.getBusinessObject(capitalAccount));
}
String intrestAccount = properties.get(Mortgages.INTREST_ACCOUNT);
if(intrestAccount!=null){
mortgage.setIntrestAccount(accounts.getBusinessObject(intrestAccount));
}
return mortgage;
} |
dc8311a9-219d-445c-b867-57fc19521d95 | 5 | @EventHandler(priority = EventPriority.HIGH)
public void InteractDamageMob(EntityDamageEvent event){
if(event.getCause() == DamageCause.ENTITY_ATTACK){
final EntityDamageByEntityEvent realEvent = (EntityDamageByEntityEvent) event;
if(realEvent.getDamager() instanceof Player){
String damagerName = ((Player) realEvent.getDamager()).getName();
Player HitingPlayer = Bukkit.getPlayer(damagerName);
if(!HitingPlayer.hasPermission("NodeWhitelist.Whitelisted")){
if(!whitelistWaive.isWaived(HitingPlayer)){
if(!Config.GetBoolean("NoneWhitelisted.Restraints.Interact")){
event.setCancelled(true);
}
}
}
}
}
} |
66d7d791-ea31-4735-b71c-0e643287ec3c | 1 | public void method473() {
for (int j = 0; j < vertexCount; j++) {
int k = xVertex[j];
xVertex[j] = zVertex[j];
zVertex[j] = -k;
}
} |
793004bc-0cd1-4b7c-b068-718042261e06 | 3 | public void throwInItem(Item item){
int pos = -1;
for(int i = 0; i < neededItems.length; i++){
if(item.getName().equals(neededItems[i])){
neededItems[i] = null;
}
}
if(isFinished()){
context.dropItemOnFloor(product);
}
} |
cba331c9-fb7b-4359-85ed-f534cbcbf736 | 2 | public static void endKW(String name,DateTime startTime, DateTime EndTime, Boolean x,String errorCause){
kwstart+="<tr class="+(x?"Pass":"Fail")+"><th>"+name+"</th><td>"+Seconds.secondsBetween(startTime,EndTime).getSeconds()+"</td><td>"+(x?"Pass":"Fail")+"</td><td>"+errorCause+"</td></tr>";
} |
6242fd3a-9958-4003-b976-d440b562bfef | 7 | private static void calculatePolynomialApproximation(ApparentPlace ap,
double t0, double ghapoly[], double decpoly[], double hppoly[]) {
double gha[] = new double[3];
double dec[] = new double[3];
double hp[] = new double[3];
double earthRadius = 6378137.0/ap.getObserver().getEphemeris().getAU();
boolean isMoon = ap.getTarget().getBodyCode() == JPLEphemeris.MOON;
for (int i = 0; i < 3; i++) {
double t = t0 + 0.5 * (double)i;
try {
ap.calculateApparentPlace(t);
}
catch (JPLEphemerisException jee) {
}
double gast = ap.getEarthRotationModel().greenwichApparentSiderealTime(t);
gha[i] = (gast - ap.getRightAscension()) % TWOPI;
if (gha[i] < 0.0)
gha[i] += TWOPI;
dec[i] = ap.getDeclination();
if (isMoon) {
hp[i] = Math.asin(earthRadius/ap.getGeometricDistance());
}
}
while (gha[1] < gha[0])
gha[1] += TWOPI;
while (gha[2] < gha[1])
gha[2] += TWOPI;
calculatePolynomialCoefficients(gha, ghapoly);
calculatePolynomialCoefficients(dec, decpoly);
if (isMoon)
calculatePolynomialCoefficients(hp, hppoly);
} |
90f26418-a118-4d97-a4de-807c8f0834f6 | 8 | public static void dBoard() {
p();
System.out.println(" 0 1 2 3 4\t 0 1 2 3 4");
for (int row = 0; row < 5; row++) {
String rowStr = row + " ";
for (int col = 0; col < 5; col++) {
rowStr += board[row][col] + " ";
}
rowStr += "\t" + row + " ";
for (int col = 0; col < 5; col++) {
switch (status[row][col]) {
case NEUTRAL:
rowStr += "_" + " ";
break;
case RED:
rowStr += "r" + " ";
break;
case BLUE:
rowStr += "b" + " ";
break;
case RED_DEFENDED:
rowStr += "R" + " ";
break;
case BLUE_DEFENDED:
rowStr += "B" + " ";
break;
default:
rowStr += " " + " ";
}
}
p(rowStr);
}
p();
} |
611fe575-acf6-4bd5-8685-0568f8501bc0 | 0 | public void start(){
running = true;
core = new Thread(this, "Core");
input = new Thread(new InputManager(), "Input");
core.run();
input.run();
} |
aa0bdb34-d81b-4e1f-b7a5-d19d50511bbb | 0 | @Before
public void setUp() {
} |
a679f66d-377b-4404-a0a1-c4184d8edf68 | 0 | public void setAantalpaginas(int aantalpaginas) {
this.aantalpaginas = aantalpaginas;
} |
2ffafbcf-2852-4562-8285-c4e0a2933569 | 5 | public boolean registeredStundent(StudentVO studentVO)
throws LibraryManagementException {
PreparedStatement preparedStatement = null;
ConnectionFactory connectionFactory = new ConnectionFactory();
Connection connection = connectionFactory.getConnection();
String sqlquery = "insert into STUDENT (FIRST_NAME, LAST_NAME, "
+ "FATHER_NAME, GENDER, EMAIL, MOBILE, STUDENT_NUMBER"
+ ", ADMISSION_YEAR, ENROLL_NUMBER, U_ID, PASSWORD) values(?,?,?,?,?,?,?,?,?,?,?)";
boolean created;
int flag=0;
try {
preparedStatement = connection.prepareStatement(sqlquery);
preparedStatement.setString(1, studentVO.getFirstName());
preparedStatement.setString(2, studentVO.getLastName());
preparedStatement.setString(3, studentVO.getFatherName());
preparedStatement.setString(4, studentVO.getGender());
preparedStatement.setString(5, studentVO.getEmail());
preparedStatement.setString(6, studentVO.getMobile());
preparedStatement.setString(7, studentVO.getStudentNumber());
preparedStatement.setInt(8, studentVO.getAdmissionYear());
preparedStatement.setString(9, studentVO.getEnrollNumber());
preparedStatement.setString(10, studentVO.getuID());
preparedStatement.setString(11, studentVO.getPassword());
flag = preparedStatement.executeUpdate();
if(flag == 0) {
created = false;
} else {
created =true;
}
} catch (SQLException e) {
throw new LibraryManagementException(ExceptionCategory.SYSTEM);
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
throw new LibraryManagementException(ExceptionCategory.SYSTEM);
}
}
try {
connection.close();
} catch (SQLException e) {
throw new LibraryManagementException(ExceptionCategory.SYSTEM);
}
return created;
} |
340513e7-5fef-45c4-8a9b-75b90d294497 | 9 | public GuiApplication() {
// give every JList a ListModel
list1Model = new DefaultListModel<>();
list1.setModel(list1Model);
list2Model = new DefaultListModel<>();
list2.setModel(list2Model);
list3Model = new DefaultListModel<>();
list3.setModel(list3Model);
// click the start-button
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startButton.setEnabled(false);
urlTextField.setEnabled(false);
crawlingLabel.setText("Starting...");
list1Model.clear();
list2Model.clear();
list3Model.clear();
new Thread(){
public void run() {
crawler = new WebCrawler(urlTextField.getText().trim(), GuiApplication.this);
crawler.start();
}
}.start();
}
});
// double-click an JList-entry
list1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() != 2) return;
if (!Desktop.isDesktopSupported()) return;
try {
JList list = (JList)evt.getSource();
String url = (String)list.getModel().getElementAt(list.locationToIndex(evt.getPoint()));
Desktop.getDesktop().browse(new URI(url.substring(6)));
} catch (IOException | URISyntaxException ignored) {
}
}
});
list2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() != 2) return;
if (!Desktop.isDesktopSupported()) return;
try {
JList list = (JList)evt.getSource();
String url = (String)list.getModel().getElementAt(list.locationToIndex(evt.getPoint()));
Desktop.getDesktop().browse(new URI(url.substring(6)));
} catch (IOException | URISyntaxException ignored) {
}
}
});
list3.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() != 2) return;
if (!Desktop.isDesktopSupported()) return;
try {
JList list = (JList)evt.getSource();
String url = (String)list.getModel().getElementAt(list.locationToIndex(evt.getPoint()));
Desktop.getDesktop().browse(new URI(url.substring(6)));
} catch (IOException | URISyntaxException ignored) {
}
}
});
} |
142a1538-bb8a-4733-9590-a04708187885 | 7 | public void moveCard(GameSpot fromSpot, GameSpot toSpot, int numberOfCardsToMove) {
Deck fromDeck = getDeck(fromSpot);
Deck toDeck = getDeck(toSpot);
if(ruleService.isGoingToResolutionPile(toSpot)){
movingToResPile(fromSpot, toSpot, numberOfCardsToMove);
}else{
Deck fromCards = getFromCards(fromDeck,numberOfCardsToMove);
Card fromCard = getFromCard(fromCards, numberOfCardsToMove);
if(ruleService.spotIsEmpty(toDeck)){
if(fromCard.getRank() == Rank.KING){
transferCards(fromCards, toDeck, fromDeck);
}
}else{
Card toCard = toDeck.showTopCard();
if(ruleService.isOppositeColor(fromCard, toCard)){
if(ruleService.isOneBelow(fromCard, toCard)){
transferCards(fromCards, toDeck, fromDeck);
}
}else{
fromDeck.getCards().addAll(fromCards.getCards());
}
}
}
Card card = fromDeck.getTopCard();
try{
if(!card.isFaceUp()){
card.turnFaceUp();
}fromDeck.addCard(card);
}catch(NullPointerException e){
}
} |
80a89dbe-bd25-4fca-994a-ebf0bcff7be3 | 4 | static final public CreateActorStatement create_actor_stmt() throws ParseException {
CreateActorStatement result; Token typeTok; Token nameTok;
jj_consume_token(INSTANTIATE);
typeTok = jj_consume_token(TYPEIDENT);
result = new CreateActorStatement(typeTok.image);
jj_consume_token(LPAREN);
if (jj_2_19(4)) {
value_spec_list(result.getParameters());
} else {
;
}
jj_consume_token(RPAREN);
if (jj_2_20(4)) {
jj_consume_token(AS);
nameTok = jj_consume_token(ACTORIDENT);
result.setTarget(new ActorIdentifier(nameTok.image));
} else if (jj_2_21(4)) {
jj_consume_token(TO);
nameTok = jj_consume_token(VARIABLEIDENT);
result.setTarget(new VariableExpression(nameTok.image));
} else {
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return result;}
throw new Error("Missing return statement in function");
} |
cc18aad0-ea06-4c91-93b6-f07a61e8c619 | 0 | public EntityManager getEntityManager() {
return entityManager;
} |
09ce372b-500f-42a1-9854-3c027995f59e | 0 | @Test
public void testValidGroupCanBeCreated() throws Exception {
GroupObject validGroup = new GroupObject("habrahabr", "labrabar", "xerahabr");
createGroup(validGroup);
} |
68fb7716-268e-4365-a78e-8903e317dd3e | 9 | static void sortWith0(double[] a, int fromIndex, int toIndex, DoubleComparator cmp) {
final int length = toIndex - fromIndex + 1;
if (length < 2)
return;
if (length == 2) {
if (cmp.gt(a[fromIndex], a[toIndex])) {
double x = a[fromIndex];
a[fromIndex] = a[toIndex];
a[toIndex] = x;
}
return;
}
// FIXME bad performance
final double pivot = a[fromIndex];
int p1 = 0;
int p2 = 0;
double[] a1 = new double[length];
double[] a2 = new double[length];
for (int i = fromIndex + 1; i <= toIndex; i++) {
final double v = a[i];
if (cmp.lt(v, pivot))
a1[p1++] = v;
else
a2[p2++] = v;
}
int p = fromIndex;
for (int i = 0; i < p1; i++)
a[p++] = a1[i];
a[p++] = pivot;
for (int i = 0; i < p2; i++)
a[p++] = a2[i];
if (p1 > 0)
sortWith0(a, fromIndex, fromIndex + p1 - 1, cmp);
if (p2 > 0)
sortWith0(a, fromIndex + p1 + 1, toIndex, cmp);
} |
4098c7db-f7a5-4825-bcb1-e995c70ea68c | 7 | private String getFeatureAsString(Feature feature) {
String label = Messages.message(getFeatureName(feature)) + ":";
if (feature.hasScope()) {
for (Scope scope : feature.getScopes()) {
String key = null;
if (scope.getType() != null) {
key = scope.getType();
} else if (scope.getAbilityID() != null) {
key = scope.getAbilityID();
} else if (scope.getMethodName() != null) {
key = "model.scope." + scope.getMethodName();
}
if (key != null) {
label += (scope.isMatchNegated() ? " !" : " ")
+ Messages.message(key + ".name") + ",";
}
}
}
return label.substring(0, label.length() - 1);
} |
48595a73-b819-4eef-9c75-cbb47ff300d7 | 7 | public boolean nextToEnemy(int x, int y, int[][] activeMap) {
return ((y != activeMap.length - 1 && activeMap[y + 1][x] == -2) ||
(y != 0 && activeMap[y - 1][x] == -2) ||
(x != activeMap[0].length - 1 && activeMap[y][x + 1] == -2) ||
(x != 0 && activeMap[y][x - 1] == -2));
} |
704b5c25-4484-4399-ad81-f94c2033ec3b | 8 | @Override
public void actionPerformed(ActionEvent e) {
String aux = "";
if (e.getSource() == this.viewTI.getAbre()) {
if (this.viewTI.getGol().isSelected()) {
aux = "VW Gol";
} else if (this.viewTI.getFox().isSelected()) {
aux = "VW Fox";
} else if (this.viewTI.getUp().isSelected()) {
aux ="VW Up";
} else if (this.viewTI.getVoyage().isSelected()) {
aux ="VW Voyage";
} else if (this.viewTI.getJetta().isSelected()) {
aux ="VW Jetta";
} else if (this.viewTI.getAmarok().isSelected()) {
aux ="VW Amarok";
}
Carro model = new Carro();
Pessoa pessoa = new Pessoa();
ViewMonteSeuCarro view = new ViewMonteSeuCarro();
ControllerMonteCarro controller = new ControllerMonteCarro(view, model, pessoa);
view.getModelo().setText(aux);
controller.getCarroView().setVisible(true);
}
else if(e.getSource() == this.viewTI.getFechar()){
this.viewTI.dispose();
}
} |
69c72b68-70c9-49e2-a19a-d42ba38cefbc | 2 | public void setLength(final double newLen) {
int xFac = (x >= 0 ? 1 : -1);
int yFac = (y >= 0 ? 1 : -1);
double len = Math.sqrt(x * x + y * y);
double alpha = Math.asin(Math.abs(x) / len);
x = Math.sin(alpha) * newLen * xFac;
y = Math.cos(alpha) * newLen * yFac;
} |
02b1a833-876d-4c5a-b233-522624040ffd | 4 | @Override
public void analyse(LexicalAnalyser analyser) throws AnalyseException {
String content = analyser.getSentence();
if (content == null) {
throw new AnalyseException("Error: the sentence is null");
}
for (int index = 0; index < content.length(); index++) {
char current = content.charAt(index);
SubDFA subDFA = null;
try {
subDFA = SubDFAFactory.getSubDFAbyCharacter(current);
} catch (UnDefinedCharacterException e) {
analyser.addErrorMsg(e.getMessage());
return;
}
if (subDFA == null) {
continue;
} else {
index = subDFA.analyse(analyser, index);
index--;
}
}
} |
fc2566bc-3a39-4515-a471-9b87e23dc520 | 7 | @Override
protected void setReaction(Message message) {
try {
String[] messageParts = message.text.split(" ");
String profileId = messageParts[1];
String result;
switch (messageParts[2]) {
case "random": result = SelectRandomGame(profileId); break;
case "most_week": result = SelectMostPlayedWeek(profileId); break;
case "most_ever": result = SelectMostPlayedEver(profileId); break;
case "count": result = GetGamesCount(profileId); break;
case "played_ever": result = GetPlayedEver(profileId); break;
case "played_week": result = GetPlayedWeek(profileId); break;
default: result = "Co?"; break;
}
reaction.add( result );
} catch (Exception e) {
System.out.println(e);
setError("Cannot load given URL.", e);
}
} |
0ec0fb7a-215c-4141-9deb-05899ccaeb64 | 4 | protected void handleControlPropertyChanged(final String PROPERTY) {
if ("RESIZE".equals(PROPERTY)) {
resize();
drawBackground();
drawForeground();
} else if ("REDRAW".equals(PROPERTY)) {
drawBackground();
drawForeground();
} else if ("REDRAW_FOREGROUND".equals(PROPERTY)) {
drawForeground();
} else if ("REDRAW_BACKGROUND".equals(PROPERTY)) {
drawBackground();
}
} |
8e7b9be2-0598-4f69-9330-ee60bbf9b793 | 4 | public static String getStreamExtractor(Queue<String> parts) {
String type = next(parts);
if (type == null)
return null;
type = type.toUpperCase();
if (type.equals("SET")) {
String value = next(parts);
return String.format("new StaticExtractor(%s)", value);
}
try {
ParseType.valueOf(type);
return "ParseType." + type;
} catch (IllegalArgumentException e) {
}
try {
return String.format("new SizedStreamExtractor(%d)", Integer.parseInt(type));
} catch (NumberFormatException e) {
}
return null;
} |
1f44cd43-8ef4-43f9-b312-199fa4ddff11 | 6 | public static boolean setValidity(Tickets.Ticket ticket, int validity) {
if (validity == 1 || validity == 2 || validity == 4 || validity == 6 || validity == 8 || validity == 10) {
ticket.setValidity(validity);
return true;
} else {
return false;
}
} |
b7052bd8-742b-40d1-97e0-a97fcc0681d8 | 6 | @EventHandler
public void EndermanHunger(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getEndermanConfig().getDouble("Enderman.Hunger.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
} if (plugin.getEndermanConfig().getBoolean("Enderman.Hunger.Enabled", true) && damager instanceof Enderman && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.HUNGER, plugin.getEndermanConfig().getInt("Enderman.Hunger.Time"), plugin.getEndermanConfig().getInt("Enderman.Hunger.Power")));
}
} |
40facf87-5f18-4929-9de8-e8753c46e646 | 8 | private Map<Integer, Double> getLastUsages(List<UserData> bookmarks, double timestamp, boolean categories) {
Map<Integer, Double> usageMap = new LinkedHashMap<Integer, Double>();
for (UserData data : bookmarks) {
List<Integer> keys = (categories ? data.getCategories() : data.getTags());
double targetTimestamp = Double.parseDouble(data.getTimestamp());
for (int key : keys) {
Double val = usageMap.get(key);
if (val == null || targetTimestamp > val.doubleValue()) {
usageMap.put(key, targetTimestamp);
}
}
}
for (Map.Entry<Integer, Double> entry : usageMap.entrySet()) {
Double rec = Math.pow(timestamp - entry.getValue() + 1.0, this.dValue * (-1.0));
//Double rec = Math.exp((timestamp - entry.getValue() + 1.0) * -1.0);
if (!rec.isInfinite() && !rec.isNaN()) {
entry.setValue(rec.doubleValue());
} else {
System.out.println("BLL - NAN");
entry.setValue(0.0);
}
}
return usageMap;
} |
8c5d44f2-38e9-4b0f-883c-63ff897b236f | 3 | public static void main (String [] args) {
try {
//int reps = Integer.parseInt(args[0]);
int reps=1;
while (reps < 10) {
for(int i=0;i<reps;i++)
System.out.println("*"+"%2s");
System.out.println("\n");
reps ++;
}
} catch (NumberFormatException e) {
return;
}
} |
8bf0b57c-3209-4f4a-ac04-2d4cf0ad7c89 | 0 | protected int getMaxAge()
{
return MAX_AGE;
} |
06668b3c-c514-4a74-ada2-089e202d16f5 | 3 | @Override
public void draw(List<Row> rows, ViewEventArgs args, int from){
this.setRows(rows);
// System.out.println("at main draw: " + rows.size() + " " + this.getRows().size());
if (this.getRows() != null && this.getRows().size() > 0){
int currentTop = args.getTop();
// System.out.println("at main draw: from: " + from + " row size: " + this.getRows().size() );
for (int i = from; i < this.getRows().size(); i++){
Row row = this.getRows().get(i);
row.draw(args.getGraphics(), args.getLeft(), currentTop);
currentTop += row.getHeight();
}
}
} |
b1175ac9-0a80-469b-97cf-b29fe2f0f340 | 8 | public boolean monitor (final String addr_, int events_) {
boolean rc;
if (ctx_terminated) {
ZError.errno(ZError.ETERM);
return false;
}
// Support deregistering monitoring endpoints as well
if (addr_ == null) {
stop_monitor ();
return true;
}
// Parse addr_ string.
URI uri;
try {
uri = new URI(addr_);
} catch (URISyntaxException e) {
ZError.errno (ZError.EINVAL);
throw new IllegalArgumentException (e);
}
String protocol = uri.getScheme();
String address = uri.getAuthority();
String path = uri.getPath();
if (address == null)
address = path;
check_protocol (protocol);
// Event notification only supported over inproc://
if (!protocol.equals ("inproc")) {
ZError.errno (ZError.EPROTONOSUPPORT);
return false;
}
// Register events to monitor
monitor_events = events_;
monitor_socket = get_ctx ().create_socket(ZMQ.ZMQ_PAIR);
if (monitor_socket == null)
return false;
// Never block context termination on pending event messages
int linger = 0;
rc = monitor_socket.setsockopt (ZMQ.ZMQ_LINGER, linger);
if (!rc)
stop_monitor ();
// Spawn the monitor socket endpoint
rc = monitor_socket.bind (addr_);
if (!rc)
stop_monitor ();
return rc;
} |
0cde88b2-d78e-4581-8ace-b7d7a6290863 | 4 | @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockDestroy(BlockBreakEvent event) {
for (Entry<Integer, Game> en : GameAPIMain.getRunners().entrySet()) {
if (en.getValue() instanceof CTTGame) {
if (en.getValue().getPlayers().contains(event.getPlayer().getName())) {
if (event.getBlock().getType() != Material.GOLD_BLOCK) {
event.setCancelled(true);
} else {
event.setCancelled(true);
event.getBlock().setType(Material.AIR);
event.getPlayer().getInventory().addItem(new ItemStack(Material.GOLD_BLOCK));
}
}
}
}
} |
Subsets and Splits